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
|
|---|---|---|---|---|---|
'*
'* This file is part of the TwitterVB software
'* Copyright (c) 2009, Duane Roelands <duane@getTwitterVB.com>
'* All rights reserved.
'*
'* TwitterVB is a port of the Twitterizer library <http://code.google.com/p/twitterizer/>
'* Copyright (c) 2008, Patrick "Ricky" Smith <ricky@digitally-born.com>
'* All rights reserved.
'*
'* Redistribution and use in source and binary forms, with or without modification, are
'* permitted provided that the following conditions are met:
'*
'* - Redistributions of source code must retain the above copyright notice, this list
'* of conditions and the following disclaimer.
'* - Redistributions in binary form must reproduce the above copyright notice, this list
'* of conditions and the following disclaimer in the documentation and/or other
'* materials provided with the distribution.
'* - Neither the name of TwitterVB nor the names of its contributors may be
'* used to endorse or promote products derived from this software without specific
'* prior written permission.
'*
'* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
'* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
'* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
'* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
'* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
'* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
'* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
'* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
'* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
'* POSSIBILITY OF SUCH DAMAGE.
'*
Namespace Integration.Twitter.TwitterVB2
''' <summary>
''' Global items that need to be visible to the entire library
''' </summary>
''' <remarks></remarks>
''' <exclude/>
Public Module Globals
''' <summary>
''' The number of API calls remaining in the current API period.
''' </summary>
''' <remarks></remarks>
Public API_RemainingHits As String
''' <summary>
''' The total number of API calls allowed in the current API period.
''' </summary>
''' <remarks></remarks>
Public API_HourlyLimit As String
''' <summary>
''' The time when the next API period starts and <c>RemainingHits</c> will reset.
''' </summary>
''' <remarks></remarks>
Public API_Reset As String
''' <summary>
''' The username that will be passed to the default proxy server.
''' </summary>
''' <remarks></remarks>
Public Proxy_Username As String = String.Empty
''' <summary>
''' The password that will be passed to the default proxy server.
''' </summary>
''' <remarks></remarks>
Public Proxy_Password As String = String.Empty
''' <summary>
''' Specifies how to parse the response from the Trends methods of the Twitter API.
''' </summary>
''' <remarks></remarks>
Public Enum TrendFormat
''' <summary>
''' Returns the top ten topics that are currently trending on Twitter.
''' </summary>
''' <remarks></remarks>
Trends
''' <summary>
''' Returns the current top 10 trending topics on Twitter. The response includes the time of the request, the name of each trending topic, and query used on Twitter Search results page for that topic.
''' </summary>
''' <remarks></remarks>
Current
''' <summary>
''' Returns the top 20 trending topics for each hour in a given day.
''' </summary>
''' <remarks></remarks>
Daily
''' <summary>
''' Returns the top 30 trending topics for each day in a given week.
''' </summary>
''' <remarks></remarks>
Weekly
''' <summary>
''' Returns the top 10 trending topics for given location.
''' </summary>
''' <remarks></remarks>
ByLocation
End Enum
''' <summary>
''' Specifies which Url shortening service to use.
''' </summary>
''' <remarks></remarks>
Public Enum UrlShortener
''' <summary>
''' Indicates that the Is.Gd service will be used.
''' </summary>
''' <remarks></remarks>
IsGd
''' <summary>
''' Indicates that the TinyUrl service will be used.
''' </summary>
''' <remarks></remarks>
TinyUrl
''' <summary>
''' Indicates that the Br.st service will be used.
''' </summary>
''' <remarks></remarks>
BrSt
''' <summary>
''' Indicates that the bit.ly service will be used.
''' </summary>
''' <remarks></remarks>
BitLy
End Enum
''' <summary>
''' Controls whether a list is public or private.
''' </summary>
''' <remarks></remarks>
Public Enum ListMode
''' <summary>
''' Indicates that the list will be public.
''' </summary>
''' <remarks></remarks>
[Public]
''' <summary>
''' Indicates that the list will be private.
''' </summary>
''' <remarks></remarks>
[Private]
End Enum
End Module
End Namespace
|
Eonic/EonicWeb5
|
Assemblies/Protean.Tools/Integration/Twitter/TwitterVB2/Globals.vb
|
Visual Basic
|
apache-2.0
| 5,780
|
Imports sri = System.Runtime.InteropServices
Imports srv = System.Runtime.Versioning
Imports src = System.Runtime.ConstrainedExecution
Imports Int = System.IntPtr
Imports Uint = System.UIntPtr
Imports mws = Microsoft.Win32.SafeHandles
Namespace Native
Public Module DllInfo
Public Const KERNEL32 = "kernel32.dll"
Public Const USER32 = "user32.dll"
Public Const ADVAPI32 = "advapi32.dll"
Public Const OLE32 = "ole32.dll"
Public Const OLEAUT32 = "oleaut32.dll"
Public Const SHELL32 = "shell32.dll"
Public Const SHIM = "mscoree.dll"
Public Const CRYPT32 = "crypt32.dll"
Public Const SECUR32 = "secur32.dll"
Public Const NTDLL = "ntdll.dll"
Public Const MSVCRT = "msvcrt.dll"
End Module
Public Module Common
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="GetLastError")>
Public Function LastError() As Integer
End Function
End Module
Public Module File
Public Const DirectWrite As Integer = &H20000000 Or &H80000000
<sri.StructLayout(sri.LayoutKind.Sequential)>
Public Class SECURITY_ATTRIBUTES
Public nLength As Integer = 8 + System.IntPtr.Size
'don't remove null, or this field will disappear in bcl.small
'internal unsafe byte * pSecurityDescriptor = null;
Public pSecurityDescriptor As System.IntPtr = Nothing
Public bInheritHandle As Integer = 0
End Class
' SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)>
'<sri.DllImport(KERNEL32, SetLastError:=True, CharSet:=sri.CharSet.Auto, BestFitMapping:=False)>
'Public Function CreateFile(lpFileName As String,
' dwDesiredAccess As System.IO.FileAccess, dwShareMode As System.IO.FileShare,
' securityAttrs As SECURITY_ATTRIBUTES, dwCreationDisposition As System.IO.FileMode,
' dwFlagsAndAttributes As System.IO.FileOptions, hTemplateFile As System.IntPtr) As mws.SafeFileHandle
'End Function
'Public Declare Function Open Lib "kernel32.dll" Alias "CreateFile" () As mws.SafeFileHandle
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="CreateFile", CharSet:=sri.CharSet.Auto, BestFitMapping:=False)>
Public Function Open(FileName As String,
FileAccess As System.IO.FileAccess, ShareMode As System.IO.FileShare,
SecurityATB As SECURITY_ATTRIBUTES, FileMode As System.IO.FileMode,
FileOption As System.IO.FileOptions, hTemplateFile As System.IntPtr) As mws.SafeFileHandle
End Function
'Might be wrong but I think lo and hi == {int, int} == long
' (Long)FullLength = (Long)hi << 32 Or (Uint)lo
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="SetFilePointerEx"),
srv.ResourceExposure(srv.ResourceScope.None)>
Public Function Seek(handle As mws.SafeFileHandle, MoveValue As Long, ByRef PositionAfterSeek As Long, origin As System.IO.SeekOrigin) As Boolean
End Function
'''<param name="lpOverlapped">Contains information used in asynchronous (or overlapped) input and output (I/O)</param>
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="ReadFile"),
srv.ResourceExposure(srv.ResourceScope.None)>
Public Function Read(handle As mws.SafeFileHandle, Data As System.IntPtr, Length As UInteger, ByRef Count As UInteger, lpOverlapped As Int) As Boolean
End Function
'''<param name="lpOverlapped">Contains information used in asynchronous (or overlapped) input and output (I/O)</param>
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="WriteFile"),
srv.ResourceExposure(srv.ResourceScope.None)>
Public Function Write(handle As mws.SafeFileHandle, Data As System.IntPtr, Length As UInteger, ByRef Count As UInteger, lpOverlapped As Int) As Boolean
End Function
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="GetFileSizeEx"),
srv.ResourceExposure(srv.ResourceScope.None)>
Public Function Size(hFile As mws.SafeFileHandle, ByRef highSize As ULong) As Boolean
End Function
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="CancelIo"),
srv.ResourceExposure(srv.ResourceScope.None)>
Public Function Cancel(hFile As mws.SafeFileHandle) As Boolean
End Function
End Module
Public Module Link
'''<param name="lpSecurityAttributes">Must be Null.</param>
<sri.DllImport(KERNEL32, EntryPoint:="CreateHardLink")>
Public Function Hard(NewAddress As String, TargetAddress As String, lpSecurityAttributes As Object) As Boolean
End Function
<sri.DllImport(KERNEL32, EntryPoint:="CreateSymbolicLink")>
Public Function Symbolic(NewAddress As String, TargetAddress As String, IsFolder As UInteger) As Boolean
End Function
End Module
Public Module Memory
<sri.DllImport(KERNEL32, EntryPoint:="LocalAlloc"),
System.Runtime.Versioning.ResourceExposure(srv.ResourceScope.None),
src.ReliabilityContract(src.Consistency.WillNotCorruptState, src.Cer.MayFail)>
Public Function Alloc(uFlags As Integer, sizetdwBytes As System.IntPtr) As System.IntPtr
End Function
'Unuseable
'<sri.DllImport(KERNEL32, EntryPoint:="LocalReAlloc"),
'System.Runtime.Versioning.ResourceExposure(srv.ResourceScope.None),
'src.ReliabilityContract(src.Consistency.WillNotCorruptState, src.Cer.MayFail)>
'Public Function ReAlloc(Address As System.IntPtr, sizetdwBytes As System.IntPtr, uFlags As Integer) As System.IntPtr
'End Function
<sri.DllImport(KERNEL32, EntryPoint:="CopyMemory"),
System.Runtime.Versioning.ResourceExposure(srv.ResourceScope.None)>
Public Sub Copy(Target As System.IntPtr, Source As System.IntPtr, Size As Long)
End Sub
<sri.DllImport(KERNEL32, EntryPoint:="MoveMemory"),
System.Runtime.Versioning.ResourceExposure(srv.ResourceScope.None)>
Public Sub Move(Target As System.IntPtr, Source As System.IntPtr, Size As Long)
End Sub
<sri.DllImport(KERNEL32, EntryPoint:="FillMemory"),
System.Runtime.Versioning.ResourceExposure(srv.ResourceScope.None)>
Public Sub Fill([From] As System.IntPtr, Count As Long, Value As Byte)
End Sub
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="LocalFree"),
System.Runtime.Versioning.ResourceExposure(srv.ResourceScope.None),
src.ReliabilityContract(src.Consistency.WillNotCorruptState, src.Cer.Success)>
Public Function Free(Address As System.IntPtr) As System.IntPtr
End Function
<sri.DllImport(KERNEL32, SetLastError:=True, EntryPoint:="LocalSize"),
System.Runtime.Versioning.ResourceExposure(srv.ResourceScope.None),
src.ReliabilityContract(src.Consistency.WillNotCorruptState, src.Cer.Success)>
Public Function Size(Address As System.IntPtr) As System.UIntPtr
End Function
<sri.DllImport(KERNEL32, EntryPoint:="RtlZeroMemory"),
System.Runtime.Versioning.ResourceExposure(srv.ResourceScope.None),
src.ReliabilityContract(src.Consistency.WillNotCorruptState, src.Cer.Success)>
Public Sub Clear(Address As System.IntPtr, Length As System.IntPtr)
End Sub
<sri.DllImport(MSVCRT, EntryPoint:="memcmp", CallingConvention:=sri.CallingConvention.Cdecl)>
Public Function Compare(A() As Byte, B() As Byte, Length As UInteger) As System.IntPtr
End Function
<sri.DllImport(MSVCRT, EntryPoint:="memcmp", CallingConvention:=sri.CallingConvention.Cdecl)>
Public Function Compare(A As System.IntPtr, B As System.IntPtr, Length As UInteger) As System.IntPtr
End Function
'<sri.DllImport(MSVCRT, EntryPoint:="memcmp", CallingConvention:=sri.CallingConvention.Cdecl)>
'Public Function Compare(A As Object, B As Object, Length As UInteger) As System.IntPtr
'End Function
'CallingConvention:=sri.CallingConvention.Cdecl
'<sri.DllImport(MSVCRT, EntryPoint:="memcmp")>
'Public Function Compare(A As Object, B As Object, Length As Long) As System.IntPtr
'End Function
End Module
End Namespace
|
RevensofT/.Net-Anarchy
|
Assistance/Native.vb
|
Visual Basic
|
apache-2.0
| 8,454
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class Register
'''<summary>
'''RegisterUser control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents RegisterUser As Global.System.Web.UI.WebControls.CreateUserWizard
'''<summary>
'''RegisterUserWizardStep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents RegisterUserWizardStep As Global.System.Web.UI.WebControls.CreateUserWizardStep
End Class
|
UCHIC/nwisanalyst
|
src/nwisanalyst/Account/Register.aspx.designer.vb
|
Visual Basic
|
bsd-3-clause
| 1,090
|
' 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.CodeGen
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenSelectCase
Inherits BasicTestBase
Private Shared Sub VerifySynthesizedStringHashMethod(compVerifier As CompilationVerifier, expected As Boolean)
Dim methodName = PrivateImplementationDetails.SynthesizedStringHashFunctionName + "(String)"
compVerifier.VerifyMemberInIL(methodName, expected)
If expected Then
compVerifier.VerifyIL(methodName, <![CDATA[
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (UInteger V_0,
Integer V_1)
IL_0000: ldc.i4 0x811c9dc5
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: brfalse.s IL_002a
IL_0009: ldc.i4.0
IL_000a: stloc.1
IL_000b: br.s IL_0021
IL_000d: ldarg.0
IL_000e: ldloc.1
IL_000f: callvirt "Function String.get_Chars(Integer) As Char"
IL_0014: ldloc.0
IL_0015: xor
IL_0016: ldc.i4 0x1000193
IL_001b: mul
IL_001c: stloc.0
IL_001d: ldloc.1
IL_001e: ldc.i4.1
IL_001f: add
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.0
IL_0023: callvirt "Function String.get_Length() As Integer"
IL_0028: blt.s IL_000d
IL_002a: ldloc.0
IL_002b: ret
}
]]>)
End If
End Sub
<Fact()>
Public Sub SelectCase_Empty()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.WriteLine("Foo")
Return 0
End Function
Sub Main()
Select Case Foo()
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:="Foo").VerifyIL("M1.Main", <![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: pop
IL_0006: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact()>
Public Sub SimpleSelectCase_IfList()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![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)
Select Case number
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 1 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>,
expectedOutput:=<![CDATA[0:Less than 1
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 91 (0x5b)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: bge.s IL_0011
IL_0006: ldstr "Less than 1"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: ldc.i4.1
IL_0013: blt.s IL_0024
IL_0015: ldloc.0
IL_0016: ldc.i4.5
IL_0017: bgt.s IL_0024
IL_0019: ldstr "Between 1 and 5, inclusive"
IL_001e: call "Sub System.Console.WriteLine(String)"
IL_0023: ret
IL_0024: ldloc.0
IL_0025: ldc.i4.6
IL_0026: beq.s IL_0030
IL_0028: ldloc.0
IL_0029: ldc.i4.7
IL_002a: beq.s IL_0030
IL_002c: ldloc.0
IL_002d: ldc.i4.8
IL_002e: bne.un.s IL_003b
IL_0030: ldstr "Between 6 and 8, inclusive"
IL_0035: call "Sub System.Console.WriteLine(String)"
IL_003a: ret
IL_003b: ldloc.0
IL_003c: ldc.i4.s 9
IL_003e: blt.s IL_0050
IL_0040: ldloc.0
IL_0041: ldc.i4.s 10
IL_0043: bgt.s IL_0050
IL_0045: ldstr "Equal to 9 or 10"
IL_004a: call "Sub System.Console.WriteLine(String)"
IL_004f: ret
IL_0050: ldstr "Greater than 10"
IL_0055: call "Sub System.Console.WriteLine(String)"
IL_005a: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_Boolean()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 To 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(count As Integer)
Dim b As Boolean = count
Select Case b
Case 9, 10
If count <> 0 Then
Console.WriteLine("Non zero")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
Case 1, 2, 3, 4, 5
Case Else
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Non zero
2:Non zero
3:Non zero
4:Non zero
5:Non zero
6:Non zero
7:Non zero
8:Non zero
9:Non zero
10:Non zero
11:Non zero]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 40 (0x28)
.maxstack 2
.locals init (Boolean V_0) //b
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: cgt.un
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: brfalse.s IL_001a
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: bne.un.s IL_0027
IL_000c: ldarg.0
IL_000d: brfalse.s IL_0027
IL_000f: ldstr "Non zero"
IL_0014: call "Sub System.Console.WriteLine(String)"
IL_0019: ret
IL_001a: ldarg.0
IL_001b: brtrue.s IL_0027
IL_001d: ldstr "Equal to 0"
IL_0022: call "Sub System.Console.WriteLine(String)"
IL_0027: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_DateTime()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test(Nothing)
Test(#1/1/0001 12:00:00 AM#)
Test(#8/13/2002 12:15:10 PM#)
Test(#8/13/2002 12:00:00 PM#)
Test(#8/13/2002 12:16 PM#)
Test(#8/13/2002 12:15 PM#)
Test(#8/13/2002 12:05 PM#)
Test(#8/13/2002 12:17 PM#)
Test(#8/13/2002#)
End Sub
Dim cul = System.Globalization.CultureInfo.InvariantCulture
Sub Test(d as DateTime)
Console.WriteLine(d.ToString("M/d/yyyy h:mm:ss tt", cul))
Select Case d
Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#
Console.WriteLine("Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#")
Case Is >= #8/13/2002 12:16:15 PM#
Console.WriteLine("Case Is >= #8/13/2002 12:16:15 PM#")
Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#
Console.WriteLine("Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#")
Case #8/13/2002 12 PM#
Console.WriteLine("Case #8/13/2002 12 PM#")
Case #8/13/2002 12:05 PM#
Console.WriteLine("Case #8/13/2002 12:05 PM#")
Case Nothing
Console.WriteLine("Case Nothing")
Case Else
Console.WriteLine("Case Else")
End Select
Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[1/1/0001 12:00:00 AM
Case Nothing
1/1/0001 12:00:00 AM
Case Nothing
8/13/2002 12:15:10 PM
Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#
8/13/2002 12:00:00 PM
Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#
8/13/2002 12:16:00 PM
Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#
8/13/2002 12:15:00 PM
Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#
8/13/2002 12:05:00 PM
Case #8/13/2002 12:05 PM#
8/13/2002 12:17:00 PM
Case Is >= #8/13/2002 12:16:15 PM#
8/13/2002 12:00:00 AM
Case Else]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 293 (0x125)
.maxstack 3
.locals init (Date V_0)
IL_0000: ldarga.s V_0
IL_0002: ldstr "M/d/yyyy h:mm:ss tt"
IL_0007: ldsfld "M1.cul As Object"
IL_000c: castclass "System.IFormatProvider"
IL_0011: call "Function Date.ToString(String, System.IFormatProvider) As String"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ldarg.0
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: ldc.i8 0x8c410da33ff5b00
IL_0027: newobj "Sub Date..ctor(Long)"
IL_002c: call "Function Date.Compare(Date, Date) As Integer"
IL_0031: brfalse.s IL_0049
IL_0033: ldloc.0
IL_0034: ldc.i8 0x8c410d815986000
IL_003d: newobj "Sub Date..ctor(Long)"
IL_0042: call "Function Date.Compare(Date, Date) As Integer"
IL_0047: brtrue.s IL_0058
IL_0049: ldstr "Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#"
IL_004e: call "Sub System.Console.WriteLine(String)"
IL_0053: br IL_011f
IL_0058: ldloc.0
IL_0059: ldc.i8 0x8c410da5abd9180
IL_0062: newobj "Sub Date..ctor(Long)"
IL_0067: call "Function Date.Compare(Date, Date) As Integer"
IL_006c: ldc.i4.0
IL_006d: blt.s IL_007e
IL_006f: ldstr "Case Is >= #8/13/2002 12:16:15 PM#"
IL_0074: call "Sub System.Console.WriteLine(String)"
IL_0079: br IL_011f
IL_007e: ldloc.0
IL_007f: ldc.i8 0x8c410da0a463400
IL_0088: newobj "Sub Date..ctor(Long)"
IL_008d: call "Function Date.Compare(Date, Date) As Integer"
IL_0092: ldc.i4.0
IL_0093: blt.s IL_00b8
IL_0095: ldloc.0
IL_0096: ldc.i8 0x8c410da51ccc000
IL_009f: newobj "Sub Date..ctor(Long)"
IL_00a4: call "Function Date.Compare(Date, Date) As Integer"
IL_00a9: ldc.i4.0
IL_00aa: bgt.s IL_00b8
IL_00ac: ldstr "Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#"
IL_00b1: call "Sub System.Console.WriteLine(String)"
IL_00b6: br.s IL_011f
IL_00b8: ldloc.0
IL_00b9: ldc.i8 0x8c410d815986000
IL_00c2: newobj "Sub Date..ctor(Long)"
IL_00c7: call "Function Date.Compare(Date, Date) As Integer"
IL_00cc: brtrue.s IL_00da
IL_00ce: ldstr "Case #8/13/2002 12 PM#"
IL_00d3: call "Sub System.Console.WriteLine(String)"
IL_00d8: br.s IL_011f
IL_00da: ldloc.0
IL_00db: ldc.i8 0x8c410d8c868be00
IL_00e4: newobj "Sub Date..ctor(Long)"
IL_00e9: call "Function Date.Compare(Date, Date) As Integer"
IL_00ee: brtrue.s IL_00fc
IL_00f0: ldstr "Case #8/13/2002 12:05 PM#"
IL_00f5: call "Sub System.Console.WriteLine(String)"
IL_00fa: br.s IL_011f
IL_00fc: ldloc.0
IL_00fd: ldsfld "Date.MinValue As Date"
IL_0102: call "Function Date.Compare(Date, Date) As Integer"
IL_0107: brtrue.s IL_0115
IL_0109: ldstr "Case Nothing"
IL_010e: call "Sub System.Console.WriteLine(String)"
IL_0113: br.s IL_011f
IL_0115: ldstr "Case Else"
IL_011a: call "Sub System.Console.WriteLine(String)"
IL_011f: call "Sub System.Console.WriteLine()"
IL_0124: ret
}]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_SwitchTable_Integer()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![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)
Select Case number
Case 0
Console.WriteLine("Equal to 0")
Case 1, 2, 3, 4, 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9, 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 109 (0x6d)
.maxstack 1
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: switch (
IL_0036,
IL_0041,
IL_0041,
IL_0041,
IL_0041,
IL_0041,
IL_004c,
IL_004c,
IL_004c,
IL_0057,
IL_0057)
IL_0034: br.s IL_0062
IL_0036: ldstr "Equal to 0"
IL_003b: call "Sub System.Console.WriteLine(String)"
IL_0040: ret
IL_0041: ldstr "Between 1 and 5, inclusive"
IL_0046: call "Sub System.Console.WriteLine(String)"
IL_004b: ret
IL_004c: ldstr "Between 6 and 8, inclusive"
IL_0051: call "Sub System.Console.WriteLine(String)"
IL_0056: ret
IL_0057: ldstr "Equal to 9 or 10"
IL_005c: call "Sub System.Console.WriteLine(String)"
IL_0061: ret
IL_0062: ldstr "Greater than 10"
IL_0067: call "Sub System.Console.WriteLine(String)"
IL_006c: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_SwitchTable_Signed()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 To 11
Console.WriteLine(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(count As Integer)
Dim i8 As SByte = count
Dim i16 As Int16 = count
Dim i64 As Int64 = count
Select Case i8
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case i16
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case i64
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:
Equal to 0
Equal to 0
Equal to 0
1:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
2:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
3:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
4:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
5:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
6:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
7:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
8:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
9:
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
10:
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
11:
Greater than 10
Greater than 10
Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 451 (0x1c3)
.maxstack 3
.locals init (SByte V_0, //i8
Short V_1, //i16
Long V_2) //i64
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: conv.ovf.i2
IL_0005: stloc.1
IL_0006: ldarg.0
IL_0007: conv.i8
IL_0008: stloc.2
IL_0009: ldloc.0
IL_000a: switch (
IL_0053,
IL_0076,
IL_0076,
IL_0076,
IL_0076,
IL_0076,
IL_0062,
IL_0062,
IL_0062,
IL_003d,
IL_003d)
IL_003b: br.s IL_008b
IL_003d: ldarg.0
IL_003e: ldc.i4.s 9
IL_0040: blt.s IL_009a
IL_0042: ldarg.0
IL_0043: ldc.i4.s 10
IL_0045: bgt.s IL_009a
IL_0047: ldstr "Equal to 9 or 10"
IL_004c: call "Sub System.Console.WriteLine(String)"
IL_0051: br.s IL_009a
IL_0053: ldarg.0
IL_0054: brtrue.s IL_009a
IL_0056: ldstr "Equal to 0"
IL_005b: call "Sub System.Console.WriteLine(String)"
IL_0060: br.s IL_009a
IL_0062: ldarg.0
IL_0063: ldc.i4.6
IL_0064: blt.s IL_009a
IL_0066: ldarg.0
IL_0067: ldc.i4.8
IL_0068: bgt.s IL_009a
IL_006a: ldstr "Between 6 and 8, inclusive"
IL_006f: call "Sub System.Console.WriteLine(String)"
IL_0074: br.s IL_009a
IL_0076: ldarg.0
IL_0077: ldc.i4.1
IL_0078: blt.s IL_009a
IL_007a: ldarg.0
IL_007b: ldc.i4.s 10
IL_007d: bgt.s IL_009a
IL_007f: ldstr "Between 1 and 5, inclusive"
IL_0084: call "Sub System.Console.WriteLine(String)"
IL_0089: br.s IL_009a
IL_008b: ldarg.0
IL_008c: ldc.i4.s 10
IL_008e: ble.s IL_009a
IL_0090: ldstr "Greater than 10"
IL_0095: call "Sub System.Console.WriteLine(String)"
IL_009a: ldloc.1
IL_009b: switch (
IL_00e4,
IL_0107,
IL_0107,
IL_0107,
IL_0107,
IL_0107,
IL_00f3,
IL_00f3,
IL_00f3,
IL_00ce,
IL_00ce)
IL_00cc: br.s IL_011c
IL_00ce: ldarg.0
IL_00cf: ldc.i4.s 9
IL_00d1: blt.s IL_012b
IL_00d3: ldarg.0
IL_00d4: ldc.i4.s 10
IL_00d6: bgt.s IL_012b
IL_00d8: ldstr "Equal to 9 or 10"
IL_00dd: call "Sub System.Console.WriteLine(String)"
IL_00e2: br.s IL_012b
IL_00e4: ldarg.0
IL_00e5: brtrue.s IL_012b
IL_00e7: ldstr "Equal to 0"
IL_00ec: call "Sub System.Console.WriteLine(String)"
IL_00f1: br.s IL_012b
IL_00f3: ldarg.0
IL_00f4: ldc.i4.6
IL_00f5: blt.s IL_012b
IL_00f7: ldarg.0
IL_00f8: ldc.i4.8
IL_00f9: bgt.s IL_012b
IL_00fb: ldstr "Between 6 and 8, inclusive"
IL_0100: call "Sub System.Console.WriteLine(String)"
IL_0105: br.s IL_012b
IL_0107: ldarg.0
IL_0108: ldc.i4.1
IL_0109: blt.s IL_012b
IL_010b: ldarg.0
IL_010c: ldc.i4.s 10
IL_010e: bgt.s IL_012b
IL_0110: ldstr "Between 1 and 5, inclusive"
IL_0115: call "Sub System.Console.WriteLine(String)"
IL_011a: br.s IL_012b
IL_011c: ldarg.0
IL_011d: ldc.i4.s 10
IL_011f: ble.s IL_012b
IL_0121: ldstr "Greater than 10"
IL_0126: call "Sub System.Console.WriteLine(String)"
IL_012b: ldloc.2
IL_012c: dup
IL_012d: ldc.i4.s 10
IL_012f: conv.i8
IL_0130: ble.un.s IL_0135
IL_0132: pop
IL_0133: br.s IL_01b3
IL_0135: conv.u4
IL_0136: switch (
IL_017e,
IL_019f,
IL_019f,
IL_019f,
IL_019f,
IL_019f,
IL_018c,
IL_018c,
IL_018c,
IL_0169,
IL_0169)
IL_0167: br.s IL_01b3
IL_0169: ldarg.0
IL_016a: ldc.i4.s 9
IL_016c: blt.s IL_01c2
IL_016e: ldarg.0
IL_016f: ldc.i4.s 10
IL_0171: bgt.s IL_01c2
IL_0173: ldstr "Equal to 9 or 10"
IL_0178: call "Sub System.Console.WriteLine(String)"
IL_017d: ret
IL_017e: ldarg.0
IL_017f: brtrue.s IL_01c2
IL_0181: ldstr "Equal to 0"
IL_0186: call "Sub System.Console.WriteLine(String)"
IL_018b: ret
IL_018c: ldarg.0
IL_018d: ldc.i4.6
IL_018e: blt.s IL_01c2
IL_0190: ldarg.0
IL_0191: ldc.i4.8
IL_0192: bgt.s IL_01c2
IL_0194: ldstr "Between 6 and 8, inclusive"
IL_0199: call "Sub System.Console.WriteLine(String)"
IL_019e: ret
IL_019f: ldarg.0
IL_01a0: ldc.i4.1
IL_01a1: blt.s IL_01c2
IL_01a3: ldarg.0
IL_01a4: ldc.i4.s 10
IL_01a6: bgt.s IL_01c2
IL_01a8: ldstr "Between 1 and 5, inclusive"
IL_01ad: call "Sub System.Console.WriteLine(String)"
IL_01b2: ret
IL_01b3: ldarg.0
IL_01b4: ldc.i4.s 10
IL_01b6: ble.s IL_01c2
IL_01b8: ldstr "Greater than 10"
IL_01bd: call "Sub System.Console.WriteLine(String)"
IL_01c2: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_SwitchTable_Unsigned()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 To 11
Console.WriteLine(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(count As Integer)
Dim b As Byte = count
Dim ui16 As UInt16 = count
Dim ui32 As UInt32 = count
Dim ui64 As UInt64 = count
Select Case b
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case ui16
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case ui32
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case ui64
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:
Equal to 0
Equal to 0
Equal to 0
Equal to 0
1:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
2:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
3:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
4:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
5:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
6:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
7:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
8:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
9:
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
10:
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
11:
Greater than 10
Greater than 10
Greater than 10
Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 599 (0x257)
.maxstack 3
.locals init (Byte V_0, //b
UShort V_1, //ui16
UInteger V_2, //ui32
ULong V_3) //ui64
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: conv.ovf.u2
IL_0005: stloc.1
IL_0006: ldarg.0
IL_0007: conv.ovf.u4
IL_0008: stloc.2
IL_0009: ldarg.0
IL_000a: conv.ovf.u8
IL_000b: stloc.3
IL_000c: ldloc.0
IL_000d: switch (
IL_0056,
IL_0079,
IL_0079,
IL_0079,
IL_0079,
IL_0079,
IL_0065,
IL_0065,
IL_0065,
IL_0040,
IL_0040)
IL_003e: br.s IL_008e
IL_0040: ldarg.0
IL_0041: ldc.i4.s 9
IL_0043: blt.s IL_009d
IL_0045: ldarg.0
IL_0046: ldc.i4.s 10
IL_0048: bgt.s IL_009d
IL_004a: ldstr "Equal to 9 or 10"
IL_004f: call "Sub System.Console.WriteLine(String)"
IL_0054: br.s IL_009d
IL_0056: ldarg.0
IL_0057: brtrue.s IL_009d
IL_0059: ldstr "Equal to 0"
IL_005e: call "Sub System.Console.WriteLine(String)"
IL_0063: br.s IL_009d
IL_0065: ldarg.0
IL_0066: ldc.i4.6
IL_0067: blt.s IL_009d
IL_0069: ldarg.0
IL_006a: ldc.i4.8
IL_006b: bgt.s IL_009d
IL_006d: ldstr "Between 6 and 8, inclusive"
IL_0072: call "Sub System.Console.WriteLine(String)"
IL_0077: br.s IL_009d
IL_0079: ldarg.0
IL_007a: ldc.i4.1
IL_007b: blt.s IL_009d
IL_007d: ldarg.0
IL_007e: ldc.i4.s 10
IL_0080: bgt.s IL_009d
IL_0082: ldstr "Between 1 and 5, inclusive"
IL_0087: call "Sub System.Console.WriteLine(String)"
IL_008c: br.s IL_009d
IL_008e: ldarg.0
IL_008f: ldc.i4.s 10
IL_0091: ble.s IL_009d
IL_0093: ldstr "Greater than 10"
IL_0098: call "Sub System.Console.WriteLine(String)"
IL_009d: ldloc.1
IL_009e: switch (
IL_00e7,
IL_010a,
IL_010a,
IL_010a,
IL_010a,
IL_010a,
IL_00f6,
IL_00f6,
IL_00f6,
IL_00d1,
IL_00d1)
IL_00cf: br.s IL_011f
IL_00d1: ldarg.0
IL_00d2: ldc.i4.s 9
IL_00d4: blt.s IL_012e
IL_00d6: ldarg.0
IL_00d7: ldc.i4.s 10
IL_00d9: bgt.s IL_012e
IL_00db: ldstr "Equal to 9 or 10"
IL_00e0: call "Sub System.Console.WriteLine(String)"
IL_00e5: br.s IL_012e
IL_00e7: ldarg.0
IL_00e8: brtrue.s IL_012e
IL_00ea: ldstr "Equal to 0"
IL_00ef: call "Sub System.Console.WriteLine(String)"
IL_00f4: br.s IL_012e
IL_00f6: ldarg.0
IL_00f7: ldc.i4.6
IL_00f8: blt.s IL_012e
IL_00fa: ldarg.0
IL_00fb: ldc.i4.8
IL_00fc: bgt.s IL_012e
IL_00fe: ldstr "Between 6 and 8, inclusive"
IL_0103: call "Sub System.Console.WriteLine(String)"
IL_0108: br.s IL_012e
IL_010a: ldarg.0
IL_010b: ldc.i4.1
IL_010c: blt.s IL_012e
IL_010e: ldarg.0
IL_010f: ldc.i4.s 10
IL_0111: bgt.s IL_012e
IL_0113: ldstr "Between 1 and 5, inclusive"
IL_0118: call "Sub System.Console.WriteLine(String)"
IL_011d: br.s IL_012e
IL_011f: ldarg.0
IL_0120: ldc.i4.s 10
IL_0122: ble.s IL_012e
IL_0124: ldstr "Greater than 10"
IL_0129: call "Sub System.Console.WriteLine(String)"
IL_012e: ldloc.2
IL_012f: switch (
IL_0178,
IL_019b,
IL_019b,
IL_019b,
IL_019b,
IL_019b,
IL_0187,
IL_0187,
IL_0187,
IL_0162,
IL_0162)
IL_0160: br.s IL_01b0
IL_0162: ldarg.0
IL_0163: ldc.i4.s 9
IL_0165: blt.s IL_01bf
IL_0167: ldarg.0
IL_0168: ldc.i4.s 10
IL_016a: bgt.s IL_01bf
IL_016c: ldstr "Equal to 9 or 10"
IL_0171: call "Sub System.Console.WriteLine(String)"
IL_0176: br.s IL_01bf
IL_0178: ldarg.0
IL_0179: brtrue.s IL_01bf
IL_017b: ldstr "Equal to 0"
IL_0180: call "Sub System.Console.WriteLine(String)"
IL_0185: br.s IL_01bf
IL_0187: ldarg.0
IL_0188: ldc.i4.6
IL_0189: blt.s IL_01bf
IL_018b: ldarg.0
IL_018c: ldc.i4.8
IL_018d: bgt.s IL_01bf
IL_018f: ldstr "Between 6 and 8, inclusive"
IL_0194: call "Sub System.Console.WriteLine(String)"
IL_0199: br.s IL_01bf
IL_019b: ldarg.0
IL_019c: ldc.i4.1
IL_019d: blt.s IL_01bf
IL_019f: ldarg.0
IL_01a0: ldc.i4.s 10
IL_01a2: bgt.s IL_01bf
IL_01a4: ldstr "Between 1 and 5, inclusive"
IL_01a9: call "Sub System.Console.WriteLine(String)"
IL_01ae: br.s IL_01bf
IL_01b0: ldarg.0
IL_01b1: ldc.i4.s 10
IL_01b3: ble.s IL_01bf
IL_01b5: ldstr "Greater than 10"
IL_01ba: call "Sub System.Console.WriteLine(String)"
IL_01bf: ldloc.3
IL_01c0: dup
IL_01c1: ldc.i4.s 10
IL_01c3: conv.i8
IL_01c4: ble.un.s IL_01c9
IL_01c6: pop
IL_01c7: br.s IL_0247
IL_01c9: conv.u4
IL_01ca: switch (
IL_0212,
IL_0233,
IL_0233,
IL_0233,
IL_0233,
IL_0233,
IL_0220,
IL_0220,
IL_0220,
IL_01fd,
IL_01fd)
IL_01fb: br.s IL_0247
IL_01fd: ldarg.0
IL_01fe: ldc.i4.s 9
IL_0200: blt.s IL_0256
IL_0202: ldarg.0
IL_0203: ldc.i4.s 10
IL_0205: bgt.s IL_0256
IL_0207: ldstr "Equal to 9 or 10"
IL_020c: call "Sub System.Console.WriteLine(String)"
IL_0211: ret
IL_0212: ldarg.0
IL_0213: brtrue.s IL_0256
IL_0215: ldstr "Equal to 0"
IL_021a: call "Sub System.Console.WriteLine(String)"
IL_021f: ret
IL_0220: ldarg.0
IL_0221: ldc.i4.6
IL_0222: blt.s IL_0256
IL_0224: ldarg.0
IL_0225: ldc.i4.8
IL_0226: bgt.s IL_0256
IL_0228: ldstr "Between 6 and 8, inclusive"
IL_022d: call "Sub System.Console.WriteLine(String)"
IL_0232: ret
IL_0233: ldarg.0
IL_0234: ldc.i4.1
IL_0235: blt.s IL_0256
IL_0237: ldarg.0
IL_0238: ldc.i4.s 10
IL_023a: bgt.s IL_0256
IL_023c: ldstr "Between 1 and 5, inclusive"
IL_0241: call "Sub System.Console.WriteLine(String)"
IL_0246: ret
IL_0247: ldarg.0
IL_0248: ldc.i4.s 10
IL_024a: ble.s IL_0256
IL_024c: ldstr "Greater than 10"
IL_0251: call "Sub System.Console.WriteLine(String)"
IL_0256: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub CaseElseOnlySelectCase()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Dim number As Integer = 0
Select Case number
Case Else
Console.WriteLine("CaseElse")
End Select
Select Case 0
Case Else
Console.WriteLine("CaseElse")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[CaseElse
CaseElse]]>).VerifyIL("M1.Main", <![CDATA[
{
// Code size 25 (0x19)
.maxstack 1
.locals init (Integer V_0, //number
Integer V_1)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldstr "CaseElse"
IL_0007: call "Sub System.Console.WriteLine(String)"
IL_000c: ldc.i4.0
IL_000d: stloc.1
IL_000e: ldstr "CaseElse"
IL_0013: call "Sub System.Console.WriteLine(String)"
IL_0018: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_NonNullableExpr_NothingCaseClause()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Dim x As Integer
Select Case x
Case Nothing, 1, 2, 3, 4
Console.Write("Success")
Case 0
Console.Write("Fail")
Case Else
Console.Write("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 57 (0x39)
.maxstack 2
.locals init (Integer V_0, //x
Integer V_1)
IL_0000: ldloc.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: brfalse.s IL_0015
IL_0005: ldloc.1
IL_0006: ldc.i4.1
IL_0007: beq.s IL_0015
IL_0009: ldloc.1
IL_000a: ldc.i4.2
IL_000b: beq.s IL_0015
IL_000d: ldloc.1
IL_000e: ldc.i4.3
IL_000f: beq.s IL_0015
IL_0011: ldloc.1
IL_0012: ldc.i4.4
IL_0013: bne.un.s IL_0020
IL_0015: ldstr "Success"
IL_001a: call "Sub System.Console.Write(String)"
IL_001f: ret
IL_0020: ldloc.1
IL_0021: brtrue.s IL_002e
IL_0023: ldstr "Fail"
IL_0028: call "Sub System.Console.Write(String)"
IL_002d: ret
IL_002e: ldstr "Fail"
IL_0033: call "Sub System.Console.Write(String)"
IL_0038: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_NothingSelectExpr()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case Nothing
Case 1, 2, 3, 4
Console.Write("Fail")
Case 0
Console.Write("Success")
Case Else
Console.Write("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 143 (0x8f)
.maxstack 3
.locals init (Object V_0)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: box "Integer"
IL_0009: ldc.i4.0
IL_000a: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object, Object, Boolean) As Object"
IL_000f: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0014: brtrue.s IL_0052
IL_0016: ldloc.0
IL_0017: ldc.i4.2
IL_0018: box "Integer"
IL_001d: ldc.i4.0
IL_001e: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object, Object, Boolean) As Object"
IL_0023: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0028: brtrue.s IL_0052
IL_002a: ldloc.0
IL_002b: ldc.i4.3
IL_002c: box "Integer"
IL_0031: ldc.i4.0
IL_0032: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object, Object, Boolean) As Object"
IL_0037: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_003c: brtrue.s IL_0052
IL_003e: ldloc.0
IL_003f: ldc.i4.4
IL_0040: box "Integer"
IL_0045: ldc.i4.0
IL_0046: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object, Object, Boolean) As Object"
IL_004b: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0050: br.s IL_0053
IL_0052: ldc.i4.1
IL_0053: box "Boolean"
IL_0058: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_005d: brfalse.s IL_006a
IL_005f: ldstr "Fail"
IL_0064: call "Sub System.Console.Write(String)"
IL_0069: ret
IL_006a: ldloc.0
IL_006b: ldc.i4.0
IL_006c: box "Integer"
IL_0071: ldc.i4.0
IL_0072: call "Function Microsoft.VisualBasic.CompilerServices.Operators.ConditionalCompareObjectEqual(Object, Object, Boolean) As Boolean"
IL_0077: brfalse.s IL_0084
IL_0079: ldstr "Success"
IL_007e: call "Sub System.Console.Write(String)"
IL_0083: ret
IL_0084: ldstr "Fail"
IL_0089: call "Sub System.Console.Write(String)"
IL_008e: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ValueClause_01()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case 0, 1
Console.WriteLine("Success")
Case 1 - 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: bgt.un.s IL_0011
IL_0006: ldstr "Success"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldstr "Fail"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ValueClause_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case 1, 2
Console.WriteLine("Fail")
Case 1 - 1
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brfalse.s IL_0016
IL_0005: ldloc.0
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ldc.i4.1
IL_0009: bgt.un.s IL_0021
IL_000b: ldstr "Fail"
IL_0010: call "Sub System.Console.WriteLine(String)"
IL_0015: ret
IL_0016: ldstr "Success"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
IL_0021: ldstr "Fail"
IL_0026: call "Sub System.Console.WriteLine(String)"
IL_002b: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ValueClause_03()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case 1, 2
Console.WriteLine("Fail")
Case 3, 4
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Success")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: ldc.i4.1
IL_0006: ble.un.s IL_0010
IL_0008: ldloc.0
IL_0009: ldc.i4.3
IL_000a: sub
IL_000b: ldc.i4.1
IL_000c: ble.un.s IL_001b
IL_000e: br.s IL_0026
IL_0010: ldstr "Fail"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldstr "Fail"
IL_0020: call "Sub System.Console.WriteLine(String)"
IL_0025: ret
IL_0026: ldstr "Success"
IL_002b: call "Sub System.Console.WriteLine(String)"
IL_0030: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_RelationalClause()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case Is < 1
Console.WriteLine("Success")
Case 0
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 42 (0x2a)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: bge.s IL_0011
IL_0006: ldstr "Success"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: brtrue.s IL_001f
IL_0014: ldstr "Fail"
IL_0019: call "Sub System.Console.WriteLine(String)"
IL_001e: ret
IL_001f: ldstr "Fail"
IL_0024: call "Sub System.Console.WriteLine(String)"
IL_0029: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_RelationalAndRangeClause_01()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case Is < 0
Console.WriteLine("Fail")
Case -1 To 1
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: bge.s IL_0011
IL_0006: ldstr "Fail"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: ldc.i4.m1
IL_0013: blt.s IL_0024
IL_0015: ldloc.0
IL_0016: ldc.i4.1
IL_0017: bgt.s IL_0024
IL_0019: ldstr "Success"
IL_001e: call "Sub System.Console.WriteLine(String)"
IL_0023: ret
IL_0024: ldstr "Fail"
IL_0029: call "Sub System.Console.WriteLine(String)"
IL_002e: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_RelationalAndRangeClause_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case Is < 0
Console.WriteLine("Fail")
Case -2 To -1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Success")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: bge.s IL_0011
IL_0006: ldstr "Fail"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: ldc.i4.s -2
IL_0014: blt.s IL_0025
IL_0016: ldloc.0
IL_0017: ldc.i4.m1
IL_0018: bgt.s IL_0025
IL_001a: ldstr "Fail"
IL_001f: call "Sub System.Console.WriteLine(String)"
IL_0024: ret
IL_0025: ldstr "Success"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_NoTrueClause()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case Is < 0
Console.WriteLine("Fail")
Return
Case -2 To -1
Console.WriteLine("Fail")
Return
End Select
Console.WriteLine("Success")
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: bge.s IL_0011
IL_0006: ldstr "Fail"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: ldc.i4.s -2
IL_0014: blt.s IL_0025
IL_0016: ldloc.0
IL_0017: ldc.i4.m1
IL_0018: bgt.s IL_0025
IL_001a: ldstr "Fail"
IL_001f: call "Sub System.Console.WriteLine(String)"
IL_0024: ret
IL_0025: ldstr "Success"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_01()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case Foo()
Console.WriteLine("Success")
Case 0
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: bne.un.s IL_0015
IL_000a: ldstr "Success"
IL_000f: call "Sub System.Console.WriteLine(String)"
IL_0014: ret
IL_0015: ldloc.0
IL_0016: brtrue.s IL_0023
IL_0018: ldstr "Fail"
IL_001d: call "Sub System.Console.WriteLine(String)"
IL_0022: ret
IL_0023: ldstr "Fail"
IL_0028: call "Sub System.Console.WriteLine(String)"
IL_002d: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation__02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case Foo(), 0
Console.WriteLine("Success")
Case 1 - 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: beq.s IL_000d
IL_000a: ldloc.0
IL_000b: brtrue.s IL_0018
IL_000d: ldstr "Success"
IL_0012: call "Sub System.Console.WriteLine(String)"
IL_0017: ret
IL_0018: ldloc.0
IL_0019: brtrue.s IL_0026
IL_001b: ldstr "Fail"
IL_0020: call "Sub System.Console.WriteLine(String)"
IL_0025: ret
IL_0026: ldstr "Fail"
IL_002b: call "Sub System.Console.WriteLine(String)"
IL_0030: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation__03()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case Foo() + 1, 2
Console.WriteLine("Fail")
Case 3, 4
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Success")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 57 (0x39)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: add.ovf
IL_000a: beq.s IL_0010
IL_000c: ldloc.0
IL_000d: ldc.i4.2
IL_000e: bne.un.s IL_001b
IL_0010: ldstr "Fail"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: ldc.i4.3
IL_001d: beq.s IL_0023
IL_001f: ldloc.0
IL_0020: ldc.i4.4
IL_0021: bne.un.s IL_002e
IL_0023: ldstr "Fail"
IL_0028: call "Sub System.Console.WriteLine(String)"
IL_002d: ret
IL_002e: ldstr "Success"
IL_0033: call "Sub System.Console.WriteLine(String)"
IL_0038: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_04()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case Is < Foo() + 1
Console.WriteLine("Success")
Case 0
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: add.ovf
IL_000a: bge.s IL_0017
IL_000c: ldstr "Success"
IL_0011: call "Sub System.Console.WriteLine(String)"
IL_0016: ret
IL_0017: ldloc.0
IL_0018: brtrue.s IL_0025
IL_001a: ldstr "Fail"
IL_001f: call "Sub System.Console.WriteLine(String)"
IL_0024: ret
IL_0025: ldstr "Fail"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_05()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case 0
Case Foo() - 1 To Foo() + 1
Console.WriteLine("Success")
Case 0
Console.Write("Fail")
Case Else
Console.Write("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: sub.ovf
IL_000a: blt.s IL_0021
IL_000c: ldloc.0
IL_000d: call "Function M1.Foo() As Integer"
IL_0012: ldc.i4.1
IL_0013: add.ovf
IL_0014: bgt.s IL_0021
IL_0016: ldstr "Success"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
IL_0021: ldloc.0
IL_0022: brtrue.s IL_002f
IL_0024: ldstr "Fail"
IL_0029: call "Sub System.Console.Write(String)"
IL_002e: ret
IL_002f: ldstr "Fail"
IL_0034: call "Sub System.Console.Write(String)"
IL_0039: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_06_ShortCircuit()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case 0
Case Foo() + 1 To Foo() + 2
Console.WriteLine("Fail")
Case 0
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: add.ovf
IL_000a: blt.s IL_0021
IL_000c: ldloc.0
IL_000d: call "Function M1.Foo() As Integer"
IL_0012: ldc.i4.2
IL_0013: add.ovf
IL_0014: bgt.s IL_0021
IL_0016: ldstr "Fail"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
IL_0021: ldloc.0
IL_0022: brtrue.s IL_002f
IL_0024: ldstr "Success"
IL_0029: call "Sub System.Console.WriteLine(String)"
IL_002e: ret
IL_002f: ldstr "Fail"
IL_0034: call "Sub System.Console.WriteLine(String)"
IL_0039: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_07_ShortCircuit()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case 0
Case Foo() - 1 To 1
Console.Write("Success,")
Case 0
Console.Write("Fail,")
Case Else
Console.Write("Fail")
End Select
Select Case 0
Case 1 To Foo()
Console.Write("Fail,")
Case Else
Console.Write("Success,")
End Select
Select Case 0
Case Foo() - 1 To -2
Console.WriteLine("Fail")
Case 0
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success,Success,Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 142 (0x8e)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
Integer V_2)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: sub.ovf
IL_000a: blt.s IL_001c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: bgt.s IL_001c
IL_0010: ldstr "Success,"
IL_0015: call "Sub System.Console.Write(String)"
IL_001a: br.s IL_0035
IL_001c: ldloc.0
IL_001d: brtrue.s IL_002b
IL_001f: ldstr "Fail,"
IL_0024: call "Sub System.Console.Write(String)"
IL_0029: br.s IL_0035
IL_002b: ldstr "Fail"
IL_0030: call "Sub System.Console.Write(String)"
IL_0035: ldc.i4.0
IL_0036: stloc.1
IL_0037: ldloc.1
IL_0038: ldc.i4.1
IL_0039: blt.s IL_004f
IL_003b: ldloc.1
IL_003c: call "Function M1.Foo() As Integer"
IL_0041: bgt.s IL_004f
IL_0043: ldstr "Fail,"
IL_0048: call "Sub System.Console.Write(String)"
IL_004d: br.s IL_0059
IL_004f: ldstr "Success,"
IL_0054: call "Sub System.Console.Write(String)"
IL_0059: ldc.i4.0
IL_005a: stloc.2
IL_005b: ldloc.2
IL_005c: call "Function M1.Foo() As Integer"
IL_0061: ldc.i4.1
IL_0062: sub.ovf
IL_0063: blt.s IL_0075
IL_0065: ldloc.2
IL_0066: ldc.i4.s -2
IL_0068: bgt.s IL_0075
IL_006a: ldstr "Fail"
IL_006f: call "Sub System.Console.WriteLine(String)"
IL_0074: ret
IL_0075: ldloc.2
IL_0076: brtrue.s IL_0083
IL_0078: ldstr "Success"
IL_007d: call "Sub System.Console.WriteLine(String)"
IL_0082: ret
IL_0083: ldstr "Fail"
IL_0088: call "Sub System.Console.WriteLine(String)"
IL_008d: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_08()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case -1 To Foo() + 1
Console.WriteLine("Success")
Case 0
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.m1
IL_0004: blt.s IL_001b
IL_0006: ldloc.0
IL_0007: call "Function M1.Foo() As Integer"
IL_000c: ldc.i4.1
IL_000d: add.ovf
IL_000e: bgt.s IL_001b
IL_0010: ldstr "Success"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: brtrue.s IL_0029
IL_001e: ldstr "Fail"
IL_0023: call "Sub System.Console.WriteLine(String)"
IL_0028: ret
IL_0029: ldstr "Fail"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_09()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case 0
Case Is < 0
Console.WriteLine("Fail")
Case Foo() - 1 To Foo() + 1
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: bge.s IL_0011
IL_0006: ldstr "Fail"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: call "Function M1.Foo() As Integer"
IL_0017: ldc.i4.1
IL_0018: sub.ovf
IL_0019: blt.s IL_0030
IL_001b: ldloc.0
IL_001c: call "Function M1.Foo() As Integer"
IL_0021: ldc.i4.1
IL_0022: add.ovf
IL_0023: bgt.s IL_0030
IL_0025: ldstr "Success"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
IL_0030: ldstr "Fail"
IL_0035: call "Sub System.Console.WriteLine(String)"
IL_003a: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_SelectExprEvaluation_IfList()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case Foo()
Case -2 To -1
Console.WriteLine("Fail")
Case 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Success")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 2
.locals init (Integer V_0)
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.s -2
IL_0009: blt.s IL_001a
IL_000b: ldloc.0
IL_000c: ldc.i4.m1
IL_000d: bgt.s IL_001a
IL_000f: ldstr "Fail"
IL_0014: call "Sub System.Console.WriteLine(String)"
IL_0019: ret
IL_001a: ldloc.0
IL_001b: ldc.i4.1
IL_001c: bne.un.s IL_0029
IL_001e: ldstr "Fail"
IL_0023: call "Sub System.Console.WriteLine(String)"
IL_0028: ret
IL_0029: ldstr "Success"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_SelectExprEvaluation_SwitchTable()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case Foo()
Case -1, 1, 3
Console.WriteLine("Fail")
Case -2, 0, 2
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 74 (0x4a)
.maxstack 2
.locals init (Integer V_0)
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.s -2
IL_0009: sub
IL_000a: switch (
IL_0034,
IL_0029,
IL_0034,
IL_0029,
IL_0034,
IL_0029)
IL_0027: br.s IL_003f
IL_0029: ldstr "Fail"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
IL_0034: ldstr "Success"
IL_0039: call "Sub System.Console.WriteLine(String)"
IL_003e: ret
IL_003f: ldstr "Fail"
IL_0044: call "Sub System.Console.WriteLine(String)"
IL_0049: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_SwitchTable_DuplicateCase()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case Foo()
Case -1, 1, 3
Console.WriteLine("Fail")
Case 2.5 - 2.4
Console.WriteLine("Success")
Case -2, 0, 2
Console.WriteLine("Fail")
Case 0
Console.WriteLine("Fail")
Case 1 - 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 85 (0x55)
.maxstack 2
.locals init (Integer V_0)
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.s -2
IL_0009: sub
IL_000a: switch (
IL_003f,
IL_0029,
IL_0034,
IL_0029,
IL_003f,
IL_0029)
IL_0027: br.s IL_004a
IL_0029: ldstr "Fail"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
IL_0034: ldstr "Success"
IL_0039: call "Sub System.Console.WriteLine(String)"
IL_003e: ret
IL_003f: ldstr "Fail"
IL_0044: call "Sub System.Console.WriteLine(String)"
IL_0049: ret
IL_004a: ldstr "Fail"
IL_004f: call "Sub System.Console.WriteLine(String)"
IL_0054: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_IfList_Conversions()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Dim success As Boolean = True
For count = 0 To 13
Test(count, success)
Next
If success Then
Console.Write("Success")
Else
Console.Write("Fail")
End If
End Sub
Sub Test(count As Integer, ByRef success As Boolean)
Dim Bo As Boolean
Dim Ob As Object
Dim SB As SByte
Dim By As Byte
Dim Sh As Short
Dim US As UShort
Dim [In] As Integer
Dim UI As UInteger
Dim Lo As Long
Dim UL As ULong
Dim De As Decimal
Dim Si As Single
Dim [Do] As Double
Dim St As String
Bo = False
Ob = 1
SB = 2
By = 3
Sh = 4
US = 5
[In] = 6
UI = 7
Lo = 8
UL = 9
Si = 10
[Do] = 11
De = 12D
St = "13"
Select Case count
Case Bo
success = success AndAlso If(count = 0, True, False)
Case Ob
success = success AndAlso If(count = 1, True, False)
Case SB
success = success AndAlso If(count = 2, True, False)
Case By
success = success AndAlso If(count = 3, True, False)
Case Sh
success = success AndAlso If(count = 4, True, False)
Case US
success = success AndAlso If(count = 5, True, False)
Case [In]
success = success AndAlso If(count = 6, True, False)
Case UI
success = success AndAlso If(count = 7, True, False)
Case Lo
success = success AndAlso If(count = 8, True, False)
Case UL
success = success AndAlso If(count = 9, True, False)
Case Si
success = success AndAlso If(count = 10, True, False)
Case [Do]
success = success AndAlso If(count = 11, True, False)
Case De
success = success AndAlso If(count = 12, True, False)
Case St
success = success AndAlso If(count = 13, True, False)
Case Else
success = False
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Test", <![CDATA[
{
// Code size 453 (0x1c5)
.maxstack 3
.locals init (Boolean V_0, //Bo
Object V_1, //Ob
SByte V_2, //SB
Byte V_3, //By
Short V_4, //Sh
UShort V_5, //US
Integer V_6, //In
UInteger V_7, //UI
Long V_8, //Lo
ULong V_9, //UL
Decimal V_10, //De
Single V_11, //Si
Double V_12, //Do
String V_13, //St
Integer V_14)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: box "Integer"
IL_0008: stloc.1
IL_0009: ldc.i4.2
IL_000a: stloc.2
IL_000b: ldc.i4.3
IL_000c: stloc.3
IL_000d: ldc.i4.4
IL_000e: stloc.s V_4
IL_0010: ldc.i4.5
IL_0011: stloc.s V_5
IL_0013: ldc.i4.6
IL_0014: stloc.s V_6
IL_0016: ldc.i4.7
IL_0017: stloc.s V_7
IL_0019: ldc.i4.8
IL_001a: conv.i8
IL_001b: stloc.s V_8
IL_001d: ldc.i4.s 9
IL_001f: conv.i8
IL_0020: stloc.s V_9
IL_0022: ldc.r4 10
IL_0027: stloc.s V_11
IL_0029: ldc.r8 11
IL_0032: stloc.s V_12
IL_0034: ldloca.s V_10
IL_0036: ldc.i4.s 12
IL_0038: conv.i8
IL_0039: call "Sub Decimal..ctor(Long)"
IL_003e: ldstr "13"
IL_0043: stloc.s V_13
IL_0045: ldarg.0
IL_0046: stloc.s V_14
IL_0048: ldloc.s V_14
IL_004a: ldloc.0
IL_004b: ldc.i4.0
IL_004c: cgt.un
IL_004e: neg
IL_004f: bne.un.s IL_0062
IL_0051: ldarg.1
IL_0052: ldarg.1
IL_0053: ldind.u1
IL_0054: brfalse.s IL_005f
IL_0056: ldarg.0
IL_0057: brfalse.s IL_005c
IL_0059: ldc.i4.0
IL_005a: br.s IL_0060
IL_005c: ldc.i4.1
IL_005d: br.s IL_0060
IL_005f: ldc.i4.0
IL_0060: stind.i1
IL_0061: ret
IL_0062: ldloc.s V_14
IL_0064: box "Integer"
IL_0069: ldloc.1
IL_006a: ldc.i4.0
IL_006b: call "Function Microsoft.VisualBasic.CompilerServices.Operators.ConditionalCompareObjectEqual(Object, Object, Boolean) As Boolean"
IL_0070: brfalse.s IL_0084
IL_0072: ldarg.1
IL_0073: ldarg.1
IL_0074: ldind.u1
IL_0075: brfalse.s IL_0081
IL_0077: ldarg.0
IL_0078: ldc.i4.1
IL_0079: beq.s IL_007e
IL_007b: ldc.i4.0
IL_007c: br.s IL_0082
IL_007e: ldc.i4.1
IL_007f: br.s IL_0082
IL_0081: ldc.i4.0
IL_0082: stind.i1
IL_0083: ret
IL_0084: ldloc.s V_14
IL_0086: ldloc.2
IL_0087: bne.un.s IL_009b
IL_0089: ldarg.1
IL_008a: ldarg.1
IL_008b: ldind.u1
IL_008c: brfalse.s IL_0098
IL_008e: ldarg.0
IL_008f: ldc.i4.2
IL_0090: beq.s IL_0095
IL_0092: ldc.i4.0
IL_0093: br.s IL_0099
IL_0095: ldc.i4.1
IL_0096: br.s IL_0099
IL_0098: ldc.i4.0
IL_0099: stind.i1
IL_009a: ret
IL_009b: ldloc.s V_14
IL_009d: ldloc.3
IL_009e: bne.un.s IL_00b2
IL_00a0: ldarg.1
IL_00a1: ldarg.1
IL_00a2: ldind.u1
IL_00a3: brfalse.s IL_00af
IL_00a5: ldarg.0
IL_00a6: ldc.i4.3
IL_00a7: beq.s IL_00ac
IL_00a9: ldc.i4.0
IL_00aa: br.s IL_00b0
IL_00ac: ldc.i4.1
IL_00ad: br.s IL_00b0
IL_00af: ldc.i4.0
IL_00b0: stind.i1
IL_00b1: ret
IL_00b2: ldloc.s V_14
IL_00b4: ldloc.s V_4
IL_00b6: bne.un.s IL_00ca
IL_00b8: ldarg.1
IL_00b9: ldarg.1
IL_00ba: ldind.u1
IL_00bb: brfalse.s IL_00c7
IL_00bd: ldarg.0
IL_00be: ldc.i4.4
IL_00bf: beq.s IL_00c4
IL_00c1: ldc.i4.0
IL_00c2: br.s IL_00c8
IL_00c4: ldc.i4.1
IL_00c5: br.s IL_00c8
IL_00c7: ldc.i4.0
IL_00c8: stind.i1
IL_00c9: ret
IL_00ca: ldloc.s V_14
IL_00cc: ldloc.s V_5
IL_00ce: bne.un.s IL_00e2
IL_00d0: ldarg.1
IL_00d1: ldarg.1
IL_00d2: ldind.u1
IL_00d3: brfalse.s IL_00df
IL_00d5: ldarg.0
IL_00d6: ldc.i4.5
IL_00d7: beq.s IL_00dc
IL_00d9: ldc.i4.0
IL_00da: br.s IL_00e0
IL_00dc: ldc.i4.1
IL_00dd: br.s IL_00e0
IL_00df: ldc.i4.0
IL_00e0: stind.i1
IL_00e1: ret
IL_00e2: ldloc.s V_14
IL_00e4: ldloc.s V_6
IL_00e6: bne.un.s IL_00fa
IL_00e8: ldarg.1
IL_00e9: ldarg.1
IL_00ea: ldind.u1
IL_00eb: brfalse.s IL_00f7
IL_00ed: ldarg.0
IL_00ee: ldc.i4.6
IL_00ef: beq.s IL_00f4
IL_00f1: ldc.i4.0
IL_00f2: br.s IL_00f8
IL_00f4: ldc.i4.1
IL_00f5: br.s IL_00f8
IL_00f7: ldc.i4.0
IL_00f8: stind.i1
IL_00f9: ret
IL_00fa: ldloc.s V_14
IL_00fc: ldloc.s V_7
IL_00fe: conv.ovf.i4.un
IL_00ff: bne.un.s IL_0113
IL_0101: ldarg.1
IL_0102: ldarg.1
IL_0103: ldind.u1
IL_0104: brfalse.s IL_0110
IL_0106: ldarg.0
IL_0107: ldc.i4.7
IL_0108: beq.s IL_010d
IL_010a: ldc.i4.0
IL_010b: br.s IL_0111
IL_010d: ldc.i4.1
IL_010e: br.s IL_0111
IL_0110: ldc.i4.0
IL_0111: stind.i1
IL_0112: ret
IL_0113: ldloc.s V_14
IL_0115: ldloc.s V_8
IL_0117: conv.ovf.i4
IL_0118: bne.un.s IL_012c
IL_011a: ldarg.1
IL_011b: ldarg.1
IL_011c: ldind.u1
IL_011d: brfalse.s IL_0129
IL_011f: ldarg.0
IL_0120: ldc.i4.8
IL_0121: beq.s IL_0126
IL_0123: ldc.i4.0
IL_0124: br.s IL_012a
IL_0126: ldc.i4.1
IL_0127: br.s IL_012a
IL_0129: ldc.i4.0
IL_012a: stind.i1
IL_012b: ret
IL_012c: ldloc.s V_14
IL_012e: ldloc.s V_9
IL_0130: conv.ovf.i4.un
IL_0131: bne.un.s IL_0146
IL_0133: ldarg.1
IL_0134: ldarg.1
IL_0135: ldind.u1
IL_0136: brfalse.s IL_0143
IL_0138: ldarg.0
IL_0139: ldc.i4.s 9
IL_013b: beq.s IL_0140
IL_013d: ldc.i4.0
IL_013e: br.s IL_0144
IL_0140: ldc.i4.1
IL_0141: br.s IL_0144
IL_0143: ldc.i4.0
IL_0144: stind.i1
IL_0145: ret
IL_0146: ldloc.s V_14
IL_0148: ldloc.s V_11
IL_014a: conv.r8
IL_014b: call "Function System.Math.Round(Double) As Double"
IL_0150: conv.ovf.i4
IL_0151: bne.un.s IL_0166
IL_0153: ldarg.1
IL_0154: ldarg.1
IL_0155: ldind.u1
IL_0156: brfalse.s IL_0163
IL_0158: ldarg.0
IL_0159: ldc.i4.s 10
IL_015b: beq.s IL_0160
IL_015d: ldc.i4.0
IL_015e: br.s IL_0164
IL_0160: ldc.i4.1
IL_0161: br.s IL_0164
IL_0163: ldc.i4.0
IL_0164: stind.i1
IL_0165: ret
IL_0166: ldloc.s V_14
IL_0168: ldloc.s V_12
IL_016a: call "Function System.Math.Round(Double) As Double"
IL_016f: conv.ovf.i4
IL_0170: bne.un.s IL_0185
IL_0172: ldarg.1
IL_0173: ldarg.1
IL_0174: ldind.u1
IL_0175: brfalse.s IL_0182
IL_0177: ldarg.0
IL_0178: ldc.i4.s 11
IL_017a: beq.s IL_017f
IL_017c: ldc.i4.0
IL_017d: br.s IL_0183
IL_017f: ldc.i4.1
IL_0180: br.s IL_0183
IL_0182: ldc.i4.0
IL_0183: stind.i1
IL_0184: ret
IL_0185: ldloc.s V_14
IL_0187: ldloc.s V_10
IL_0189: call "Function System.Convert.ToInt32(Decimal) As Integer"
IL_018e: bne.un.s IL_01a3
IL_0190: ldarg.1
IL_0191: ldarg.1
IL_0192: ldind.u1
IL_0193: brfalse.s IL_01a0
IL_0195: ldarg.0
IL_0196: ldc.i4.s 12
IL_0198: beq.s IL_019d
IL_019a: ldc.i4.0
IL_019b: br.s IL_01a1
IL_019d: ldc.i4.1
IL_019e: br.s IL_01a1
IL_01a0: ldc.i4.0
IL_01a1: stind.i1
IL_01a2: ret
IL_01a3: ldloc.s V_14
IL_01a5: ldloc.s V_13
IL_01a7: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String) As Integer"
IL_01ac: bne.un.s IL_01c1
IL_01ae: ldarg.1
IL_01af: ldarg.1
IL_01b0: ldind.u1
IL_01b1: brfalse.s IL_01be
IL_01b3: ldarg.0
IL_01b4: ldc.i4.s 13
IL_01b6: beq.s IL_01bb
IL_01b8: ldc.i4.0
IL_01b9: br.s IL_01bf
IL_01bb: ldc.i4.1
IL_01bc: br.s IL_01bf
IL_01be: ldc.i4.0
IL_01bf: stind.i1
IL_01c0: ret
IL_01c1: ldarg.1
IL_01c2: ldc.i4.0
IL_01c3: stind.i1
IL_01c4: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
' TODO: Update test case once bug 10352 and bug 10354 are fixed.
' TODO: Verify switch table is used in codegen for select case statement.
<WorkItem(542910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542910")>
<WorkItem(10354, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/10354")>
<Fact()>
Public Sub SelectCase_SwitchTable_Conversions_01()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Dim success As Boolean = True
For count = 0 To 12
Test(count, success)
Next
If success Then
Console.Write("Success")
Else
Console.Write("Fail")
End If
End Sub
Sub Test(count As Integer, ByRef success As Boolean)
Const Bo As Boolean = False
'Const Ob As Object = 1
Const SB As SByte = 2
Const By As Byte = 3
Const Sh As Short = 4
Const US As UShort = 5
Const [In] As Integer = 6
Const UI As UInteger = 7
Const Lo As Long = 8
Const UL As ULong = 9
Const Si As Single = 10
Const [Do] As Double = 11
Const De As Decimal = 12D
Select Case count
Case Bo
success = success AndAlso If(count = 0, True, False)
' Case Ob
Case 1
success = success AndAlso If(count = 1, True, False)
Case SB
success = success AndAlso If(count = 2, True, False)
Case By
success = success AndAlso If(count = 3, True, False)
Case Sh
success = success AndAlso If(count = 4, True, False)
Case US
success = success AndAlso If(count = 5, True, False)
Case [In]
success = success AndAlso If(count = 6, True, False)
Case UI
success = success AndAlso If(count = 7, True, False)
Case Lo
success = success AndAlso If(count = 8, True, False)
Case UL
success = success AndAlso If(count = 9, True, False)
Case Si
success = success AndAlso If(count = 10, True, False)
Case [Do]
success = success AndAlso If(count = 11, True, False)
Case De
success = success AndAlso If(count = 12, True, False)
Case Else
success = False
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Test", <![CDATA[
{
// Code size 306 (0x132)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: switch (
IL_0041,
IL_0052,
IL_0064,
IL_0076,
IL_0088,
IL_009a,
IL_00ac,
IL_00be,
IL_00d0,
IL_00e2,
IL_00f5,
IL_0108,
IL_011b)
IL_003c: br IL_012e
IL_0041: ldarg.1
IL_0042: ldarg.1
IL_0043: ldind.u1
IL_0044: brfalse.s IL_004f
IL_0046: ldarg.0
IL_0047: brfalse.s IL_004c
IL_0049: ldc.i4.0
IL_004a: br.s IL_0050
IL_004c: ldc.i4.1
IL_004d: br.s IL_0050
IL_004f: ldc.i4.0
IL_0050: stind.i1
IL_0051: ret
IL_0052: ldarg.1
IL_0053: ldarg.1
IL_0054: ldind.u1
IL_0055: brfalse.s IL_0061
IL_0057: ldarg.0
IL_0058: ldc.i4.1
IL_0059: beq.s IL_005e
IL_005b: ldc.i4.0
IL_005c: br.s IL_0062
IL_005e: ldc.i4.1
IL_005f: br.s IL_0062
IL_0061: ldc.i4.0
IL_0062: stind.i1
IL_0063: ret
IL_0064: ldarg.1
IL_0065: ldarg.1
IL_0066: ldind.u1
IL_0067: brfalse.s IL_0073
IL_0069: ldarg.0
IL_006a: ldc.i4.2
IL_006b: beq.s IL_0070
IL_006d: ldc.i4.0
IL_006e: br.s IL_0074
IL_0070: ldc.i4.1
IL_0071: br.s IL_0074
IL_0073: ldc.i4.0
IL_0074: stind.i1
IL_0075: ret
IL_0076: ldarg.1
IL_0077: ldarg.1
IL_0078: ldind.u1
IL_0079: brfalse.s IL_0085
IL_007b: ldarg.0
IL_007c: ldc.i4.3
IL_007d: beq.s IL_0082
IL_007f: ldc.i4.0
IL_0080: br.s IL_0086
IL_0082: ldc.i4.1
IL_0083: br.s IL_0086
IL_0085: ldc.i4.0
IL_0086: stind.i1
IL_0087: ret
IL_0088: ldarg.1
IL_0089: ldarg.1
IL_008a: ldind.u1
IL_008b: brfalse.s IL_0097
IL_008d: ldarg.0
IL_008e: ldc.i4.4
IL_008f: beq.s IL_0094
IL_0091: ldc.i4.0
IL_0092: br.s IL_0098
IL_0094: ldc.i4.1
IL_0095: br.s IL_0098
IL_0097: ldc.i4.0
IL_0098: stind.i1
IL_0099: ret
IL_009a: ldarg.1
IL_009b: ldarg.1
IL_009c: ldind.u1
IL_009d: brfalse.s IL_00a9
IL_009f: ldarg.0
IL_00a0: ldc.i4.5
IL_00a1: beq.s IL_00a6
IL_00a3: ldc.i4.0
IL_00a4: br.s IL_00aa
IL_00a6: ldc.i4.1
IL_00a7: br.s IL_00aa
IL_00a9: ldc.i4.0
IL_00aa: stind.i1
IL_00ab: ret
IL_00ac: ldarg.1
IL_00ad: ldarg.1
IL_00ae: ldind.u1
IL_00af: brfalse.s IL_00bb
IL_00b1: ldarg.0
IL_00b2: ldc.i4.6
IL_00b3: beq.s IL_00b8
IL_00b5: ldc.i4.0
IL_00b6: br.s IL_00bc
IL_00b8: ldc.i4.1
IL_00b9: br.s IL_00bc
IL_00bb: ldc.i4.0
IL_00bc: stind.i1
IL_00bd: ret
IL_00be: ldarg.1
IL_00bf: ldarg.1
IL_00c0: ldind.u1
IL_00c1: brfalse.s IL_00cd
IL_00c3: ldarg.0
IL_00c4: ldc.i4.7
IL_00c5: beq.s IL_00ca
IL_00c7: ldc.i4.0
IL_00c8: br.s IL_00ce
IL_00ca: ldc.i4.1
IL_00cb: br.s IL_00ce
IL_00cd: ldc.i4.0
IL_00ce: stind.i1
IL_00cf: ret
IL_00d0: ldarg.1
IL_00d1: ldarg.1
IL_00d2: ldind.u1
IL_00d3: brfalse.s IL_00df
IL_00d5: ldarg.0
IL_00d6: ldc.i4.8
IL_00d7: beq.s IL_00dc
IL_00d9: ldc.i4.0
IL_00da: br.s IL_00e0
IL_00dc: ldc.i4.1
IL_00dd: br.s IL_00e0
IL_00df: ldc.i4.0
IL_00e0: stind.i1
IL_00e1: ret
IL_00e2: ldarg.1
IL_00e3: ldarg.1
IL_00e4: ldind.u1
IL_00e5: brfalse.s IL_00f2
IL_00e7: ldarg.0
IL_00e8: ldc.i4.s 9
IL_00ea: beq.s IL_00ef
IL_00ec: ldc.i4.0
IL_00ed: br.s IL_00f3
IL_00ef: ldc.i4.1
IL_00f0: br.s IL_00f3
IL_00f2: ldc.i4.0
IL_00f3: stind.i1
IL_00f4: ret
IL_00f5: ldarg.1
IL_00f6: ldarg.1
IL_00f7: ldind.u1
IL_00f8: brfalse.s IL_0105
IL_00fa: ldarg.0
IL_00fb: ldc.i4.s 10
IL_00fd: beq.s IL_0102
IL_00ff: ldc.i4.0
IL_0100: br.s IL_0106
IL_0102: ldc.i4.1
IL_0103: br.s IL_0106
IL_0105: ldc.i4.0
IL_0106: stind.i1
IL_0107: ret
IL_0108: ldarg.1
IL_0109: ldarg.1
IL_010a: ldind.u1
IL_010b: brfalse.s IL_0118
IL_010d: ldarg.0
IL_010e: ldc.i4.s 11
IL_0110: beq.s IL_0115
IL_0112: ldc.i4.0
IL_0113: br.s IL_0119
IL_0115: ldc.i4.1
IL_0116: br.s IL_0119
IL_0118: ldc.i4.0
IL_0119: stind.i1
IL_011a: ret
IL_011b: ldarg.1
IL_011c: ldarg.1
IL_011d: ldind.u1
IL_011e: brfalse.s IL_012b
IL_0120: ldarg.0
IL_0121: ldc.i4.s 12
IL_0123: beq.s IL_0128
IL_0125: ldc.i4.0
IL_0126: br.s IL_012c
IL_0128: ldc.i4.1
IL_0129: br.s IL_012c
IL_012b: ldc.i4.0
IL_012c: stind.i1
IL_012d: ret
IL_012e: ldarg.1
IL_012f: ldc.i4.0
IL_0130: stind.i1
IL_0131: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_SwitchTable_Conversions_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case Foo()
Case -1, 1, 3
Console.WriteLine("Fail")
Case 2.5 - 2.4
Console.WriteLine("Success")
Case -2, 0, 2
Console.WriteLine("Fail")
Case 0
Console.WriteLine("Fail")
Case 1 - 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 85 (0x55)
.maxstack 2
.locals init (Integer V_0)
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.s -2
IL_0009: sub
IL_000a: switch (
IL_003f,
IL_0029,
IL_0034,
IL_0029,
IL_003f,
IL_0029)
IL_0027: br.s IL_004a
IL_0029: ldstr "Fail"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
IL_0034: ldstr "Success"
IL_0039: call "Sub System.Console.WriteLine(String)"
IL_003e: ret
IL_003f: ldstr "Fail"
IL_0044: call "Sub System.Console.WriteLine(String)"
IL_0049: ret
IL_004a: ldstr "Fail"
IL_004f: call "Sub System.Console.WriteLine(String)"
IL_0054: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SwitchOnNullableInt64WithInt32Label()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module C
Function F(ByVal x As Long?) As Boolean
Select Case x
Case 1:
Return True
Case Else
Return False
End Select
End Function
Sub Main()
System.Console.WriteLine(F(1))
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="True").VerifyIL("C.F(Long?)", <![CDATA[
{
// Code size 56 (0x38)
.maxstack 2
.locals init (Boolean V_0, //F
Long? V_1,
Boolean? V_2)
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldloca.s V_1
IL_0004: call "Function Long?.get_HasValue() As Boolean"
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_2
IL_000d: initobj "Boolean?"
IL_0013: ldloc.2
IL_0014: br.s IL_0026
IL_0016: ldloca.s V_1
IL_0018: call "Function Long?.GetValueOrDefault() As Long"
IL_001d: ldc.i4.1
IL_001e: conv.i8
IL_001f: ceq
IL_0021: newobj "Sub Boolean?..ctor(Boolean)"
IL_0026: stloc.2
IL_0027: ldloca.s V_2
IL_0029: call "Function Boolean?.GetValueOrDefault() As Boolean"
IL_002e: brfalse.s IL_0034
IL_0030: ldc.i4.1
IL_0031: stloc.0
IL_0032: br.s IL_0036
IL_0034: ldc.i4.0
IL_0035: stloc.0
IL_0036: ldloc.0
IL_0037: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
#Region "Select case string tests"
<Fact, WorkItem(651996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651996")>
Public Sub SelectCase_Hash_SwitchTable_String_OptionCompareBinary()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 420 (0x1a4)
.maxstack 3
.locals init (String V_0,
UInteger V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function ComputeStringHash(String) As UInteger"
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldc.i4 0x330ca589
IL_000f: bgt.un.s IL_005a
IL_0011: ldloc.1
IL_0012: ldc.i4 0x300ca0d0
IL_0017: bgt.un.s IL_0034
IL_0019: ldloc.1
IL_001a: ldc.i4 0x1beb2a44
IL_001f: beq IL_015d
IL_0024: ldloc.1
IL_0025: ldc.i4 0x300ca0d0
IL_002a: beq IL_010d
IL_002f: br IL_0199
IL_0034: ldloc.1
IL_0035: ldc.i4 0x310ca263
IL_003a: beq IL_00fa
IL_003f: ldloc.1
IL_0040: ldc.i4 0x320ca3f6
IL_0045: beq IL_012d
IL_004a: ldloc.1
IL_004b: ldc.i4 0x330ca589
IL_0050: beq IL_011d
IL_0055: br IL_0199
IL_005a: ldloc.1
IL_005b: ldc.i4 0x360caa42
IL_0060: bgt.un.s IL_007f
IL_0062: ldloc.1
IL_0063: ldc.i4 0x340ca71c
IL_0068: beq.s IL_00b8
IL_006a: ldloc.1
IL_006b: ldc.i4 0x350ca8af
IL_0070: beq.s IL_00a2
IL_0072: ldloc.1
IL_0073: ldc.i4 0x360caa42
IL_0078: beq.s IL_00e4
IL_007a: br IL_0199
IL_007f: ldloc.1
IL_0080: ldc.i4 0x370cabd5
IL_0085: beq.s IL_00ce
IL_0087: ldloc.1
IL_0088: ldc.i4 0x3c0cb3b4
IL_008d: beq IL_014d
IL_0092: ldloc.1
IL_0093: ldc.i4 0x3d0cb547
IL_0098: beq IL_013d
IL_009d: br IL_0199
IL_00a2: ldloc.0
IL_00a3: ldstr "0"
IL_00a8: ldc.i4.0
IL_00a9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ae: brfalse IL_016d
IL_00b3: br IL_0199
IL_00b8: ldloc.0
IL_00b9: ldstr "1"
IL_00be: ldc.i4.0
IL_00bf: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00c4: brfalse IL_0178
IL_00c9: br IL_0199
IL_00ce: ldloc.0
IL_00cf: ldstr "2"
IL_00d4: ldc.i4.0
IL_00d5: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00da: brfalse IL_0178
IL_00df: br IL_0199
IL_00e4: ldloc.0
IL_00e5: ldstr "3"
IL_00ea: ldc.i4.0
IL_00eb: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00f0: brfalse IL_0178
IL_00f5: br IL_0199
IL_00fa: ldloc.0
IL_00fb: ldstr "4"
IL_0100: ldc.i4.0
IL_0101: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0106: brfalse.s IL_0178
IL_0108: br IL_0199
IL_010d: ldloc.0
IL_010e: ldstr "5"
IL_0113: ldc.i4.0
IL_0114: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0119: brfalse.s IL_0178
IL_011b: br.s IL_0199
IL_011d: ldloc.0
IL_011e: ldstr "6"
IL_0123: ldc.i4.0
IL_0124: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0129: brfalse.s IL_0183
IL_012b: br.s IL_0199
IL_012d: ldloc.0
IL_012e: ldstr "7"
IL_0133: ldc.i4.0
IL_0134: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0139: brfalse.s IL_0183
IL_013b: br.s IL_0199
IL_013d: ldloc.0
IL_013e: ldstr "8"
IL_0143: ldc.i4.0
IL_0144: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0149: brfalse.s IL_0183
IL_014b: br.s IL_0199
IL_014d: ldloc.0
IL_014e: ldstr "9"
IL_0153: ldc.i4.0
IL_0154: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0159: brfalse.s IL_018e
IL_015b: br.s IL_0199
IL_015d: ldloc.0
IL_015e: ldstr "10"
IL_0163: ldc.i4.0
IL_0164: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0169: brfalse.s IL_018e
IL_016b: br.s IL_0199
IL_016d: ldstr "Equal to 0"
IL_0172: call "Sub System.Console.WriteLine(String)"
IL_0177: ret
IL_0178: ldstr "Between 1 and 5, inclusive"
IL_017d: call "Sub System.Console.WriteLine(String)"
IL_0182: ret
IL_0183: ldstr "Between 6 and 8, inclusive"
IL_0188: call "Sub System.Console.WriteLine(String)"
IL_018d: ret
IL_018e: ldstr "Equal to 9 or 10"
IL_0193: call "Sub System.Console.WriteLine(String)"
IL_0198: ret
IL_0199: ldstr "Greater than 10"
IL_019e: call "Sub System.Console.WriteLine(String)"
IL_01a3: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
' verify that hash method is Friend
Dim reference = compVerifier.Compilation.EmitToImageReference()
Dim comp = VisualBasicCompilation.Create("Name", references:={reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal))
Dim pid = DirectCast(comp.GlobalNamespace.GetMembers().Single(Function(s) s.Name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)), NamedTypeSymbol)
Dim member = pid.GetMembers(PrivateImplementationDetails.SynthesizedStringHashFunctionName).Single()
Assert.Equal(Accessibility.Friend, member.DeclaredAccessibility)
End Sub
<Fact()>
Public Sub SelectCase_NonHash_SwitchTable_String_OptionCompareBinary()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 6
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case Else
Console.WriteLine("Greater than 5")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Greater than 5]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 121 (0x79)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "0"
IL_0008: ldc.i4.0
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brfalse.s IL_0058
IL_0010: ldloc.0
IL_0011: ldstr "1"
IL_0016: ldc.i4.0
IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_001c: brfalse.s IL_0063
IL_001e: ldloc.0
IL_001f: ldstr "2"
IL_0024: ldc.i4.0
IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_002a: brfalse.s IL_0063
IL_002c: ldloc.0
IL_002d: ldstr "3"
IL_0032: ldc.i4.0
IL_0033: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0038: brfalse.s IL_0063
IL_003a: ldloc.0
IL_003b: ldstr "4"
IL_0040: ldc.i4.0
IL_0041: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0046: brfalse.s IL_0063
IL_0048: ldloc.0
IL_0049: ldstr "5"
IL_004e: ldc.i4.0
IL_004f: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0054: brfalse.s IL_0063
IL_0056: br.s IL_006e
IL_0058: ldstr "Equal to 0"
IL_005d: call "Sub System.Console.WriteLine(String)"
IL_0062: ret
IL_0063: ldstr "Between 1 and 5, inclusive"
IL_0068: call "Sub System.Console.WriteLine(String)"
IL_006d: ret
IL_006e: ldstr "Greater than 5"
IL_0073: call "Sub System.Console.WriteLine(String)"
IL_0078: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact()>
Public Sub SelectCase_IfList_String_OptionCompareText()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(True),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 211 (0xd3)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "0"
IL_0008: ldc.i4.1
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brtrue.s IL_001b
IL_0010: ldstr "Equal to 0"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: ldstr "1"
IL_0021: ldc.i4.1
IL_0022: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0027: brfalse.s IL_0061
IL_0029: ldloc.0
IL_002a: ldstr "2"
IL_002f: ldc.i4.1
IL_0030: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0035: brfalse.s IL_0061
IL_0037: ldloc.0
IL_0038: ldstr "3"
IL_003d: ldc.i4.1
IL_003e: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0043: brfalse.s IL_0061
IL_0045: ldloc.0
IL_0046: ldstr "4"
IL_004b: ldc.i4.1
IL_004c: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0051: brfalse.s IL_0061
IL_0053: ldloc.0
IL_0054: ldstr "5"
IL_0059: ldc.i4.1
IL_005a: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_005f: brtrue.s IL_006c
IL_0061: ldstr "Between 1 and 5, inclusive"
IL_0066: call "Sub System.Console.WriteLine(String)"
IL_006b: ret
IL_006c: ldloc.0
IL_006d: ldstr "6"
IL_0072: ldc.i4.1
IL_0073: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0078: brfalse.s IL_0096
IL_007a: ldloc.0
IL_007b: ldstr "7"
IL_0080: ldc.i4.1
IL_0081: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0086: brfalse.s IL_0096
IL_0088: ldloc.0
IL_0089: ldstr "8"
IL_008e: ldc.i4.1
IL_008f: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0094: brtrue.s IL_00a1
IL_0096: ldstr "Between 6 and 8, inclusive"
IL_009b: call "Sub System.Console.WriteLine(String)"
IL_00a0: ret
IL_00a1: ldloc.0
IL_00a2: ldstr "9"
IL_00a7: ldc.i4.1
IL_00a8: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ad: brfalse.s IL_00bd
IL_00af: ldloc.0
IL_00b0: ldstr "10"
IL_00b5: ldc.i4.1
IL_00b6: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00bb: brtrue.s IL_00c8
IL_00bd: ldstr "Equal to 9 or 10"
IL_00c2: call "Sub System.Console.WriteLine(String)"
IL_00c7: ret
IL_00c8: ldstr "Greater than 10"
IL_00cd: call "Sub System.Console.WriteLine(String)"
IL_00d2: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact()>
Public Sub SelectCase_Hash_SwitchTable_String_MDConstant()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test("a")
Test("A")
End Sub
Sub Test(str as String)
Dim x As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Select Case str
Case "a"
Console.WriteLine("Equal to a")
Case "A"
Console.WriteLine("Equal to A")
Case "1", "2", "3", "4", "5", "6", "4", "5", "6"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[Equal to a
Equal to A]]>)
End Sub
<Fact, WorkItem(651996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651996")>
Public Sub SelectCase_Hash_SwitchTable_String_OptionCompareBinary_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test("a")
Test("A")
End Sub
Sub Test(str as String)
Select Case str
Case "a"
Console.WriteLine("Equal to a")
Case "A"
Console.WriteLine("Equal to A")
Case "1", "2", "3", "4", "5", "6", "4", "5", "6"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[Equal to a
Equal to A]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 302 (0x12e)
.maxstack 3
.locals init (String V_0,
UInteger V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function ComputeStringHash(String) As UInteger"
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldc.i4 0x340ca71c
IL_000f: bgt.un.s IL_004c
IL_0011: ldloc.1
IL_0012: ldc.i4 0x310ca263
IL_0017: bgt.un.s IL_0034
IL_0019: ldloc.1
IL_001a: ldc.i4 0x300ca0d0
IL_001f: beq IL_00e2
IL_0024: ldloc.1
IL_0025: ldc.i4 0x310ca263
IL_002a: beq IL_00d2
IL_002f: br IL_0123
IL_0034: ldloc.1
IL_0035: ldc.i4 0x330ca589
IL_003a: beq IL_00f2
IL_003f: ldloc.1
IL_0040: ldc.i4 0x340ca71c
IL_0045: beq.s IL_00a2
IL_0047: br IL_0123
IL_004c: ldloc.1
IL_004d: ldc.i4 0x370cabd5
IL_0052: bgt.un.s IL_0069
IL_0054: ldloc.1
IL_0055: ldc.i4 0x360caa42
IL_005a: beq.s IL_00c2
IL_005c: ldloc.1
IL_005d: ldc.i4 0x370cabd5
IL_0062: beq.s IL_00b2
IL_0064: br IL_0123
IL_0069: ldloc.1
IL_006a: ldc.i4 0xc40bf6cc
IL_006f: beq.s IL_008f
IL_0071: ldloc.1
IL_0072: ldc.i4 0xe40c292c
IL_0077: bne.un IL_0123
IL_007c: ldloc.0
IL_007d: ldstr "a"
IL_0082: ldc.i4.0
IL_0083: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0088: brfalse.s IL_0102
IL_008a: br IL_0123
IL_008f: ldloc.0
IL_0090: ldstr "A"
IL_0095: ldc.i4.0
IL_0096: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_009b: brfalse.s IL_010d
IL_009d: br IL_0123
IL_00a2: ldloc.0
IL_00a3: ldstr "1"
IL_00a8: ldc.i4.0
IL_00a9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ae: brfalse.s IL_0118
IL_00b0: br.s IL_0123
IL_00b2: ldloc.0
IL_00b3: ldstr "2"
IL_00b8: ldc.i4.0
IL_00b9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00be: brfalse.s IL_0118
IL_00c0: br.s IL_0123
IL_00c2: ldloc.0
IL_00c3: ldstr "3"
IL_00c8: ldc.i4.0
IL_00c9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ce: brfalse.s IL_0118
IL_00d0: br.s IL_0123
IL_00d2: ldloc.0
IL_00d3: ldstr "4"
IL_00d8: ldc.i4.0
IL_00d9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00de: brfalse.s IL_0118
IL_00e0: br.s IL_0123
IL_00e2: ldloc.0
IL_00e3: ldstr "5"
IL_00e8: ldc.i4.0
IL_00e9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ee: brfalse.s IL_0118
IL_00f0: br.s IL_0123
IL_00f2: ldloc.0
IL_00f3: ldstr "6"
IL_00f8: ldc.i4.0
IL_00f9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00fe: brfalse.s IL_0118
IL_0100: br.s IL_0123
IL_0102: ldstr "Equal to a"
IL_0107: call "Sub System.Console.WriteLine(String)"
IL_010c: ret
IL_010d: ldstr "Equal to A"
IL_0112: call "Sub System.Console.WriteLine(String)"
IL_0117: ret
IL_0118: ldstr "Error"
IL_011d: call "Sub System.Console.WriteLine(String)"
IL_0122: ret
IL_0123: ldstr "Error"
IL_0128: call "Sub System.Console.WriteLine(String)"
IL_012d: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact()>
Public Sub SelectCase_NonHash_SwitchTable_String_OptionCompareBinary_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test("a")
Test("A")
End Sub
Sub Test(str as String)
Select Case str
Case "a"
Console.WriteLine("Equal to a")
Case "A"
Console.WriteLine("Equal to A")
Case "1", "1", "1", "1", "1", "1", "1", "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[Equal to a
Equal to A]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 90 (0x5a)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "a"
IL_0008: ldc.i4.0
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brfalse.s IL_002e
IL_0010: ldloc.0
IL_0011: ldstr "A"
IL_0016: ldc.i4.0
IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_001c: brfalse.s IL_0039
IL_001e: ldloc.0
IL_001f: ldstr "1"
IL_0024: ldc.i4.0
IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_002a: brfalse.s IL_0044
IL_002c: br.s IL_004f
IL_002e: ldstr "Equal to a"
IL_0033: call "Sub System.Console.WriteLine(String)"
IL_0038: ret
IL_0039: ldstr "Equal to A"
IL_003e: call "Sub System.Console.WriteLine(String)"
IL_0043: ret
IL_0044: ldstr "Error"
IL_0049: call "Sub System.Console.WriteLine(String)"
IL_004e: ret
IL_004f: ldstr "Error"
IL_0054: call "Sub System.Console.WriteLine(String)"
IL_0059: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact()>
Public Sub SelectCase_IfList_String_OptionCompareText_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test("a")
Test("A")
End Sub
Sub Test(str as String)
Select Case str
Case "a"
Console.WriteLine("Equal to a")
Case "A"
Console.WriteLine("Error")
Case "1", "2", "3", "4", "5", "6", "4", "5", "6"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(True),
expectedOutput:=<![CDATA[Equal to a
Equal to a]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 200 (0xc8)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "a"
IL_0008: ldc.i4.1
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brtrue.s IL_001b
IL_0010: ldstr "Equal to a"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: ldstr "A"
IL_0021: ldc.i4.1
IL_0022: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0027: brtrue.s IL_0034
IL_0029: ldstr "Error"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
IL_0034: ldloc.0
IL_0035: ldstr "1"
IL_003a: ldc.i4.1
IL_003b: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0040: brfalse.s IL_00b2
IL_0042: ldloc.0
IL_0043: ldstr "2"
IL_0048: ldc.i4.1
IL_0049: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_004e: brfalse.s IL_00b2
IL_0050: ldloc.0
IL_0051: ldstr "3"
IL_0056: ldc.i4.1
IL_0057: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_005c: brfalse.s IL_00b2
IL_005e: ldloc.0
IL_005f: ldstr "4"
IL_0064: ldc.i4.1
IL_0065: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_006a: brfalse.s IL_00b2
IL_006c: ldloc.0
IL_006d: ldstr "5"
IL_0072: ldc.i4.1
IL_0073: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0078: brfalse.s IL_00b2
IL_007a: ldloc.0
IL_007b: ldstr "6"
IL_0080: ldc.i4.1
IL_0081: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0086: brfalse.s IL_00b2
IL_0088: ldloc.0
IL_0089: ldstr "4"
IL_008e: ldc.i4.1
IL_008f: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0094: brfalse.s IL_00b2
IL_0096: ldloc.0
IL_0097: ldstr "5"
IL_009c: ldc.i4.1
IL_009d: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00a2: brfalse.s IL_00b2
IL_00a4: ldloc.0
IL_00a5: ldstr "6"
IL_00aa: ldc.i4.1
IL_00ab: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00b0: brtrue.s IL_00bd
IL_00b2: ldstr "Error"
IL_00b7: call "Sub System.Console.WriteLine(String)"
IL_00bc: ret
IL_00bd: ldstr "Error"
IL_00c2: call "Sub System.Console.WriteLine(String)"
IL_00c7: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact, WorkItem(651996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651996")>
Public Sub SelectCase_SwitchTable_String_RelationalEqualityClause()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", = "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case Is = "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 420 (0x1a4)
.maxstack 3
.locals init (String V_0,
UInteger V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function ComputeStringHash(String) As UInteger"
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldc.i4 0x330ca589
IL_000f: bgt.un.s IL_005a
IL_0011: ldloc.1
IL_0012: ldc.i4 0x300ca0d0
IL_0017: bgt.un.s IL_0034
IL_0019: ldloc.1
IL_001a: ldc.i4 0x1beb2a44
IL_001f: beq IL_015d
IL_0024: ldloc.1
IL_0025: ldc.i4 0x300ca0d0
IL_002a: beq IL_010d
IL_002f: br IL_0199
IL_0034: ldloc.1
IL_0035: ldc.i4 0x310ca263
IL_003a: beq IL_00fa
IL_003f: ldloc.1
IL_0040: ldc.i4 0x320ca3f6
IL_0045: beq IL_012d
IL_004a: ldloc.1
IL_004b: ldc.i4 0x330ca589
IL_0050: beq IL_011d
IL_0055: br IL_0199
IL_005a: ldloc.1
IL_005b: ldc.i4 0x360caa42
IL_0060: bgt.un.s IL_007f
IL_0062: ldloc.1
IL_0063: ldc.i4 0x340ca71c
IL_0068: beq.s IL_00b8
IL_006a: ldloc.1
IL_006b: ldc.i4 0x350ca8af
IL_0070: beq.s IL_00a2
IL_0072: ldloc.1
IL_0073: ldc.i4 0x360caa42
IL_0078: beq.s IL_00e4
IL_007a: br IL_0199
IL_007f: ldloc.1
IL_0080: ldc.i4 0x370cabd5
IL_0085: beq.s IL_00ce
IL_0087: ldloc.1
IL_0088: ldc.i4 0x3c0cb3b4
IL_008d: beq IL_014d
IL_0092: ldloc.1
IL_0093: ldc.i4 0x3d0cb547
IL_0098: beq IL_013d
IL_009d: br IL_0199
IL_00a2: ldloc.0
IL_00a3: ldstr "0"
IL_00a8: ldc.i4.0
IL_00a9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ae: brfalse IL_016d
IL_00b3: br IL_0199
IL_00b8: ldloc.0
IL_00b9: ldstr "1"
IL_00be: ldc.i4.0
IL_00bf: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00c4: brfalse IL_0178
IL_00c9: br IL_0199
IL_00ce: ldloc.0
IL_00cf: ldstr "2"
IL_00d4: ldc.i4.0
IL_00d5: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00da: brfalse IL_0178
IL_00df: br IL_0199
IL_00e4: ldloc.0
IL_00e5: ldstr "3"
IL_00ea: ldc.i4.0
IL_00eb: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00f0: brfalse IL_0178
IL_00f5: br IL_0199
IL_00fa: ldloc.0
IL_00fb: ldstr "4"
IL_0100: ldc.i4.0
IL_0101: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0106: brfalse.s IL_0178
IL_0108: br IL_0199
IL_010d: ldloc.0
IL_010e: ldstr "5"
IL_0113: ldc.i4.0
IL_0114: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0119: brfalse.s IL_0178
IL_011b: br.s IL_0199
IL_011d: ldloc.0
IL_011e: ldstr "6"
IL_0123: ldc.i4.0
IL_0124: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0129: brfalse.s IL_0183
IL_012b: br.s IL_0199
IL_012d: ldloc.0
IL_012e: ldstr "7"
IL_0133: ldc.i4.0
IL_0134: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0139: brfalse.s IL_0183
IL_013b: br.s IL_0199
IL_013d: ldloc.0
IL_013e: ldstr "8"
IL_0143: ldc.i4.0
IL_0144: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0149: brfalse.s IL_0183
IL_014b: br.s IL_0199
IL_014d: ldloc.0
IL_014e: ldstr "9"
IL_0153: ldc.i4.0
IL_0154: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0159: brfalse.s IL_018e
IL_015b: br.s IL_0199
IL_015d: ldloc.0
IL_015e: ldstr "10"
IL_0163: ldc.i4.0
IL_0164: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0169: brfalse.s IL_018e
IL_016b: br.s IL_0199
IL_016d: ldstr "Equal to 0"
IL_0172: call "Sub System.Console.WriteLine(String)"
IL_0177: ret
IL_0178: ldstr "Between 1 and 5, inclusive"
IL_017d: call "Sub System.Console.WriteLine(String)"
IL_0182: ret
IL_0183: ldstr "Between 6 and 8, inclusive"
IL_0188: call "Sub System.Console.WriteLine(String)"
IL_018d: ret
IL_018e: ldstr "Equal to 9 or 10"
IL_0193: call "Sub System.Console.WriteLine(String)"
IL_0198: ret
IL_0199: ldstr "Greater than 10"
IL_019e: call "Sub System.Console.WriteLine(String)"
IL_01a3: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact()>
Public Sub SelectCase_IfList_String_RelationalRangeClauses()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6" To "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9" To "8"
Console.WriteLine("Fail")
Case >= "9", <= "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(True),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 242 (0xf2)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "0"
IL_0008: ldc.i4.1
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brtrue.s IL_001b
IL_0010: ldstr "Equal to 0"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: ldstr "1"
IL_0021: ldc.i4.1
IL_0022: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0027: brfalse.s IL_0061
IL_0029: ldloc.0
IL_002a: ldstr "2"
IL_002f: ldc.i4.1
IL_0030: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0035: brfalse.s IL_0061
IL_0037: ldloc.0
IL_0038: ldstr "3"
IL_003d: ldc.i4.1
IL_003e: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0043: brfalse.s IL_0061
IL_0045: ldloc.0
IL_0046: ldstr "4"
IL_004b: ldc.i4.1
IL_004c: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0051: brfalse.s IL_0061
IL_0053: ldloc.0
IL_0054: ldstr "5"
IL_0059: ldc.i4.1
IL_005a: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_005f: brtrue.s IL_006c
IL_0061: ldstr "Between 1 and 5, inclusive"
IL_0066: call "Sub System.Console.WriteLine(String)"
IL_006b: ret
IL_006c: ldloc.0
IL_006d: ldstr "6"
IL_0072: ldc.i4.1
IL_0073: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0078: ldc.i4.0
IL_0079: blt.s IL_0095
IL_007b: ldloc.0
IL_007c: ldstr "8"
IL_0081: ldc.i4.1
IL_0082: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0087: ldc.i4.0
IL_0088: bgt.s IL_0095
IL_008a: ldstr "Between 6 and 8, inclusive"
IL_008f: call "Sub System.Console.WriteLine(String)"
IL_0094: ret
IL_0095: ldloc.0
IL_0096: ldstr "9"
IL_009b: ldc.i4.1
IL_009c: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00a1: ldc.i4.0
IL_00a2: blt.s IL_00be
IL_00a4: ldloc.0
IL_00a5: ldstr "8"
IL_00aa: ldc.i4.1
IL_00ab: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00b0: ldc.i4.0
IL_00b1: bgt.s IL_00be
IL_00b3: ldstr "Fail"
IL_00b8: call "Sub System.Console.WriteLine(String)"
IL_00bd: ret
IL_00be: ldloc.0
IL_00bf: ldstr "9"
IL_00c4: ldc.i4.1
IL_00c5: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ca: ldc.i4.0
IL_00cb: bge.s IL_00dc
IL_00cd: ldloc.0
IL_00ce: ldstr "10"
IL_00d3: ldc.i4.1
IL_00d4: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00d9: ldc.i4.0
IL_00da: bgt.s IL_00e7
IL_00dc: ldstr "Equal to 9 or 10"
IL_00e1: call "Sub System.Console.WriteLine(String)"
IL_00e6: ret
IL_00e7: ldstr "Greater than 10"
IL_00ec: call "Sub System.Console.WriteLine(String)"
IL_00f1: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact, WorkItem(651996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651996")>
Public Sub SelectCase_String_Multiple_Hash_SwitchTable()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Console.Write(x.ToString() + ":")
Test2(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
Sub Test2(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[0:Equal to 0
0:Equal to 0
1:Between 1 and 5, inclusive
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
9:Equal to 9 or 10
10:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 420 (0x1a4)
.maxstack 3
.locals init (String V_0,
UInteger V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function ComputeStringHash(String) As UInteger"
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldc.i4 0x330ca589
IL_000f: bgt.un.s IL_005a
IL_0011: ldloc.1
IL_0012: ldc.i4 0x300ca0d0
IL_0017: bgt.un.s IL_0034
IL_0019: ldloc.1
IL_001a: ldc.i4 0x1beb2a44
IL_001f: beq IL_015d
IL_0024: ldloc.1
IL_0025: ldc.i4 0x300ca0d0
IL_002a: beq IL_010d
IL_002f: br IL_0199
IL_0034: ldloc.1
IL_0035: ldc.i4 0x310ca263
IL_003a: beq IL_00fa
IL_003f: ldloc.1
IL_0040: ldc.i4 0x320ca3f6
IL_0045: beq IL_012d
IL_004a: ldloc.1
IL_004b: ldc.i4 0x330ca589
IL_0050: beq IL_011d
IL_0055: br IL_0199
IL_005a: ldloc.1
IL_005b: ldc.i4 0x360caa42
IL_0060: bgt.un.s IL_007f
IL_0062: ldloc.1
IL_0063: ldc.i4 0x340ca71c
IL_0068: beq.s IL_00b8
IL_006a: ldloc.1
IL_006b: ldc.i4 0x350ca8af
IL_0070: beq.s IL_00a2
IL_0072: ldloc.1
IL_0073: ldc.i4 0x360caa42
IL_0078: beq.s IL_00e4
IL_007a: br IL_0199
IL_007f: ldloc.1
IL_0080: ldc.i4 0x370cabd5
IL_0085: beq.s IL_00ce
IL_0087: ldloc.1
IL_0088: ldc.i4 0x3c0cb3b4
IL_008d: beq IL_014d
IL_0092: ldloc.1
IL_0093: ldc.i4 0x3d0cb547
IL_0098: beq IL_013d
IL_009d: br IL_0199
IL_00a2: ldloc.0
IL_00a3: ldstr "0"
IL_00a8: ldc.i4.0
IL_00a9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ae: brfalse IL_016d
IL_00b3: br IL_0199
IL_00b8: ldloc.0
IL_00b9: ldstr "1"
IL_00be: ldc.i4.0
IL_00bf: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00c4: brfalse IL_0178
IL_00c9: br IL_0199
IL_00ce: ldloc.0
IL_00cf: ldstr "2"
IL_00d4: ldc.i4.0
IL_00d5: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00da: brfalse IL_0178
IL_00df: br IL_0199
IL_00e4: ldloc.0
IL_00e5: ldstr "3"
IL_00ea: ldc.i4.0
IL_00eb: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00f0: brfalse IL_0178
IL_00f5: br IL_0199
IL_00fa: ldloc.0
IL_00fb: ldstr "4"
IL_0100: ldc.i4.0
IL_0101: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0106: brfalse.s IL_0178
IL_0108: br IL_0199
IL_010d: ldloc.0
IL_010e: ldstr "5"
IL_0113: ldc.i4.0
IL_0114: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0119: brfalse.s IL_0178
IL_011b: br.s IL_0199
IL_011d: ldloc.0
IL_011e: ldstr "6"
IL_0123: ldc.i4.0
IL_0124: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0129: brfalse.s IL_0183
IL_012b: br.s IL_0199
IL_012d: ldloc.0
IL_012e: ldstr "7"
IL_0133: ldc.i4.0
IL_0134: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0139: brfalse.s IL_0183
IL_013b: br.s IL_0199
IL_013d: ldloc.0
IL_013e: ldstr "8"
IL_0143: ldc.i4.0
IL_0144: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0149: brfalse.s IL_0183
IL_014b: br.s IL_0199
IL_014d: ldloc.0
IL_014e: ldstr "9"
IL_0153: ldc.i4.0
IL_0154: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0159: brfalse.s IL_018e
IL_015b: br.s IL_0199
IL_015d: ldloc.0
IL_015e: ldstr "10"
IL_0163: ldc.i4.0
IL_0164: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0169: brfalse.s IL_018e
IL_016b: br.s IL_0199
IL_016d: ldstr "Equal to 0"
IL_0172: call "Sub System.Console.WriteLine(String)"
IL_0177: ret
IL_0178: ldstr "Between 1 and 5, inclusive"
IL_017d: call "Sub System.Console.WriteLine(String)"
IL_0182: ret
IL_0183: ldstr "Between 6 and 8, inclusive"
IL_0188: call "Sub System.Console.WriteLine(String)"
IL_018d: ret
IL_018e: ldstr "Equal to 9 or 10"
IL_0193: call "Sub System.Console.WriteLine(String)"
IL_0198: ret
IL_0199: ldstr "Greater than 10"
IL_019e: call "Sub System.Console.WriteLine(String)"
IL_01a3: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact()>
Public Sub MissingReferenceToVBRuntime()
CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Class
]]></file>
</compilation>, OutputKind.DynamicallyLinkedLibrary).
VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "number").WithArguments("Microsoft.VisualBasic.CompilerServices.Operators.CompareString"))
End Sub
<WorkItem(529047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529047")>
<Fact>
Public Sub SelectOutOfMethod()
CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Class m1
Select ""
End Select
End Class
]]></file>
</compilation>).
VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Select """""),
Diagnostic(ERRID.ERR_EndSelectNoSelect, "End Select"))
End Sub
<WorkItem(529047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529047")>
<Fact>
Public Sub SelectOutOfMethod_1()
CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Select ""
End Select
]]></file>
</compilation>).
VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Select """""),
Diagnostic(ERRID.ERR_EndSelectNoSelect, "End Select"))
End Sub
<WorkItem(543410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543410")>
<Fact()>
Public Sub SelectCase_GetType()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Select GetType(Object)
End Select
End Sub
End Module
]]></file>
</compilation>).VerifyIL("M1.Main", <![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldtoken "Object"
IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_000a: pop
IL_000b: ret
}
]]>)
End Sub
<WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")>
<WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")>
<Fact()>
Public Sub MissingCharsProperty()
CompilationUtils.CreateCompilationWithReferences(
<compilation>
<file name="a.vb"><![CDATA[
Class M1
Shared Sub Main()
End Sub
Shared Function Test(number as String) as string
Select Case number
Case "0"
return "0"
Case "1"
return "1"
Case "2"
return "2"
Case "3"
return "3"
Case "4"
return "4"
Case Else
return "Else"
End Select
End Function
End Class
]]></file>
</compilation>, references:={AacorlibRef}).
VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "number").WithArguments("System.String.get_Chars"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "number").WithArguments("Microsoft.VisualBasic.CompilerServices.Operators.CompareString"))
End Sub
<Fact>
Public Sub SelectCase_Nothing001()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Main()
Dim str As String = ""
Select Case str
Case CStr(Nothing)
System.Console.WriteLine("null")
Case "1"
System.Console.WriteLine("1")
'Case "1"
' System.Console.WriteLine("2")
'Case "3"
' System.Console.WriteLine("3")
'Case "4"
' System.Console.WriteLine("4")
'Case "5"
' System.Console.WriteLine("5")
'Case "6"
' System.Console.WriteLine("6")
'Case "7"
' System.Console.WriteLine("7")
'Case "8"
' System.Console.WriteLine("8")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="null").VerifyIL("Module1.Main", <![CDATA[
{
// Code size 53 (0x35)
.maxstack 3
.locals init (String V_0) //str
IL_0000: ldstr ""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldnull
IL_0008: ldc.i4.0
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brfalse.s IL_001f
IL_0010: ldloc.0
IL_0011: ldstr "1"
IL_0016: ldc.i4.0
IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_001c: brfalse.s IL_002a
IL_001e: ret
IL_001f: ldstr "null"
IL_0024: call "Sub System.Console.WriteLine(String)"
IL_0029: ret
IL_002a: ldstr "1"
IL_002f: call "Sub System.Console.WriteLine(String)"
IL_0034: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_Nothing002()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Main()
Dim str As String = ""
Select Case str
Case CStr(Nothing)
System.Console.WriteLine("null")
Case "1"
System.Console.WriteLine("1")
Case "1"
System.Console.WriteLine("2")
Case "3"
System.Console.WriteLine("3")
Case "4"
System.Console.WriteLine("4")
Case "5"
System.Console.WriteLine("5")
Case "6"
System.Console.WriteLine("6")
Case "7"
System.Console.WriteLine("7")
Case "8"
System.Console.WriteLine("8")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="null").VerifyIL("Module1.Main", <![CDATA[
{
// Code size 317 (0x13d)
.maxstack 3
.locals init (String V_0, //str
UInteger V_1)
IL_0000: ldstr ""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call "Function ComputeStringHash(String) As UInteger"
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: ldc.i4 0x330ca589
IL_0013: bgt.un.s IL_0045
IL_0015: ldloc.1
IL_0016: ldc.i4 0x310ca263
IL_001b: bgt.un.s IL_0031
IL_001d: ldloc.1
IL_001e: ldc.i4 0x300ca0d0
IL_0023: beq IL_00a9
IL_0028: ldloc.1
IL_0029: ldc.i4 0x310ca263
IL_002e: beq.s IL_009a
IL_0030: ret
IL_0031: ldloc.1
IL_0032: ldc.i4 0x320ca3f6
IL_0037: beq IL_00c7
IL_003c: ldloc.1
IL_003d: ldc.i4 0x330ca589
IL_0042: beq.s IL_00b8
IL_0044: ret
IL_0045: ldloc.1
IL_0046: ldc.i4 0x360caa42
IL_004b: bgt.un.s IL_005e
IL_004d: ldloc.1
IL_004e: ldc.i4 0x340ca71c
IL_0053: beq.s IL_007c
IL_0055: ldloc.1
IL_0056: ldc.i4 0x360caa42
IL_005b: beq.s IL_008b
IL_005d: ret
IL_005e: ldloc.1
IL_005f: ldc.i4 0x3d0cb547
IL_0064: beq.s IL_00d6
IL_0066: ldloc.1
IL_0067: ldc.i4 0x811c9dc5
IL_006c: bne.un IL_013c
IL_0071: ldloc.0
IL_0072: ldnull
IL_0073: ldc.i4.0
IL_0074: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0079: brfalse.s IL_00e5
IL_007b: ret
IL_007c: ldloc.0
IL_007d: ldstr "1"
IL_0082: ldc.i4.0
IL_0083: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0088: brfalse.s IL_00f0
IL_008a: ret
IL_008b: ldloc.0
IL_008c: ldstr "3"
IL_0091: ldc.i4.0
IL_0092: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0097: brfalse.s IL_00fb
IL_0099: ret
IL_009a: ldloc.0
IL_009b: ldstr "4"
IL_00a0: ldc.i4.0
IL_00a1: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00a6: brfalse.s IL_0106
IL_00a8: ret
IL_00a9: ldloc.0
IL_00aa: ldstr "5"
IL_00af: ldc.i4.0
IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00b5: brfalse.s IL_0111
IL_00b7: ret
IL_00b8: ldloc.0
IL_00b9: ldstr "6"
IL_00be: ldc.i4.0
IL_00bf: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00c4: brfalse.s IL_011c
IL_00c6: ret
IL_00c7: ldloc.0
IL_00c8: ldstr "7"
IL_00cd: ldc.i4.0
IL_00ce: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00d3: brfalse.s IL_0127
IL_00d5: ret
IL_00d6: ldloc.0
IL_00d7: ldstr "8"
IL_00dc: ldc.i4.0
IL_00dd: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00e2: brfalse.s IL_0132
IL_00e4: ret
IL_00e5: ldstr "null"
IL_00ea: call "Sub System.Console.WriteLine(String)"
IL_00ef: ret
IL_00f0: ldstr "1"
IL_00f5: call "Sub System.Console.WriteLine(String)"
IL_00fa: ret
IL_00fb: ldstr "3"
IL_0100: call "Sub System.Console.WriteLine(String)"
IL_0105: ret
IL_0106: ldstr "4"
IL_010b: call "Sub System.Console.WriteLine(String)"
IL_0110: ret
IL_0111: ldstr "5"
IL_0116: call "Sub System.Console.WriteLine(String)"
IL_011b: ret
IL_011c: ldstr "6"
IL_0121: call "Sub System.Console.WriteLine(String)"
IL_0126: ret
IL_0127: ldstr "7"
IL_012c: call "Sub System.Console.WriteLine(String)"
IL_0131: ret
IL_0132: ldstr "8"
IL_0137: call "Sub System.Console.WriteLine(String)"
IL_013c: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact>
Public Sub SelectCase_Nothing003()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Main()
Dim str As String = ""
Select Case str
Case CStr("")
System.Console.WriteLine("empty")
Case CStr(Nothing)
System.Console.WriteLine("null")
Case "1"
System.Console.WriteLine("1")
Case "1"
System.Console.WriteLine("2")
Case "3"
System.Console.WriteLine("3")
Case "4"
System.Console.WriteLine("4")
Case "5"
System.Console.WriteLine("5")
Case "6"
System.Console.WriteLine("6")
Case "7"
System.Console.WriteLine("7")
Case "8"
System.Console.WriteLine("8")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="empty")
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact>
Public Sub Regression947580()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
boo(42)
End Sub
Function boo(i As Integer) As String
Select Case i
Case 42
Dim x = "foo"
If x <> "bar" Then
Exit Select
End If
Return x
End Select
Return Nothing
End Function
End Module
]]></file>
</compilation>, expectedOutput:="").VerifyIL("Module1.boo", <![CDATA[
{
// Code size 35 (0x23)
.maxstack 3
.locals init (String V_0, //boo
Integer V_1,
String V_2) //x
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: ldc.i4.s 42
IL_0005: bne.un.s IL_001f
IL_0007: ldstr "foo"
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: ldstr "bar"
IL_0013: ldc.i4.0
IL_0014: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0019: brtrue.s IL_001f
IL_001b: ldloc.2
IL_001c: stloc.0
IL_001d: br.s IL_0021
IL_001f: ldnull
IL_0020: stloc.0
IL_0021: ldloc.0
IL_0022: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub Regression947580a()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
boo(42)
End Sub
Function boo(i As Integer) As String
Select Case i
Case 42
Dim x = "foo"
If x <> "bar" Then
Exit Select
End If
Exit Select
End Select
Return Nothing
End Function
End Module
]]></file>
</compilation>, expectedOutput:="").VerifyIL("Module1.boo", <![CDATA[
{
// Code size 26 (0x1a)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.s 42
IL_0005: bne.un.s IL_0018
IL_0007: ldstr "foo"
IL_000c: ldstr "bar"
IL_0011: ldc.i4.0
IL_0012: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0017: pop
IL_0018: ldnull
IL_0019: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
#End Region
End Class
End Namespace
|
weltkante/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSelectCase.vb
|
Visual Basic
|
apache-2.0
| 151,313
|
Namespace Security.UserOptions_MessengerSettings
Public Class Open
Inherits SecurityItemBase
Public Sub New()
_ConceptItemName = "Open"
_ConceptName = "User Options_Messenger Settings"
_Description = "Allow access to 'Messenger Settings'"
_IsEnterprise = True
_IsSmallBusiness = True
_IsViewer = True
_IsWeb = False
_IsWebPlus = False
End Sub
End Class
End Namespace
|
nublet/DMS
|
DMS.Forms.Shared/Security/Items/UserOptions/MessengerSettings/Open.vb
|
Visual Basic
|
mit
| 504
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fUDevoluciones_Clientes"
'-------------------------------------------------------------------------------------------'
Partial Class fUDevoluciones_Clientes
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 TOP 40")
loComandoSeleccionar.AppendLine(" Clientes.Cod_Cli,")
loComandoSeleccionar.AppendLine(" Clientes.Nom_Cli,")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Documento,")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Fec_Ini,")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Cod_Art,")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art,")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Cod_Uni,")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Cod_Alm,")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Can_Art1,")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Precio1")
loComandoSeleccionar.AppendLine(" FROM Clientes")
loComandoSeleccionar.AppendLine(" JOIN Devoluciones_Clientes ON Devoluciones_Clientes.Cod_Cli = Clientes.Cod_Cli")
loComandoSeleccionar.AppendLine(" JOIN Renglones_DClientes ON Devoluciones_Clientes.Documento = Renglones_DClientes.Documento")
loComandoSeleccionar.AppendLine(" JOIN Articulos ON Renglones_DClientes.Cod_Art = Articulos.Cod_Art")
loComandoSeleccionar.AppendLine(" WHERE")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Status IN ('Confirmado','Afectado','Procesado')")
loComandoSeleccionar.AppendLine(" AND " & cusAplicacion.goFormatos.pcCondicionPrincipal)
loComandoSeleccionar.AppendLine(" ORDER BY Devoluciones_Clientes.Fec_Ini DESC")
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("fUDevoluciones_Clientes", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfUDevoluciones_Clientes.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
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' Douglas Cortez: 20/05/2010 : Codigo inicial
'-------------------------------------------------------------------------------------------'
' MAT: 23/05/2011: mejora de la vista de diseño
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
fUDevoluciones_Clientes.aspx.vb
|
Visual Basic
|
mit
| 5,533
|
'------------------------------------------------------------------------------
' <auto-generated>
' Este código lo generó una herramienta.
'
' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
' se regenera el código.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Semaforos.My.MySettings
Get
Return Global.Semaforos.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
SSTyT/dashboard-semaforos
|
Semaforos/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,982
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.Civ_4_Mod_Launcher.Form1
End Sub
End Class
End Namespace
|
TC01/civ4-launcher
|
My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,480
|
Imports InTheHand.net
Imports InTheHand.windows.forms
Public Class Form1
Inherits System.Windows.Forms.Form
Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
'
' TODO ******************** argh FileDialog *****************
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
MyBase.Dispose(disposing)
End Sub
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents btnBeam As System.Windows.Forms.Button
Friend WithEvents mnuBeam As System.Windows.Forms.MenuItem
Friend WithEvents mnuQuit As System.Windows.Forms.MenuItem
Friend WithEvents ofdFileToBeam As System.Windows.Forms.OpenFileDialog
Private Sub InitializeComponent()
Me.MainMenu1 = New System.Windows.Forms.MainMenu
Me.mnuBeam = New System.Windows.Forms.MenuItem
Me.mnuQuit = New System.Windows.Forms.MenuItem
Me.ofdFileToBeam = New System.Windows.Forms.OpenFileDialog
Me.btnBeam = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'MainMenu1
'
Me.MainMenu1.MenuItems.Add(Me.mnuBeam)
Me.MainMenu1.MenuItems.Add(Me.mnuQuit)
'
'mnuBeam
'
Me.mnuBeam.Text = "&Beam File"
'
'mnuQuit
'
Me.mnuQuit.Text = "&Quit"
'
'ofdFileToBeam
'
Me.ofdFileToBeam.Filter = "AllFiles|*.*"
'
'btnBeam
'
Me.btnBeam.Location = New System.Drawing.Point(152, 120)
Me.btnBeam.Name = "btnBeam"
Me.btnBeam.Size = New System.Drawing.Size(80, 24)
Me.btnBeam.TabIndex = 0
Me.btnBeam.Text = "Beam File"
'
'Form1
'
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit
Me.ClientSize = New System.Drawing.Size(240, 160)
Me.Controls.Add(Me.btnBeam)
Me.Menu = Me.MainMenu1
Me.MinimizeBox = False
Me.Name = "Form1"
Me.Text = "Object Push"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub btnBeam_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBeam.Click, mnuBeam.Click
Dim sbdd As New SelectBluetoothDeviceDialog
sbdd.ShowAuthenticated = True
sbdd.ShowRemembered = True
sbdd.ShowUnknown = True
If sbdd.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
If ofdFileToBeam.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Cursor.Current = Cursors.WaitCursor
Dim theuri As New Uri("obex://" + sbdd.SelectedDevice.DeviceAddress.ToString() + "/" + System.IO.Path.GetFileName(ofdFileToBeam.FileName))
Dim request As New ObexWebRequest(theuri)
request.ReadFile(ofdFileToBeam.FileName)
Dim response As ObexWebResponse = CType(request.GetResponse(), ObexWebResponse)
MessageBox.Show(response.StatusCode.ToString())
response.Close()
Cursor.Current = Cursors.Default
End If
End If
End Sub
Private Sub mnuQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuQuit.Click
Me.Close()
End Sub
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
Dim br As Bluetooth.BluetoothRadio = Bluetooth.BluetoothRadio.PrimaryRadio
If Not br Is Nothing Then
If br.Mode = Bluetooth.RadioMode.PowerOff Then
br.Mode = Bluetooth.RadioMode.Connectable
End If
Else
MessageBox.Show("Your device uses an unsupported Bluetooth software stack")
btnBeam.Enabled = False
End If
End Sub
Private backgroundImage As Image
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
If backgroundImage Is Nothing Then
Dim s As System.IO.Stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ThirtyTwoFeet.32feet.128.png")
backgroundImage = New Bitmap(s)
End If
e.Graphics.DrawImage(backgroundImage, 0, 0)
End Sub
End Class
|
inthehand/32feet
|
Legacy/Samples/ObjectPush/ObexPushVB/Form1.vb
|
Visual Basic
|
mit
| 4,647
|
Imports CloudinaryDotNet
Public Class Image
Public Property Caption As String
Public Property ShowTransform As Transformation
Public Property Url As String
Public Property Format As String
Public Property PublicId As String
End Class
|
RTLcoil/CloudinaryDotNet
|
samples/basic_mvc4_vb/Models/Image.vb
|
Visual Basic
|
mit
| 265
|
Imports System.Reflection
Imports System.Runtime.CompilerServices
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.
<Assembly: AssemblyTitle("CreateDocument")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("CreateDocument")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
' Setting ComVisible to false makes the types in this assembly not visible
' to COM components. If you need to access a type in this assembly from
' COM, set the ComVisible attribute to true on that type.
<Assembly: ComVisible(False)>
' The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("d4e0aff9-6709-4b7c-8731-d4f3ae613cf6")>
' 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")>
|
SolidEdgeCommunity/Samples
|
Assembly/CreateDocument/vb/CreateDocument/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,390
|
Namespace UI
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class NavigatorForm
Inherits DockableForm
'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 NavigateBarTheme1 As MT.Common.Controls.OutlookStyleNavigateBar.NavigateBarTheme = New MT.Common.Controls.OutlookStyleNavigateBar.NavigateBarTheme
Me.AppNavigation = New MT.Common.Controls.OutlookStyleNavigateBar.NavigateBar
CType(Me.ErrorNotify, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'AppNavigation
'
Me.AppNavigation.BackColor = System.Drawing.SystemColors.ControlLightLight
Me.AppNavigation.CollapsibleScreenWidth = 120
Me.AppNavigation.Dock = System.Windows.Forms.DockStyle.Fill
Me.AppNavigation.IsShowCollapsibleScreen = True
Me.AppNavigation.Location = New System.Drawing.Point(0, 0)
Me.AppNavigation.MinimumSize = New System.Drawing.Size(22, 100)
Me.AppNavigation.Name = "AppNavigation"
Me.AppNavigation.NavigateBarButtonHeight = 32
Me.AppNavigation.NavigateBarDisplayedButtonCount = 0
Me.AppNavigation.NavigateBarPaintAngle = 90.0!
Me.AppNavigation.SaveAndRestoreSettings = True
Me.AppNavigation.SelectedButton = Nothing
Me.AppNavigation.Size = New System.Drawing.Size(277, 427)
Me.AppNavigation.TabIndex = 1
NavigateBarTheme1.DarkColor = System.Drawing.Color.FromArgb(CType(CType(123, Byte), Integer), CType(CType(164, Byte), Integer), CType(CType(224, Byte), Integer))
NavigateBarTheme1.DarkDarkColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(45, Byte), Integer), CType(CType(150, Byte), Integer))
NavigateBarTheme1.LightColor = System.Drawing.Color.FromArgb(CType(CType(203, Byte), Integer), CType(CType(225, Byte), Integer), CType(CType(252, Byte), Integer))
NavigateBarTheme1.MouseOverDarkColor = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(203, Byte), Integer), CType(CType(136, Byte), Integer))
NavigateBarTheme1.MouseOverLightColor = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(222, Byte), Integer))
NavigateBarTheme1.SelectedDarkColor = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(223, Byte), Integer), CType(CType(154, Byte), Integer))
NavigateBarTheme1.SelectedLightColor = System.Drawing.Color.FromArgb(CType(CType(254, Byte), Integer), CType(CType(128, Byte), Integer), CType(CType(62, Byte), Integer))
Me.AppNavigation.Theme = NavigateBarTheme1
'
'NavigatorForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(277, 427)
Me.Controls.Add(Me.AppNavigation)
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "NavigatorForm"
Me.Text = "NavigatorForm"
CType(Me.ErrorNotify, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Protected Friend WithEvents AppNavigation As MT.Common.Controls.OutlookStyleNavigateBar.NavigateBar
End Class
End Namespace
|
okyereadugyamfi/softlogik
|
SPCode/UI/Form/NavigatorForm.Designer.vb
|
Visual Basic
|
mit
| 4,329
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rEGanancias_Perdidas_xCentroCostos"
'-------------------------------------------------------------------------------------------'
Partial Class rEGanancias_Perdidas_xCentroCostos
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 lcFechaDesde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcFechaHasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcCuentaContableDesde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcCuentaContableHasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcCentroCostoDesde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcCentroCostoHasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcCuentaGastoDesde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcCuentaGastoHasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcAuxiliarDesde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcAuxiliarHasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcMonedaDesde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcMonedaHasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcTipoComprobante As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
'Dim lcSoloConMovimiento As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7))
'Dim lcNivelMostrar As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8))
Dim llSoloMovimientos As Boolean = CStr(cusAplicacion.goReportes.paParametrosIniciales(7)).Trim().ToUpper().Equals("SI")
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim lcActivo As String = Strings.Trim(goOpciones.mObtener("CODCUEACT", ""))
Dim lcPasivo As String = Strings.Trim(goOpciones.mObtener("CODCUEPAS", ""))
Dim lcCapital As String = Strings.Trim(goOpciones.mObtener("CODCUECAP", ""))
If (lcActivo="") OrElse (lcPasivo = "") OrElse (lcCapital = "") Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Operación no Completada", _
"Debe establecer la opciones 'CODCUEACT', 'CODCUEPAS' y 'CODCUECAP' para indicar cuales son las cuentas" & _
" raiz del Activo, Pasivo y Capital respectivamente.", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Advertencia, _
"auto", _
"auto")
Return
End If
lcActivo = goServicios.mObtenerCampoFormatoSQL(lcActivo & "%")
lcPasivo = goServicios.mObtenerCampoFormatoSQL(lcPasivo & "%")
lcCapital = goServicios.mObtenerCampoFormatoSQL(lcCapital & "%")
Dim loConsulta As New StringBuilder()
Dim lnTamaño1 As Integer = CInt(goOpciones.mObtener("ANCNIV1", ""))
Dim lnTamaño2 As Integer = CInt(goOpciones.mObtener("ANCNIV2", ""))
Dim lnTamaño3 As Integer = CInt(goOpciones.mObtener("ANCNIV3", ""))
Dim lnTamaño4 As Integer = CInt(goOpciones.mObtener("ANCNIV4", ""))
Dim lnTamaño5 As Integer = CInt(goOpciones.mObtener("ANCNIV5", ""))
Dim lnTamaño6 As Integer = CInt(goOpciones.mObtener("ANCNIV6", ""))
Dim lnCantidad As Integer = CInt(goOpciones.mObtener("CANNIVCUE", "")) 'Niveles usados por la empresa
Dim lnNivelMax As Integer = CInt(cusAplicacion.goReportes.paParametrosIniciales(8)) 'Nivel máximo a mostrar en reporte
Dim lcSeparador As String = CStr(goOpciones.mObtener("CARSEPCUE", "")).Trim() 'Separador de Niveles de la empresa
Dim lnLongMax As Integer = 0
'Establece el nivel máximo a mostrar
If lnCantidad<=0 Then
lnCantidad = 1
ElseIf (lnCantidad > 6) Then
lnCantidad = 6
End If
lnCantidad = Math.Min(lnCantidad, lnNivelMax)
'Establece las longitudes de todos los niveles
If (lnCantidad < 1) Then
lnTamaño1 = 0
ElseIf (lnTamaño1 <= 0) Then
lnTamaño1 = Math.Max(lnTamaño1, 1)
End If
If (lnCantidad < 2) Then
lnTamaño2 = 0
ElseIf (lnTamaño2 <= 0) Then
lnTamaño2 = Math.Max(lnTamaño2, 1)
End If
lnTamaño2 += lnTamaño1
If (lnCantidad < 3) Then
lnTamaño3 = 0
ElseIf (lnTamaño3 <= 0) Then
lnTamaño3 = Math.Max(lnTamaño3, 1)
End If
lnTamaño3 += lnTamaño2
If (lnCantidad < 4) Then
lnTamaño4 = 0
ElseIf (lnTamaño4 <= 0) Then
lnTamaño4 = Math.Max(lnTamaño4, 1)
End If
lnTamaño4 += lnTamaño3
If (lnCantidad < 5) Then
lnTamaño5 = 0
ElseIf (lnTamaño5 <= 0) Then
lnTamaño5 = Math.Max(lnTamaño5, 1)
End If
lnTamaño5 += lnTamaño4
If (lnCantidad < 6) Then
lnTamaño6 = 0
ElseIf (lnTamaño6 <= 0) Then
lnTamaño6 = Math.Max(lnTamaño6, 1)
End If
lnTamaño6 += lnTamaño5
Select Case lnNivelMax
Case 1
lnLongMax = lnTamaño1
Case 2
lnLongMax = lnTamaño2
Case 3
lnLongMax = lnTamaño3
Case 4
lnLongMax = lnTamaño4
Case 5
lnLongMax = lnTamaño5
Case 6
lnLongMax = lnTamaño6
Case 7 'Mostrar Todos
lnLongMax = lnTamaño6
End Select
loConsulta.AppendLine("")
loConsulta.AppendLine("")
loConsulta.AppendLine("DECLARE @lcActivo VARCHAR(30)")
loConsulta.AppendLine("DECLARE @lcPasivo VARCHAR(30)")
loConsulta.AppendLine("DECLARE @lcCapital VARCHAR(30)")
loConsulta.AppendLine("DECLARE @lnCero DECIMAL(28, 10)")
loConsulta.AppendLine("")
loConsulta.AppendLine("SET @lcActivo = " & lcActivo)
loConsulta.AppendLine("SET @lcPasivo = " & lcPasivo)
loConsulta.AppendLine("SET @lcCapital = " & lcCapital)
loConsulta.AppendLine("SET @lnCero = 0")
loConsulta.AppendLine("")
loConsulta.AppendLine("DECLARE @lnTamaño1 INT; SET @lnTamaño1= " & lnTamaño1.ToString() & ";")
loConsulta.AppendLine("DECLARE @lnTamaño2 INT; SET @lnTamaño2= " & lnTamaño2.ToString() & ";")
loConsulta.AppendLine("DECLARE @lnTamaño3 INT; SET @lnTamaño3= " & lnTamaño3.ToString() & ";")
loConsulta.AppendLine("DECLARE @lnTamaño4 INT; SET @lnTamaño4= " & lnTamaño4.ToString() & ";")
loConsulta.AppendLine("DECLARE @lnTamaño5 INT; SET @lnTamaño5= " & lnTamaño5.ToString() & ";")
loConsulta.AppendLine("DECLARE @lnTamaño6 INT; SET @lnTamaño6= " & lnTamaño6.ToString() & ";")
loConsulta.AppendLine("DECLARE @llUsarTasa BIT; SET @llUsarTasa = 0;")
loConsulta.AppendLine("")
loConsulta.AppendLine("DECLARE @lnNivelMax AS INT;")
loConsulta.AppendLine("SET @lnNivelMax = " & lnNivelMax.ToString())
loConsulta.AppendLine("DECLARE @lnLongMaxima AS INT;")
loConsulta.AppendLine("SET @lnLongMaxima = " & lnLongMax.ToString())
loConsulta.AppendLine("")
loConsulta.AppendLine("")
loConsulta.AppendLine("")
loConsulta.AppendLine("")
loConsulta.AppendLine("SELECT SUBSTRING(CC.Cod_Cue, 1, @lnLongMaxima) AS Cod_Cue,")
loConsulta.AppendLine(" SUBSTRING(CC.Cod_Cue, 1, CASE WHEN (LEN(RTRIM(CC.Cod_Cue))>@lnTamaño1 AND @lnNivelMax > 1) THEN @lnTamaño1 ELSE 0 END) AS Cod_Niv_1,")
loConsulta.AppendLine(" SUBSTRING(CC.Cod_Cue, 1, CASE WHEN (LEN(RTRIM(CC.Cod_Cue))>@lnTamaño2 AND @lnNivelMax > 2) THEN @lnTamaño2 ELSE 0 END) AS Cod_Niv_2,")
loConsulta.AppendLine(" SUBSTRING(CC.Cod_Cue, 1, CASE WHEN (LEN(RTRIM(CC.Cod_Cue))>@lnTamaño3 AND @lnNivelMax > 3) THEN @lnTamaño3 ELSE 0 END) AS Cod_Niv_3,")
loConsulta.AppendLine(" SUBSTRING(CC.Cod_Cue, 1, CASE WHEN (LEN(RTRIM(CC.Cod_Cue))>@lnTamaño4 AND @lnNivelMax > 4) THEN @lnTamaño4 ELSE 0 END) AS Cod_Niv_4,")
loConsulta.AppendLine(" SUBSTRING(CC.Cod_Cue, 1, CASE WHEN (LEN(RTRIM(CC.Cod_Cue))>@lnTamaño5 AND @lnNivelMax > 5) THEN @lnTamaño5 ELSE 0 END) AS Cod_Niv_5,")
loConsulta.AppendLine(" SUBSTRING(CC.Cod_Cue, 1, CASE WHEN (LEN(RTRIM(CC.Cod_Cue))>@lnTamaño6 AND @lnNivelMax > 6) THEN @lnTamaño6 ELSE 0 END) AS Cod_Niv_6,")
loConsulta.AppendLine(" COALESCE(Renglones_Comprobantes.Cod_Cen, '') AS Cod_Cen,")
loConsulta.AppendLine(" SUM(CASE WHEN (Renglones_Comprobantes.Fec_Ini < " & lcFechaDesde & ")")
loConsulta.AppendLine(" THEN COALESCE(Renglones_Comprobantes.Mon_Deb - Renglones_Comprobantes.Mon_Hab, @lnCero)*(CASE WHEN @llUsarTasa=1 THEN COALESCE(Renglones_Comprobantes.Tasa,1) ELSE 1 END)")
loConsulta.AppendLine(" ELSE @lnCero")
loConsulta.AppendLine(" END")
loConsulta.AppendLine(" ) AS saldo,")
loConsulta.AppendLine(" SUM(CASE WHEN (Renglones_Comprobantes.Fec_Ini>=" & lcFechaDesde & " AND Renglones_Comprobantes.Fec_Ini<=" & lcFechaHasta & ")")
loConsulta.AppendLine(" THEN COALESCE(Renglones_Comprobantes.Mon_Deb, @lnCero)*(CASE WHEN @llUsarTasa=1 THEN COALESCE(Renglones_Comprobantes.Tasa,1) ELSE 1 END)")
loConsulta.AppendLine(" ELSE @lnCero")
loConsulta.AppendLine(" END")
loConsulta.AppendLine(" ) AS Debe,")
loConsulta.AppendLine(" SUM(CASE WHEN (Renglones_Comprobantes.Fec_Ini>=" & lcFechaDesde & " AND Renglones_Comprobantes.Fec_Ini<=" & lcFechaHasta & ")")
loConsulta.AppendLine(" THEN COALESCE(Renglones_Comprobantes.Mon_Hab, @lnCero)*(CASE WHEN @llUsarTasa=1 THEN COALESCE(Renglones_Comprobantes.Tasa,1) ELSE 1 END)")
loConsulta.AppendLine(" ELSE @lnCero")
loConsulta.AppendLine(" END")
loConsulta.AppendLine(" ) AS Haber,")
loConsulta.AppendLine(" SUM(CASE WHEN (Renglones_Comprobantes.Fec_Ini>=" & lcFechaDesde & " AND Renglones_Comprobantes.Fec_Ini<=" & lcFechaHasta & ")")
loConsulta.AppendLine(" THEN COALESCE(Renglones_Comprobantes.Mon_Deb - Renglones_Comprobantes.Mon_Hab, @lnCero)*(CASE WHEN @llUsarTasa=1 THEN COALESCE(Renglones_Comprobantes.Tasa,1) ELSE 1 END)")
loConsulta.AppendLine(" ELSE @lnCero")
loConsulta.AppendLine(" END")
loConsulta.AppendLine(" ) AS Monto")
loConsulta.AppendLine("INTO #tmpMovimientos")
loConsulta.AppendLine("FROM Cuentas_Contables AS CC")
loConsulta.AppendLine(" LEFT OUTER JOIN Renglones_Comprobantes ")
loConsulta.AppendLine(" INNER JOIN Comprobantes")
loConsulta.AppendLine(" ON (Renglones_Comprobantes.Adicional = Comprobantes.Adicional ")
loConsulta.AppendLine(" AND Renglones_Comprobantes.Documento = Comprobantes.Documento")
loConsulta.AppendLine(" AND Comprobantes.Tipo = " & lcTipoComprobante & " AND Comprobantes.Status <> 'Anulado'")
loConsulta.AppendLine(" )")
loConsulta.AppendLine(" ON CC.Cod_Cue = Renglones_Comprobantes.Cod_Cue ")
loConsulta.AppendLine(" AND (Renglones_Comprobantes.fec_ini <= " & lcFechaHasta & ")")
loConsulta.AppendLine("WHERE CC.Movimiento=1")
loConsulta.AppendLine(" AND CC.Cod_Cue BETWEEN " & lcCuentaContableDesde & " AND " & lcCuentaContableHasta)
loConsulta.AppendLine(" AND Renglones_Comprobantes.Cod_Cen BETWEEN " & lcCentroCostoDesde & " AND " & lcCentroCostoHasta)
loConsulta.AppendLine(" AND Renglones_Comprobantes.Cod_Gas BETWEEN " & lcCuentaGastoDesde & " AND " & lcCuentaGastoHasta)
loConsulta.AppendLine(" AND Renglones_Comprobantes.Cod_Aux BETWEEN " & lcAuxiliarDesde & " AND " & lcAuxiliarHasta)
loConsulta.AppendLine(" AND Renglones_Comprobantes.Cod_Mon BETWEEN " & lcMonedaDesde & " AND " & lcMonedaHasta)
loConsulta.AppendLine("GROUP BY CC.Cod_Cue, Renglones_Comprobantes.Cod_Cen")
loConsulta.AppendLine("")
If (lcSeparador <> "") Then
Dim lcSeparadorSQL As String = goServicios.mObtenerCampoFormatoSQL("%" & lcSeparador)
loConsulta.AppendLine("")
loConsulta.AppendLine("UPDATE #tmpMovimientos")
loConsulta.AppendLine("SET Cod_Cue = SUBSTRING(Cod_Cue, 1, LEN(Cod_Cue) - 1)")
loConsulta.AppendLine("WHERE COALESCE(Cod_Cue, '') LIKE " & lcSeparadorSQL )
loConsulta.AppendLine("")
loConsulta.AppendLine("UPDATE #tmpMovimientos")
loConsulta.AppendLine("SET Cod_Niv_1 = SUBSTRING(Cod_Niv_1, 1, LEN(Cod_Niv_1) - 1)")
loConsulta.AppendLine("WHERE COALESCE(Cod_Niv_1, '') LIKE " & lcSeparadorSQL )
loConsulta.AppendLine("")
loConsulta.AppendLine("UPDATE #tmpMovimientos ")
loConsulta.AppendLine("SET Cod_Niv_2 = SUBSTRING(Cod_Niv_2, 1, LEN(Cod_Niv_2) - 1)")
loConsulta.AppendLine("WHERE COALESCE(Cod_Niv_2, '') LIKE " & lcSeparadorSQL )
loConsulta.AppendLine("")
loConsulta.AppendLine("UPDATE #tmpMovimientos ")
loConsulta.AppendLine("SET Cod_Niv_3 = SUBSTRING(Cod_Niv_3, 1, LEN(Cod_Niv_3) - 1)")
loConsulta.AppendLine("WHERE COALESCE(Cod_Niv_3, '') LIKE " & lcSeparadorSQL )
loConsulta.AppendLine("")
loConsulta.AppendLine("UPDATE #tmpMovimientos ")
loConsulta.AppendLine("SET Cod_Niv_4 = SUBSTRING(Cod_Niv_4, 1, LEN(Cod_Niv_4) - 1)")
loConsulta.AppendLine("WHERE COALESCE(Cod_Niv_4, '') LIKE " & lcSeparadorSQL )
loConsulta.AppendLine("")
loConsulta.AppendLine("UPDATE #tmpMovimientos ")
loConsulta.AppendLine("SET Cod_Niv_5 = SUBSTRING(Cod_Niv_5, 1, LEN(Cod_Niv_5) - 1)")
loConsulta.AppendLine("WHERE COALESCE(Cod_Niv_5, '') LIKE " & lcSeparadorSQL )
loConsulta.AppendLine("")
loConsulta.AppendLine("UPDATE #tmpMovimientos ")
loConsulta.AppendLine("SET Cod_Niv_6 = SUBSTRING(Cod_Niv_6, 1, LEN(Cod_Niv_6) - 1)")
loConsulta.AppendLine("WHERE COALESCE(Cod_Niv_6, '') LIKE " & lcSeparadorSQL )
loConsulta.AppendLine("")
End If
loConsulta.AppendLine("")
loConsulta.AppendLine("")
loConsulta.AppendLine("SELECT Cuentas_Contables.Cod_Cue AS Cod_Cue,")
loConsulta.AppendLine(" Cuentas_Contables.Nom_Cue AS Nom_Cue,")
loConsulta.AppendLine(" Cuentas_Contables.Movimiento AS Movimiento,")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Cen, ")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_1, ")
loConsulta.AppendLine(" (SELECT TOP 1 Nom_Cue FROM Cuentas_Contables WHERE Cuentas_Contables.Cod_Cue = #tmpMovimientos.Cod_Niv_1) AS Nom_Niv_1,")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_2, ")
loConsulta.AppendLine(" (SELECT TOP 1 Nom_Cue FROM Cuentas_Contables WHERE Cuentas_Contables.Cod_Cue = #tmpMovimientos.Cod_Niv_2) AS Nom_Niv_2,")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_3, ")
loConsulta.AppendLine(" (SELECT TOP 1 Nom_Cue FROM Cuentas_Contables WHERE Cuentas_Contables.Cod_Cue = #tmpMovimientos.Cod_Niv_3) AS Nom_Niv_3,")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_4, ")
loConsulta.AppendLine(" (SELECT TOP 1 Nom_Cue FROM Cuentas_Contables WHERE Cuentas_Contables.Cod_Cue = #tmpMovimientos.Cod_Niv_4) AS Nom_Niv_4,")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_5, ")
loConsulta.AppendLine(" (SELECT TOP 1 Nom_Cue FROM Cuentas_Contables WHERE Cuentas_Contables.Cod_Cue = #tmpMovimientos.Cod_Niv_5) AS Nom_Niv_5,")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_6, (")
loConsulta.AppendLine(" SELECT TOP 1 Nom_Cue FROM Cuentas_Contables WHERE Cuentas_Contables.Cod_Cue = #tmpMovimientos.Cod_Niv_6) AS Nom_Niv_6,")
loConsulta.AppendLine(" SUM(#tmpMovimientos.Saldo) AS Saldo_Inicial,")
loConsulta.AppendLine(" SUM(#tmpMovimientos.Debe) AS Debe,")
loConsulta.AppendLine(" SUM(#tmpMovimientos.Haber) AS Haber,")
loConsulta.AppendLine(" SUM(#tmpMovimientos.Monto + #tmpMovimientos.Saldo) AS Saldo_Actual")
loConsulta.AppendLine("FROM #tmpMovimientos")
loConsulta.AppendLine(" JOIN Cuentas_Contables")
loConsulta.AppendLine(" ON Cuentas_Contables.Cod_Cue = #tmpMovimientos.Cod_Cue")
loConsulta.AppendLine("WHERE ( NOT Cuentas_Contables.Cod_Cue LIKE @lcActivo ")
loConsulta.AppendLine(" AND NOT Cuentas_Contables.Cod_Cue LIKE @lcPasivo ")
loConsulta.AppendLine(" AND NOT Cuentas_Contables.Cod_Cue LIKE @lcCapital ")
loConsulta.AppendLine(" )")
loConsulta.AppendLine("GROUP BY Cuentas_Contables.Cod_Cue, ")
loConsulta.AppendLine(" Cuentas_Contables.Nom_Cue, ")
loConsulta.AppendLine(" Cuentas_Contables.Movimiento,")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Cen, ")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_1, ")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_2, ")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_3,")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_4, ")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_5, ")
loConsulta.AppendLine(" #tmpMovimientos.Cod_Niv_6")
If llSoloMovimientos Then
loConsulta.AppendLine("HAVING ABS(SUM(#tmpMovimientos.Saldo)) + ABS(SUM(#tmpMovimientos.Debe)) + ABS(SUM(#tmpMovimientos.Haber)) > 0")
End If
loConsulta.AppendLine("ORDER BY " & lcOrdenamiento)
loConsulta.AppendLine("")
loConsulta.AppendLine("DROP TABLE #tmpMovimientos")
loConsulta.AppendLine("")
loConsulta.AppendLine("")
loConsulta.AppendLine("")
'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.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("rEGanancias_Perdidas_xCentroCostos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrEGanancias_Perdidas_xCentroCostos.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' RJG: 26/10/11: Codigo inicial, a partir de rEGanancias_Perdidas.'
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
Reportes - Contabilidad/rEGanancias_Perdidas_xCentroCostos.aspx.vb
|
Visual Basic
|
mit
| 20,089
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fProforma_Invoice_OnyxTD"
'-------------------------------------------------------------------------------------------'
Partial Class fProforma_Invoice_OnyxTD
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 Cotizaciones.Cod_Cli, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Cotizaciones.Nom_Cli = '') THEN Clientes.Nom_Cli ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Cotizaciones.Nom_Cli = '') THEN Clientes.Nom_Cli ELSE Cotizaciones.Nom_Cli END) END) AS Nom_Cli, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Cotizaciones.Nom_Cli = '') THEN Clientes.Rif ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Cotizaciones.Rif = '') THEN Clientes.Rif ELSE Cotizaciones.Rif END) END) AS Rif, ")
loComandoSeleccionar.AppendLine(" Clientes.Nit, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Cotizaciones.Nom_Cli = '') THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (SUBSTRING(Cotizaciones.Dir_Fis,1, 200) = '') THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE SUBSTRING(Cotizaciones.Dir_Fis,1, 200) END) END) AS Dir_Fis, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Cotizaciones.Nom_Cli = '') THEN Clientes.Telefonos ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Cotizaciones.Telefonos = '') THEN Clientes.Telefonos ELSE Cotizaciones.Telefonos END) END) AS Telefonos, ")
loComandoSeleccionar.AppendLine(" Clientes.Fax, ")
loComandoSeleccionar.AppendLine(" Clientes.Generico, ")
loComandoSeleccionar.AppendLine(" Clientes.Dir_Ent, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Nom_Cli As Nom_Gen, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Rif As Rif_Gen, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Nit As Nit_Gen, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Dir_Fis As Dir_Gen, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Telefonos As Tel_Gen, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Documento, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Fec_Fin, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Mon_Bru, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Mon_Imp1, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Por_Imp1, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Mon_Net, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Por_Des1, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Mon_Des1 As Mon_Des, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Por_Rec1, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Mon_Rec1 AS Mon_Rec, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_For AS Cod_For, ")
loComandoSeleccionar.AppendLine(" SUBSTRING(Formas_Pagos.Nom_For,1,25) AS Nom_For, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Comentario, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Notas, ")
loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_Tra, ")
loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven, ")
loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Cod_Art, ")
loComandoSeleccionar.AppendLine(" CASE WHEN Articulos.Generico = 0 THEN Articulos.Nom_Art ")
loComandoSeleccionar.AppendLine(" ELSE Renglones_Cotizaciones.Notas END AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Renglon, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Renglones_Cotizaciones.Cod_Uni2='') THEN Renglones_Cotizaciones.Can_Art1")
loComandoSeleccionar.AppendLine(" ELSE Renglones_Cotizaciones.Can_Art2 END) AS Can_Art1, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Renglones_Cotizaciones.Cod_Uni2='') THEN Renglones_Cotizaciones.Cod_Uni")
loComandoSeleccionar.AppendLine(" ELSE Renglones_Cotizaciones.Cod_Uni2 END) AS Cod_Uni, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Renglones_Cotizaciones.Cod_Uni2='') THEN Renglones_Cotizaciones.Precio1")
loComandoSeleccionar.AppendLine(" ELSE Renglones_Cotizaciones.Precio1*Renglones_Cotizaciones.Can_Uni2 END) AS Precio1, ")
loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Mon_Net As Neto, ")
loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Por_Imp1 As Por_Imp, ")
loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Cod_Imp, ")
loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Mon_Imp1 As Impuesto, ")
loComandoSeleccionar.AppendLine(" RTRIM(LTRIM(Articulos.Garantia)) As Garantia,")
'loComandoSeleccionar.AppendLine(" Articulos.Peso, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Renglones_Cotizaciones.Cod_Uni2='') THEN (Renglones_Cotizaciones.Can_Art1 * Articulos.Peso) ")
loComandoSeleccionar.AppendLine(" ELSE (Renglones_Cotizaciones.Can_Art2 * Articulos.Peso) END) AS Peso, ")
'loComandoSeleccionar.AppendLine(" Articulos.Volumen, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Renglones_Cotizaciones.Cod_Uni2='') THEN (Renglones_Cotizaciones.Can_Art1 * Articulos.Volumen) ")
loComandoSeleccionar.AppendLine(" ELSE (Renglones_Cotizaciones.Can_Art2 * Articulos.Volumen) END) AS Volumen, ")
loComandoSeleccionar.AppendLine(" Articulos.Cod_Ubi, ")
loComandoSeleccionar.AppendLine(" Transportes.Nom_Tra, ")
loComandoSeleccionar.AppendLine(" Clientes.Cod_Pai, ")
loComandoSeleccionar.AppendLine(" Paises.Nom_Pai, ")
loComandoSeleccionar.AppendLine(" Clientes.Cod_Est, ")
loComandoSeleccionar.AppendLine(" Estados.Nom_Est, ")
loComandoSeleccionar.AppendLine(" Clientes.Cod_Ciu, ")
loComandoSeleccionar.AppendLine(" Ciudades.Nom_Ciu, ")
loComandoSeleccionar.AppendLine(" Clientes.Contacto, ")
loComandoSeleccionar.AppendLine(" Clientes.Correo ")
loComandoSeleccionar.AppendLine(" FROM Cotizaciones, ")
loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones, ")
loComandoSeleccionar.AppendLine(" Clientes, ")
loComandoSeleccionar.AppendLine(" Formas_Pagos, ")
loComandoSeleccionar.AppendLine(" Vendedores, ")
loComandoSeleccionar.AppendLine(" Articulos, ")
loComandoSeleccionar.AppendLine(" Transportes, ")
loComandoSeleccionar.AppendLine(" Paises, ")
loComandoSeleccionar.AppendLine(" Estados, ")
loComandoSeleccionar.AppendLine(" Ciudades ")
loComandoSeleccionar.AppendLine(" WHERE Cotizaciones.Documento = Renglones_Cotizaciones.Documento ")
loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Cli = Clientes.Cod_Cli ")
loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_For = Formas_Pagos.Cod_For ")
loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Ven = Vendedores.Cod_Ven ")
loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Tra = Transportes.Cod_Tra ")
loComandoSeleccionar.AppendLine(" AND Paises.Cod_Pai = Clientes.Cod_Pai ")
loComandoSeleccionar.AppendLine(" AND Estados.Cod_Est = Clientes.Cod_Est ")
loComandoSeleccionar.AppendLine(" AND Ciudades.Cod_Ciu = Clientes.Cod_Ciu ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Cotizaciones.Cod_Art AND " & cusAplicacion.goFormatos.pcCondicionPrincipal)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(loComandoSeleccionar.ToString, "curReportes")
'--------------------------------------------------'
' Carga la imagen del logo en cusReportes '
'--------------------------------------------------'
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fProforma_Invoice_OnyxTD", laDatosReporte)
loObjetoReporte.SetParameterValue("Leyenda_Cotizaciones_Tipo1", goOpciones.mObtener("LEYCOTVEN1", "M"))
loObjetoReporte.SetParameterValue("Leyenda_Cotizaciones_Tipo2", goOpciones.mObtener("LEYCOTVEN2", "M"))
loObjetoReporte.SetParameterValue("Leyenda_Cotizaciones_Tipo3", goOpciones.mObtener("LEYCOTVEN3", "M"))
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfProforma_Invoice_OnyxTD.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal1.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' MAT: 09/03/11: Codigo inicial
'-------------------------------------------------------------------------------------------'
' MAT: 14/03/11: Corrección de las unidades del reporte según requerimientos
'-------------------------------------------------------------------------------------------'
' MAT: 05/09/11: Creación de los parámetros para las leyendas en el formato
'-------------------------------------------------------------------------------------------'
' JFP: 09/10/12: Adecuacion a OnyxTD
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
fProforma_Invoice_OnyxTD.aspx.vb
|
Visual Basic
|
mit
| 12,315
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
Imports Microsoft.CodeAnalysis.PickMembers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateConstructorFromMembers
Public Class GenerateEqualsAndGetHashCodeFromMembersTests
Inherits AbstractVisualBasicCodeActionTest
Private Const GenerateOperatorsId = GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId
Private Const ImplementIEquatableId = GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider(
DirectCast(parameters.fixProviderData, IPickMembersService))
End Function
<WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestEqualsOnSingleField() As Task
Await TestInRegularAndScriptAsync(
"Class Z
[|Private a As Integer|]
End Class",
"Class Z
Private a As Integer
Public Overrides Function Equals(obj As Object) As Boolean
Dim z = TryCast(obj, Z)
Return z IsNot Nothing AndAlso
a = z.a
End Function
End Class",
ignoreTrivia:=False)
End Function
<WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestGetHashCodeOnSingleField() As Task
Await TestInRegularAndScriptAsync(
"Class Z
[|Private a As Integer|]
End Class",
"Class Z
Private a As Integer
Public Overrides Function Equals(obj As Object) As Boolean
Dim z = TryCast(obj, Z)
Return z IsNot Nothing AndAlso
a = z.a
End Function
Public Overrides Function GetHashCode() As Integer
Return -1757793268 + a.GetHashCode()
End Function
End Class",
index:=1)
End Function
<WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestBothOnSingleField() As Task
Await TestInRegularAndScriptAsync(
"Class Z
[|Private a As Integer|]
End Class",
"Class Z
Private a As Integer
Public Overrides Function Equals(obj As Object) As Boolean
Dim z = TryCast(obj, Z)
Return z IsNot Nothing AndAlso
a = z.a
End Function
Public Overrides Function GetHashCode() As Integer
Return -1757793268 + a.GetHashCode()
End Function
End Class",
index:=1, ignoreTrivia:=False)
End Function
<WorkItem(545205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545205")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestTypeWithNumberInName() As Task
Await TestInRegularAndScriptAsync(
"Partial Class c1(Of V As {New}, U)
[|Dim x As New V|]
End Class",
"Imports System.Collections.Generic
Partial Class c1(Of V As {New}, U)
Dim x As New V
Public Overrides Function Equals(obj As Object) As Boolean
Dim c = TryCast(obj, c1(Of V, U))
Return c IsNot Nothing AndAlso
EqualityComparer(Of V).Default.Equals(x, c.x)
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestGenerateOperators1() As Task
Await TestWithPickMembersDialogAsync(
"
Imports System.Collections.Generic
Class Program
Public s As String
[||]
End Class",
"
Imports System.Collections.Generic
Class Program
Public s As String
Public Overrides Function Equals(obj As Object) As Boolean
Dim program = TryCast(obj, Program)
Return program IsNot Nothing AndAlso
s = program.s
End Function
Public Shared Operator =(program1 As Program, program2 As Program) As Boolean
Return EqualityComparer(Of Program).Default.Equals(program1, program2)
End Operator
Public Shared Operator <>(program1 As Program, program2 As Program) As Boolean
Return Not program1 = program2
End Operator
End Class",
chosenSymbols:=Nothing,
optionsCallback:=Sub(options) EnableOption(options, GenerateOperatorsId))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestGenerateOperators3() As Task
Await TestWithPickMembersDialogAsync(
"
Imports System.Collections.Generic
Class Program
Public s As String
[||]
Public Shared Operator =(program1 As Program, program2 As Program) As Boolean
Return True
End Operator
End Class",
"
Imports System.Collections.Generic
Class Program
Public s As String
Public Overrides Function Equals(obj As Object) As Boolean
Dim program = TryCast(obj, Program)
Return program IsNot Nothing AndAlso
s = program.s
End Function
Public Shared Operator =(program1 As Program, program2 As Program) As Boolean
Return True
End Operator
End Class",
chosenSymbols:=Nothing,
optionsCallback:=Sub(Options) Assert.Null(Options.FirstOrDefault(Function(o) o.Id = GenerateOperatorsId)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestGenerateOperators4() As Task
Await TestWithPickMembersDialogAsync(
"
Imports System.Collections.Generic
Structure Program
Public s As String
[||]
End Structure",
"
Imports System.Collections.Generic
Structure Program
Public s As String
Public Overrides Function Equals(obj As Object) As Boolean
If Not (TypeOf obj Is Program) Then
Return False
End If
Dim program = DirectCast(obj, Program)
Return s = program.s
End Function
Public Shared Operator =(program1 As Program, program2 As Program) As Boolean
Return program1.Equals(program2)
End Operator
Public Shared Operator <>(program1 As Program, program2 As Program) As Boolean
Return Not program1 = program2
End Operator
End Structure",
chosenSymbols:=Nothing,
optionsCallback:=Sub(options) EnableOption(options, GenerateOperatorsId),
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestImplementIEquatable1() As Task
Await TestWithPickMembersDialogAsync(
"
Imports System.Collections.Generic
structure Program
Public s As String
[||]
End structure",
"
Imports System
Imports System.Collections.Generic
structure Program
Implements IEquatable(Of Program)
Public s As String
Public Overrides Function Equals(obj As Object) As Boolean
Return (TypeOf obj Is Program) AndAlso Equals(DirectCast(obj, Program))
End Function
Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals
Return s = other.s
End Function
End structure",
chosenSymbols:=Nothing,
optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId),
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestImplementIEquatable2() As Task
Await TestWithPickMembersDialogAsync(
"
Imports System.Collections.Generic
Class Program
Public s As String
[||]
End Class",
"
Imports System
Imports System.Collections.Generic
Class Program
Implements IEquatable(Of Program)
Public s As String
Public Overrides Function Equals(obj As Object) As Boolean
Return Equals(TryCast(obj, Program))
End Function
Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals
Return other IsNot Nothing AndAlso
s = other.s
End Function
End Class",
chosenSymbols:=Nothing,
optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId),
ignoreTrivia:=False)
End Function
End Class
End Namespace
|
kelltrick/roslyn
|
src/EditorFeatures/VisualBasicTest/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.vb
|
Visual Basic
|
apache-2.0
| 8,912
|
' 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.Reflection.Metadata
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Roslyn.Test.Utilities
Imports Xunit
Imports Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class WinMdTests
Inherits ExpressionCompilerTestBase
''' <summary>
''' Handle runtime assemblies rather than Windows.winmd
''' (compile-time assembly) since those are the assemblies
''' loaded in the debuggee.
''' </summary>
<WorkItem(981104)>
<ConditionalFact(GetType(OSVersionWin8))>
Public Sub Win8RuntimeAssemblies()
Const source =
"Class C
Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, compOptions:=TestOptions.DebugDll, references:=WinRtRefs)
Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")
Assert.True(runtimeAssemblies.Length >= 2)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), ' no reference to Windows.winmd
exeBytes,
New SymReader(pdbBytes))
Dim context = CreateMethodContext(runtime, "C.M")
Dim resultProperties As ResultProperties = Nothing
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(p Is Nothing, f, Nothing)", resultProperties, errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldnull
IL_0004: ret
IL_0005: ldarg.0
IL_0006: ret
}")
End Sub
<Fact>
Public Sub Win8OnWin8()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage")
End Sub
<Fact>
Public Sub Win8OnWin10()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage")
End Sub
<Fact>
Public Sub Win10OnWin10()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows")
End Sub
Private Sub CompileTimeAndRuntimeAssemblies(
compileReferences As ImmutableArray(Of MetadataReference),
runtimeReferences As ImmutableArray(Of MetadataReference),
storageAssemblyName As String)
Const source =
"Class C
Shared Sub M(a As LibraryA.A, b As LibraryB.B, t As Windows.Data.Text.TextSegment, f As Windows.Storage.StorageFolder)
End Sub
End Class"
Dim runtime = CreateRuntime(source, compileReferences, runtimeReferences)
Dim context = CreateMethodContext(runtime, "C.M")
Dim resultProperties As ResultProperties = Nothing
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(a, If(b, If(t, f)))", resultProperties, errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldarg.1
IL_0006: dup
IL_0007: brtrue.s IL_0010
IL_0009: pop
IL_000a: ldarg.2
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldarg.3
IL_0010: ret
}")
testData = New CompilationTestData()
Dim result = context.CompileExpression("f", resultProperties, errorMessage, testData)
Assert.Null(errorMessage)
Dim methodData = testData.GetMethodData("<>x.<>m0")
methodData.VerifyIL(
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.3
IL_0001: ret
}")
' Check return type is from runtime assembly.
Dim assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference()
Dim comp = VisualBasicCompilation.Create(
assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName(),
references:=runtimeReferences.Concat(ImmutableArray.Create(Of MetadataReference)(assemblyReference)))
Dim assembly = ImmutableArray.CreateRange(result.Assembly)
Using metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))
Dim reader = metadata.MetadataReader
Dim typeDef = reader.GetTypeDef("<>x")
Dim methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0")
Dim [module] = DirectCast(comp.GetMember("<>x").ContainingModule, PEModuleSymbol)
Dim metadataDecoder = New MetadataDecoder([module])
Dim signatureHeader As SignatureHeader = Nothing
Dim metadataException As BadImageFormatException = Nothing
Dim parameters = metadataDecoder.GetSignatureForMethod(methodHandle, signatureHeader, metadataException)
Assert.Equal(parameters.Length, 5)
Dim actualReturnType = parameters(0).Type
Assert.Equal(actualReturnType.TypeKind, TypeKind.Class) ' not error
Dim expectedReturnType = comp.GetMember("Windows.Storage.StorageFolder")
Assert.Equal(expectedReturnType, actualReturnType)
Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name)
End Using
End Sub
''' <summary>
''' Assembly-qualified name containing "ContentType=WindowsRuntime",
''' and referencing runtime assembly.
''' </summary>
<WorkItem(1116143)>
<ConditionalFact(GetType(OSVersionWin8))>
Public Sub AssemblyQualifiedName()
Const source =
"Class C
Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet)
End Sub
End Class"
Dim runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")))
Dim context = CreateMethodContext(runtime, "C.M")
Dim resultProperties As ResultProperties = Nothing
Dim errorMessage As String = Nothing
Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
InspectionContextFactory.Empty.
Add("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime").
Add("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
"If(DirectCast(s.Attributes, Object), d.UniversalTime)",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
resultProperties,
errorMessage,
missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData)
Assert.Empty(missingAssemblyIdentities)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Function Windows.Storage.StorageFolder.get_Attributes() As Windows.Storage.FileAttributes""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""Windows.Foundation.DateTime.UniversalTime As Long""
IL_0031: box ""Long""
IL_0036: ret
}")
End Sub
Private Function CreateRuntime(
source As String,
compileReferences As ImmutableArray(Of MetadataReference),
runtimeReferences As ImmutableArray(Of MetadataReference)) As RuntimeInstance
Dim comp = CreateCompilationWithMscorlib(
{source},
compOptions:=TestOptions.DebugDll,
assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName(),
references:=compileReferences)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Return CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
runtimeReferences.AddIntrinsicAssembly(),
exeBytes,
New SymReader(pdbBytes))
End Function
Private Shared Function ToVersion1_3(bytes As Byte()) As Byte()
Return ExpressionCompilerTestHelpers.ToVersion1_3(bytes)
End Function
Private Shared Function ToVersion1_4(bytes As Byte()) As Byte()
Return ExpressionCompilerTestHelpers.ToVersion1_4(bytes)
End Function
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/WinMdTests.vb
|
Visual Basic
|
apache-2.0
| 12,899
|
Imports System.Data
Imports bv.common.Enums
Public Class CaseSamples_Db
Inherits BaseDbService
Public Sub New()
ObjectName = "CaseSamples"
End Sub
Public Const TableSamples As String = "CaseSamples"
Public Const TableCaseActivity As String = "CaseActivity"
Public Const TableSamplesToCollect As String = "SamplesToCollect"
Public Const TableVectorSamplesToCollect As String = "VectorSamplesToCollect"
Public Const TableFiltered As String = "FilteredByDisease"
Public Overrides Function GetDetail(ByVal ID As Object) As DataSet
If ID Is Nothing Then
Return New DataSet
End If
Dim ds As New DataSet
Try
Dim cmd As IDbCommand
' SELECT
cmd = CreateSPCommand("spCaseSamples_SelectDetail")
AddParam(cmd, "@idfCase", ID)
AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage)
FillDataset(cmd, ds, TableSamples)
CorrectTable(ds.Tables(0), TableSamples)
CorrectTable(ds.Tables(1), TableCaseActivity)
CorrectTable(ds.Tables(2), TableSamplesToCollect)
CorrectTable(ds.Tables(3), TableVectorSamplesToCollect)
ClearColumnsAttibutes(ds)
'TimeUtils.UTC2Local(ds.Tables(TableSamples), "datAccession")
Dim t As DataTable = ds.Tables(TableCaseActivity)
If (t.Rows.Count = 0) Then
Dim cs As DataRow = t.NewRow()
cs("idfVetCase") = ID
t.Rows.Add(cs)
End If
ds.EnforceConstraints = False
m_ID = ID
Return ds
Catch ex As Exception
m_Error = New ErrorMessage(StandardError.FillDatasetError, ex)
Return Nothing
End Try
End Function
Private Sub ModifyCase(ByVal ds As DataSet, Optional ByVal transaction As IDbTransaction = Nothing)
' when creating epi/cs for vet case, ds.Tables(TableCaseActivity) sometimes doesn't has any row
' Note: Dirty fix.
If (ds.Tables.Contains(TableCaseActivity) = False) Then Exit Sub
If ds.HasChanges() Then
Dim row As DataRow = ds.Tables(TableCaseActivity).Rows(0)
Dim command As IDbCommand = CreateSPCommand("spLabSampleReceive_ModifyCase", Connection, transaction)
AddParam(command, "@idfCase", ID, ParameterDirection.Input)
AddParam(command, "@strSampleNotes", row("strSampleNotes"), ParameterDirection.Input)
ExecCommand(command, command.Connection, transaction, True)
End If
End Sub
Public Overrides Function PostDetail(ByVal ds As DataSet, ByVal postType As Integer, Optional ByVal transaction As IDbTransaction = Nothing) As Boolean
If ds Is Nothing OrElse ds.Tables.Count = 0 Then Return True
If IgnoreChanges Then Return True
Try
'ExecPostProcedure("spCaseSamples_Post", ds.Tables(TableSamples), Connection, transaction)
For Each row As DataRow In ds.Tables(TableSamples).Rows
If row.RowState = DataRowState.Added Then
Dim cmd As IDbCommand = CreateSPCommand("spLabSample_Create", Connection, transaction)
'AddTypedParam(cmd1, "@Action", SqlDbType.Int)
'AddParam(cmd, "@idfCase", m_ID)
If (row("idfMaterial") Is DBNull.Value) Then
AddTypedParam(cmd, "@idfMaterial", SqlDbType.BigInt, ParameterDirection.InputOutput)
Else
AddParam(cmd, "@idfMaterial", row("idfMaterial"), ParameterDirection.InputOutput)
End If
AddParam(cmd, "@strFieldBarcode", row("strFieldBarcode"))
AddParam(cmd, "@idfsSampleType", row("idfsSampleType"))
AddParam(cmd, "@idfParty", row("idfParty"))
AddParam(cmd, "@idfCase", row("idfCase"))
AddParam(cmd, "@idfMonitoringSession", row("idfMonitoringSession"))
AddParam(cmd, "@idfVectorSurveillanceSession", row("idfVectorSurveillanceSession"))
AddParam(cmd, "@datFieldCollectionDate", row("datFieldCollectionDate"))
AddParam(cmd, "@datFieldSentDate", row("datFieldSentDate"))
AddParam(cmd, "@idfFieldCollectedByOffice", row("idfFieldCollectedByOffice"))
AddParam(cmd, "@idfFieldCollectedByPerson", row("idfFieldCollectedByPerson"))
AddParam(cmd, "@idfMainTest", row("idfMainTest"))
AddParam(cmd, "@idfSendToOffice", row("idfSendToOffice"))
If (row.Table.Columns.Contains("idfsBirdStatus")) Then
AddParam(cmd, "@idfsBirdStatus", row("idfsBirdStatus"))
Else
AddTypedParam(cmd, "@idfsBirdStatus", SqlDbType.BigInt)
End If
ExecCommand(cmd, cmd.Connection, transaction, True)
Dim idfMaterial As Object = GetParamValue(cmd, "@idfMaterial")
If Not row("idfMaterial").Equals(idfMaterial) Then
row("idfMaterial") = idfMaterial
End If
ElseIf row.RowState = DataRowState.Modified Then
Dim cmd As IDbCommand = CreateSPCommand("spLabSample_Update", Connection, transaction)
AddParam(cmd, "@idfMaterial", row("idfMaterial"))
AddParam(cmd, "@strFieldBarcode", row("strFieldBarcode"))
AddParam(cmd, "@idfsSampleType", row("idfsSampleType"))
AddParam(cmd, "@idfParty", row("idfParty"))
AddParam(cmd, "@datFieldCollectionDate", row("datFieldCollectionDate"))
AddParam(cmd, "@datFieldSentDate", row("datFieldSentDate"))
AddParam(cmd, "@idfFieldCollectedByOffice", row("idfFieldCollectedByOffice"))
AddParam(cmd, "@idfFieldCollectedByPerson", row("idfFieldCollectedByPerson"))
AddParam(cmd, "@idfMainTest", row("idfMainTest"))
AddParam(cmd, "@idfSendToOffice", row("idfSendToOffice"))
If (row.Table.Columns.Contains("idfsBirdStatus")) Then
AddParam(cmd, "@idfsBirdStatus", row("idfsBirdStatus"))
Else
AddTypedParam(cmd, "@idfsBirdStatus", SqlDbType.BigInt)
End If
ExecCommand(cmd, cmd.Connection, transaction, True)
ElseIf row.RowState = DataRowState.Deleted Then
Dim cmd As IDbCommand = CreateSPCommand("spLabSample_Delete", Connection, transaction)
AddParam(cmd, "@idfMaterial", row("idfMaterial", DataRowVersion.Original))
ExecCommand(cmd, cmd.Connection, transaction, True)
End If
Next
ModifyCase(ds, transaction)
Catch ex As Exception
m_Error = New ErrorMessage(StandardError.PostError, ex)
Return False
Finally
'DbDisposeHelper.DisposeDataset(dsCopy)
'SetReadonlyState(ds, False)
End Try
Return True
End Function
Public Function CreateSample(ByVal ds As DataSet, Optional ByVal partyID As Object = Nothing, Optional ByVal sourceRow As DataRow = Nothing, Optional materialID As Object = Nothing) As DataRow
Dim materialRow As DataRow = ds.Tables(TableSamples).NewRow()
InitNewRow(materialRow, partyID, sourceRow, materialID)
ds.EnforceConstraints = False
ds.Tables(TableSamples).Rows.Add(materialRow)
Return materialRow
End Function
Public Overridable Sub LinkSample(row As DataRow, parentID As Object)
row("idfCase") = parentID
End Sub
Public Sub DeleteSample(ByVal ds As DataSet, ByVal sampleID As Object)
' Delete Material Row
Dim row As DataRow = ds.Tables(TableSamples).Rows.Find(sampleID)
If Not row Is Nothing Then
row.Delete()
End If
End Sub
Public Sub DeletePartySamples(ByVal ds As DataSet, ByVal partyID As Object)
Dim partyLinkView As DataView = New DataView(ds.Tables(TableSamples))
partyLinkView.RowFilter = String.Format("idfParty='{0}'", partyID.ToString)
For Each row As DataRowView In partyLinkView
DeleteSample(ds, row.Row("idfMaterial"))
Next
End Sub
Public Function CanDeleteSample(ByVal row As DataRow) As Boolean
If row.RowState <> DataRowState.Added AndAlso Utils.Str(row("Used")) = "1" Then
Return False
End If
End Function
Public Shared Function CheckAccessIn(ByVal materialId As Long) As Boolean
Dim value As Object
Dim errMsg As ErrorMessage = Nothing
Dim cmd As IDbCommand = CreateSPCommand("spLabSample_CheckAccession", ConnectionManager.DefaultInstance.Connection)
AddParam(cmd, "@idfMaterial", materialId, ParameterDirection.Input)
value = ExecScalar(cmd, cmd.Connection, errMsg)
If (Utils.IsEmpty(value)) Then
'can delete
Return True
Else
'cannot delete
Return False
End If
End Function
Public Shared Function CheckAccessionForSpecies(ByVal speciesId As Long) As Boolean
Dim value As Object
Dim errMsg As ErrorMessage = Nothing
Dim cmd As IDbCommand = CreateSPCommand("spLabSample_CheckAccessionForSpecies", ConnectionManager.DefaultInstance.Connection)
AddParam(cmd, "@idfSpecies", speciesId, ParameterDirection.Input)
value = ExecScalar(cmd, cmd.Connection, errMsg)
If Not Utils.IsEmpty(value) AndAlso CLng(value) = 1 Then
'cannot delete
Return False
Else
'can delete
Return True
End If
End Function
Public Function GetFilteredCase(ByVal speciesType As Long) As DataTable
Dim cmd As IDbCommand = CreateSPCommand("spLabSample_SampleTypeFilter", ConnectionManager.DefaultInstance.Connection)
AddParam(cmd, "@idfCase", ID)
AddParam(cmd, "@idfsSpeciesType", speciesType)
Try
Return ExecTable(cmd)
Catch ex As Exception
Dbg.Debug("spLabSample_SampleTypeFilter error: {0}", ex)
Return Nothing
End Try
End Function
Public Sub InitNewRow(ByVal materialRow As DataRow, partyID As Object, sourceRow As DataRow, Optional materialID As Object = Nothing)
If materialID Is Nothing Then
materialRow("idfMaterial") = NewIntID()
Else
materialRow("idfMaterial") = materialID
End If
LinkSample(materialRow, ID)
Dim collectionDate As Object = DBNull.Value
If (Not sourceRow Is Nothing) Then
collectionDate = sourceRow("datFieldCollectionDate")
materialRow("idfSendToOffice") = sourceRow("idfSendToOffice")
materialRow("idfFieldCollectedByPerson") = sourceRow("idfFieldCollectedByPerson")
materialRow("idfFieldCollectedByOffice") = sourceRow("idfFieldCollectedByOffice")
End If
If Utils.IsEmpty(collectionDate) Then
collectionDate = DateTime.Now.Date
End If
materialRow("datFieldCollectionDate") = collectionDate
If Not Utils.IsEmpty(partyID) Then materialRow("idfParty") = partyID
End Sub
Public Shared Sub PrepareFilteredSamples(diagnosisList() As Long, ds As DataSet, samplesList As DataView)
If diagnosisList Is Nothing OrElse diagnosisList.Length = 0 Then
If ds.Tables.Contains(TableFiltered) Then
ds.Tables.Remove(TableFiltered)
End If
Exit Sub
End If
Dim ref As DataTable = samplesList.Table
Dim table As DataTable
If ds.Tables.Contains(TableFiltered) Then
table = ds.Tables(TableFiltered)
table.Rows.Clear()
Else
table = ref.Clone()
table.TableName = TableFiltered
ds.Tables.Add(table)
End If
Dim filter As String = ""
For Each diag As Long In diagnosisList
If filter.Length > 0 Then filter = filter + " OR "
filter = filter + "idfsDiagnosis=" + diag.ToString()
Next
Dim view As DataView = New DataView(ds.Tables(TableSamplesToCollect))
view.RowFilter = filter
view.Sort = "idfsReference"
For Each row As DataRow In ref.Rows
If view.FindRows(row("idfsReference")).Length > 0 Then
table.Rows.Add(row.ItemArray)
End If
Next
table.AcceptChanges()
End Sub
End Class
|
EIDSS/EIDSS-Legacy
|
EIDSS v6.1/vb/EIDSS/EIDSS_Common_Db/CasePanels/CaseSamples_Db.vb
|
Visual Basic
|
bsd-2-clause
| 13,124
|
Imports Launcher.My
Imports Launcher.My.Resources
Namespace Forms
Public Class FrmOptions
Private Sub chkCheckUpdates_CheckedChanged(sender As Object, e As EventArgs) Handles chkCheckUpdates.CheckedChanged
chkInstallUpdates.Enabled = chkCheckUpdates.Checked
End Sub
Private Sub chkSaveOutput_CheckedChanged(sender As Object, e As EventArgs) Handles chkSaveOutput.CheckedChanged
'Enable and disable the Output Path field if needed
tbOutputPath.Enabled = chkSaveOutput.Checked
cmdOutputPath.Enabled = chkSaveOutput.Checked
End Sub
Private Sub cmdCancel_Click(sender As Object, e As EventArgs) Handles cmdCancel.Click
Close()
End Sub
Private Sub cmdGamePath_Click(sender As Object, e As EventArgs) Handles cmdGamePath.Click
FBD.SelectedPath = tbGamePath.Text
If FBD.ShowDialog() = Windows.Forms.DialogResult.OK Then
tbGamePath.Text = FBD.SelectedPath
End If
End Sub
Private Sub cmdOk_Click(sender As Object, e As EventArgs) Handles cmdOk.Click
'Save OpenRCT2 config when changed
If configHasChangedGame() Then
GameConfig.values = toGameConfigValues()
End If
'Save Launcher config when changed
If configHasChangedLauncher() Then
configSaveLauncher()
End If
'Check for an update
Call frmLauncher.GameUpdate(False)
Close()
End Sub
Private Sub cmdOutputPath_Click(sender As Object, e As EventArgs) Handles cmdOutputPath.Click
SFD.FileName = tbOutputPath.Text
If SFD.ShowDialog() = Windows.Forms.DialogResult.OK Then
tbOutputPath.Text = SFD.FileName
End If
End Sub
Private Sub cmdReset_Click(sender As Object, e As EventArgs) Handles cmdReset.Click
fromGameConfigValues(New GameConfigValues(GameConfigValues.Constructor.DefaultValues))
chkVerbose.Checked = My.Settings.PropertyValues("Verbose").Property.DefaultValue
tbArguments.Text = My.Settings.PropertyValues("Arguments").Property.DefaultValue
chkSaveOutput.Checked = My.Settings.PropertyValues("SaveOutput").Property.DefaultValue
tbOutputPath.Text = My.Settings.PropertyValues("OutputPath").Property.DefaultValue
chkCheckUpdates.Checked = My.Settings.PropertyValues("CheckUpdates").Property.DefaultValue
chkInstallUpdates.Checked = My.Settings.PropertyValues("InstallUpdates").Property.DefaultValue
rdoDevelop.Checked = False
rdoStable.Checked = True
tbOutputPath.Enabled = chkSaveOutput.Checked
cmdOutputPath.Enabled = chkSaveOutput.Checked
chkInstallUpdates.Enabled = chkCheckUpdates.Checked
End Sub
Private Function configHasChangedGame() As Boolean
Return Not toGameConfigValues().Equals(GameConfig.values)
End Function
Private Function configHasChangedLauncher() As Boolean
'Compare all fields with the current configuration to detect if any changes where made
If chkVerbose.Checked <> Settings.Verbose Then
Return True
End If
If tbArguments.Text <> Settings.Arguments Then
Return True
End If
If chkSaveOutput.Checked <> Settings.SaveOutput Then
Return True
End If
If tbOutputPath.Text <> Settings.OutputPath Then
Return True
End If
If chkCheckUpdates.Checked <> Settings.CheckUpdates Then
Return True
End If
If chkInstallUpdates.Checked <> Settings.InstallUpdates Then
Return True
End If
If rdoDevelop.Checked <> Settings.DownloadDevelop Then
Return True
End If
Return False
End Function
Private Sub configSaveLauncher()
Settings.Verbose = chkVerbose.Checked
Settings.Arguments = tbArguments.Text
Settings.SaveOutput = chkSaveOutput.Checked
Settings.OutputPath = tbOutputPath.Text
Settings.CheckUpdates = chkCheckUpdates.Checked
Settings.InstallUpdates = chkInstallUpdates.Checked
Settings.DownloadDevelop = rdoDevelop.Checked
Settings.HasChanged = True
End Sub
Private Sub frmOptions_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If configHasChangedGame() Or configHasChangedLauncher() Then 'Has the configuration been changed?
Dim result As DialogResult = MessageBox.Show(frmOptions_closeConfirmation_text, common_confirm, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information)
Select Case result
Case Windows.Forms.DialogResult.Yes 'Save and close
If configHasChangedGame() Then
GameConfig.values = toGameConfigValues()
End If
If configHasChangedLauncher() Then
configSaveLauncher()
End If
Case Windows.Forms.DialogResult.Cancel 'Return to options window
e.Cancel = True
End Select
End If
End Sub
Private Sub frmOptions_Load(sender As Object, e As EventArgs) Handles MyBase.Load
fromGameConfigValues(GameConfig.values)
chkVerbose.Checked = Settings.Verbose
tbArguments.Text = Settings.Arguments
chkSaveOutput.Checked = Settings.SaveOutput
tbOutputPath.Text = Settings.OutputPath
chkCheckUpdates.Checked = Settings.CheckUpdates
chkInstallUpdates.Checked = Settings.InstallUpdates
tbOutputPath.Enabled = chkSaveOutput.Checked
cmdOutputPath.Enabled = chkSaveOutput.Checked
chkInstallUpdates.Enabled = chkCheckUpdates.Checked
If Settings.DownloadDevelop = False Then
rdoDevelop.Checked = False
rdoStable.Checked = True
Else
rdoStable.Checked = False
rdoDevelop.Checked = True
End If
End Sub
Private Sub fromGameConfigValues(c As GameConfigValues)
chkAlwaysShowGridlines.Checked = c.AlwaysShowGridlines
cbAutosave.SelectedIndex = c.Autosave
chkAutoStaff.Checked = c.AutoStaff
chkBuildInPauseMode.Checked = c.BuildInPauseMode
tbChannel.Text = c.Channel
chkChatPeepNames.Checked = c.ChatPeepNames
chkChatPeepTracking.Checked = c.ChatPeepTracking
chkConfirmationPrompt.Checked = c.ConfirmationPrompt
chkConsoleSmallFont.Checked = c.ConsoleSmallFont
cbConstructionMarkerColour.SelectedIndex = c.ConstructionMarkerColour
cbCurrency.SelectedIndex = c.CurrencyFormat
cbDateFormat.SelectedIndex = c.DateFormat
chkDayNightCycle.Checked = c.DayNightCycle
chkDebuggingTools.Checked = c.DebuggingTools
chkDisableAllBreakdowns.Checked = c.DisableAllBreakdowns
chkDisableBrakesFailure.Checked = c.DisableBrakesFailure
chkEdgeScrolling.Checked = c.EdgeScrolling
chkFastLiftHill.Checked = c.FastLiftHill
chkFollowerPeepNames.Checked = c.FollowerPeepNames
chkFollowerPeepTracking.Checked = c.FollowerPeepTracking
numFullscreenHeight.Value = c.FullscreenHeight
cbFullscreenMode.SelectedIndex = c.FullscreenMode
numFullscreenWidth.Value = c.FullscreenWidth
tbGamePath.Text = c.GamePath
chkHardwareDisplay.Checked = c.HardwareDisplay
chkInvertViewportDrag.Checked = c.InvertViewportDrag
chkLandscapeSmoothing.Checked = c.LandscapeSmoothing
cbLanguage.SelectedIndex = c.Language - 1
numMasterVolume.Value = c.MasterVolume
cbMeasurementFormat.SelectedIndex = c.MeasurementFormat
chkMinimizeFullscreenFocusLoss.Checked = c.MinimizeFullscreenFocusLoss
numMusicVolume.Value = c.MusicVolume
chkNews.Checked = c.News
chkNoTestCrashes.Checked = c.NoTestCrashes
chkPlayIntro.Checked = c.PlayIntro
chkRideMusic.Checked = c.RideMusic
chkSavePluginData.Checked = c.SavePluginData
cbScreenshotFormat.SelectedIndex = c.ScreenshotFormat
chkSelectByTrackType.Checked = c.SelectByTrackType
cbShowHeightAsUnits.SelectedIndex = 1 + c.ShowHeightAsUnits
chkSound.Checked = c.Sound
cbTemperatureFormat.SelectedIndex = c.TemperatureFormat
chkTestUnfinishedTracks.Checked = c.TestUnfinishedTracks
cbTitleMusic.SelectedIndex = c.TitleMusic
chkToolbarShowCheats.Checked = c.ToolbarShowCheats
chkToolbarShowFinances.Checked = c.ToolbarShowFinances
chkToolbarShowRecentMessages.Checked = c.ToolbarShowRecentMessages
chkToolbarShowResearch.Checked = c.ToolbarShowResearch
chkUncapFPS.Checked = c.UncapFPS
chkUnlockAllPrices.Checked = c.UnlockAllPrices
numWindowHeight.Value = c.WindowHeight
numWindowSnapProximity.Value = c.WindowSnapProximity
numWindowWidth.Value = c.WindowWidth
End Sub
Private Function toGameConfigValues() As GameConfigValues
Dim c As New GameConfigValues()
c.AlwaysShowGridlines = chkAlwaysShowGridlines.Checked
c.Autosave = cbAutosave.SelectedIndex
c.AutoStaff = chkAutoStaff.Checked
c.BuildInPauseMode = chkBuildInPauseMode.Checked
c.Channel = tbChannel.Text
c.ChatPeepNames = chkChatPeepNames.Checked
c.ChatPeepTracking = chkChatPeepTracking.Checked
c.ConfirmationPrompt = chkConfirmationPrompt.Checked
c.ConsoleSmallFont = chkConsoleSmallFont.Checked
c.ConstructionMarkerColour = cbConstructionMarkerColour.SelectedIndex
c.CurrencyFormat = cbCurrency.SelectedIndex
c.DateFormat = cbDateFormat.SelectedIndex
c.DayNightCycle = chkDayNightCycle.Checked
c.DebuggingTools = chkDebuggingTools.Checked
c.DisableAllBreakdowns = chkDisableAllBreakdowns.Checked
c.DisableBrakesFailure = chkDisableBrakesFailure.Checked
c.EdgeScrolling = chkEdgeScrolling.Checked
c.FastLiftHill = chkFastLiftHill.Checked
c.FollowerPeepNames = chkFollowerPeepNames.Checked
c.FollowerPeepTracking = chkFollowerPeepTracking.Checked
c.FullscreenHeight = numFullscreenHeight.Value
c.FullscreenMode = cbFullscreenMode.SelectedIndex
c.FullscreenWidth = numFullscreenWidth.Value
c.GamePath = tbGamePath.Text
c.HardwareDisplay = chkHardwareDisplay.Checked
c.InvertViewportDrag = chkInvertViewportDrag.Checked
c.LandscapeSmoothing = chkLandscapeSmoothing.Checked
c.Language = cbLanguage.SelectedIndex + 1
c.MasterVolume = numMasterVolume.Value
c.MeasurementFormat = cbMeasurementFormat.SelectedIndex
c.MinimizeFullscreenFocusLoss = chkMinimizeFullscreenFocusLoss.Checked
c.MusicVolume = numMusicVolume.Value
c.News = chkNews.Checked
c.NoTestCrashes = chkNoTestCrashes.Checked
c.PlayIntro = chkPlayIntro.Checked
c.RideMusic = chkRideMusic.Checked
c.SavePluginData = chkSavePluginData.Checked
c.ScreenshotFormat = cbScreenshotFormat.SelectedIndex
c.SelectByTrackType = chkSelectByTrackType.Checked
c.ShowHeightAsUnits = 1 - cbShowHeightAsUnits.SelectedIndex
c.Sound = chkSound.Checked
c.TemperatureFormat = cbTemperatureFormat.SelectedIndex
c.TestUnfinishedTracks = chkTestUnfinishedTracks.Checked
c.TitleMusic = cbTitleMusic.SelectedIndex
c.ToolbarShowCheats = chkToolbarShowCheats.Checked
c.ToolbarShowFinances = chkToolbarShowFinances.Checked
c.ToolbarShowRecentMessages = chkToolbarShowRecentMessages.Checked
c.ToolbarShowResearch = chkToolbarShowResearch.Checked
c.UncapFPS = chkUncapFPS.Checked
c.UnlockAllPrices = chkUnlockAllPrices.Checked
c.WindowHeight = numWindowHeight.Value
c.WindowSnapProximity = numWindowSnapProximity.Value
c.WindowWidth = numWindowWidth.Value
Return c
End Function
End Class
End Namespace
|
PFCKrutonium/OpenRCT2Launcher
|
Launcher/Launcher/Forms/Options.vb
|
Visual Basic
|
mit
| 14,973
|
#Region "Microsoft.VisualBasic::a4b262792cadfc5115b47d1f2607373b, src\metadb\Massbank\Public\NCBI\PubChem\MetaData.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Class MetaData
'
' Properties: PUBCHEM_ATOM_DEF_STEREO_COUNT, PUBCHEM_ATOM_UDEF_STEREO_COUNT, PUBCHEM_BOND_DEF_STEREO_COUNT, PUBCHEM_BOND_UDEF_STEREO_COUNT, PUBCHEM_BONDANNOTATIONS
' PUBCHEM_CACTVS_COMPLEXITY, PUBCHEM_CACTVS_HBOND_ACCEPTOR, PUBCHEM_CACTVS_HBOND_DONOR, PUBCHEM_CACTVS_ROTATABLE_BOND, PUBCHEM_CACTVS_SUBSKEYS
' PUBCHEM_CACTVS_TAUTO_COUNT, PUBCHEM_CACTVS_TPSA, PUBCHEM_COMPONENT_COUNT, PUBCHEM_COMPOUND_CANONICALIZED, PUBCHEM_COMPOUND_CID
' PUBCHEM_COORDINATE_TYPE, PUBCHEM_EXACT_MASS, PUBCHEM_HEAVY_ATOM_COUNT, PUBCHEM_ISOTOPIC_ATOM_COUNT, PUBCHEM_IUPAC_CAS_NAME
' PUBCHEM_IUPAC_INCHI, PUBCHEM_IUPAC_INCHIKEY, PUBCHEM_IUPAC_NAME, PUBCHEM_IUPAC_OPENEYE_NAME, PUBCHEM_IUPAC_SYSTEMATIC_NAME
' PUBCHEM_IUPAC_TRADITIONAL_NAME, PUBCHEM_MOLECULAR_FORMULA, PUBCHEM_MOLECULAR_WEIGHT, PUBCHEM_MONOISOTOPIC_WEIGHT, PUBCHEM_OPENEYE_CAN_SMILES
' PUBCHEM_OPENEYE_ISO_SMILES, PUBCHEM_TOTAL_CHARGE, PUBCHEM_XLOGP3_AA
'
' Constructor: (+1 Overloads) Sub New
' Function: Data
'
'
' /********************************************************************************/
#End Region
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports BioNovoGene.BioDeep.Chemoinformatics.SDF
Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel
Namespace NCBI.PubChem
''' <summary>
''' NCBI compound annotation meta data in sdf file.
''' </summary>
Public Class MetaData
Public Property PUBCHEM_COMPOUND_CID As String
Public Property PUBCHEM_COMPOUND_CANONICALIZED As String
Public Property PUBCHEM_CACTVS_COMPLEXITY As String
Public Property PUBCHEM_CACTVS_HBOND_ACCEPTOR As String
Public Property PUBCHEM_CACTVS_HBOND_DONOR As String
Public Property PUBCHEM_CACTVS_ROTATABLE_BOND As String
Public Property PUBCHEM_CACTVS_SUBSKEYS As String
Public Property PUBCHEM_IUPAC_OPENEYE_NAME As String
Public Property PUBCHEM_IUPAC_CAS_NAME As String
Public Property PUBCHEM_IUPAC_NAME As String
Public Property PUBCHEM_IUPAC_SYSTEMATIC_NAME As String
Public Property PUBCHEM_IUPAC_TRADITIONAL_NAME As String
Public Property PUBCHEM_IUPAC_INCHI As String
Public Property PUBCHEM_IUPAC_INCHIKEY As String
Public Property PUBCHEM_XLOGP3_AA As String
Public Property PUBCHEM_EXACT_MASS As String
Public Property PUBCHEM_MOLECULAR_FORMULA As String
Public Property PUBCHEM_MOLECULAR_WEIGHT As String
Public Property PUBCHEM_OPENEYE_CAN_SMILES As String
Public Property PUBCHEM_OPENEYE_ISO_SMILES As String
Public Property PUBCHEM_CACTVS_TPSA As String
Public Property PUBCHEM_MONOISOTOPIC_WEIGHT As String
Public Property PUBCHEM_TOTAL_CHARGE As String
Public Property PUBCHEM_HEAVY_ATOM_COUNT As String
Public Property PUBCHEM_ATOM_DEF_STEREO_COUNT As String
Public Property PUBCHEM_ATOM_UDEF_STEREO_COUNT As String
Public Property PUBCHEM_BOND_DEF_STEREO_COUNT As String
Public Property PUBCHEM_BOND_UDEF_STEREO_COUNT As String
Public Property PUBCHEM_ISOTOPIC_ATOM_COUNT As String
Public Property PUBCHEM_COMPONENT_COUNT As String
Public Property PUBCHEM_CACTVS_TAUTO_COUNT As String
Public Property PUBCHEM_COORDINATE_TYPE As String
Public Property PUBCHEM_BONDANNOTATIONS As String
''' <summary>
''' Schema cache of current data reader class object
''' </summary>
Shared ReadOnly properties As Dictionary(Of String, PropertyInfo)
Shared Sub New()
properties = DataFramework.Schema(Of MetaData)(PropertyAccess.Writeable, True)
End Sub
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Shared Function Data(sdf As SDF) As MetaData
Return sdf.Data(Of MetaData)(properties)
End Function
End Class
End Namespace
|
xieguigang/spectrum
|
src/metadb/Massbank/Public/NCBI/PubChem/MetaData.vb
|
Visual Basic
|
mit
| 5,691
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Navigation
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
' Note: by default, TestWorkspace produces a composition from all assemblies except EditorServicesTest2.
' This type has to be defined here until we get that cleaned up. Otherwise, other tests may import it.
<ExportWorkspaceServiceFactory(GetType(IDocumentNavigationService), ServiceLayer.Host), [Shared]>
Public Class MockDocumentNavigationServiceProvider
Implements IWorkspaceServiceFactory
Private _instance As MockDocumentNavigationService = New MockDocumentNavigationService()
<ImportingConstructor>
Public Sub New()
End Sub
Public Function CreateService(workspaceServices As HostWorkspaceServices) As IWorkspaceService Implements IWorkspaceServiceFactory.CreateService
Return _instance
End Function
Friend Class MockDocumentNavigationService
Implements IDocumentNavigationService
Public ProvidedDocumentId As DocumentId
Public ProvidedTextSpan As TextSpan
Public ProvidedLineNumber As Integer
Public ProvidedOffset As Integer
Public ProvidedPosition As Integer
Public ProvidedVirtualSpace As Integer
Public ProvidedOptions As OptionSet
Public CanNavigateToLineAndOffsetReturnValue As Boolean = True
Public CanNavigateToPositionReturnValue As Boolean = True
Public CanNavigateToSpanReturnValue As Boolean = True
Public TryNavigateToLineAndOffsetReturnValue As Boolean = True
Public TryNavigateToPositionReturnValue As Boolean = True
Public TryNavigateToSpanReturnValue As Boolean = True
Public Function CanNavigateToLineAndOffset(workspace As Workspace, documentId As DocumentId, lineNumber As Integer, offset As Integer) As Boolean Implements IDocumentNavigationService.CanNavigateToLineAndOffset
Me.ProvidedDocumentId = documentId
Me.ProvidedLineNumber = lineNumber
Return CanNavigateToLineAndOffsetReturnValue
End Function
Public Function CanNavigateToPosition(workspace As Workspace, documentId As DocumentId, position As Integer, Optional virtualSpace As Integer = 0) As Boolean Implements IDocumentNavigationService.CanNavigateToPosition
Me.ProvidedDocumentId = documentId
Me.ProvidedPosition = position
Me.ProvidedVirtualSpace = virtualSpace
Return CanNavigateToPositionReturnValue
End Function
Public Function CanNavigateToSpan(workspace As Workspace, documentId As DocumentId, textSpan As TextSpan) As Boolean Implements IDocumentNavigationService.CanNavigateToSpan
Me.ProvidedDocumentId = documentId
Me.ProvidedTextSpan = textSpan
Return CanNavigateToSpanReturnValue
End Function
Public Function TryNavigateToLineAndOffset(workspace As Workspace, documentId As DocumentId, lineNumber As Integer, offset As Integer, Optional options As OptionSet = Nothing) As Boolean Implements IDocumentNavigationService.TryNavigateToLineAndOffset
Me.ProvidedDocumentId = documentId
Me.ProvidedLineNumber = lineNumber
Me.ProvidedOffset = offset
Me.ProvidedOptions = options
Return TryNavigateToLineAndOffsetReturnValue
End Function
Public Function TryNavigateToPosition(workspace As Workspace, documentId As DocumentId, position As Integer, Optional virtualSpace As Integer = 0, Optional options As OptionSet = Nothing) As Boolean Implements IDocumentNavigationService.TryNavigateToPosition
Me.ProvidedDocumentId = documentId
Me.ProvidedPosition = position
Me.ProvidedVirtualSpace = virtualSpace
Me.ProvidedOptions = options
Return TryNavigateToPositionReturnValue
End Function
Public Function TryNavigateToSpan(workspace As Workspace, documentId As DocumentId, textSpan As TextSpan, Optional options As OptionSet = Nothing) As Boolean Implements IDocumentNavigationService.TryNavigateToSpan
Me.ProvidedDocumentId = documentId
Me.ProvidedTextSpan = textSpan
Me.ProvidedOptions = options
Return TryNavigateToSpanReturnValue
End Function
End Class
End Class
End Namespace
|
nguerrera/roslyn
|
src/EditorFeatures/TestUtilities2/Utilities/MockDocumentNavigationServiceProvider.vb
|
Visual Basic
|
apache-2.0
| 4,933
|
' 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.Immutable
Imports System.IO
Imports System.Reflection.Metadata
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.InternalUtilities
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The Compilation object is an immutable representation of a single invocation of the
''' compiler. Although immutable, a Compilation is also on-demand, in that a compilation can be
''' created quickly, but will that compiler parts or all of the code in order to respond to
''' method or properties. Also, a compilation can produce a new compilation with a small change
''' from the current compilation. This is, in many cases, more efficient than creating a new
''' compilation from scratch, as the new compilation can share information from the old
''' compilation.
''' </summary>
Public NotInheritable Class VisualBasicCompilation
Inherits Compilation
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'
' Changes to the public interface of this class should remain synchronized with the C#
' version. Do not make any changes to the public interface without making the corresponding
' change to the C# version.
'
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' most of time all compilation would use same MyTemplate. no reason to create (reparse) one for each compilation
''' as long as its parse option is same
''' </summary>
Private Shared ReadOnly s_myTemplateCache As ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree) =
New ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree)(capacity:=5)
''' <summary>
''' The SourceAssemblySymbol for this compilation. Do not access directly, use Assembly
''' property instead. This field is lazily initialized by ReferenceManager,
''' ReferenceManager.CacheLockObject must be locked while ReferenceManager "calculates" the
''' value and assigns it, several threads must not perform duplicate "calculation"
''' simultaneously.
''' </summary>
Private _lazyAssemblySymbol As SourceAssemblySymbol
''' <summary>
''' Holds onto data related to reference binding.
''' The manager is shared among multiple compilations that we expect to have the same result of reference binding.
''' In most cases this can be determined without performing the binding. If the compilation however contains a circular
''' metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results.
''' We do so by creating a new reference manager for such compilation.
''' </summary>
Private _referenceManager As ReferenceManager
''' <summary>
''' The options passed to the constructor of the Compilation
''' </summary>
Private ReadOnly _options As VisualBasicCompilationOptions
''' <summary>
''' The global namespace symbol. Lazily populated on first access.
''' </summary>
Private _lazyGlobalNamespace As NamespaceSymbol
''' <summary>
''' The syntax trees explicitly given to the compilation at creation, in ordinal order.
''' </summary>
Private ReadOnly _syntaxTrees As ImmutableArray(Of SyntaxTree)
Private ReadOnly _syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer)
''' <summary>
''' The syntax trees of this compilation plus all 'hidden' trees
''' added to the compilation by compiler, e.g. Vb Core Runtime.
''' </summary>
Private _lazyAllSyntaxTrees As ImmutableArray(Of SyntaxTree)
''' <summary>
''' A map between syntax trees and the root declarations in the declaration table.
''' Incrementally updated between compilation versions when source changes are made.
''' </summary>
Private ReadOnly _rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry)
''' <summary>
''' Imports appearing in <see cref="SyntaxTree"/>s in this compilation.
''' </summary>
''' <remarks>
''' Unlike in C#, we don't need to use a set because the <see cref="SourceFile"/> objects
''' that record the imports are persisted.
''' </remarks>
Private _lazyImportInfos As ConcurrentQueue(Of ImportInfo)
''' <summary>
''' Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly.
''' </summary>
''' <remarks>
''' NOTE: Presently, we do not cache the per-tree diagnostics.
''' </remarks>
Private _lazyClsComplianceDiagnostics As ImmutableArray(Of Diagnostic)
''' <summary>
''' A SyntaxTree and the associated RootSingleNamespaceDeclaration for an embedded
''' syntax tree in the Compilation. Unlike the entries in m_rootNamespaces, the
''' SyntaxTree here is lazy since the tree cannot be evaluated until the references
''' have been resolved (as part of binding the source module), and at that point, the
''' SyntaxTree may be Nothing if the embedded tree is not needed for the Compilation.
''' </summary>
Private Structure EmbeddedTreeAndDeclaration
Public ReadOnly Tree As Lazy(Of SyntaxTree)
Public ReadOnly DeclarationEntry As DeclarationTableEntry
Public Sub New(treeOpt As Func(Of SyntaxTree), rootNamespaceOpt As Func(Of RootSingleNamespaceDeclaration))
Me.Tree = New Lazy(Of SyntaxTree)(treeOpt)
Me.DeclarationEntry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(rootNamespaceOpt), isEmbedded:=True)
End Sub
End Structure
Private ReadOnly _embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration)
''' <summary>
''' The declaration table that holds onto declarations from source. Incrementally updated
''' between compilation versions when source changes are made.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _declarationTable As DeclarationTable
''' <summary>
''' Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent.
''' </summary>
Private ReadOnly _anonymousTypeManager As AnonymousTypeManager
''' <summary>
''' Manages automatically embedded content.
''' </summary>
Private _lazyEmbeddedSymbolManager As EmbeddedSymbolManager
''' <summary>
''' MyTemplate automatically embedded from resource in the compiler.
''' It doesn't feel like it should be managed by EmbeddedSymbolManager
''' because MyTemplate is treated as user code, i.e. can be extended via
''' partial declarations, doesn't require "on-demand" metadata generation, etc.
'''
''' SyntaxTree.Dummy means uninitialized.
''' </summary>
Private _lazyMyTemplate As SyntaxTree = VisualBasicSyntaxTree.Dummy
Private ReadOnly _scriptClass As Lazy(Of ImplicitNamedTypeSymbol)
''' <summary>
''' Contains the main method of this assembly, if there is one.
''' </summary>
Private _lazyEntryPoint As EntryPoint
''' <summary>
''' The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue.
''' </summary>
Private _lazyCompilationUnitCompletedTrees As HashSet(Of SyntaxTree)
''' <summary>
''' The common language version among the trees of the compilation.
''' </summary>
Private ReadOnly _languageVersion As LanguageVersion
Public Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Public Overrides ReadOnly Property IsCaseSensitive As Boolean
Get
Return False
End Get
End Property
Friend ReadOnly Property Declarations As DeclarationTable
Get
Return _declarationTable
End Get
End Property
Friend ReadOnly Property MergedRootDeclaration As MergedNamespaceDeclaration
Get
Return Declarations.GetMergedRoot(Me)
End Get
End Property
Public Shadows ReadOnly Property Options As VisualBasicCompilationOptions
Get
Return _options
End Get
End Property
''' <summary>
''' The language version that was used to parse the syntax trees of this compilation.
''' </summary>
Public ReadOnly Property LanguageVersion As LanguageVersion
Get
Return _languageVersion
End Get
End Property
Friend ReadOnly Property AnonymousTypeManager As AnonymousTypeManager
Get
Return Me._anonymousTypeManager
End Get
End Property
Friend Overrides ReadOnly Property CommonAnonymousTypeManager As CommonAnonymousTypeManager
Get
Return Me._anonymousTypeManager
End Get
End Property
''' <summary>
''' SyntaxTree of MyTemplate for the compilation. Settable for testing purposes only.
''' </summary>
Friend Property MyTemplate As SyntaxTree
Get
If _lazyMyTemplate Is VisualBasicSyntaxTree.Dummy Then
Dim compilationOptions = Me.Options
If compilationOptions.EmbedVbCoreRuntime OrElse compilationOptions.SuppressEmbeddedDeclarations Then
_lazyMyTemplate = Nothing
Else
' first see whether we can use one from global cache
Dim parseOptions = If(compilationOptions.ParseOptions, VisualBasicParseOptions.Default)
Dim tree As SyntaxTree = Nothing
If s_myTemplateCache.TryGetValue(parseOptions, tree) Then
Debug.Assert(tree IsNot Nothing)
Debug.Assert(tree IsNot VisualBasicSyntaxTree.Dummy)
Debug.Assert(tree.IsMyTemplate)
Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy)
Else
' we need to make one.
Dim text As String = EmbeddedResources.VbMyTemplateText
' The My template regularly makes use of more recent language features. Care is
' taken to ensure these are compatible with 2.0 runtimes so there is no danger
' with allowing the newer syntax here.
Dim options = parseOptions.WithLanguageVersion(LanguageVersion.Default)
tree = VisualBasicSyntaxTree.ParseText(text, options:=options, isMyTemplate:=True)
If tree.GetDiagnostics().Any() Then
Throw ExceptionUtilities.Unreachable
End If
If Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Is VisualBasicSyntaxTree.Dummy Then
' set global cache
s_myTemplateCache(parseOptions) = tree
End If
End If
End If
Debug.Assert(_lazyMyTemplate Is Nothing OrElse _lazyMyTemplate.IsMyTemplate)
End If
Return _lazyMyTemplate
End Get
Set(value As SyntaxTree)
Debug.Assert(_lazyMyTemplate Is VisualBasicSyntaxTree.Dummy)
Debug.Assert(value IsNot VisualBasicSyntaxTree.Dummy)
Debug.Assert(value Is Nothing OrElse value.IsMyTemplate)
If value?.GetDiagnostics().Any() Then
Throw ExceptionUtilities.Unreachable
End If
_lazyMyTemplate = value
End Set
End Property
Friend ReadOnly Property EmbeddedSymbolManager As EmbeddedSymbolManager
Get
If _lazyEmbeddedSymbolManager Is Nothing Then
Dim embedded = If(Options.EmbedVbCoreRuntime, EmbeddedSymbolKind.VbCore, EmbeddedSymbolKind.None) Or
If(IncludeInternalXmlHelper(), EmbeddedSymbolKind.XmlHelper, EmbeddedSymbolKind.None)
If embedded <> EmbeddedSymbolKind.None Then
embedded = embedded Or EmbeddedSymbolKind.EmbeddedAttribute
End If
Interlocked.CompareExchange(_lazyEmbeddedSymbolManager, New EmbeddedSymbolManager(embedded), Nothing)
End If
Return _lazyEmbeddedSymbolManager
End Get
End Property
#Region "Constructors and Factories"
''' <summary>
''' Create a new compilation from scratch.
''' </summary>
''' <param name="assemblyName">Simple assembly name.</param>
''' <param name="syntaxTrees">The syntax trees with the source code for the new compilation.</param>
''' <param name="references">The references for the new compilation.</param>
''' <param name="options">The compiler options to use.</param>
''' <returns>A new compilation.</returns>
Public Shared Function Create(
assemblyName As String,
Optional syntaxTrees As IEnumerable(Of SyntaxTree) = Nothing,
Optional references As IEnumerable(Of MetadataReference) = Nothing,
Optional options As VisualBasicCompilationOptions = Nothing
) As VisualBasicCompilation
Return Create(assemblyName,
options,
If(syntaxTrees IsNot Nothing, syntaxTrees.Cast(Of SyntaxTree), Nothing),
references,
previousSubmission:=Nothing,
returnType:=Nothing,
hostObjectType:=Nothing,
isSubmission:=False)
End Function
''' <summary>
''' Creates a new compilation that can be used in scripting.
''' </summary>
Friend Shared Function CreateScriptCompilation(
assemblyName As String,
Optional syntaxTree As SyntaxTree = Nothing,
Optional references As IEnumerable(Of MetadataReference) = Nothing,
Optional options As VisualBasicCompilationOptions = Nothing,
Optional previousScriptCompilation As VisualBasicCompilation = Nothing,
Optional returnType As Type = Nothing,
Optional globalsType As Type = Nothing) As VisualBasicCompilation
CheckSubmissionOptions(options)
ValidateScriptCompilationParameters(previousScriptCompilation, returnType, globalsType)
Return Create(
assemblyName,
If(options, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).WithReferencesSupersedeLowerVersions(True),
If((syntaxTree IsNot Nothing), {syntaxTree}, SpecializedCollections.EmptyEnumerable(Of SyntaxTree)()),
references,
previousScriptCompilation,
returnType,
globalsType,
isSubmission:=True)
End Function
Private Shared Function Create(
assemblyName As String,
options As VisualBasicCompilationOptions,
syntaxTrees As IEnumerable(Of SyntaxTree),
references As IEnumerable(Of MetadataReference),
previousSubmission As VisualBasicCompilation,
returnType As Type,
hostObjectType As Type,
isSubmission As Boolean
) As VisualBasicCompilation
Debug.Assert(Not isSubmission OrElse options.ReferencesSupersedeLowerVersions)
If options Is Nothing Then
options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)
End If
Dim validatedReferences = ValidateReferences(Of VisualBasicCompilationReference)(references)
Dim c As VisualBasicCompilation = Nothing
Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c))
Dim declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)()
Dim declTable = AddEmbeddedTrees(DeclarationTable.Empty, embeddedTrees)
c = New VisualBasicCompilation(
assemblyName,
options,
validatedReferences,
ImmutableArray(Of SyntaxTree).Empty,
ImmutableDictionary.Create(Of SyntaxTree, Integer)(),
declMap,
embeddedTrees,
declTable,
previousSubmission,
returnType,
hostObjectType,
isSubmission,
referenceManager:=Nothing,
reuseReferenceManager:=False)
If syntaxTrees IsNot Nothing Then
c = c.AddSyntaxTrees(syntaxTrees)
End If
Debug.Assert(c._lazyAssemblySymbol Is Nothing)
Return c
End Function
Private Sub New(
assemblyName As String,
options As VisualBasicCompilationOptions,
references As ImmutableArray(Of MetadataReference),
syntaxTrees As ImmutableArray(Of SyntaxTree),
syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer),
rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry),
embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration),
declarationTable As DeclarationTable,
previousSubmission As VisualBasicCompilation,
submissionReturnType As Type,
hostObjectType As Type,
isSubmission As Boolean,
referenceManager As ReferenceManager,
reuseReferenceManager As Boolean,
Optional eventQueue As AsyncQueue(Of CompilationEvent) = Nothing
)
MyBase.New(assemblyName, references, SyntaxTreeCommonFeatures(syntaxTrees), isSubmission, eventQueue)
Debug.Assert(rootNamespaces IsNot Nothing)
Debug.Assert(declarationTable IsNot Nothing)
Debug.Assert(syntaxTrees.All(Function(tree) syntaxTrees(syntaxTreeOrdinalMap(tree)) Is tree))
Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer(Of SyntaxTree).Default))
Debug.Assert(embeddedTrees.All(Function(treeAndDeclaration) declarationTable.Contains(treeAndDeclaration.DeclarationEntry)))
_options = options
_syntaxTrees = syntaxTrees
_syntaxTreeOrdinalMap = syntaxTreeOrdinalMap
_rootNamespaces = rootNamespaces
_embeddedTrees = embeddedTrees
_declarationTable = declarationTable
_anonymousTypeManager = New AnonymousTypeManager(Me)
_languageVersion = CommonLanguageVersion(syntaxTrees)
_scriptClass = New Lazy(Of ImplicitNamedTypeSymbol)(AddressOf BindScriptClass)
If isSubmission Then
Debug.Assert(previousSubmission Is Nothing OrElse previousSubmission.HostObjectType Is hostObjectType)
Me.ScriptCompilationInfo = New VisualBasicScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType)
Else
Debug.Assert(previousSubmission Is Nothing AndAlso submissionReturnType Is Nothing AndAlso hostObjectType Is Nothing)
End If
If reuseReferenceManager Then
referenceManager.AssertCanReuseForCompilation(Me)
_referenceManager = referenceManager
Else
_referenceManager = New ReferenceManager(MakeSourceAssemblySimpleName(),
options.AssemblyIdentityComparer,
If(referenceManager IsNot Nothing, referenceManager.ObservedMetadata, Nothing))
End If
Debug.Assert(_lazyAssemblySymbol Is Nothing)
If Me.EventQueue IsNot Nothing Then
Me.EventQueue.TryEnqueue(New CompilationStartedEvent(Me))
End If
End Sub
Friend Overrides Sub ValidateDebugEntryPoint(debugEntryPoint As IMethodSymbol, diagnostics As DiagnosticBag)
Debug.Assert(debugEntryPoint IsNot Nothing)
' Debug entry point has to be a method definition from this compilation.
Dim methodSymbol = TryCast(debugEntryPoint, MethodSymbol)
If methodSymbol?.DeclaringCompilation IsNot Me OrElse Not methodSymbol.IsDefinition Then
diagnostics.Add(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None)
End If
End Sub
Private Function CommonLanguageVersion(syntaxTrees As ImmutableArray(Of SyntaxTree)) As LanguageVersion
' We don't check m_Options.ParseOptions.LanguageVersion for consistency, because
' it isn't consistent in practice. In fact sometimes m_Options.ParseOptions is Nothing.
Dim result As LanguageVersion? = Nothing
For Each tree In syntaxTrees
Dim version = CType(tree.Options, VisualBasicParseOptions).LanguageVersion
If result Is Nothing Then
result = version
ElseIf result <> version Then
Throw New ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, NameOf(syntaxTrees))
End If
Next
Return If(result, LanguageVersion.Default.MapSpecifiedToEffectiveVersion)
End Function
''' <summary>
''' Create a duplicate of this compilation with different symbol instances
''' </summary>
Public Shadows Function Clone() As VisualBasicCompilation
Return New VisualBasicCompilation(
Me.AssemblyName,
_options,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
_embeddedTrees,
_declarationTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=True,
eventQueue:=Nothing) ' no event queue when cloning
End Function
Private Function UpdateSyntaxTrees(
syntaxTrees As ImmutableArray(Of SyntaxTree),
syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer),
rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry),
declarationTable As DeclarationTable,
referenceDirectivesChanged As Boolean) As VisualBasicCompilation
Return New VisualBasicCompilation(
Me.AssemblyName,
_options,
Me.ExternalReferences,
syntaxTrees,
syntaxTreeOrdinalMap,
rootNamespaces,
_embeddedTrees,
declarationTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=Not referenceDirectivesChanged)
End Function
''' <summary>
''' Creates a new compilation with the specified name.
''' </summary>
Public Shadows Function WithAssemblyName(assemblyName As String) As VisualBasicCompilation
' Can't reuse references since the source assembly name changed and the referenced symbols might
' have internals-visible-to relationship with this compilation or they might had a circular reference
' to this compilation.
Return New VisualBasicCompilation(
assemblyName,
Me.Options,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
_embeddedTrees,
_declarationTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=String.Equals(assemblyName, Me.AssemblyName, StringComparison.Ordinal))
End Function
Public Shadows Function WithReferences(ParamArray newReferences As MetadataReference()) As VisualBasicCompilation
Return WithReferences(DirectCast(newReferences, IEnumerable(Of MetadataReference)))
End Function
''' <summary>
''' Creates a new compilation with the specified references.
''' </summary>
''' <remarks>
''' The new <see cref="VisualBasicCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying
''' metadata as soon as the are needed.
'''
''' The New compilation uses whatever metadata is currently being provided by the <see cref="MetadataReference"/>.
''' E.g. if the current compilation references a metadata file that has changed since the creation of the compilation
''' the New compilation is going to use the updated version, while the current compilation will be using the previous (it doesn't change).
''' </remarks>
Public Shadows Function WithReferences(newReferences As IEnumerable(Of MetadataReference)) As VisualBasicCompilation
Dim declTable = RemoveEmbeddedTrees(_declarationTable, _embeddedTrees)
Dim c As VisualBasicCompilation = Nothing
Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c))
declTable = AddEmbeddedTrees(declTable, embeddedTrees)
' References might have changed, don't reuse reference manager.
' Don't even reuse observed metadata - let the manager query for the metadata again.
c = New VisualBasicCompilation(
Me.AssemblyName,
Me.Options,
ValidateReferences(Of VisualBasicCompilationReference)(newReferences),
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
embeddedTrees,
declTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
referenceManager:=Nothing,
reuseReferenceManager:=False)
Return c
End Function
Public Shadows Function WithOptions(newOptions As VisualBasicCompilationOptions) As VisualBasicCompilation
If newOptions Is Nothing Then
Throw New ArgumentNullException(NameOf(newOptions))
End If
Dim c As VisualBasicCompilation = Nothing
Dim embeddedTrees = _embeddedTrees
Dim declTable = _declarationTable
Dim declMap = Me._rootNamespaces
If Not String.Equals(Me.Options.RootNamespace, newOptions.RootNamespace, StringComparison.Ordinal) Then
' If the root namespace was updated we have to update declaration table
' entries for all the syntax trees of the compilation
'
' NOTE: we use case-sensitive comparison so that the new compilation
' gets a root namespace with correct casing
declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)()
declTable = DeclarationTable.Empty
embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c))
declTable = AddEmbeddedTrees(declTable, embeddedTrees)
Dim discardedReferenceDirectivesChanged As Boolean = False
For Each tree In _syntaxTrees
AddSyntaxTreeToDeclarationMapAndTable(tree, newOptions, Me.IsSubmission, declMap, declTable, discardedReferenceDirectivesChanged) ' declMap and declTable passed ByRef
Next
ElseIf Me.Options.EmbedVbCoreRuntime <> newOptions.EmbedVbCoreRuntime OrElse Me.Options.ParseOptions <> newOptions.ParseOptions Then
declTable = RemoveEmbeddedTrees(declTable, _embeddedTrees)
embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c))
declTable = AddEmbeddedTrees(declTable, embeddedTrees)
End If
c = New VisualBasicCompilation(
Me.AssemblyName,
newOptions,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
declMap,
embeddedTrees,
declTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=_options.CanReuseCompilationReferenceManager(newOptions))
Return c
End Function
''' <summary>
''' Returns a new compilation with the given compilation set as the previous submission.
''' </summary>
Friend Shadows Function WithScriptCompilationInfo(info As VisualBasicScriptCompilationInfo) As VisualBasicCompilation
If info Is ScriptCompilationInfo Then
Return Me
End If
' Reference binding doesn't depend on previous submission so we can reuse it.
Return New VisualBasicCompilation(
Me.AssemblyName,
Me.Options,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
_embeddedTrees,
_declarationTable,
info?.PreviousScriptCompilation,
info?.ReturnTypeOpt,
info?.GlobalsType,
info IsNot Nothing,
_referenceManager,
reuseReferenceManager:=True)
End Function
''' <summary>
''' Returns a new compilation with a given event queue.
''' </summary>
Friend Overrides Function WithEventQueue(eventQueue As AsyncQueue(Of CompilationEvent)) As Compilation
Return New VisualBasicCompilation(
Me.AssemblyName,
Me.Options,
Me.ExternalReferences,
_syntaxTrees,
_syntaxTreeOrdinalMap,
_rootNamespaces,
_embeddedTrees,
_declarationTable,
Me.PreviousSubmission,
Me.SubmissionReturnType,
Me.HostObjectType,
Me.IsSubmission,
_referenceManager,
reuseReferenceManager:=True,
eventQueue:=eventQueue)
End Function
#End Region
#Region "Submission"
Friend Shadows ReadOnly Property ScriptCompilationInfo As VisualBasicScriptCompilationInfo
Friend Overrides ReadOnly Property CommonScriptCompilationInfo As ScriptCompilationInfo
Get
Return ScriptCompilationInfo
End Get
End Property
Friend Shadows ReadOnly Property PreviousSubmission As VisualBasicCompilation
Get
Return ScriptCompilationInfo?.PreviousScriptCompilation
End Get
End Property
Friend Overrides Function HasSubmissionResult() As Boolean
Debug.Assert(IsSubmission)
' submission can be empty or comprise of a script file
Dim tree = SyntaxTrees.SingleOrDefault()
If tree Is Nothing Then
Return False
End If
Dim root = tree.GetCompilationUnitRoot()
If root.HasErrors Then
Return False
End If
' TODO: look for return statements
' https://github.com/dotnet/roslyn/issues/5773
Dim lastStatement = root.Members.LastOrDefault()
If lastStatement Is Nothing Then
Return False
End If
Dim model = GetSemanticModel(tree)
Select Case lastStatement.Kind
Case SyntaxKind.PrintStatement
Dim expression = DirectCast(lastStatement, PrintStatementSyntax).Expression
Dim info = model.GetTypeInfo(expression)
' always true, even for info.Type = Void
Return True
Case SyntaxKind.ExpressionStatement
Dim expression = DirectCast(lastStatement, ExpressionStatementSyntax).Expression
Dim info = model.GetTypeInfo(expression)
Return info.Type.SpecialType <> SpecialType.System_Void
Case SyntaxKind.CallStatement
Dim expression = DirectCast(lastStatement, CallStatementSyntax).Invocation
Dim info = model.GetTypeInfo(expression)
Return info.Type.SpecialType <> SpecialType.System_Void
Case Else
Return False
End Select
End Function
Friend Function GetSubmissionInitializer() As SynthesizedInteractiveInitializerMethod
Return If(IsSubmission AndAlso ScriptClass IsNot Nothing,
ScriptClass.GetScriptInitializer(),
Nothing)
End Function
#End Region
#Region "Syntax Trees"
''' <summary>
''' Get a read-only list of the syntax trees that this compilation was created with.
''' </summary>
Public Shadows ReadOnly Property SyntaxTrees As ImmutableArray(Of SyntaxTree)
Get
Return _syntaxTrees
End Get
End Property
''' <summary>
''' Get a read-only list of the syntax trees that this compilation was created with PLUS
''' the trees that were automatically added to it, i.e. Vb Core Runtime tree.
''' </summary>
Friend Shadows ReadOnly Property AllSyntaxTrees As ImmutableArray(Of SyntaxTree)
Get
If _lazyAllSyntaxTrees.IsDefault Then
Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance()
builder.AddRange(_syntaxTrees)
For Each embeddedTree In _embeddedTrees
Dim tree = embeddedTree.Tree.Value
If tree IsNot Nothing Then
builder.Add(tree)
End If
Next
ImmutableInterlocked.InterlockedInitialize(_lazyAllSyntaxTrees, builder.ToImmutableAndFree())
End If
Return _lazyAllSyntaxTrees
End Get
End Property
''' <summary>
''' Is the passed in syntax tree in this compilation?
''' </summary>
Public Shadows Function ContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean
If syntaxTree Is Nothing Then
Throw New ArgumentNullException(NameOf(syntaxTree))
End If
Dim vbtree = syntaxTree
Return vbtree IsNot Nothing AndAlso _rootNamespaces.ContainsKey(vbtree)
End Function
Public Shadows Function AddSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation
Return AddSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree)))
End Function
Public Shadows Function AddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation
If trees Is Nothing Then
Throw New ArgumentNullException(NameOf(trees))
End If
If Not trees.Any() Then
Return Me
End If
' We're using a try-finally for this builder because there's a test that
' specifically checks for one or more of the argument exceptions below
' and we don't want to see console spew (even though we don't generally
' care about pool "leaks" in exceptional cases). Alternatively, we
' could create a new ArrayBuilder.
Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance()
Try
builder.AddRange(_syntaxTrees)
Dim referenceDirectivesChanged = False
Dim oldTreeCount = _syntaxTrees.Length
Dim ordinalMap = _syntaxTreeOrdinalMap
Dim declMap = _rootNamespaces
Dim declTable = _declarationTable
Dim i = 0
For Each tree As SyntaxTree In trees
If tree Is Nothing Then
Throw New ArgumentNullException(String.Format(VBResources.Trees0, i))
End If
If Not tree.HasCompilationUnitRoot Then
Throw New ArgumentException(String.Format(VBResources.TreesMustHaveRootNode, i))
End If
If tree.IsEmbeddedOrMyTemplateTree() Then
Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree)
End If
If declMap.ContainsKey(tree) Then
Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, String.Format(VBResources.Trees0, i))
End If
AddSyntaxTreeToDeclarationMapAndTable(tree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged) ' declMap and declTable passed ByRef
builder.Add(tree)
ordinalMap = ordinalMap.Add(tree, oldTreeCount + i)
i += 1
Next
If IsSubmission AndAlso declMap.Count > 1 Then
Throw New ArgumentException(VBResources.SubmissionCanHaveAtMostOneSyntaxTree, NameOf(trees))
End If
Return UpdateSyntaxTrees(builder.ToImmutable(), ordinalMap, declMap, declTable, referenceDirectivesChanged)
Finally
builder.Free()
End Try
End Function
Private Shared Sub AddSyntaxTreeToDeclarationMapAndTable(
tree As SyntaxTree,
compilationOptions As VisualBasicCompilationOptions,
isSubmission As Boolean,
ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry),
ByRef declTable As DeclarationTable,
ByRef referenceDirectivesChanged As Boolean
)
Dim entry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(Function() ForTree(tree, compilationOptions, isSubmission)), isEmbedded:=False)
declMap = declMap.Add(tree, entry) ' Callers are responsible for checking for existing entries.
declTable = declTable.AddRootDeclaration(entry)
referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives
End Sub
Private Shared Function ForTree(tree As SyntaxTree, options As VisualBasicCompilationOptions, isSubmission As Boolean) As RootSingleNamespaceDeclaration
Return DeclarationTreeBuilder.ForTree(tree, options.GetRootNamespaceParts(), If(options.ScriptClassName, ""), isSubmission)
End Function
Public Shadows Function RemoveSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation
Return RemoveSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree)))
End Function
Public Shadows Function RemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation
If trees Is Nothing Then
Throw New ArgumentNullException(NameOf(trees))
End If
If Not trees.Any() Then
Return Me
End If
Dim referenceDirectivesChanged = False
Dim removeSet As New HashSet(Of SyntaxTree)()
Dim declMap = _rootNamespaces
Dim declTable = _declarationTable
For Each tree As SyntaxTree In trees
If tree.IsEmbeddedOrMyTemplateTree() Then
Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree)
End If
RemoveSyntaxTreeFromDeclarationMapAndTable(tree, declMap, declTable, referenceDirectivesChanged)
removeSet.Add(tree)
Next
Debug.Assert(removeSet.Count > 0)
' We're going to have to revise the ordinals of all
' trees after the first one removed, so just build
' a new map.
' CONSIDER: an alternative approach would be to set the map to empty and
' re-calculate it the next time we need it. This might save us time in the
' case where remove calls are made sequentially (rare?).
Dim ordinalMap = ImmutableDictionary.Create(Of SyntaxTree, Integer)()
Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance()
Dim i = 0
For Each tree In _syntaxTrees
If Not removeSet.Contains(tree) Then
builder.Add(tree)
ordinalMap = ordinalMap.Add(tree, i)
i += 1
End If
Next
Return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged)
End Function
Private Shared Sub RemoveSyntaxTreeFromDeclarationMapAndTable(
tree As SyntaxTree,
ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry),
ByRef declTable As DeclarationTable,
ByRef referenceDirectivesChanged As Boolean
)
Dim root As DeclarationTableEntry = Nothing
If Not declMap.TryGetValue(tree, root) Then
Throw New ArgumentException(String.Format(VBResources.SyntaxTreeNotFoundToRemove, tree))
End If
declTable = declTable.RemoveRootDeclaration(root)
declMap = declMap.Remove(tree)
referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives
End Sub
Public Shadows Function RemoveAllSyntaxTrees() As VisualBasicCompilation
Return UpdateSyntaxTrees(ImmutableArray(Of SyntaxTree).Empty,
ImmutableDictionary.Create(Of SyntaxTree, Integer)(),
ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)(),
AddEmbeddedTrees(DeclarationTable.Empty, _embeddedTrees),
referenceDirectivesChanged:=_declarationTable.ReferenceDirectives.Any())
End Function
Public Shadows Function ReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As VisualBasicCompilation
If oldTree Is Nothing Then
Throw New ArgumentNullException(NameOf(oldTree))
End If
If newTree Is Nothing Then
Return Me.RemoveSyntaxTrees(oldTree)
ElseIf newTree Is oldTree Then
Return Me
End If
If Not newTree.HasCompilationUnitRoot Then
Throw New ArgumentException(VBResources.TreeMustHaveARootNodeWithCompilationUnit, NameOf(newTree))
End If
Dim vbOldTree = oldTree
Dim vbNewTree = newTree
If vbOldTree.IsEmbeddedOrMyTemplateTree() Then
Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree)
End If
If vbNewTree.IsEmbeddedOrMyTemplateTree() Then
Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree)
End If
Dim declMap = _rootNamespaces
If declMap.ContainsKey(vbNewTree) Then
Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, NameOf(newTree))
End If
Dim declTable = _declarationTable
Dim referenceDirectivesChanged = False
' TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse.
' This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke
' that replaces the tree with a new one.
RemoveSyntaxTreeFromDeclarationMapAndTable(vbOldTree, declMap, declTable, referenceDirectivesChanged)
AddSyntaxTreeToDeclarationMapAndTable(vbNewTree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged)
Dim ordinalMap = _syntaxTreeOrdinalMap
Debug.Assert(ordinalMap.ContainsKey(oldTree)) ' Checked by RemoveSyntaxTreeFromDeclarationMapAndTable
Dim oldOrdinal = ordinalMap(oldTree)
Dim newArray = _syntaxTrees.ToArray()
newArray(oldOrdinal) = vbNewTree
' CONSIDER: should this be an operation on ImmutableDictionary?
ordinalMap = ordinalMap.Remove(oldTree)
ordinalMap = ordinalMap.Add(newTree, oldOrdinal)
Return UpdateSyntaxTrees(newArray.AsImmutableOrNull(), ordinalMap, declMap, declTable, referenceDirectivesChanged)
End Function
Private Shared Function CreateEmbeddedTrees(compReference As Lazy(Of VisualBasicCompilation)) As ImmutableArray(Of EmbeddedTreeAndDeclaration)
Return ImmutableArray.Create(
New EmbeddedTreeAndDeclaration(
Function()
Dim compilation = compReference.Value
Return If(compilation.Options.EmbedVbCoreRuntime Or compilation.IncludeInternalXmlHelper,
EmbeddedSymbolManager.EmbeddedSyntax,
Nothing)
End Function,
Function()
Dim compilation = compReference.Value
Return If(compilation.Options.EmbedVbCoreRuntime Or compilation.IncludeInternalXmlHelper,
ForTree(EmbeddedSymbolManager.EmbeddedSyntax, compilation.Options, isSubmission:=False),
Nothing)
End Function),
New EmbeddedTreeAndDeclaration(
Function()
Dim compilation = compReference.Value
Return If(compilation.Options.EmbedVbCoreRuntime,
EmbeddedSymbolManager.VbCoreSyntaxTree,
Nothing)
End Function,
Function()
Dim compilation = compReference.Value
Return If(compilation.Options.EmbedVbCoreRuntime,
ForTree(EmbeddedSymbolManager.VbCoreSyntaxTree, compilation.Options, isSubmission:=False),
Nothing)
End Function),
New EmbeddedTreeAndDeclaration(
Function()
Dim compilation = compReference.Value
Return If(compilation.IncludeInternalXmlHelper(),
EmbeddedSymbolManager.InternalXmlHelperSyntax,
Nothing)
End Function,
Function()
Dim compilation = compReference.Value
Return If(compilation.IncludeInternalXmlHelper(),
ForTree(EmbeddedSymbolManager.InternalXmlHelperSyntax, compilation.Options, isSubmission:=False),
Nothing)
End Function),
New EmbeddedTreeAndDeclaration(
Function()
Dim compilation = compReference.Value
Return compilation.MyTemplate
End Function,
Function()
Dim compilation = compReference.Value
Return If(compilation.MyTemplate IsNot Nothing,
ForTree(compilation.MyTemplate, compilation.Options, isSubmission:=False),
Nothing)
End Function))
End Function
Private Shared Function AddEmbeddedTrees(
declTable As DeclarationTable,
embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration)
) As DeclarationTable
For Each embeddedTree In embeddedTrees
declTable = declTable.AddRootDeclaration(embeddedTree.DeclarationEntry)
Next
Return declTable
End Function
Private Shared Function RemoveEmbeddedTrees(
declTable As DeclarationTable,
embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration)
) As DeclarationTable
For Each embeddedTree In embeddedTrees
declTable = declTable.RemoveRootDeclaration(embeddedTree.DeclarationEntry)
Next
Return declTable
End Function
''' <summary>
''' Returns True if the set of references contains those assemblies needed for XML
''' literals.
''' If those assemblies are included, we should include the InternalXmlHelper
''' SyntaxTree in the Compilation so the helper methods are available for binding XML.
''' </summary>
Private Function IncludeInternalXmlHelper() As Boolean
' In new flavors of the framework, types, that XML helpers depend upon, are
' defined in assemblies with different names. Let's not hardcode these names,
' let's check for presence of types instead.
Return Not Me.Options.SuppressEmbeddedDeclarations AndAlso
InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Linq_Enumerable) AndAlso
InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XElement) AndAlso
InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XName) AndAlso
InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XAttribute) AndAlso
InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XNamespace)
End Function
Private Function InternalXmlHelperDependencyIsSatisfied(type As WellKnownType) As Boolean
Dim metadataName = MetadataTypeName.FromFullName(WellKnownTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True)
Dim sourceAssembly = Me.SourceAssembly
' Lookup only in references. An attempt to lookup in assembly being built will get us in a cycle.
' We are explicitly ignoring scenario where the type might be defined in an added module.
For Each reference As AssemblySymbol In sourceAssembly.SourceModule.GetReferencedAssemblySymbols()
Debug.Assert(Not reference.IsMissing)
Dim candidate As NamedTypeSymbol = reference.LookupTopLevelMetadataType(metadataName, digThroughForwardedTypes:=False)
If sourceAssembly.IsValidWellKnownType(candidate) AndAlso AssemblySymbol.IsAcceptableMatchForGetTypeByNameAndArity(candidate) Then
Return True
End If
Next
Return False
End Function
' TODO: This comparison probably will change to compiler command line order, or at least needs
' TODO: to be resolved. See bug 8520.
''' <summary>
''' Compare two source locations, using their containing trees, and then by Span.First within a tree.
''' Can be used to get a total ordering on declarations, for example.
''' </summary>
Friend Overrides Function CompareSourceLocations(first As Location, second As Location) As Integer
Return LexicalSortKey.Compare(first, second, Me)
End Function
''' <summary>
''' Compare two source locations, using their containing trees, and then by Span.First within a tree.
''' Can be used to get a total ordering on declarations, for example.
''' </summary>
Friend Overrides Function CompareSourceLocations(first As SyntaxReference, second As SyntaxReference) As Integer
Return LexicalSortKey.Compare(first, second, Me)
End Function
Friend Overrides Function GetSyntaxTreeOrdinal(tree As SyntaxTree) As Integer
Debug.Assert(Me.ContainsSyntaxTree(tree))
Return _syntaxTreeOrdinalMap(tree)
End Function
#End Region
#Region "References"
Friend Overrides Function CommonGetBoundReferenceManager() As CommonReferenceManager
Return GetBoundReferenceManager()
End Function
Friend Shadows Function GetBoundReferenceManager() As ReferenceManager
If _lazyAssemblySymbol Is Nothing Then
_referenceManager.CreateSourceAssemblyForCompilation(Me)
Debug.Assert(_lazyAssemblySymbol IsNot Nothing)
End If
' referenceManager can only be accessed after we initialized the lazyAssemblySymbol.
' In fact, initialization of the assembly symbol might change the reference manager.
Return _referenceManager
End Function
' for testing only:
Friend Function ReferenceManagerEquals(other As VisualBasicCompilation) As Boolean
Return _referenceManager Is other._referenceManager
End Function
Public Overrides ReadOnly Property DirectiveReferences As ImmutableArray(Of MetadataReference)
Get
Return GetBoundReferenceManager().DirectiveReferences
End Get
End Property
Friend Overrides ReadOnly Property ReferenceDirectiveMap As IDictionary(Of (path As String, content As String), MetadataReference)
Get
Return GetBoundReferenceManager().ReferenceDirectiveMap
End Get
End Property
''' <summary>
''' Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation.
''' </summary>
''' <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or Nothing if there is none.</returns>
''' <remarks>
''' Uses object identity when comparing two references.
''' </remarks>
Friend Shadows Function GetAssemblyOrModuleSymbol(reference As MetadataReference) As Symbol
If (reference Is Nothing) Then
Throw New ArgumentNullException(NameOf(reference))
End If
If reference.Properties.Kind = MetadataImageKind.Assembly Then
Return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference)
Else
Debug.Assert(reference.Properties.Kind = MetadataImageKind.Module)
Dim index As Integer = GetBoundReferenceManager().GetReferencedModuleIndex(reference)
Return If(index < 0, Nothing, Me.Assembly.Modules(index))
End If
End Function
''' <summary>
''' Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
''' </summary>
Friend Shadows Function GetMetadataReference(assemblySymbol As AssemblySymbol) As MetadataReference
Return Me.GetBoundReferenceManager().GetMetadataReference(assemblySymbol)
End Function
Public Overrides ReadOnly Property ReferencedAssemblyNames As IEnumerable(Of AssemblyIdentity)
Get
Return [Assembly].Modules.SelectMany(Function(m) m.GetReferencedAssemblies())
End Get
End Property
Friend Overrides ReadOnly Property ReferenceDirectives As IEnumerable(Of ReferenceDirective)
Get
Return _declarationTable.ReferenceDirectives
End Get
End Property
Public Overrides Function ToMetadataReference(Optional aliases As ImmutableArray(Of String) = Nothing, Optional embedInteropTypes As Boolean = False) As CompilationReference
Return New VisualBasicCompilationReference(Me, aliases, embedInteropTypes)
End Function
Public Shadows Function AddReferences(ParamArray references As MetadataReference()) As VisualBasicCompilation
Return DirectCast(MyBase.AddReferences(references), VisualBasicCompilation)
End Function
Public Shadows Function AddReferences(references As IEnumerable(Of MetadataReference)) As VisualBasicCompilation
Return DirectCast(MyBase.AddReferences(references), VisualBasicCompilation)
End Function
Public Shadows Function RemoveReferences(ParamArray references As MetadataReference()) As VisualBasicCompilation
Return DirectCast(MyBase.RemoveReferences(references), VisualBasicCompilation)
End Function
Public Shadows Function RemoveReferences(references As IEnumerable(Of MetadataReference)) As VisualBasicCompilation
Return DirectCast(MyBase.RemoveReferences(references), VisualBasicCompilation)
End Function
Public Shadows Function RemoveAllReferences() As VisualBasicCompilation
Return DirectCast(MyBase.RemoveAllReferences(), VisualBasicCompilation)
End Function
Public Shadows Function ReplaceReference(oldReference As MetadataReference, newReference As MetadataReference) As VisualBasicCompilation
Return DirectCast(MyBase.ReplaceReference(oldReference, newReference), VisualBasicCompilation)
End Function
''' <summary>
''' Determine if enum arrays can be initialized using block initialization.
''' </summary>
''' <returns>True if it's safe to use block initialization for enum arrays.</returns>
''' <remarks>
''' In NetFx 4.0, block array initializers do not work on all combinations of {32/64 X Debug/Retail} when array elements are enums.
''' This is fixed in 4.5 thus enabling block array initialization for a very common case.
''' We look for the presence of <see cref="System.Runtime.GCLatencyMode.SustainedLowLatency"/> which was introduced in .NET Framework 4.5
''' </remarks>
Friend ReadOnly Property EnableEnumArrayBlockInitialization As Boolean
Get
Dim sustainedLowLatency = GetWellKnownTypeMember(WellKnownMember.System_Runtime_GCLatencyMode__SustainedLowLatency)
Return sustainedLowLatency IsNot Nothing AndAlso sustainedLowLatency.ContainingAssembly = Assembly.CorLibrary
End Get
End Property
#End Region
#Region "Symbols"
Friend ReadOnly Property SourceAssembly As SourceAssemblySymbol
Get
GetBoundReferenceManager()
Return _lazyAssemblySymbol
End Get
End Property
''' <summary>
''' Gets the AssemblySymbol that represents the assembly being created.
''' </summary>
Friend Shadows ReadOnly Property Assembly As AssemblySymbol
Get
Return Me.SourceAssembly
End Get
End Property
''' <summary>
''' Get a ModuleSymbol that refers to the module being created by compiling all of the code. By
''' getting the GlobalNamespace property of that module, all of the namespace and types defined in source code
''' can be obtained.
''' </summary>
Friend Shadows ReadOnly Property SourceModule As ModuleSymbol
Get
Return Me.Assembly.Modules(0)
End Get
End Property
''' <summary>
''' Gets the merged root namespace that contains all namespaces and types defined in source code or in
''' referenced metadata, merged into a single namespace hierarchy. This namespace hierarchy is how the compiler
''' binds types that are referenced in code.
''' </summary>
Friend Shadows ReadOnly Property GlobalNamespace As NamespaceSymbol
Get
If _lazyGlobalNamespace Is Nothing Then
Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing)
End If
Return _lazyGlobalNamespace
End Get
End Property
''' <summary>
''' Get the "root" or default namespace that all source types are declared inside. This may be the
''' global namespace or may be another namespace.
''' </summary>
Friend ReadOnly Property RootNamespace As NamespaceSymbol
Get
Return DirectCast(Me.SourceModule, SourceModuleSymbol).RootNamespace
End Get
End Property
''' <summary>
''' Given a namespace symbol, returns the corresponding namespace symbol with Compilation extent
''' that refers to that namespace in this compilation. Returns Nothing if there is no corresponding
''' namespace. This should not occur if the namespace symbol came from an assembly referenced by this
''' compilation.
''' </summary>
Friend Shadows Function GetCompilationNamespace(namespaceSymbol As INamespaceSymbol) As NamespaceSymbol
If namespaceSymbol Is Nothing Then
Throw New ArgumentNullException(NameOf(namespaceSymbol))
End If
Dim vbNs = TryCast(namespaceSymbol, NamespaceSymbol)
If vbNs IsNot Nothing AndAlso vbNs.Extent.Kind = NamespaceKind.Compilation AndAlso vbNs.Extent.Compilation Is Me Then
' If we already have a namespace with the right extent, use that.
Return vbNs
ElseIf namespaceSymbol.ContainingNamespace Is Nothing Then
' If is the root namespace, return the merged root namespace
Debug.Assert(namespaceSymbol.Name = "", "Namespace with Nothing container should be root namespace with empty name")
Return GlobalNamespace
Else
Dim containingNs = GetCompilationNamespace(namespaceSymbol.ContainingNamespace)
If containingNs Is Nothing Then
Return Nothing
End If
' Get the child namespace of the given name, if any.
Return containingNs.GetMembers(namespaceSymbol.Name).OfType(Of NamespaceSymbol)().FirstOrDefault()
End If
End Function
Friend Shadows Function GetEntryPoint(cancellationToken As CancellationToken) As MethodSymbol
Dim entryPoint As EntryPoint = GetEntryPointAndDiagnostics(cancellationToken)
Return If(entryPoint Is Nothing, Nothing, entryPoint.MethodSymbol)
End Function
Friend Function GetEntryPointAndDiagnostics(cancellationToken As CancellationToken) As EntryPoint
If Not Me.Options.OutputKind.IsApplication() AndAlso ScriptClass Is Nothing Then
Return Nothing
End If
If Me.Options.MainTypeName IsNot Nothing AndAlso Not Me.Options.MainTypeName.IsValidClrTypeName() Then
Debug.Assert(Not Me.Options.Errors.IsDefaultOrEmpty)
Return New EntryPoint(Nothing, ImmutableArray(Of Diagnostic).Empty)
End If
If _lazyEntryPoint Is Nothing Then
Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing
Dim entryPoint = FindEntryPoint(cancellationToken, diagnostics)
Interlocked.CompareExchange(_lazyEntryPoint, New EntryPoint(entryPoint, diagnostics), Nothing)
End If
Return _lazyEntryPoint
End Function
Private Function FindEntryPoint(cancellationToken As CancellationToken, ByRef sealedDiagnostics As ImmutableArray(Of Diagnostic)) As MethodSymbol
Dim diagnostics = DiagnosticBag.GetInstance()
Dim entryPointCandidates = ArrayBuilder(Of MethodSymbol).GetInstance()
Try
Dim mainType As SourceMemberContainerTypeSymbol
Dim mainTypeName As String = Me.Options.MainTypeName
Dim globalNamespace As NamespaceSymbol = Me.SourceModule.GlobalNamespace
Dim errorTarget As Object
If mainTypeName IsNot Nothing Then
' Global code is the entry point, ignore all other Mains.
If ScriptClass IsNot Nothing Then
' CONSIDER: we could use the symbol instead of just the name.
diagnostics.Add(ERRID.WRN_MainIgnored, NoLocation.Singleton, mainTypeName)
Return ScriptClass.GetScriptEntryPoint()
End If
Dim mainTypeOrNamespace = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split("."c)).OfType(Of NamedTypeSymbol)().OfMinimalArity()
If mainTypeOrNamespace Is Nothing Then
diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainTypeName)
Return Nothing
End If
mainType = TryCast(mainTypeOrNamespace, SourceMemberContainerTypeSymbol)
If mainType Is Nothing OrElse (mainType.TypeKind <> TypeKind.Class AndAlso mainType.TypeKind <> TypeKind.Structure AndAlso mainType.TypeKind <> TypeKind.Module) Then
diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainType)
Return Nothing
End If
' Dev10 reports ERR_StartupCodeNotFound1 but that doesn't make much sense
If mainType.IsGenericType Then
diagnostics.Add(ERRID.ERR_GenericSubMainsFound1, NoLocation.Singleton, mainType)
Return Nothing
End If
errorTarget = mainType
' NOTE: unlike in C#, we're not going search the member list of mainType directly.
' Instead, we're going to mimic dev10's behavior by doing a lookup for "Main",
' starting in mainType. Among other things, this implies that the entrypoint
' could be in a base class and that it could be hidden by a non-method member
' named "Main".
Dim binder As Binder = BinderBuilder.CreateBinderForType(mainType.ContainingSourceModule, mainType.SyntaxReferences(0).SyntaxTree, mainType)
Dim lookupResult As LookupResult = LookupResult.GetInstance()
Dim entryPointLookupOptions As LookupOptions = LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods
binder.LookupMember(lookupResult, mainType, WellKnownMemberNames.EntryPointMethodName, arity:=0, options:=entryPointLookupOptions, useSiteDiagnostics:=Nothing)
If (Not lookupResult.IsGoodOrAmbiguous) OrElse lookupResult.Symbols(0).Kind <> SymbolKind.Method Then
diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainType)
lookupResult.Free()
Return Nothing
End If
For Each candidate In lookupResult.Symbols
' The entrypoint cannot be in another assembly.
' NOTE: filter these out here, rather than below, so that we
' report "not found", rather than "invalid", as in dev10.
If candidate.ContainingAssembly = Me.Assembly Then
entryPointCandidates.Add(DirectCast(candidate, MethodSymbol))
End If
Next
lookupResult.Free()
Else
mainType = Nothing
errorTarget = Me.AssemblyName
For Each candidate In Me.GetSymbolsWithName(WellKnownMemberNames.EntryPointMethodName, SymbolFilter.Member, cancellationToken)
Dim method = TryCast(candidate, MethodSymbol)
If method?.IsEntryPointCandidate = True Then
entryPointCandidates.Add(method)
End If
Next
' Global code is the entry point, ignore all other Mains.
If ScriptClass IsNot Nothing Then
For Each main In entryPointCandidates
diagnostics.Add(ERRID.WRN_MainIgnored, main.Locations.First(), main)
Next
Return ScriptClass.GetScriptEntryPoint()
End If
End If
If entryPointCandidates.Count = 0 Then
diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, errorTarget)
Return Nothing
End If
Dim hasViableGenericEntryPoints As Boolean = False
Dim viableEntryPoints = ArrayBuilder(Of MethodSymbol).GetInstance()
For Each candidate In entryPointCandidates
If Not candidate.IsViableMainMethod Then
Continue For
End If
If candidate.IsGenericMethod OrElse candidate.ContainingType.IsGenericType Then
hasViableGenericEntryPoints = True
Else
viableEntryPoints.Add(candidate)
End If
Next
Dim entryPoint As MethodSymbol = Nothing
If viableEntryPoints.Count = 0 Then
If hasViableGenericEntryPoints Then
diagnostics.Add(ERRID.ERR_GenericSubMainsFound1, NoLocation.Singleton, errorTarget)
Else
diagnostics.Add(ERRID.ERR_InValidSubMainsFound1, NoLocation.Singleton, errorTarget)
End If
ElseIf viableEntryPoints.Count > 1 Then
viableEntryPoints.Sort(LexicalOrderSymbolComparer.Instance)
diagnostics.Add(ERRID.ERR_MoreThanOneValidMainWasFound2,
NoLocation.Singleton,
Me.AssemblyName,
New FormattedSymbolList(viableEntryPoints.ToArray(), CustomSymbolDisplayFormatter.ErrorMessageFormatNoModifiersNoReturnType))
Else
entryPoint = viableEntryPoints(0)
If entryPoint.IsAsync Then
' The rule we follow:
' First determine the Sub Main using pre-async rules, and give the pre-async errors if there were 0 or >1 results
' If there was exactly one result, but it was async, then give an error. Otherwise proceed.
' This doesn't follow the same pattern as "error due to being generic". That's because
' maybe one day we'll want to allow Async Sub Main but without breaking back-compat.
Dim sourceMethod = TryCast(entryPoint, SourceMemberMethodSymbol)
Debug.Assert(sourceMethod IsNot Nothing)
If sourceMethod IsNot Nothing Then
Dim location As Location = sourceMethod.NonMergedLocation
Debug.Assert(location IsNot Nothing)
If location IsNot Nothing Then
Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_AsyncSubMain)
End If
End If
End If
End If
viableEntryPoints.Free()
Return entryPoint
Finally
entryPointCandidates.Free()
sealedDiagnostics = diagnostics.ToReadOnlyAndFree()
End Try
End Function
Friend Class EntryPoint
Public ReadOnly MethodSymbol As MethodSymbol
Public ReadOnly Diagnostics As ImmutableArray(Of Diagnostic)
Public Sub New(methodSymbol As MethodSymbol, diagnostics As ImmutableArray(Of Diagnostic))
Me.MethodSymbol = methodSymbol
Me.Diagnostics = diagnostics
End Sub
End Class
''' <summary>
''' Returns the list of member imports that apply to all syntax trees in this compilation.
''' </summary>
Friend ReadOnly Property MemberImports As ImmutableArray(Of NamespaceOrTypeSymbol)
Get
Return DirectCast(Me.SourceModule, SourceModuleSymbol).MemberImports.SelectAsArray(Function(m) m.NamespaceOrType)
End Get
End Property
''' <summary>
''' Returns the list of alias imports that apply to all syntax trees in this compilation.
''' </summary>
Friend ReadOnly Property AliasImports As ImmutableArray(Of AliasSymbol)
Get
Return DirectCast(Me.SourceModule, SourceModuleSymbol).AliasImports.SelectAsArray(Function(a) a.Alias)
End Get
End Property
Friend Overrides Sub ReportUnusedImports(filterTree As SyntaxTree, diagnostics As DiagnosticBag, cancellationToken As CancellationToken)
If _lazyImportInfos IsNot Nothing AndAlso (filterTree Is Nothing OrElse filterTree.Options.DocumentationMode <> DocumentationMode.None) Then
Dim unusedBuilder As ArrayBuilder(Of TextSpan) = Nothing
For Each info As ImportInfo In _lazyImportInfos
cancellationToken.ThrowIfCancellationRequested()
Dim infoTree As SyntaxTree = info.Tree
If (filterTree Is Nothing OrElse filterTree Is infoTree) AndAlso infoTree.Options.DocumentationMode <> DocumentationMode.None Then
Dim clauseSpans = info.ClauseSpans
Dim numClauseSpans = clauseSpans.Length
If numClauseSpans = 1 Then
' Do less work in common case (one clause per statement).
If Not Me.IsImportDirectiveUsed(infoTree, clauseSpans(0).Start) Then
diagnostics.Add(ERRID.HDN_UnusedImportStatement, infoTree.GetLocation(info.StatementSpan))
End If
Else
If unusedBuilder IsNot Nothing Then
unusedBuilder.Clear()
End If
For Each clauseSpan In info.ClauseSpans
If Not Me.IsImportDirectiveUsed(infoTree, clauseSpan.Start) Then
If unusedBuilder Is Nothing Then
unusedBuilder = ArrayBuilder(Of TextSpan).GetInstance()
End If
unusedBuilder.Add(clauseSpan)
End If
Next
If unusedBuilder IsNot Nothing AndAlso unusedBuilder.Count > 0 Then
If unusedBuilder.Count = numClauseSpans Then
diagnostics.Add(ERRID.HDN_UnusedImportStatement, infoTree.GetLocation(info.StatementSpan))
Else
For Each clauseSpan In unusedBuilder
diagnostics.Add(ERRID.HDN_UnusedImportClause, infoTree.GetLocation(clauseSpan))
Next
End If
End If
End If
End If
Next
If unusedBuilder IsNot Nothing Then
unusedBuilder.Free()
End If
End If
CompleteTrees(filterTree)
End Sub
Friend Overrides Sub CompleteTrees(filterTree As SyntaxTree)
' By definition, a tree Is complete when all of its compiler diagnostics have been reported.
' Since unused imports are the last thing we compute And report, a tree Is complete when
' the unused imports have been reported.
If EventQueue IsNot Nothing Then
If filterTree IsNot Nothing Then
CompleteTree(filterTree)
Else
For Each tree As SyntaxTree In SyntaxTrees
CompleteTree(tree)
Next
End If
End If
End Sub
Private Sub CompleteTree(tree As SyntaxTree)
If tree.IsEmbeddedOrMyTemplateTree Then
' The syntax trees added to AllSyntaxTrees by the compiler
' do not count toward completion.
Return
End If
Debug.Assert(AllSyntaxTrees.Contains(tree))
If _lazyCompilationUnitCompletedTrees Is Nothing Then
Interlocked.CompareExchange(_lazyCompilationUnitCompletedTrees, New HashSet(Of SyntaxTree)(), Nothing)
End If
SyncLock _lazyCompilationUnitCompletedTrees
If _lazyCompilationUnitCompletedTrees.Add(tree) Then
' signal the end of the compilation unit
EventQueue.TryEnqueue(New CompilationUnitCompletedEvent(Me, tree))
If _lazyCompilationUnitCompletedTrees.Count = SyntaxTrees.Length Then
' if that was the last tree, signal the end of compilation
CompleteCompilationEventQueue_NoLock()
End If
End If
End SyncLock
End Sub
Friend Function ShouldAddEvent(symbol As Symbol) As Boolean
Return EventQueue IsNot Nothing AndAlso symbol.IsInSource()
End Function
Friend Sub SymbolDeclaredEvent(symbol As Symbol)
If ShouldAddEvent(symbol) Then
EventQueue.TryEnqueue(New SymbolDeclaredCompilationEvent(Me, symbol))
End If
End Sub
Friend Sub RecordImports(syntax As ImportsStatementSyntax)
LazyInitializer.EnsureInitialized(_lazyImportInfos).Enqueue(New ImportInfo(syntax))
End Sub
Private Structure ImportInfo
Public ReadOnly Tree As SyntaxTree
Public ReadOnly StatementSpan As TextSpan
Public ReadOnly ClauseSpans As ImmutableArray(Of TextSpan)
' CONSIDER: ClauseSpans will usually be a singleton. If we're
' creating too much garbage, it might be worthwhile to store
' a single clause span in a separate field.
Public Sub New(syntax As ImportsStatementSyntax)
Me.Tree = syntax.SyntaxTree
Me.StatementSpan = syntax.Span
Dim builder = ArrayBuilder(Of TextSpan).GetInstance()
For Each clause In syntax.ImportsClauses
builder.Add(clause.Span)
Next
Me.ClauseSpans = builder.ToImmutableAndFree()
End Sub
End Structure
Friend ReadOnly Property DeclaresTheObjectClass As Boolean
Get
Return SourceAssembly.DeclaresTheObjectClass
End Get
End Property
Friend Function MightContainNoPiaLocalTypes() As Boolean
Return SourceAssembly.MightContainNoPiaLocalTypes()
End Function
' NOTE(cyrusn): There is a bit of a discoverability problem with this method and the same
' named method in SyntaxTreeSemanticModel. Technically, i believe these are the appropriate
' locations for these methods. This method has no dependencies on anything but the
' compilation, while the other method needs a bindings object to determine what bound node
' an expression syntax binds to. Perhaps when we document these methods we should explain
' where a user can find the other.
''' <summary>
''' Determine what kind of conversion, if any, there is between the types
''' "source" and "destination".
''' </summary>
Public Shadows Function ClassifyConversion(source As ITypeSymbol, destination As ITypeSymbol) As Conversion
If source Is Nothing Then
Throw New ArgumentNullException(NameOf(source))
End If
If destination Is Nothing Then
Throw New ArgumentNullException(NameOf(destination))
End If
Dim vbsource = source.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(source))
Dim vbdest = destination.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(destination))
If vbsource.IsErrorType() OrElse vbdest.IsErrorType() Then
Return New Conversion(Nothing) ' No conversion
End If
Return New Conversion(Conversions.ClassifyConversion(vbsource, vbdest, Nothing))
End Function
Public Overrides Function ClassifyCommonConversion(source As ITypeSymbol, destination As ITypeSymbol) As CommonConversion
Return ClassifyConversion(source, destination).ToCommonConversion()
End Function
Friend Overrides Function ClassifyConvertibleConversion(source As IOperation, destination As ITypeSymbol, ByRef constantValue As [Optional](Of Object)) As IConvertibleConversion
constantValue = Nothing
If destination Is Nothing Then
Return New Conversion(Nothing) ' No conversion
End If
Dim sourceType As ITypeSymbol = source.Type
If sourceType Is Nothing Then
If source.ConstantValue.HasValue AndAlso source.ConstantValue.Value Is Nothing AndAlso destination.IsReferenceType Then
constantValue = source.ConstantValue
Return New Conversion(New KeyValuePair(Of ConversionKind, MethodSymbol)(ConversionKind.WideningNothingLiteral, Nothing))
End If
Return New Conversion(Nothing) ' No conversion
End If
Dim result As Conversion = ClassifyConversion(sourceType, destination)
If result.IsReference AndAlso source.ConstantValue.HasValue AndAlso source.ConstantValue.Value Is Nothing Then
constantValue = source.ConstantValue
End If
Return result
End Function
''' <summary>
''' A symbol representing the implicit Script class. This is null if the class is not
''' defined in the compilation.
''' </summary>
Friend Shadows ReadOnly Property ScriptClass As NamedTypeSymbol
Get
Return SourceScriptClass
End Get
End Property
Friend ReadOnly Property SourceScriptClass As ImplicitNamedTypeSymbol
Get
Return _scriptClass.Value
End Get
End Property
''' <summary>
''' Resolves a symbol that represents script container (Script class).
''' Uses the full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol.
''' </summary>
''' <returns>
''' The Script class symbol or null if it is not defined.
''' </returns>
Private Function BindScriptClass() As ImplicitNamedTypeSymbol
Return DirectCast(CommonBindScriptClass(), ImplicitNamedTypeSymbol)
End Function
''' <summary>
''' Get symbol for predefined type from Cor Library referenced by this compilation.
''' </summary>
Friend Shadows Function GetSpecialType(typeId As SpecialType) As NamedTypeSymbol
Dim result = Assembly.GetSpecialType(typeId)
Debug.Assert(result.SpecialType = typeId)
Return result
End Function
''' <summary>
''' Get symbol for predefined type member from Cor Library referenced by this compilation.
''' </summary>
Friend Shadows Function GetSpecialTypeMember(memberId As SpecialMember) As Symbol
Return Assembly.GetSpecialTypeMember(memberId)
End Function
Friend Overrides Function CommonGetSpecialTypeMember(specialMember As SpecialMember) As ISymbol
Return GetSpecialTypeMember(specialMember)
End Function
Friend Function GetTypeByReflectionType(type As Type, diagnostics As DiagnosticBag) As TypeSymbol
' TODO: See CSharpCompilation.GetTypeByReflectionType
Return GetSpecialType(SpecialType.System_Object)
End Function
''' <summary>
''' Lookup a type within the compilation's assembly and all referenced assemblies
''' using its canonical CLR metadata name (names are compared case-sensitively).
''' </summary>
''' <param name="fullyQualifiedMetadataName">
''' </param>
''' <returns>
''' Symbol for the type or null if type cannot be found or is ambiguous.
''' </returns>
Friend Shadows Function GetTypeByMetadataName(fullyQualifiedMetadataName As String) As NamedTypeSymbol
Return Me.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences:=True, isWellKnownType:=False, conflicts:=Nothing)
End Function
Friend Shadows ReadOnly Property ObjectType As NamedTypeSymbol
Get
Return Assembly.ObjectType
End Get
End Property
Friend Shadows Function CreateArrayTypeSymbol(elementType As TypeSymbol, Optional rank As Integer = 1) As ArrayTypeSymbol
If elementType Is Nothing Then
Throw New ArgumentNullException(NameOf(elementType))
End If
Return ArrayTypeSymbol.CreateVBArray(elementType, Nothing, rank, Me)
End Function
Friend ReadOnly Property HasTupleNamesAttributes As Boolean
Get
Return GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames) IsNot Nothing
End Get
End Property
Friend Function CanEmitSpecialType(type As SpecialType) As Boolean
Dim typeSymbol = GetSpecialType(type)
Dim diagnostic = typeSymbol.GetUseSiteErrorInfo
Return diagnostic Is Nothing OrElse diagnostic.Severity <> DiagnosticSeverity.Error
End Function
Private Protected Overrides Function IsSymbolAccessibleWithinCore(symbol As ISymbol, within As ISymbol, throughType As ITypeSymbol) As Boolean
Dim symbol0 = symbol.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(symbol))
Dim within0 = within.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(within))
Dim throughType0 = throughType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(throughType))
Return If(within0.Kind = SymbolKind.Assembly,
AccessCheck.IsSymbolAccessible(symbol0, DirectCast(within0, AssemblySymbol), useSiteDiagnostics:=Nothing),
AccessCheck.IsSymbolAccessible(symbol0, DirectCast(within0, NamedTypeSymbol), throughType0, useSiteDiagnostics:=Nothing))
End Function
<Obsolete("Compilation.IsSymbolAccessibleWithin is not designed for use within the compilers", True)>
Friend Shadows Function IsSymbolAccessibleWithin(symbol As ISymbol, within As ISymbol, Optional throughType As ITypeSymbol = Nothing) As Boolean
Throw New NotImplementedException
End Function
#End Region
#Region "Binding"
'''<summary>
''' Get a fresh SemanticModel. Note that each invocation gets a fresh SemanticModel, each of
''' which has a cache. Therefore, one effectively clears the cache by discarding the
''' SemanticModel.
'''</summary>
Public Shadows Function GetSemanticModel(syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False) As SemanticModel
Return New SyntaxTreeSemanticModel(Me, DirectCast(Me.SourceModule, SourceModuleSymbol), syntaxTree, ignoreAccessibility)
End Function
Friend ReadOnly Property FeatureStrictEnabled As Boolean
Get
Return Me.Feature("strict") IsNot Nothing
End Get
End Property
#End Region
#Region "Diagnostics"
Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider
Get
Return VisualBasic.MessageProvider.Instance
End Get
End Property
''' <summary>
''' Get all diagnostics for the entire compilation. This includes diagnostics from parsing, declarations, and
''' the bodies of methods. Getting all the diagnostics is potentially a length operations, as it requires parsing and
''' compiling all the code. The set of diagnostics is not caches, so each call to this method will recompile all
''' methods.
''' </summary>
''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param>
Public Overrides Function GetDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return GetDiagnostics(DefaultDiagnosticsStage, True, cancellationToken)
End Function
''' <summary>
''' Get parse diagnostics for the entire compilation. This includes diagnostics from parsing BUT NOT from declarations and
''' the bodies of methods or initializers. The set of parse diagnostics is cached, so calling this method a second time
''' should be fast.
''' </summary>
Public Overrides Function GetParseDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return GetDiagnostics(CompilationStage.Parse, False, cancellationToken)
End Function
''' <summary>
''' Get declarations diagnostics for the entire compilation. This includes diagnostics from declarations, BUT NOT
''' the bodies of methods or initializers. The set of declaration diagnostics is cached, so calling this method a second time
''' should be fast.
''' </summary>
''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param>
Public Overrides Function GetDeclarationDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return GetDiagnostics(CompilationStage.Declare, False, cancellationToken)
End Function
''' <summary>
''' Get method body diagnostics for the entire compilation. This includes diagnostics only from
''' the bodies of methods and initializers. These diagnostics are NOT cached, so calling this method a second time
''' repeats significant work.
''' </summary>
''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param>
Public Overrides Function GetMethodBodyDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return GetDiagnostics(CompilationStage.Compile, False, cancellationToken)
End Function
''' <summary>
''' Get all errors in the compilation, up through the given compilation stage. Note that this may
''' require significant work by the compiler, as all source code must be compiled to the given
''' level in order to get the errors. Errors on Options should be inspected by the user prior to constructing the compilation.
''' </summary>
''' <returns>
''' Returns all errors. The errors are not sorted in any particular order, and the client
''' should sort the errors as desired.
''' </returns>
Friend Overloads Function GetDiagnostics(stage As CompilationStage, Optional includeEarlierStages As Boolean = True, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Dim diagnostics = DiagnosticBag.GetInstance()
GetDiagnostics(stage, includeEarlierStages, diagnostics, cancellationToken)
Return diagnostics.ToReadOnlyAndFree()
End Function
Friend Overrides Sub GetDiagnostics(stage As CompilationStage,
includeEarlierStages As Boolean,
diagnostics As DiagnosticBag,
Optional cancellationToken As CancellationToken = Nothing)
Dim builder = DiagnosticBag.GetInstance()
' Add all parsing errors.
If (stage = CompilationStage.Parse OrElse stage > CompilationStage.Parse AndAlso includeEarlierStages) Then
' Embedded trees shouldn't have any errors, let's avoid making decision if they should be added too early.
' Otherwise IDE performance might be affect.
If Options.ConcurrentBuild Then
Dim options = New ParallelOptions() With {.CancellationToken = cancellationToken}
Parallel.For(0, SyntaxTrees.Length, options,
UICultureUtilities.WithCurrentUICulture(Sub(i As Integer) builder.AddRange(SyntaxTrees(i).GetDiagnostics(cancellationToken))))
Else
For Each tree In SyntaxTrees
cancellationToken.ThrowIfCancellationRequested()
builder.AddRange(tree.GetDiagnostics(cancellationToken))
Next
End If
Dim parseOptionsReported = New HashSet(Of ParseOptions)
If Options.ParseOptions IsNot Nothing Then
parseOptionsReported.Add(Options.ParseOptions) ' This is reported in Options.Errors at CompilationStage.Declare
End If
For Each tree In SyntaxTrees
cancellationToken.ThrowIfCancellationRequested()
If Not tree.Options.Errors.IsDefaultOrEmpty AndAlso parseOptionsReported.Add(tree.Options) Then
Dim location = tree.GetLocation(TextSpan.FromBounds(0, 0))
For Each err In tree.Options.Errors
builder.Add(err.WithLocation(location))
Next
End If
Next
End If
' Add declaration errors
If (stage = CompilationStage.Declare OrElse stage > CompilationStage.Declare AndAlso includeEarlierStages) Then
CheckAssemblyName(builder)
builder.AddRange(Options.Errors)
builder.AddRange(GetBoundReferenceManager().Diagnostics)
builder.AddRange(SourceAssembly.GetAllDeclarationErrors(cancellationToken))
builder.AddRange(GetClsComplianceDiagnostics(cancellationToken))
If EventQueue IsNot Nothing AndAlso SyntaxTrees.Length = 0 Then
EnsureCompilationEventQueueCompleted()
End If
End If
' Add method body compilation errors.
If (stage = CompilationStage.Compile OrElse stage > CompilationStage.Compile AndAlso includeEarlierStages) Then
' Note: this phase does not need to be parallelized because
' it is already implemented in method compiler
Dim methodBodyDiagnostics = DiagnosticBag.GetInstance()
GetDiagnosticsForAllMethodBodies(builder.HasAnyErrors(), methodBodyDiagnostics, stage, cancellationToken)
builder.AddRangeAndFree(methodBodyDiagnostics)
End If
' Before returning diagnostics, we filter some of them
' to honor the compiler options (e.g., /nowarn and /warnaserror)
FilterAndAppendAndFreeDiagnostics(diagnostics, builder)
End Sub
Private Function GetClsComplianceDiagnostics(cancellationToken As CancellationToken, Optional filterTree As SyntaxTree = Nothing, Optional filterSpanWithinTree As TextSpan? = Nothing) As ImmutableArray(Of Diagnostic)
If filterTree IsNot Nothing Then
Dim builder = DiagnosticBag.GetInstance()
ClsComplianceChecker.CheckCompliance(Me, builder, cancellationToken, filterTree, filterSpanWithinTree)
Return builder.ToReadOnlyAndFree()
End If
Debug.Assert(filterSpanWithinTree Is Nothing)
If _lazyClsComplianceDiagnostics.IsDefault Then
Dim builder = DiagnosticBag.GetInstance()
ClsComplianceChecker.CheckCompliance(Me, builder, cancellationToken)
ImmutableInterlocked.InterlockedInitialize(_lazyClsComplianceDiagnostics, builder.ToReadOnlyAndFree())
End If
Debug.Assert(Not _lazyClsComplianceDiagnostics.IsDefault)
Return _lazyClsComplianceDiagnostics
End Function
Private Shared Iterator Function FilterDiagnosticsByLocation(diagnostics As IEnumerable(Of Diagnostic), tree As SyntaxTree, filterSpanWithinTree As TextSpan?) As IEnumerable(Of Diagnostic)
For Each diagnostic In diagnostics
If diagnostic.HasIntersectingLocation(tree, filterSpanWithinTree) Then
Yield diagnostic
End If
Next
End Function
Friend Function GetDiagnosticsForSyntaxTree(stage As CompilationStage,
tree As SyntaxTree,
filterSpanWithinTree As TextSpan?,
includeEarlierStages As Boolean,
Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
If Not SyntaxTrees.Contains(tree) Then
Throw New ArgumentException("Cannot GetDiagnosticsForSyntax for a tree that is not part of the compilation", NameOf(tree))
End If
Dim builder = DiagnosticBag.GetInstance()
If (stage = CompilationStage.Parse OrElse stage > CompilationStage.Parse AndAlso includeEarlierStages) Then
' Add all parsing errors.
cancellationToken.ThrowIfCancellationRequested()
Dim syntaxDiagnostics = tree.GetDiagnostics(cancellationToken)
syntaxDiagnostics = FilterDiagnosticsByLocation(syntaxDiagnostics, tree, filterSpanWithinTree)
builder.AddRange(syntaxDiagnostics)
End If
' Add declaring errors
If (stage = CompilationStage.Declare OrElse stage > CompilationStage.Declare AndAlso includeEarlierStages) Then
Dim declarationDiags = DirectCast(SourceModule, SourceModuleSymbol).GetDeclarationErrorsInTree(tree, filterSpanWithinTree, AddressOf FilterDiagnosticsByLocation, cancellationToken)
Dim filteredDiags = FilterDiagnosticsByLocation(declarationDiags, tree, filterSpanWithinTree)
builder.AddRange(filteredDiags)
builder.AddRange(GetClsComplianceDiagnostics(cancellationToken, tree, filterSpanWithinTree))
End If
' Add method body declaring errors.
If (stage = CompilationStage.Compile OrElse stage > CompilationStage.Compile AndAlso includeEarlierStages) Then
Dim methodBodyDiagnostics = DiagnosticBag.GetInstance()
GetDiagnosticsForMethodBodiesInTree(tree, filterSpanWithinTree, builder.HasAnyErrors(), methodBodyDiagnostics, stage, cancellationToken)
' This diagnostics can include diagnostics for initializers that do not belong to the tree.
' Let's filter them out.
If Not methodBodyDiagnostics.IsEmptyWithoutResolution Then
Dim allDiags = methodBodyDiagnostics.AsEnumerableWithoutResolution()
Dim filteredDiags = FilterDiagnosticsByLocation(allDiags, tree, filterSpanWithinTree)
For Each diag In filteredDiags
builder.Add(diag)
Next
End If
End If
Dim result = DiagnosticBag.GetInstance()
FilterAndAppendAndFreeDiagnostics(result, builder)
Return result.ToReadOnlyAndFree(Of Diagnostic)()
End Function
' Get diagnostics by compiling all method bodies.
Private Sub GetDiagnosticsForAllMethodBodies(hasDeclarationErrors As Boolean, diagnostics As DiagnosticBag, stage As CompilationStage, cancellationToken As CancellationToken)
MethodCompiler.GetCompileDiagnostics(Me, SourceModule.GlobalNamespace, Nothing, Nothing, hasDeclarationErrors, diagnostics, stage >= CompilationStage.Emit, cancellationToken)
DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, Nothing, Nothing, diagnostics, cancellationToken)
Me.ReportUnusedImports(Nothing, diagnostics, cancellationToken)
End Sub
' Get diagnostics by compiling all method bodies in the given tree.
Private Sub GetDiagnosticsForMethodBodiesInTree(tree As SyntaxTree, filterSpanWithinTree As TextSpan?, hasDeclarationErrors As Boolean, diagnostics As DiagnosticBag, stage As CompilationStage, cancellationToken As CancellationToken)
Dim sourceMod = DirectCast(SourceModule, SourceModuleSymbol)
MethodCompiler.GetCompileDiagnostics(Me,
SourceModule.GlobalNamespace,
tree,
filterSpanWithinTree,
hasDeclarationErrors,
diagnostics,
stage >= CompilationStage.Emit,
cancellationToken)
DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, Nothing, Nothing, diagnostics, cancellationToken, tree, filterSpanWithinTree)
' Report unused import diagnostics only if computing diagnostics for the entire tree.
' Otherwise we cannot determine if a particular directive is used outside of the given sub-span within the tree.
If Not filterSpanWithinTree.HasValue OrElse filterSpanWithinTree.Value = tree.GetRoot(cancellationToken).FullSpan Then
Me.ReportUnusedImports(tree, diagnostics, cancellationToken)
End If
End Sub
Friend Overrides Function AnalyzerForLanguage(analyzers As ImmutableArray(Of DiagnosticAnalyzer), analyzerManager As AnalyzerManager) As AnalyzerDriver
Dim getKind As Func(Of SyntaxNode, SyntaxKind) = Function(node As SyntaxNode) node.Kind
Dim isComment As Func(Of SyntaxTrivia, Boolean) = Function(trivia As SyntaxTrivia) trivia.Kind() = SyntaxKind.CommentTrivia
Return New AnalyzerDriver(Of SyntaxKind)(analyzers, getKind, analyzerManager, isComment)
End Function
#End Region
#Region "Resources"
Protected Overrides Sub AppendDefaultVersionResource(resourceStream As Stream)
Dim fileVersion As String = If(SourceAssembly.FileVersion, SourceAssembly.Identity.Version.ToString())
'for some parameters, alink used to supply whitespace instead of null.
Win32ResourceConversions.AppendVersionToResourceStream(resourceStream,
Not Me.Options.OutputKind.IsApplication(),
fileVersion:=fileVersion,
originalFileName:=Me.SourceModule.Name,
internalName:=Me.SourceModule.Name,
productVersion:=If(SourceAssembly.InformationalVersion, fileVersion),
assemblyVersion:=SourceAssembly.Identity.Version,
fileDescription:=If(SourceAssembly.Title, " "),
legalCopyright:=If(SourceAssembly.Copyright, " "),
legalTrademarks:=SourceAssembly.Trademark,
productName:=SourceAssembly.Product,
comments:=SourceAssembly.Description,
companyName:=SourceAssembly.Company)
End Sub
#End Region
#Region "Emit"
Friend Overrides ReadOnly Property LinkerMajorVersion As Byte
Get
Return &H50
End Get
End Property
Friend Overrides ReadOnly Property IsDelaySigned As Boolean
Get
Return SourceAssembly.IsDelaySigned
End Get
End Property
Friend Overrides ReadOnly Property StrongNameKeys As StrongNameKeys
Get
Return SourceAssembly.StrongNameKeys
End Get
End Property
Friend Overrides Function CreateModuleBuilder(
emitOptions As EmitOptions,
debugEntryPoint As IMethodSymbol,
sourceLinkStream As Stream,
embeddedTexts As IEnumerable(Of EmbeddedText),
manifestResources As IEnumerable(Of ResourceDescription),
testData As CompilationTestData,
diagnostics As DiagnosticBag,
cancellationToken As CancellationToken) As CommonPEModuleBuilder
Return CreateModuleBuilder(
emitOptions,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
manifestResources,
testData,
diagnostics,
ImmutableArray(Of NamedTypeSymbol).Empty,
cancellationToken)
End Function
Friend Overloads Function CreateModuleBuilder(
emitOptions As EmitOptions,
debugEntryPoint As IMethodSymbol,
sourceLinkStream As Stream,
embeddedTexts As IEnumerable(Of EmbeddedText),
manifestResources As IEnumerable(Of ResourceDescription),
testData As CompilationTestData,
diagnostics As DiagnosticBag,
additionalTypes As ImmutableArray(Of NamedTypeSymbol),
cancellationToken As CancellationToken) As CommonPEModuleBuilder
Debug.Assert(Not IsSubmission OrElse HasCodeToEmit())
' Get the runtime metadata version from the cor library. If this fails we have no reasonable value to give.
Dim runtimeMetadataVersion = GetRuntimeMetadataVersion()
Dim moduleSerializationProperties = ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion)
If manifestResources Is Nothing Then
manifestResources = SpecializedCollections.EmptyEnumerable(Of ResourceDescription)()
End If
' if there is no stream to write to, then there is no need for a module
Dim moduleBeingBuilt As PEModuleBuilder
If Options.OutputKind.IsNetModule() Then
Debug.Assert(additionalTypes.IsEmpty)
moduleBeingBuilt = New PENetModuleBuilder(
DirectCast(Me.SourceModule, SourceModuleSymbol),
emitOptions,
moduleSerializationProperties,
manifestResources)
Else
Dim kind = If(Options.OutputKind.IsValid(), Options.OutputKind, OutputKind.DynamicallyLinkedLibrary)
moduleBeingBuilt = New PEAssemblyBuilder(
SourceAssembly,
emitOptions,
kind,
moduleSerializationProperties,
manifestResources,
additionalTypes)
End If
If debugEntryPoint IsNot Nothing Then
moduleBeingBuilt.SetDebugEntryPoint(DirectCast(debugEntryPoint, MethodSymbol), diagnostics)
End If
moduleBeingBuilt.SourceLinkStreamOpt = sourceLinkStream
If embeddedTexts IsNot Nothing Then
moduleBeingBuilt.EmbeddedTexts = embeddedTexts
End If
If testData IsNot Nothing Then
moduleBeingBuilt.SetMethodTestData(testData.Methods)
testData.Module = moduleBeingBuilt
End If
Return moduleBeingBuilt
End Function
Friend Overrides Function CompileMethods(
moduleBuilder As CommonPEModuleBuilder,
emittingPdb As Boolean,
emitMetadataOnly As Boolean,
emitTestCoverageData As Boolean,
diagnostics As DiagnosticBag,
filterOpt As Predicate(Of ISymbol),
cancellationToken As CancellationToken) As Boolean
' The diagnostics should include syntax and declaration errors. We insert these before calling Emitter.Emit, so that we don't emit
' metadata if there are declaration errors or method body errors (but we do insert all errors from method body binding...)
Dim hasDeclarationErrors = Not FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, True, cancellationToken), exclude:=Nothing)
Dim moduleBeingBuilt = DirectCast(moduleBuilder, PEModuleBuilder)
Me.EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(Me)
' The translation of global imports assumes absence of error symbols.
' We don't need to translate them if there are any declaration errors since
' we are not going to emit the metadata.
If Not hasDeclarationErrors Then
moduleBeingBuilt.TranslateImports(diagnostics)
End If
If emitMetadataOnly Then
If hasDeclarationErrors Then
Return False
End If
If moduleBeingBuilt.SourceModule.HasBadAttributes Then
' If there were errors but no declaration diagnostics, explicitly add a "Failed to emit module" error.
diagnostics.Add(ERRID.ERR_ModuleEmitFailure, NoLocation.Singleton, moduleBeingBuilt.SourceModule.Name)
Return False
End If
SynthesizedMetadataCompiler.ProcessSynthesizedMembers(Me, moduleBeingBuilt, cancellationToken)
Else
' start generating PDB checksums if we need to emit PDBs
If (emittingPdb OrElse emitTestCoverageData) AndAlso
Not CreateDebugDocuments(moduleBeingBuilt.DebugDocumentsBuilder, moduleBeingBuilt.EmbeddedTexts, diagnostics) Then
Return False
End If
' Perform initial bind of method bodies in spite of earlier errors. This is the same
' behavior as when calling GetDiagnostics()
' Use a temporary bag so we don't have to refilter pre-existing diagnostics.
Dim methodBodyDiagnosticBag = DiagnosticBag.GetInstance()
MethodCompiler.CompileMethodBodies(
Me,
moduleBeingBuilt,
emittingPdb,
emitTestCoverageData,
hasDeclarationErrors,
filterOpt,
methodBodyDiagnosticBag,
cancellationToken)
Dim hasMethodBodyErrors As Boolean = Not FilterAndAppendAndFreeDiagnostics(diagnostics, methodBodyDiagnosticBag)
If hasDeclarationErrors OrElse hasMethodBodyErrors Then
Return False
End If
End If
cancellationToken.ThrowIfCancellationRequested()
' TODO (tomat): XML doc comments diagnostics
Return True
End Function
Friend Overrides Function GenerateResourcesAndDocumentationComments(
moduleBuilder As CommonPEModuleBuilder,
xmlDocStream As Stream,
win32Resources As Stream,
outputNameOverride As String,
diagnostics As DiagnosticBag,
cancellationToken As CancellationToken) As Boolean
' Use a temporary bag so we don't have to refilter pre-existing diagnostics.
Dim resourceDiagnostics = DiagnosticBag.GetInstance()
SetupWin32Resources(moduleBuilder, win32Resources, resourceDiagnostics)
' give the name of any added modules, but not the name of the primary module.
ReportManifestResourceDuplicates(
moduleBuilder.ManifestResources,
SourceAssembly.Modules.Skip(1).Select(Function(x) x.Name),
AddedModulesResourceNames(resourceDiagnostics),
resourceDiagnostics)
If Not FilterAndAppendAndFreeDiagnostics(diagnostics, resourceDiagnostics) Then
Return False
End If
cancellationToken.ThrowIfCancellationRequested()
' Use a temporary bag so we don't have to refilter pre-existing diagnostics.
Dim xmlDiagnostics = DiagnosticBag.GetInstance()
Dim assemblyName = FileNameUtilities.ChangeExtension(outputNameOverride, extension:=Nothing)
DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, assemblyName, xmlDocStream, xmlDiagnostics, cancellationToken)
Return FilterAndAppendAndFreeDiagnostics(diagnostics, xmlDiagnostics)
End Function
Private Iterator Function AddedModulesResourceNames(diagnostics As DiagnosticBag) As IEnumerable(Of String)
Dim modules As ImmutableArray(Of ModuleSymbol) = SourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1
Dim m = DirectCast(modules(i), Symbols.Metadata.PE.PEModuleSymbol)
Try
For Each resource In m.Module.GetEmbeddedResourcesOrThrow()
Yield resource.Name
Next
Catch mrEx As BadImageFormatException
diagnostics.Add(ERRID.ERR_UnsupportedModule1, NoLocation.Singleton, m)
End Try
Next
End Function
Friend Overrides Function EmitDifference(
baseline As EmitBaseline,
edits As IEnumerable(Of SemanticEdit),
isAddedSymbol As Func(Of ISymbol, Boolean),
metadataStream As Stream,
ilStream As Stream,
pdbStream As Stream,
updatedMethods As ICollection(Of MethodDefinitionHandle),
testData As CompilationTestData,
cancellationToken As CancellationToken) As EmitDifferenceResult
Return EmitHelpers.EmitDifference(
Me,
baseline,
edits,
isAddedSymbol,
metadataStream,
ilStream,
pdbStream,
updatedMethods,
testData,
cancellationToken)
End Function
Friend Function GetRuntimeMetadataVersion() As String
Dim corLibrary = TryCast(Assembly.CorLibrary, Symbols.Metadata.PE.PEAssemblySymbol)
Return If(corLibrary Is Nothing, String.Empty, corLibrary.Assembly.ManifestModule.MetadataVersion)
End Function
Friend Overrides Sub AddDebugSourceDocumentsForChecksumDirectives(
documentsBuilder As DebugDocumentsBuilder,
tree As SyntaxTree,
diagnosticBag As DiagnosticBag)
Dim checksumDirectives = tree.GetRoot().GetDirectives(Function(d) d.Kind = SyntaxKind.ExternalChecksumDirectiveTrivia AndAlso
Not d.ContainsDiagnostics)
For Each directive In checksumDirectives
Dim checksumDirective As ExternalChecksumDirectiveTriviaSyntax = DirectCast(directive, ExternalChecksumDirectiveTriviaSyntax)
Dim path = checksumDirective.ExternalSource.ValueText
Dim checkSumText = checksumDirective.Checksum.ValueText
Dim normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(path, basePath:=tree.FilePath)
Dim existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath)
If existingDoc IsNot Nothing Then
' directive matches a file path on an actual tree.
' Dev12 compiler just ignores the directive in this case which means that
' checksum of the actual tree always wins and no warning is given.
' We will continue doing the same.
If existingDoc.IsComputedChecksum Then
Continue For
End If
Dim sourceInfo = existingDoc.GetSourceInfo()
If CheckSumMatches(checkSumText, sourceInfo.Checksum) Then
Dim guid As Guid = Guid.Parse(checksumDirective.Guid.ValueText)
If guid = sourceInfo.ChecksumAlgorithmId Then
' all parts match, nothing to do
Continue For
End If
End If
' did not match to an existing document
' produce a warning and ignore the directive
diagnosticBag.Add(ERRID.WRN_MultipleDeclFileExtChecksum, New SourceLocation(checksumDirective), path)
Else
Dim newDocument = New DebugSourceDocument(
normalizedPath,
DebugSourceDocument.CorSymLanguageTypeBasic,
MakeCheckSumBytes(checksumDirective.Checksum.ValueText),
Guid.Parse(checksumDirective.Guid.ValueText))
documentsBuilder.AddDebugDocument(newDocument)
End If
Next
End Sub
Private Shared Function CheckSumMatches(bytesText As String, bytes As ImmutableArray(Of Byte)) As Boolean
If bytesText.Length <> bytes.Length * 2 Then
Return False
End If
For i As Integer = 0 To bytesText.Length \ 2 - 1
' 1A in text becomes 0x1A
Dim b As Integer = SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2)) * 16 +
SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2 + 1))
If b <> bytes(i) Then
Return False
End If
Next
Return True
End Function
Private Shared Function MakeCheckSumBytes(bytesText As String) As ImmutableArray(Of Byte)
Dim builder As ArrayBuilder(Of Byte) = ArrayBuilder(Of Byte).GetInstance()
For i As Integer = 0 To bytesText.Length \ 2 - 1
' 1A in text becomes 0x1A
Dim b As Byte = CByte(SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2)) * 16 +
SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2 + 1)))
builder.Add(b)
Next
Return builder.ToImmutableAndFree()
End Function
Friend Overrides ReadOnly Property DebugSourceDocumentLanguageId As Guid
Get
Return DebugSourceDocument.CorSymLanguageTypeBasic
End Get
End Property
Friend Overrides Function HasCodeToEmit() As Boolean
For Each syntaxTree In SyntaxTrees
Dim unit = syntaxTree.GetCompilationUnitRoot()
If unit.Members.Count > 0 Then
Return True
End If
Next
Return False
End Function
#End Region
#Region "Common Members"
Protected Overrides Function CommonWithReferences(newReferences As IEnumerable(Of MetadataReference)) As Compilation
Return WithReferences(newReferences)
End Function
Protected Overrides Function CommonWithAssemblyName(assemblyName As String) As Compilation
Return WithAssemblyName(assemblyName)
End Function
Protected Overrides Function CommonWithScriptCompilationInfo(info As ScriptCompilationInfo) As Compilation
Return WithScriptCompilationInfo(DirectCast(info, VisualBasicScriptCompilationInfo))
End Function
Protected Overrides ReadOnly Property CommonAssembly As IAssemblySymbol
Get
Return Me.Assembly
End Get
End Property
Protected Overrides ReadOnly Property CommonGlobalNamespace As INamespaceSymbol
Get
Return Me.GlobalNamespace
End Get
End Property
Protected Overrides ReadOnly Property CommonOptions As CompilationOptions
Get
Return Options
End Get
End Property
Protected Overrides Function CommonGetSemanticModel(syntaxTree As SyntaxTree, ignoreAccessibility As Boolean) As SemanticModel
Return Me.GetSemanticModel(syntaxTree, ignoreAccessibility)
End Function
Protected Overrides ReadOnly Property CommonSyntaxTrees As IEnumerable(Of SyntaxTree)
Get
Return Me.SyntaxTrees
End Get
End Property
Protected Overrides Function CommonAddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As Compilation
Dim array = TryCast(trees, SyntaxTree())
If array IsNot Nothing Then
Return Me.AddSyntaxTrees(array)
End If
If trees Is Nothing Then
Throw New ArgumentNullException(NameOf(trees))
End If
Return Me.AddSyntaxTrees(trees.Cast(Of SyntaxTree)())
End Function
Protected Overrides Function CommonRemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As Compilation
Dim array = TryCast(trees, SyntaxTree())
If array IsNot Nothing Then
Return Me.RemoveSyntaxTrees(array)
End If
If trees Is Nothing Then
Throw New ArgumentNullException(NameOf(trees))
End If
Return Me.RemoveSyntaxTrees(trees.Cast(Of SyntaxTree)())
End Function
Protected Overrides Function CommonRemoveAllSyntaxTrees() As Compilation
Return Me.RemoveAllSyntaxTrees()
End Function
Protected Overrides Function CommonReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As Compilation
Return Me.ReplaceSyntaxTree(oldTree, newTree)
End Function
Protected Overrides Function CommonWithOptions(options As CompilationOptions) As Compilation
Return Me.WithOptions(DirectCast(options, VisualBasicCompilationOptions))
End Function
Protected Overrides Function CommonContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean
Return Me.ContainsSyntaxTree(syntaxTree)
End Function
Protected Overrides Function CommonGetAssemblyOrModuleSymbol(reference As MetadataReference) As ISymbol
Return Me.GetAssemblyOrModuleSymbol(reference)
End Function
Protected Overrides Function CommonClone() As Compilation
Return Me.Clone()
End Function
Protected Overrides ReadOnly Property CommonSourceModule As IModuleSymbol
Get
Return Me.SourceModule
End Get
End Property
Protected Overrides Function CommonGetSpecialType(specialType As SpecialType) As INamedTypeSymbol
Return Me.GetSpecialType(specialType)
End Function
Protected Overrides Function CommonGetCompilationNamespace(namespaceSymbol As INamespaceSymbol) As INamespaceSymbol
Return Me.GetCompilationNamespace(namespaceSymbol)
End Function
Protected Overrides Function CommonGetTypeByMetadataName(metadataName As String) As INamedTypeSymbol
Return Me.GetTypeByMetadataName(metadataName)
End Function
Protected Overrides ReadOnly Property CommonScriptClass As INamedTypeSymbol
Get
Return Me.ScriptClass
End Get
End Property
Protected Overrides Function CommonCreateErrorTypeSymbol(container As INamespaceOrTypeSymbol, name As String, arity As Integer) As INamedTypeSymbol
Return New ExtendedErrorTypeSymbol(
container.EnsureVbSymbolOrNothing(Of NamespaceOrTypeSymbol)(NameOf(container)),
name, arity)
End Function
Protected Overrides Function CommonCreateErrorNamespaceSymbol(container As INamespaceSymbol, name As String) As INamespaceSymbol
Return New MissingNamespaceSymbol(
container.EnsureVbSymbolOrNothing(Of NamespaceSymbol)(NameOf(container)),
name)
End Function
Protected Overrides Function CommonCreateArrayTypeSymbol(elementType As ITypeSymbol, rank As Integer) As IArrayTypeSymbol
Return CreateArrayTypeSymbol(elementType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(elementType)), rank)
End Function
Protected Overrides Function CommonCreateTupleTypeSymbol(elementTypes As ImmutableArray(Of ITypeSymbol),
elementNames As ImmutableArray(Of String),
elementLocations As ImmutableArray(Of Location)) As INamedTypeSymbol
Dim typesBuilder = ArrayBuilder(Of TypeSymbol).GetInstance(elementTypes.Length)
For i As Integer = 0 To elementTypes.Length - 1
typesBuilder.Add(elementTypes(i).EnsureVbSymbolOrNothing(Of TypeSymbol)($"{NameOf(elementTypes)}[{i}]"))
Next
'no location for the type declaration
Return TupleTypeSymbol.Create(locationOpt:=Nothing,
elementTypes:=typesBuilder.ToImmutableAndFree(),
elementLocations:=elementLocations,
elementNames:=elementNames, compilation:=Me,
shouldCheckConstraints:=False, errorPositions:=Nothing)
End Function
Protected Overrides Function CommonCreateTupleTypeSymbol(
underlyingType As INamedTypeSymbol,
elementNames As ImmutableArray(Of String),
elementLocations As ImmutableArray(Of Location)) As INamedTypeSymbol
Dim csharpUnderlyingTuple = underlyingType.EnsureVbSymbolOrNothing(Of NamedTypeSymbol)(NameOf(underlyingType))
Dim cardinality As Integer
If Not csharpUnderlyingTuple.IsTupleCompatible(cardinality) Then
Throw New ArgumentException(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, NameOf(underlyingType))
End If
elementNames = CheckTupleElementNames(cardinality, elementNames)
CheckTupleElementLocations(cardinality, elementLocations)
Return TupleTypeSymbol.Create(
locationOpt:=Nothing,
tupleCompatibleType:=underlyingType.EnsureVbSymbolOrNothing(Of NamedTypeSymbol)(NameOf(underlyingType)),
elementLocations:=elementLocations,
elementNames:=elementNames,
errorPositions:=Nothing)
End Function
Protected Overrides Function CommonCreatePointerTypeSymbol(elementType As ITypeSymbol) As IPointerTypeSymbol
Throw New NotSupportedException(VBResources.ThereAreNoPointerTypesInVB)
End Function
Protected Overrides Function CommonCreateAnonymousTypeSymbol(
memberTypes As ImmutableArray(Of ITypeSymbol),
memberNames As ImmutableArray(Of String),
memberLocations As ImmutableArray(Of Location),
memberIsReadOnly As ImmutableArray(Of Boolean)) As INamedTypeSymbol
Dim i = 0
For Each t In memberTypes
t.EnsureVbSymbolOrNothing(Of TypeSymbol)($"{NameOf(memberTypes)}({i})")
i = i + 1
Next
Dim fields = ArrayBuilder(Of AnonymousTypeField).GetInstance()
For i = 0 To memberTypes.Length - 1
Dim type = memberTypes(i)
Dim name = memberNames(i)
Dim loc = If(memberLocations.IsDefault, Location.None, memberLocations(i))
Dim isReadOnly = memberIsReadOnly.IsDefault OrElse memberIsReadOnly(i)
fields.Add(New AnonymousTypeField(name, DirectCast(type, TypeSymbol), loc, isReadOnly))
Next
Dim descriptor = New AnonymousTypeDescriptor(
fields.ToImmutableAndFree(), Location.None, isImplicitlyDeclared:=False)
Return Me.AnonymousTypeManager.ConstructAnonymousTypeSymbol(descriptor)
End Function
Protected Overrides ReadOnly Property CommonDynamicType As ITypeSymbol
Get
Throw New NotSupportedException(VBResources.ThereIsNoDynamicTypeInVB)
End Get
End Property
Protected Overrides ReadOnly Property CommonObjectType As INamedTypeSymbol
Get
Return Me.ObjectType
End Get
End Property
Protected Overrides Function CommonGetEntryPoint(cancellationToken As CancellationToken) As IMethodSymbol
Return Me.GetEntryPoint(cancellationToken)
End Function
''' <summary>
''' Return true if there is a source declaration symbol name that meets given predicate.
''' </summary>
Public Overrides Function ContainsSymbolsWithName(predicate As Func(Of String, Boolean), Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As Boolean
If predicate Is Nothing Then
Throw New ArgumentNullException(NameOf(predicate))
End If
If filter = SymbolFilter.None Then
Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter))
End If
Return DeclarationTable.ContainsName(MergedRootDeclaration, predicate, filter, cancellationToken)
End Function
''' <summary>
''' Return source declaration symbols whose name meets given predicate.
''' </summary>
Public Overrides Function GetSymbolsWithName(predicate As Func(Of String, Boolean), Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of ISymbol)
If predicate Is Nothing Then
Throw New ArgumentNullException(NameOf(predicate))
End If
If filter = SymbolFilter.None Then
Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter))
End If
Return New PredicateSymbolSearcher(Me, filter, predicate, cancellationToken).GetSymbolsWithName()
End Function
#Disable Warning RS0026 ' Do not add multiple public overloads with optional parameters
''' <summary>
''' Return true if there is a source declaration symbol name that matches the provided name.
''' This may be faster than <see cref="ContainsSymbolsWithName(Func(Of String, Boolean),
''' SymbolFilter, CancellationToken)"/> when predicate is just a simple string check.
''' <paramref name="name"/> is case insensitive.
''' </summary>
Public Overrides Function ContainsSymbolsWithName(name As String, Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As Boolean
If name Is Nothing Then
Throw New ArgumentNullException(NameOf(name))
End If
If filter = SymbolFilter.None Then
Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter))
End If
Return DeclarationTable.ContainsName(MergedRootDeclaration, name, filter, cancellationToken)
End Function
Public Overrides Function GetSymbolsWithName(name As String, Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of ISymbol)
If name Is Nothing Then
Throw New ArgumentNullException(NameOf(name))
End If
If filter = SymbolFilter.None Then
Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter))
End If
Return New NameSymbolSearcher(Me, filter, name, cancellationToken).GetSymbolsWithName()
End Function
#Enable Warning RS0026 ' Do not add multiple public overloads with optional parameters
Friend Overrides Function IsUnreferencedAssemblyIdentityDiagnosticCode(code As Integer) As Boolean
Select Case code
Case ERRID.ERR_UnreferencedAssemblyEvent3,
ERRID.ERR_UnreferencedAssembly3
Return True
Case Else
Return False
End Select
End Function
#End Region
Private MustInherit Class AbstractSymbolSearcher
Private ReadOnly _cache As PooledDictionary(Of Declaration, NamespaceOrTypeSymbol)
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _includeNamespace As Boolean
Private ReadOnly _includeType As Boolean
Private ReadOnly _includeMember As Boolean
Private ReadOnly _cancellationToken As CancellationToken
Public Sub New(compilation As VisualBasicCompilation, filter As SymbolFilter, cancellationToken As CancellationToken)
_cache = PooledDictionary(Of Declaration, NamespaceOrTypeSymbol).GetInstance()
_compilation = compilation
_includeNamespace = (filter And SymbolFilter.Namespace) = SymbolFilter.Namespace
_includeType = (filter And SymbolFilter.Type) = SymbolFilter.Type
_includeMember = (filter And SymbolFilter.Member) = SymbolFilter.Member
_cancellationToken = cancellationToken
End Sub
Protected MustOverride Function Matches(name As String) As Boolean
Protected MustOverride Function ShouldCheckTypeForMembers(typeDeclaration As MergedTypeDeclaration) As Boolean
Public Function GetSymbolsWithName() As IEnumerable(Of ISymbol)
Dim result = New HashSet(Of ISymbol)()
Dim spine = ArrayBuilder(Of MergedNamespaceOrTypeDeclaration).GetInstance()
AppendSymbolsWithName(spine, _compilation.MergedRootDeclaration, result)
spine.Free()
_cache.Free()
Return result
End Function
Private Sub AppendSymbolsWithName(
spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration), current As MergedNamespaceOrTypeDeclaration, [set] As HashSet(Of ISymbol))
If current.Kind = DeclarationKind.Namespace Then
If _includeNamespace AndAlso Matches(current.Name) Then
Dim container = GetSpineSymbol(spine)
Dim symbol = GetSymbol(container, current)
If symbol IsNot Nothing Then
[set].Add(symbol)
End If
End If
Else
If _includeType AndAlso Matches(current.Name) Then
Dim container = GetSpineSymbol(spine)
Dim symbol = GetSymbol(container, current)
If symbol IsNot Nothing Then
[set].Add(symbol)
End If
End If
If _includeMember Then
Dim typeDeclaration = DirectCast(current, MergedTypeDeclaration)
If ShouldCheckTypeForMembers(typeDeclaration) Then
AppendMemberSymbolsWithName(spine, typeDeclaration, [set])
End If
End If
End If
spine.Add(current)
For Each child In current.Children
Dim mergedNamespaceOrType = TryCast(child, MergedNamespaceOrTypeDeclaration)
If mergedNamespaceOrType IsNot Nothing Then
If _includeMember OrElse _includeType OrElse child.Kind = DeclarationKind.Namespace Then
AppendSymbolsWithName(spine, mergedNamespaceOrType, [set])
End If
End If
Next
spine.RemoveAt(spine.Count - 1)
End Sub
Private Sub AppendMemberSymbolsWithName(
spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration), mergedType As MergedTypeDeclaration, [set] As HashSet(Of ISymbol))
_cancellationToken.ThrowIfCancellationRequested()
spine.Add(mergedType)
Dim container As NamespaceOrTypeSymbol = Nothing
For Each name In mergedType.MemberNames
If Matches(name) Then
container = If(container, GetSpineSymbol(spine))
If container IsNot Nothing Then
[set].UnionWith(container.GetMembers(name))
End If
End If
Next
spine.RemoveAt(spine.Count - 1)
End Sub
Private Function GetSpineSymbol(spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration)) As NamespaceOrTypeSymbol
If spine.Count = 0 Then
Return Nothing
End If
Dim symbol = GetCachedSymbol(spine(spine.Count - 1))
If symbol IsNot Nothing Then
Return symbol
End If
Dim current = TryCast(Me._compilation.GlobalNamespace, NamespaceOrTypeSymbol)
For i = 1 To spine.Count - 1
current = GetSymbol(current, spine(i))
Next
Return current
End Function
Private Function GetCachedSymbol(declaration As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol
Dim symbol As NamespaceOrTypeSymbol = Nothing
If Me._cache.TryGetValue(declaration, symbol) Then
Return symbol
End If
Return Nothing
End Function
Private Function GetSymbol(container As NamespaceOrTypeSymbol, declaration As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol
If container Is Nothing Then
Return Me._compilation.GlobalNamespace
End If
Dim symbol = GetCachedSymbol(declaration)
If symbol IsNot Nothing Then
Return symbol
End If
If declaration.Kind = DeclarationKind.Namespace Then
AddCache(container.GetMembers(declaration.Name).OfType(Of NamespaceOrTypeSymbol)())
Else
AddCache(container.GetTypeMembers(declaration.Name))
End If
Return GetCachedSymbol(declaration)
End Function
Private Sub AddCache(symbols As IEnumerable(Of NamespaceOrTypeSymbol))
For Each symbol In symbols
Dim mergedNamespace = TryCast(symbol, MergedNamespaceSymbol)
If mergedNamespace IsNot Nothing Then
Me._cache(mergedNamespace.ConstituentNamespaces.OfType(Of SourceNamespaceSymbol).First().MergedDeclaration) = symbol
Continue For
End If
Dim sourceNamespace = TryCast(symbol, SourceNamespaceSymbol)
If sourceNamespace IsNot Nothing Then
Me._cache(sourceNamespace.MergedDeclaration) = sourceNamespace
Continue For
End If
Dim sourceType = TryCast(symbol, SourceMemberContainerTypeSymbol)
If sourceType IsNot Nothing Then
Me._cache(sourceType.TypeDeclaration) = sourceType
End If
Next
End Sub
End Class
Private Class PredicateSymbolSearcher
Inherits AbstractSymbolSearcher
Private ReadOnly _predicate As Func(Of String, Boolean)
Public Sub New(
compilation As VisualBasicCompilation, filter As SymbolFilter, predicate As Func(Of String, Boolean), cancellationToken As CancellationToken)
MyBase.New(compilation, filter, cancellationToken)
_predicate = predicate
End Sub
Protected Overrides Function ShouldCheckTypeForMembers(current As MergedTypeDeclaration) As Boolean
Return True
End Function
Protected Overrides Function Matches(name As String) As Boolean
Return _predicate(name)
End Function
End Class
Private Class NameSymbolSearcher
Inherits AbstractSymbolSearcher
Private ReadOnly _name As String
Public Sub New(
compilation As VisualBasicCompilation, filter As SymbolFilter, name As String, cancellationToken As CancellationToken)
MyBase.New(compilation, filter, cancellationToken)
_name = name
End Sub
Protected Overrides Function ShouldCheckTypeForMembers(current As MergedTypeDeclaration) As Boolean
For Each typeDecl In current.Declarations
If typeDecl.MemberNames.Contains(_name) Then
Return True
End If
Next
Return False
End Function
Protected Overrides Function Matches(name As String) As Boolean
Return IdentifierComparison.Equals(_name, name)
End Function
End Class
End Class
End Namespace
|
swaroop-sridhar/roslyn
|
src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb
|
Visual Basic
|
apache-2.0
| 145,303
|
' 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
Imports System.Web
Public Module Extensions_875
''' <summary>
''' A HttpResponse extension method that sets the response to status code 302 (Object moved.).
''' </summary>
''' <param name="this">The @this to act on.</param>
<System.Runtime.CompilerServices.Extension> _
Public Sub SetStatusObjectMoved(this As HttpResponse)
this.StatusCode = 302
this.StatusDescription = "Object moved."
End Sub
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Web/System.Web.HttpResponse/_generated/HttpResponse.SetStatusObjectMoved.vb
|
Visual Basic
|
mit
| 805
|
' 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.Linq
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports System.Runtime.InteropServices
' NOTE: VB does not support constant expressions in flow analysis during command-line compilation, but supports them when
' analysis is being called via public API. This distinction is governed by 'suppressConstantExpressions' flag
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend MustInherit Class AbstractFlowPass(Of LocalState As AbstractLocalState)
Inherits BoundTreeVisitor
''' <summary>
''' The compilation in which the analysis is taking place. This is needed to determine which
''' conditional methods will be compiled and which will be omitted.
''' </summary>
Protected ReadOnly compilation As VisualBasicCompilation
''' <summary>
''' The symbol of method whose body is being analyzed or field or property whose
''' initializer is being analyzed
''' </summary>
Public symbol As Symbol
''' <summary>
''' The bound code of the method or initializer being analyzed
''' </summary>
Private ReadOnly _methodOrInitializerMainNode As BoundNode
''' <summary>
''' The flow analysis state at each label, computed by merging the state from branches to
''' that label with the state when we fall into the label. Entries are created when the
''' label is encountered. One case deserves special attention: when the destination of the
''' branch is a label earlier in the code, it is possible (though rarely occurs in practice)
''' that we are changing the state at a label that we've already analyzed. In that case we
''' run another pass of the analysis to allow those changes to propagate. This repeats until
''' no further changes to the state of these labels occurs. This can result in quadratic
''' performance in unlikely but possible code such as this: "int x; if (cond) goto l1; x =
''' 3; l5: print x; l4: goto l5; l3: goto l4; l2: goto l3; l1: goto l2;"
''' </summary>
Private ReadOnly _labels As New Dictionary(Of LabelSymbol, LabelStateAndNesting)
''' <summary> All of the labels seen so far in this forward scan of the body </summary>
Private _labelsSeen As New HashSet(Of LabelSymbol)
Private _placeholderReplacementMap As Dictionary(Of BoundValuePlaceholderBase, BoundExpression)
''' <summary>
''' Set to true after an analysis scan if the analysis was incomplete due to a backward
''' "goto" branch changing some analysis result. In this case the caller scans again (until
''' this is false). Since the analysis proceeds by monotonically changing the state computed
''' at each label, this must terminate.
''' </summary>
Friend backwardBranchChanged As Boolean = False
''' <summary> Actual storage for PendingBranches </summary>
Private _pendingBranches As ArrayBuilder(Of PendingBranch) = ArrayBuilder(Of PendingBranch).GetInstance()
''' <summary> The definite assignment and/or reachability state at the point currently being analyzed. </summary>
Protected State As LocalState
Protected StateWhenTrue As LocalState
Protected StateWhenFalse As LocalState
Protected IsConditionalState As Boolean
''' <summary>
''' 'Me' parameter, relevant for methods, fields, properties, otherwise Nothing
''' </summary>
Protected ReadOnly MeParameter As ParameterSymbol
''' <summary>
''' Used only in the data flows out walker, we track unassignments as well as assignments
''' </summary>
Protected ReadOnly TrackUnassignments As Boolean
''' <summary>
''' The current lexical nesting in the BoundTree.
''' </summary>
''' <remarks></remarks>
Private _nesting As ArrayBuilder(Of Integer)
''' <summary>
''' Where all diagnostics are deposited.
''' </summary>
Protected ReadOnly diagnostics As DiagnosticBag = DiagnosticBag.GetInstance()
''' <summary> Indicates whether or not support of constant expressions (boolean and nothing)
''' is enabled in this analyzer. In general, constant expressions support is enabled in analysis
''' exposed to public API consumer and disabled when used from command-line compiler. </summary>
Private ReadOnly _suppressConstantExpressions As Boolean
''' <summary>
''' Construct an object for outside-region analysis
''' </summary>
Protected Sub New(_info As FlowAnalysisInfo, suppressConstExpressionsSupport As Boolean)
MyClass.New(_info, Nothing, suppressConstExpressionsSupport, False)
End Sub
''' <summary>
''' Construct an object for region-aware analysis
''' </summary>
Protected Sub New(_info As FlowAnalysisInfo, _region As FlowAnalysisRegionInfo, suppressConstExpressionsSupport As Boolean, trackUnassignments As Boolean)
Debug.Assert(_info.Symbol.Kind = SymbolKind.Field OrElse
_info.Symbol.Kind = SymbolKind.Property OrElse
_info.Symbol.Kind = SymbolKind.Method OrElse
_info.Symbol.Kind = SymbolKind.Parameter)
Me.compilation = _info.Compilation
Me.symbol = _info.Symbol
Me.MeParameter = Me.symbol.GetMeParameter()
Me._methodOrInitializerMainNode = _info.Node
Me._firstInRegion = _region.FirstInRegion
Me._lastInRegion = _region.LastInRegion
Me._region = _region.Region
Me.TrackUnassignments = trackUnassignments
Me._loopHeadState = If(trackUnassignments, New Dictionary(Of BoundLoopStatement, LocalState)(), Nothing)
Me._suppressConstantExpressions = suppressConstExpressionsSupport
End Sub
Protected Overridable Sub InitForScan()
End Sub
Protected MustOverride Function ReachableState() As LocalState
Protected MustOverride Function UnreachableState() As LocalState
''' <summary> Set conditional state </summary>
Private Sub SetConditionalState(_whenTrue As LocalState, _whenFalse As LocalState)
Me.State = Nothing
Me.StateWhenTrue = _whenTrue
Me.StateWhenFalse = _whenFalse
Me.IsConditionalState = True
End Sub
''' <summary> Set unconditional state </summary>
Protected Sub SetState(_state As LocalState)
Me.State = _state
If Me.IsConditionalState Then
Me.StateWhenTrue = Nothing
Me.StateWhenFalse = Nothing
Me.IsConditionalState = False
End If
End Sub
''' <summary> Split state </summary>
Protected Sub Split()
If Not Me.IsConditionalState Then
SetConditionalState(Me.State, Me.State.Clone())
End If
End Sub
''' <summary> Intersect and unsplit state </summary>
Protected Sub Unsplit()
If Me.IsConditionalState Then
Me.IntersectWith(Me.StateWhenTrue, Me.StateWhenFalse)
Me.SetState(Me.StateWhenTrue)
End If
End Sub
''' <summary>
''' Pending escapes generated in the current scope (or more deeply nested scopes). When jump
''' statements (goto, break, continue, return) are processed, they are placed in the
''' Me._pendingBranches buffer to be processed later by the code handling the destination
''' statement. As a special case, the processing of try-finally statements might modify the
''' contents of the Me._pendingBranches buffer to take into account the behavior of
''' "intervening" finally clauses.
''' </summary>
Protected ReadOnly Property PendingBranches As ImmutableArray(Of PendingBranch)
Get
Return _pendingBranches.ToImmutable
End Get
End Property
''' <summary>
''' Perform a single pass of flow analysis. Note that after this pass,
''' this.backwardBranchChanged indicates if a further pass is required.
''' </summary>
''' <returns>False if the region is invalid</returns>
Protected Overridable Function Scan() As Boolean
' Clear diagnostics reported in the previous iteration
Me.diagnostics.Clear()
' initialize
Me._regionPlace = RegionPlace.Before
Me.SetState(ReachableState())
Me.backwardBranchChanged = False
If Me._nesting IsNot Nothing Then
Me._nesting.Free()
End If
Me._nesting = ArrayBuilder(Of Integer).GetInstance()
InitForScan()
' pending branches should be restored after each iteration
Dim oldPending As SavedPending = Me.SavePending()
Visit(Me._methodOrInitializerMainNode)
Me.RestorePending(oldPending)
Me._labelsSeen.Clear()
' if we are tracking regions, we must have left the region by now;
' otherwise the region was erroneous which must have been detected earlier
Return Me._firstInRegion Is Nothing OrElse Me._regionPlace = RegionPlace.After
End Function
''' <returns>False if the region is invalid</returns>
Protected Overridable Function Analyze() As Boolean
Do
If Not Me.Scan() Then
Return False
End If
Loop While Me.backwardBranchChanged
Return True
End Function
Protected Overridable Sub Free()
If Me._nesting IsNot Nothing Then
Me._nesting.Free()
End If
Me.diagnostics.Free()
Me._pendingBranches.Free()
End Sub
''' <summary>
''' If analysis is being performed in a context of a method returns method's parameters,
''' otherwise returns an empty array
''' </summary>
Protected ReadOnly Property MethodParameters As ImmutableArray(Of ParameterSymbol)
Get
Return If(Me.symbol.Kind = SymbolKind.Method, DirectCast(Me.symbol, MethodSymbol).Parameters, ImmutableArray(Of ParameterSymbol).Empty)
End Get
End Property
''' <summary>
''' Specifies whether or not method's ByRef parameters should be analyzed. If there's more than one location in
''' the method being analyzed, then the method is partial and we prefer to report an out parameter in partial
''' method error.
''' Note: VB doesn't support "out" so it doesn't warn for unassigned parameters. However, check variables passed
''' byref are assigned so that data flow analysis detects parameters flowing out.
''' </summary>
''' <returns>true if the out parameters of the method should be analyzed</returns>
Protected ReadOnly Property ShouldAnalyzeByRefParameters As Boolean
Get
Return Me.symbol.Kind = SymbolKind.Method AndAlso DirectCast(Me.symbol, MethodSymbol).Locations.Length = 1
End Get
End Property
''' <summary>
''' Method symbol or nothing
''' TODO: Need to try and get rid of this property
''' </summary>
Protected ReadOnly Property MethodSymbol As MethodSymbol
Get
Return If(Me.symbol.Kind = SymbolKind.Method, DirectCast(Me.symbol, MethodSymbol), Nothing)
End Get
End Property
''' <summary>
''' If analysis is being performed in a context of a method returns method's return type,
''' otherwise returns Nothing
''' </summary>
Protected ReadOnly Property MethodReturnType As TypeSymbol
Get
Return If(Me.symbol.Kind = SymbolKind.Method, DirectCast(Me.symbol, MethodSymbol).ReturnType, Nothing)
End Get
End Property
''' <summary>
''' Return the flow analysis state associated with a label.
''' </summary>
''' <param name="label"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function LabelState(label As LabelSymbol) As LocalState
Dim result As LabelStateAndNesting = Nothing
If _labels.TryGetValue(label, result) Then
Return result.State
End If
Return UnreachableState()
End Function
''' <summary>
''' Set the current state to one that indicates that it is unreachable.
''' </summary>
Protected Sub SetUnreachable()
Me.SetState(UnreachableState())
End Sub
Private Function IsConstantTrue(node As BoundExpression) As Boolean
If Me._suppressConstantExpressions Then
Return False
End If
If Not node.IsConstant Then
Return False
End If
Dim constantValue = node.ConstantValueOpt
If constantValue.Discriminator <> ConstantValueTypeDiscriminator.Boolean Then
Return False
End If
Return constantValue.BooleanValue
End Function
Private Function IsConstantFalse(node As BoundExpression) As Boolean
If Me._suppressConstantExpressions Then
Return False
End If
If Not node.IsConstant Then
Return False
End If
Dim constantValue = node.ConstantValueOpt
If constantValue.Discriminator <> ConstantValueTypeDiscriminator.Boolean Then
Return False
End If
Return Not constantValue.BooleanValue
End Function
Private Function IsConstantNull(node As BoundExpression) As Boolean
If Me._suppressConstantExpressions Then
Return False
End If
If Not node.IsConstant Then
Return False
End If
Return node.ConstantValueOpt.IsNull
End Function
Protected Shared Function IsNonPrimitiveValueType(type As TypeSymbol) As Boolean
Debug.Assert(type IsNot Nothing)
If Not type.IsValueType Then
Return False
End If
Select Case type.SpecialType
Case SpecialType.None,
SpecialType.System_Nullable_T,
SpecialType.System_IntPtr,
SpecialType.System_UIntPtr
Return True
Case Else
Return False
End Select
End Function
''' <summary>
''' Called at the point in a loop where the backwards branch would go to.
''' </summary>
''' <param name="node"></param>
''' <remarks></remarks>
Private Sub LoopHead(node As BoundLoopStatement)
If Me.TrackUnassignments Then
Dim previousState As LocalState
If Me._loopHeadState.TryGetValue(node, previousState) Then
IntersectWith(Me.State, previousState)
End If
Me._loopHeadState(node) = Me.State.Clone()
End If
End Sub
''' <summary>
''' Called at the point in a loop where the backward branch is placed.
''' </summary>
''' <param name="node"></param>
''' <remarks></remarks>
Private Sub LoopTail(node As BoundLoopStatement)
If Me.TrackUnassignments Then
Dim oldState = Me._loopHeadState(node)
If IntersectWith(oldState, Me.State) Then
Me._loopHeadState(node) = oldState
Me.backwardBranchChanged = True
End If
End If
End Sub
''' <summary>
''' Used to resolve exit statements in each statement form that has an Exit statement
''' (loops, switch).
''' </summary>
Private Sub ResolveBreaks(breakState As LocalState, breakLabel As LabelSymbol)
Dim newPendingBranches = ArrayBuilder(Of PendingBranch).GetInstance()
For Each pending In Me.PendingBranches
Select Case pending.Branch.Kind
Case BoundKind.ExitStatement
Dim exitStmt = TryCast(pending.Branch, BoundExitStatement)
If exitStmt.Label = breakLabel Then
IntersectWith(breakState, pending.State)
Else
' If it doesn't match then it is for an outer block
newPendingBranches.Add(pending)
End If
Case Else
newPendingBranches.Add(pending)
End Select
Next
ResetPendingBranches(newPendingBranches)
Me.SetState(breakState)
End Sub
''' <summary>
''' Used to resolve continue statements in each statement form that supports it.
''' </summary>
''' <param name = "continueLabel"></param>
Private Sub ResolveContinues(continueLabel As LabelSymbol)
Dim newPendingBranches = ArrayBuilder(Of PendingBranch).GetInstance()
For Each pending In Me.PendingBranches
Select Case pending.Branch.Kind
Case BoundKind.ContinueStatement
' When the continue XXX does not match an enclosing XXX block then no label exists
Dim continueStmt = TryCast(pending.Branch, BoundContinueStatement)
' Technically, nothing in the language specification depends on the state
' at the continue label, so we could just discard them instead of merging
' the states. In fact, we need not have added continue statements to the
' pending jump queue in the first place if we were interested solely in the
' flow analysis. However, region analysis (in support of extract method)
' depends on continue statements appearing in the pending branch queue, so
' we process them from the queue here.
If continueStmt.Label = continueLabel Then
IntersectWith(Me.State, pending.State)
Else
' If it doesn't match then it is for an outer block
newPendingBranches.Add(pending)
End If
Case Else
newPendingBranches.Add(pending)
End Select
Next
ResetPendingBranches(newPendingBranches)
End Sub
''' <summary>
''' Subclasses override this if they want to take special actions on processing a goto
''' statement, when both the jump and the label have been located.
''' </summary>
Protected Overridable Sub NoteBranch(pending As PendingBranch, stmt As BoundStatement, labelStmt As BoundLabelStatement)
End Sub
Private Function GetBranchTargetLabel(branch As BoundStatement, gotoOnly As Boolean) As LabelSymbol
Select Case branch.Kind
Case BoundKind.GotoStatement
Return DirectCast(branch, BoundGotoStatement).Label
Case BoundKind.ConditionalGoto
Return DirectCast(branch, BoundConditionalGoto).Label
Case BoundKind.ExitStatement
Return If(gotoOnly, Nothing, DirectCast(branch, BoundExitStatement).Label)
Case BoundKind.ReturnStatement
Return If(gotoOnly, Nothing, DirectCast(branch, BoundReturnStatement).ExitLabelOpt)
Case BoundKind.ContinueStatement
Return Nothing
Case BoundKind.YieldStatement
Return Nothing
Case Else
Debug.Assert(False)
End Select
Return Nothing
End Function
Protected Overridable Sub ResolveBranch(pending As PendingBranch, label As LabelSymbol, target As BoundLabelStatement, ByRef labelStateChanged As Boolean)
Dim _state = LabelState(target.Label)
NoteBranch(pending, pending.Branch, target)
Dim changed = IntersectWith(_state, pending.State)
If changed Then
labelStateChanged = True
Me._labels(target.Label) = New LabelStateAndNesting(target, _state, Me._nesting)
End If
End Sub
''' <summary>
''' To handle a label, we resolve all pending forward references to branches to that label. Returns true if the state of
''' the label changes as a result.
''' </summary>
''' <param name = "target"></param>
''' <returns></returns>
Private Function ResolveBranches(target As BoundLabelStatement) As Boolean
Dim labelStateChanged As Boolean = False
If Me.PendingBranches.Length > 0 Then
Dim newPendingBranches = ArrayBuilder(Of PendingBranch).GetInstance()
For Each pending In Me.PendingBranches
Dim label As LabelSymbol = GetBranchTargetLabel(pending.Branch, False)
If label IsNot Nothing AndAlso label = target.Label Then
ResolveBranch(pending, label, target, labelStateChanged)
Else
newPendingBranches.Add(pending)
End If
Next
ResetPendingBranches(newPendingBranches)
End If
Return labelStateChanged
End Function
Protected Class SavedPending
Public ReadOnly PendingBranches As ArrayBuilder(Of PendingBranch)
Public ReadOnly LabelsSeen As HashSet(Of LabelSymbol)
Public Sub New(ByRef _pendingBranches As ArrayBuilder(Of PendingBranch), ByRef _labelsSeen As HashSet(Of LabelSymbol))
Me.PendingBranches = _pendingBranches
Me.LabelsSeen = _labelsSeen
_pendingBranches = ArrayBuilder(Of PendingBranch).GetInstance()
_labelsSeen = New HashSet(Of LabelSymbol)
End Sub
End Class
''' <summary>
''' When branching into constructs that don't support jumps into/out of (i.e. lambdas),
''' we save the pending branches when visiting more nested constructs.
''' </summary>
Protected Function SavePending() As SavedPending
Return New SavedPending(Me._pendingBranches, Me._labelsSeen)
End Function
Private Sub ResetPendingBranches(newPendingBranches As ArrayBuilder(Of PendingBranch))
Debug.Assert(newPendingBranches IsNot Nothing)
Debug.Assert(newPendingBranches IsNot Me._pendingBranches)
Me._pendingBranches.Free()
Me._pendingBranches = newPendingBranches
End Sub
''' <summary>
''' We use this to restore the old set of pending branches and labels after visiting a construct that contains nested statements.
''' </summary>
''' <param name="oldPending">The old pending branches/labels, which are to be merged with the current ones</param>
Protected Sub RestorePending(oldPending As SavedPending, Optional mergeLabelsSeen As Boolean = False)
If ResolveBranches(Me._labelsSeen) Then
Me.backwardBranchChanged = True
End If
oldPending.PendingBranches.AddRange(Me.PendingBranches)
ResetPendingBranches(oldPending.PendingBranches)
' We only use SavePending/RestorePending when there could be no branch into the region between them.
' So there is no need to save the labels seen between the calls. If there were such a need, we would
' do "this.labelsSeen.UnionWith(oldPending.LabelsSeen);" instead of the following assignment
If mergeLabelsSeen Then
Me._labelsSeen.AddAll(oldPending.LabelsSeen)
Else
Me._labelsSeen = oldPending.LabelsSeen
End If
End Sub
''' <summary>
''' We look at all pending branches and attempt to resolve the branches with labels if the nesting of the
''' block is the nearest common parent to the branch and the label. Because the code is evaluated recursively
''' outward we only need to check if the current nesting is a prefix of both the branch and the label nesting.
''' </summary>
Private Function ResolveBranches(labelsFilter As HashSet(Of LabelSymbol)) As Boolean
Dim labelStateChanged As Boolean = False
If Me.PendingBranches.Length > 0 Then
Dim newPendingBranches = ArrayBuilder(Of PendingBranch).GetInstance()
For Each pending In Me.PendingBranches
Dim labelSymbol As LabelSymbol = Nothing
Dim labelAndNesting As LabelStateAndNesting = Nothing
If BothBranchAndLabelArePrefixedByNesting(pending, labelsFilter, labelSymbol:=labelSymbol, labelAndNesting:=labelAndNesting) Then
Dim changed As Boolean
ResolveBranch(pending, labelSymbol, labelAndNesting.Target, changed)
If changed Then
labelStateChanged = True
End If
Continue For
End If
newPendingBranches.Add(pending)
Next
ResetPendingBranches(newPendingBranches)
End If
Return labelStateChanged
End Function
Private Function BothBranchAndLabelArePrefixedByNesting(branch As PendingBranch,
Optional labelsFilter As HashSet(Of LabelSymbol) = Nothing,
Optional ignoreLast As Boolean = False,
<Out()> Optional ByRef labelSymbol As LabelSymbol = Nothing,
<Out()> Optional ByRef labelAndNesting As LabelStateAndNesting = Nothing) As Boolean
Dim branchStatement As BoundStatement = branch.Branch
If branchStatement IsNot Nothing AndAlso branch.Nesting.IsPrefixedBy(Me._nesting, ignoreLast) Then
labelSymbol = GetBranchTargetLabel(branchStatement, gotoOnly:=True)
If labelSymbol IsNot Nothing AndAlso (labelsFilter Is Nothing OrElse labelsFilter.Contains(labelSymbol)) Then
Return Me._labels.TryGetValue(labelSymbol, labelAndNesting) AndAlso
labelAndNesting.Nesting.IsPrefixedBy(Me._nesting, ignoreLast)
End If
End If
Return False
End Function
''' <summary>
''' Report an unimplemented language construct.
''' </summary>
''' <param name = "node"></param>
''' <param name = "feature"></param>
''' <returns></returns>
Protected Overridable Function Unimplemented(node As BoundNode, feature As [String]) As BoundNode
Return Nothing
End Function
Protected Overridable Function AllBitsSet() As LocalState
Return Nothing
End Function
Protected Sub SetPlaceholderSubstitute(placeholder As BoundValuePlaceholderBase, newSubstitute As BoundExpression)
Debug.Assert(placeholder IsNot Nothing)
If _placeholderReplacementMap Is Nothing Then
_placeholderReplacementMap = New Dictionary(Of BoundValuePlaceholderBase, BoundExpression)()
End If
Debug.Assert(Not _placeholderReplacementMap.ContainsKey(placeholder))
_placeholderReplacementMap(placeholder) = newSubstitute
End Sub
Protected Sub RemovePlaceholderSubstitute(placeholder As BoundValuePlaceholderBase)
Debug.Assert(placeholder IsNot Nothing)
Debug.Assert(_placeholderReplacementMap.ContainsKey(placeholder))
Me._placeholderReplacementMap.Remove(placeholder)
End Sub
Protected ReadOnly Property GetPlaceholderSubstitute(placeholder As BoundValuePlaceholderBase) As BoundExpression
Get
Dim value As BoundExpression = Nothing
If Me._placeholderReplacementMap IsNot Nothing AndAlso Me._placeholderReplacementMap.TryGetValue(placeholder, value) Then
Return value
End If
Return Nothing
End Get
End Property
Protected MustOverride Function Dump(state As LocalState) As String
#Region "Visitors"
''' <summary>
''' Visit a node.
''' </summary>
Protected Overridable Shadows Sub Visit(node As BoundNode, Optional dontLeaveRegion As Boolean = False)
VisitAlways(node, dontLeaveRegion:=dontLeaveRegion)
End Sub
''' <summary>
''' Visit a node, process
''' </summary>
Protected Sub VisitAlways(node As BoundNode, Optional dontLeaveRegion As Boolean = False)
If Me._firstInRegion Is Nothing Then
MyBase.Visit(node)
Else
If node Is Me._firstInRegion AndAlso Me._regionPlace = RegionPlace.Before Then
Me.EnterRegion()
End If
MyBase.Visit(node)
If Not dontLeaveRegion AndAlso node Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
End If
End Sub
Protected Overridable Sub VisitLvalue(node As BoundExpression, Optional dontLeaveRegion As Boolean = False)
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If node Is Me._firstInRegion AndAlso Me._regionPlace = RegionPlace.Before Then
Me.EnterRegion()
End If
Select Case node.Kind
Case BoundKind.Local
Dim local = DirectCast(node, BoundLocal)
If local.LocalSymbol.IsByRef Then
VisitRvalue(local)
End If
Case BoundKind.Parameter, BoundKind.MeReference, BoundKind.MyClassReference, BoundKind.MyBaseReference
' no need for it to be previously assigned: it is on the left.
Case BoundKind.FieldAccess
VisitFieldAccessInternal(DirectCast(node, BoundFieldAccess))
Case BoundKind.WithLValueExpressionPlaceholder,
BoundKind.WithRValueExpressionPlaceholder,
BoundKind.LValuePlaceholder,
BoundKind.RValuePlaceholder
' TODO: Other placeholder kinds?
Dim substitute As BoundExpression = GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
VisitLvalue(substitute)
Else
VisitRvalue(node, dontLeaveRegion:=True)
End If
Case Else
VisitRvalue(node, dontLeaveRegion:=True)
End Select
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If Not dontLeaveRegion AndAlso node Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
End Sub
''' <summary>
''' Visit a boolean condition expression.
''' </summary>
Protected Sub VisitCondition(node As BoundExpression)
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If node Is Me._firstInRegion AndAlso Me._regionPlace = RegionPlace.Before Then
Me.EnterRegion()
End If
Visit(node, dontLeaveRegion:=True)
If IsConstantTrue(node) Then
Me.Unsplit()
Me.SetConditionalState(Me.State, UnreachableState())
ElseIf IsConstantFalse(node) Then
Me.Unsplit()
Me.SetConditionalState(UnreachableState(), Me.State)
Else
Me.Split()
End If
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If node Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
End Sub
''' <summary>
''' Visit a general expression, where we will only need to determine if variables are
''' assigned (or not). That is, we will not be needing AssignedWhenTrue and
''' AssignedWhenFalse.
''' </summary>
Protected Sub VisitRvalue(node As BoundExpression, Optional rwContext As ReadWriteContext = ReadWriteContext.None, Optional dontLeaveRegion As Boolean = False)
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If node Is Me._firstInRegion AndAlso Me._regionPlace = RegionPlace.Before Then
Me.EnterRegion()
End If
If rwContext <> ReadWriteContext.None Then
Select Case node.Kind
Case BoundKind.Local
VisitLocalInReadWriteContext(DirectCast(node, BoundLocal), rwContext)
GoTo lUnsplitAndFinish
Case BoundKind.FieldAccess
VisitFieldAccessInReadWriteContext(DirectCast(node, BoundFieldAccess), rwContext)
GoTo lUnsplitAndFinish
End Select
End If
Visit(node, dontLeaveRegion:=True)
lUnsplitAndFinish:
Me.Unsplit()
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If Not dontLeaveRegion AndAlso node Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
End Sub
Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode
Dim sideEffects = node.SideEffects
If Not sideEffects.IsEmpty Then
For Each sideEffect In node.SideEffects
Visit(sideEffect)
Next
End If
Debug.Assert(node.ValueOpt IsNot Nothing OrElse node.HasErrors OrElse node.Type.SpecialType = SpecialType.System_Void)
If node.ValueOpt IsNot Nothing Then
VisitRvalue(node.ValueOpt)
End If
Return Nothing
End Function
Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Dim replacement As BoundExpression = GetPlaceholderSubstitute(node)
If replacement IsNot Nothing Then
VisitRvalue(replacement, ReadWriteContext.ByRefArgument)
End If
Return Nothing
End Function
Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Me.SetPlaceholderSubstitute(node.InPlaceholder, node.OriginalArgument)
Visit(node.InConversion)
Me.RemovePlaceholderSubstitute(node.InPlaceholder)
Return Nothing
End Function
Protected Overridable Sub VisitStatement(statement As BoundStatement)
Visit(statement)
End Sub
Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode
Visit(node.UnderlyingLValue)
Return Nothing
End Function
Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Visit(GetPlaceholderSubstitute(node))
Return Nothing
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement) As BoundNode
' In case we perform _region_ flow analysis processing of the region inside With
' statement expression is a little subtle. The original expression may be
' rewritten into a placeholder substitution expression and a set of initializers.
' The placeholder will be processed when we visit left-omitted part of member or
' dictionary access in the statements inside the With statement body, but the
' initializers are to be processed with BoundWithStatement itself.
' True if it is a _region_ flow analysis and the region is defined inside the original expression
Dim origExpressionContainsRegion As Boolean = False
' True if origExpressionContainsRegion is True and region encloses all the initializers
Dim regionEnclosesInitializers As Boolean = False
If Me._firstInRegion IsNot Nothing AndAlso Me._regionPlace = RegionPlace.Before Then
Debug.Assert(Me._lastInRegion IsNot Nothing)
' Check if the region defining node is somewhere inside OriginalExpression
If BoundNodeFinder.ContainsNode(node.OriginalExpression, Me._firstInRegion) Then
Debug.Assert(BoundNodeFinder.ContainsNode(node.OriginalExpression, Me._lastInRegion))
origExpressionContainsRegion = True
' Does any of initializers contain the node or the node contains initializers?
For Each initializer In node.DraftInitializers
Debug.Assert(initializer.Kind = BoundKind.AssignmentOperator)
Dim initializerExpr As BoundExpression = DirectCast(initializer, BoundAssignmentOperator).Right
If initializerExpr.Kind = BoundKind.LValueToRValueWrapper Then
initializerExpr = DirectCast(initializerExpr, BoundLValueToRValueWrapper).UnderlyingLValue
End If
regionEnclosesInitializers = True
If Me._firstInRegion Is initializerExpr OrElse Not BoundNodeFinder.ContainsNode(Me._firstInRegion, initializerExpr) Then
regionEnclosesInitializers = False
Exit For
End If
Next
End If
End If
' NOTE: If origExpressionContainsRegion is True and regionEnclosesInitializers is *False*,
' we should expect that the region is to be properly entered/left while appropriate
' initializer is visited *OR* the node is a literal/local which was not captured,
' but simply reused when needed in With statement body
'
' The assumption above is guarded by the following assert
#If DEBUG Then
If origExpressionContainsRegion AndAlso Not regionEnclosesInitializers Then
Dim containedByInitializer As Boolean = False
For Each initializer In node.DraftInitializers
Debug.Assert(initializer.Kind = BoundKind.AssignmentOperator)
Dim initializerExpr As BoundExpression = DirectCast(initializer, BoundAssignmentOperator).Right
If initializerExpr.Kind = BoundKind.LValueToRValueWrapper Then
initializerExpr = DirectCast(initializerExpr, BoundLValueToRValueWrapper).UnderlyingLValue
End If
containedByInitializer = False
Debug.Assert(initializerExpr IsNot Nothing)
If BoundNodeFinder.ContainsNode(initializerExpr, Me._firstInRegion) Then
Debug.Assert(Not containedByInitializer)
containedByInitializer = True
Exit For
End If
Next
Debug.Assert(containedByInitializer OrElse IsNotCapturedExpression(Me._firstInRegion))
End If
#End If
If origExpressionContainsRegion AndAlso regionEnclosesInitializers Then
Me.EnterRegion()
End If
' Visit initializers
For Each initializer In node.DraftInitializers
VisitRvalue(initializer)
Next
If origExpressionContainsRegion Then
If regionEnclosesInitializers Then
Me.LeaveRegion() ' This call also asserts that we are inside the region
Else
' If any of the initializers contained region, we must have exited the region by now or the node is a literal
' which was not captured in initializers, but just reused accross when/if needed in With statement body
#If DEBUG Then
Debug.Assert(Me._regionPlace = RegionPlace.After OrElse IsNotCapturedExpression(Me._firstInRegion))
#End If
End If
End If
' Visit body
VisitBlock(node.Body)
If origExpressionContainsRegion AndAlso Me._regionPlace <> RegionPlace.After Then
' The region was a part of the expression, but was not property processed/visited during
' analysis of expression and body; this *may* indicate a bug in flow analysis, otherwise
' it is the case when a struct-typed lvalue expression was never used inside the body AND
' the region was defined by nodew which were not part of initializers; thus, we never
' emitted/visited the node
Debug.Assert(Me._regionPlace = AbstractFlowPass(Of LocalState).RegionPlace.Before)
Me.SetInvalidRegion()
End If
Return Nothing
End Function
#If DEBUG Then
Private Shared Function IsNotCapturedExpression(node As BoundNode) As Boolean
If node Is Nothing Then
Return True
End If
Select Case node.Kind
Case BoundKind.Local
Return DirectCast(node, BoundLocal).Type.IsValueType
Case BoundKind.Parameter
Return DirectCast(node, BoundParameter).Type.IsValueType
Case BoundKind.Literal
Return True
Case BoundKind.MeReference
Return True
Case BoundKind.FieldAccess
Return IsNotCapturedExpression(DirectCast(node, BoundFieldAccess).ReceiverOpt)
Case Else
Return False
End Select
End Function
#End If
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
For Each argument In node.Arguments
VisitRvalue(argument)
Next
Return Nothing
End Function
Public Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Visit(node.Value)
Return Nothing
End Function
''' <summary>
''' Since each language construct must be handled according to the rules of the language specification,
''' the default visitor reports that the construct for the node is not implemented in the compiler.
''' </summary>
Public Overrides Function DefaultVisit(node As BoundNode) As BoundNode
Return Unimplemented(node, "flow analysis")
End Function
Protected Enum ReadWriteContext
None
CompoundAssignmentTarget
ByRefArgument
End Enum
Protected Overridable Sub VisitLocalInReadWriteContext(node As BoundLocal, rwContext As ReadWriteContext)
End Sub
Protected Overridable Sub VisitFieldAccessInReadWriteContext(node As BoundFieldAccess, rwContext As ReadWriteContext)
VisitFieldAccessInternal(node)
End Sub
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
' Control-flow analysis does NOT dive into a lambda, while data-flow analysis does.
Return Nothing
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
' Control-flow analysis does NOT dive into a query expression, while data-flow analysis does.
Return Nothing
End Function
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
If node.InitializerOpt IsNot Nothing Then
VisitRvalue(node.InitializerOpt) ' analyze the expression
End If
Return Nothing
End Function
Private Function IntroduceBlock() As Integer
Dim level = Me._nesting.Count
Me._nesting.Add(0)
Return level
End Function
Private Sub FinalizeBlock(level As Integer)
Me._nesting.RemoveAt(level)
End Sub
Private Sub InitializeBlockStatement(level As Integer, ByRef index As Integer)
Me._nesting(level) = index
index += 1
End Sub
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Dim level = IntroduceBlock()
Dim i As Integer = 0
For Each statement In node.Statements
InitializeBlockStatement(level, i)
VisitStatement(statement)
Next
FinalizeBlock(level)
Return Nothing
End Function
Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode
VisitRvalue(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
' receiver of a latebound access is never modified
VisitRvalue(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Dim member = node.Member
Me.Visit(node.Member)
Dim arguments = node.ArgumentsOpt
If Not arguments.IsEmpty Then
Dim isByRef As Boolean
If member.Kind <> BoundKind.LateMemberAccess Then
' this is a Set, Get or Indexing.
isByRef = False
Else
' otherwise assume it is ByRef
isByRef = True
End If
VisitLateBoundArguments(arguments, isByRef)
End If
Return Nothing
End Function
Private Sub VisitLateBoundArguments(arguments As ImmutableArray(Of BoundExpression), isByRef As Boolean)
For Each argument In arguments
VisitLateBoundArgument(argument, isByRef)
Next
If isByRef Then
For Each argument In arguments
WriteArgument(argument, False)
Next
End If
End Sub
Protected Overridable Sub VisitLateBoundArgument(arg As BoundExpression, isByRef As Boolean)
If isByRef Then
VisitLvalue(arg)
Else
VisitRvalue(arg)
End If
End Sub
Public Overrides Function VisitCall(node As BoundCall) As BoundNode
' If the method being called is a partial method without a definition, or is a conditional method
' whose condition is not true at the given syntax location, then the call has no effect and it is ignored for the purposes of
' definite assignment analysis.
Dim callsAreOmitted As Boolean = node.Method.CallsAreOmitted(node.Syntax, node.SyntaxTree)
Dim savedState As LocalState = Nothing
If callsAreOmitted Then
Debug.Assert(Not Me.IsConditionalState)
savedState = Me.State.Clone()
Me.SetUnreachable()
End If
Dim methodGroup As BoundMethodGroup = node.MethodGroupOpt
Dim receiverOpt As BoundExpression = node.ReceiverOpt
Dim method As MethodSymbol = node.Method
' if method group is present, check if we need to enter region
If methodGroup IsNot Nothing AndAlso Me._firstInRegion Is methodGroup AndAlso
Me._regionPlace = RegionPlace.Before Then
Me.EnterRegion()
End If
If receiverOpt IsNot Nothing Then
VisitCallReceiver(receiverOpt, method)
Else
' If receiver is nothing it means that the method being
' accessed is shared; we still want to visit the original receiver
' to handle shared methods called on instance receiver.
Dim originalReceiver As BoundExpression = If(methodGroup IsNot Nothing, methodGroup.ReceiverOpt, Nothing)
If originalReceiver IsNot Nothing AndAlso Not originalReceiver.WasCompilerGenerated Then
Debug.Assert(method.IsShared)
' Do not visit originalReceiver if it is Type/Namespace/TypeOrValueExpression and the method
' is shared, we want region flow analysis to return Succeeded = False in this case
Dim kind As BoundKind = originalReceiver.Kind
If (kind <> BoundKind.TypeExpression) AndAlso
(kind <> BoundKind.NamespaceExpression) AndAlso
(kind <> BoundKind.TypeOrValueExpression) Then
VisitUnreachableReceiver(originalReceiver)
End If
End If
End If
' if method group is present, check if we need to leave region
If methodGroup IsNot Nothing AndAlso Me._lastInRegion Is methodGroup AndAlso IsInside Then
Me.LeaveRegion()
End If
VisitArguments(node.Arguments, method.Parameters)
If receiverOpt IsNot Nothing AndAlso receiverOpt.IsLValue Then
WriteLValueCallReceiver(receiverOpt, method)
End If
If callsAreOmitted Then
Me.SetState(savedState)
End If
Return Nothing
End Function
Private Sub VisitCallReceiver(receiver As BoundExpression, method As MethodSymbol)
Debug.Assert(receiver IsNot Nothing)
Debug.Assert(method IsNot Nothing)
If Not method.IsReducedExtensionMethod OrElse Not receiver.IsValue() Then
Debug.Assert(method.Kind <> MethodKind.Constructor)
VisitRvalue(receiver)
Else
VisitArgument(receiver, method.CallsiteReducedFromMethod.Parameters(0))
End If
End Sub
Private Sub WriteLValueCallReceiver(receiver As BoundExpression, method As MethodSymbol)
Debug.Assert(receiver IsNot Nothing)
Debug.Assert(receiver.IsLValue)
Debug.Assert(method IsNot Nothing)
If receiver.Type.IsReferenceType Then
' If a receiver is of reference type, it will not be modified if the
' method is not an extension method, note that extension method may
' write to ByRef parameter
Dim redusedFrom As MethodSymbol = method.CallsiteReducedFromMethod
If redusedFrom Is Nothing OrElse redusedFrom.ParameterCount = 0 OrElse Not redusedFrom.Parameters(0).IsByRef Then
Return
End If
End If
WriteArgument(receiver, False)
End Sub
Private Sub VisitArguments(arguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of ParameterSymbol))
If parameters.IsDefault Then
For Each arg In arguments
VisitRvalue(arg)
Next
Else
Dim n As Integer = Math.Min(parameters.Length, arguments.Length)
' The first loop reflects passing arguments to the method/property
For i = 0 To n - 1
VisitArgument(arguments(i), parameters(i))
Next
' The second loop reflects writing to ByRef arguments after the method returned
For i = 0 To n - 1
If parameters(i).IsByRef Then
WriteArgument(arguments(i), parameters(i).IsOut)
End If
Next
End If
End Sub
Protected Overridable Sub WriteArgument(arg As BoundExpression, isOut As Boolean)
End Sub
Protected Overridable Sub VisitArgument(arg As BoundExpression, p As ParameterSymbol)
If p.IsByRef Then
VisitLvalue(arg)
Else
VisitRvalue(arg)
End If
End Sub
Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode
Dim methodGroup As BoundMethodGroup = node.MethodGroupOpt
' if method group is present, check if we need to enter region
If methodGroup IsNot Nothing AndAlso Me._firstInRegion Is methodGroup AndAlso
Me._regionPlace = AbstractFlowPass(Of LocalState).RegionPlace.Before Then
Me.EnterRegion()
End If
Dim receiverOpt As BoundExpression = node.ReceiverOpt
Dim method As MethodSymbol = node.Method
If receiverOpt IsNot Nothing Then
If Not method.IsReducedExtensionMethod OrElse Not receiverOpt.IsValue() Then
Debug.Assert(method.Kind <> MethodKind.Constructor)
VisitRvalue(receiverOpt)
Else
VisitArgument(receiverOpt, method.CallsiteReducedFromMethod.Parameters(0))
End If
Else
' If receiver is nothing it means that the method being
' accessed is shared; we still want to visit the original receiver
' to handle shared methods called on instance receiver.
Dim originalReceiver As BoundExpression = If(methodGroup IsNot Nothing, methodGroup.ReceiverOpt, Nothing)
If originalReceiver IsNot Nothing AndAlso Not originalReceiver.WasCompilerGenerated Then
Debug.Assert(method.IsShared)
' Do not visit originalReceiver if it is Type/Namespace/TypeOrValueExpression and the method
' is shared, we want region flow analysis to return Succeeded = False in this case
Dim kind As BoundKind = originalReceiver.Kind
If (kind <> BoundKind.TypeExpression) AndAlso
(kind <> BoundKind.NamespaceExpression) AndAlso
(kind <> BoundKind.TypeOrValueExpression) Then
VisitUnreachableReceiver(originalReceiver)
End If
End If
End If
' if method group is present, check if we need to leave region
If methodGroup IsNot Nothing AndAlso Me._lastInRegion Is methodGroup AndAlso IsInside Then
Me.LeaveRegion()
End If
Return Nothing
End Function
Public Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode
' Visit the child nodes in bad expressions so that uses of locals in bad expressions are recorded. This
' suppresses warnings about unused locals.
For Each child In node.ChildBoundNodes
VisitRvalue(TryCast(child, BoundExpression))
Next
Return Nothing
End Function
Public Overrides Function VisitBadStatement(node As BoundBadStatement) As BoundNode
' Visit the child nodes of the bad statement
For Each child In node.ChildBoundNodes
Dim statement = TryCast(child, BoundStatement)
If statement IsNot Nothing Then
VisitStatement(TryCast(child, BoundStatement))
Else
Visit(child)
End If
Next
Return Nothing
End Function
Public Overrides Function VisitBadVariable(node As BoundBadVariable) As BoundNode
If node.IsLValue Then
VisitLvalue(node.Expression)
Else
VisitRvalue(node.Expression)
End If
Return Nothing
End Function
Public Overrides Function VisitTypeExpression(node As BoundTypeExpression) As BoundNode
' Visit the receiver even though the expression value
' is ignored since the region may be within the receiver.
VisitUnreachableReceiver(node.UnevaluatedReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitLiteral(node As BoundLiteral) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode
Visit(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitIfStatement(node As BoundIfStatement) As BoundNode
VisitCondition(node.Condition)
Dim trueState As LocalState = Me.StateWhenTrue
Dim falseState As LocalState = Me.StateWhenFalse
Me.SetState(trueState)
VisitStatement(node.Consequence)
trueState = Me.State
Me.SetState(falseState)
If node.AlternativeOpt IsNot Nothing Then
VisitStatement(node.AlternativeOpt)
End If
Me.IntersectWith(Me.State, trueState)
Return Nothing
End Function
Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode
VisitCondition(node.Condition)
Dim trueState As LocalState = Me.StateWhenTrue
Dim falseState As LocalState = Me.StateWhenFalse
If IsConstantTrue(node.Condition) Then
Me.SetState(falseState)
VisitRvalue(node.WhenFalse)
Me.SetState(trueState)
VisitRvalue(node.WhenTrue)
ElseIf IsConstantFalse(node.Condition) Then
Me.SetState(trueState)
VisitRvalue(node.WhenTrue)
Me.SetState(falseState)
VisitRvalue(node.WhenFalse)
Else
Me.SetState(trueState)
VisitRvalue(node.WhenTrue)
Me.Unsplit()
trueState = Me.State
Me.SetState(falseState)
VisitRvalue(node.WhenFalse)
Me.Unsplit()
Me.IntersectWith(Me.State, trueState)
End If
Return Nothing
End Function
Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode
VisitRvalue(node.TestExpression)
If node.TestExpression.IsConstant AndAlso node.TestExpression.ConstantValueOpt.IsNothing Then
' this may be something like 'If(CType(Nothing, String), AnyExpression)'
VisitRvalue(node.ElseExpression)
Else
' all other cases including 'If("const", AnyExpression)'
Dim savedState As LocalState = Me.State.Clone()
VisitRvalue(node.ElseExpression)
Me.SetState(savedState)
End If
Return Nothing
End Function
Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode
VisitRvalue(node.Receiver)
If node.Receiver.IsConstant Then
If node.Receiver.ConstantValueOpt.IsNothing Then
Dim savedState As LocalState = Me.State.Clone()
SetUnreachable()
VisitRvalue(node.AccessExpression)
Me.SetState(savedState)
Else
VisitRvalue(node.AccessExpression)
End If
Else
Dim savedState As LocalState = Me.State.Clone()
VisitRvalue(node.AccessExpression)
IntersectWith(Me.State, savedState)
End If
Return Nothing
End Function
Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode
VisitRvalue(node.ReceiverOrCondition)
Dim savedState As LocalState = Me.State.Clone()
VisitRvalue(node.WhenNotNull)
IntersectWith(Me.State, savedState)
If node.WhenNullOpt IsNot Nothing Then
savedState = Me.State.Clone()
VisitRvalue(node.WhenNullOpt)
IntersectWith(Me.State, savedState)
End If
Return Nothing
End Function
Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode
Dim savedState As LocalState = Me.State.Clone()
VisitLvalue(node.ValueTypeReceiver)
IntersectWith(Me.State, savedState)
savedState = Me.State.Clone()
VisitRvalue(node.ReferenceTypeReceiver)
IntersectWith(Me.State, savedState)
Return Nothing
End Function
Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
' Set unreachable and pending branch for all returns except for the final return that is auto generated
If Not node.IsEndOfMethodReturn Then
VisitRvalue(node.ExpressionOpt)
Me._pendingBranches.Add(New PendingBranch(node, Me.State, Me._nesting))
SetUnreachable()
End If
Return Nothing
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
VisitRvalue(node.Expression)
Me._pendingBranches.Add(New PendingBranch(node, Me.State, Me._nesting))
Return Nothing
End Function
Public Overrides Function VisitStopStatement(node As BoundStopStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitEndStatement(node As BoundEndStatement) As BoundNode
SetUnreachable()
Return Nothing
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
For Each e In node.Arguments
VisitRvalue(e)
Next
VisitObjectCreationExpressionInitializer(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
VisitObjectCreationExpressionInitializer(node.InitializerOpt)
Return Nothing
End Function
Protected Overridable Sub VisitObjectCreationExpressionInitializer(node As BoundObjectInitializerExpressionBase)
Visit(node)
End Sub
Private Function VisitObjectInitializerExpressionBase(node As BoundObjectInitializerExpressionBase) As BoundNode
For Each initializer In node.Initializers
Visit(initializer)
Next
Return Nothing
End Function
Public Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Return Me.VisitObjectInitializerExpressionBase(node)
End Function
Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Return Me.VisitObjectInitializerExpressionBase(node)
End Function
Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode
Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitRedimStatement(node As BoundRedimStatement) As BoundNode
For Each clause In node.Clauses
Visit(clause)
Next
Return Nothing
End Function
Public Overrides Function VisitEraseStatement(node As BoundEraseStatement) As BoundNode
For Each clause In node.Clauses
Visit(clause)
Next
Return Nothing
End Function
Protected Overridable ReadOnly Property SuppressRedimOperandRvalueOnPreserve As Boolean
Get
Return False
End Get
End Property
Public Overrides Function VisitRedimClause(node As BoundRedimClause) As BoundNode
If node.Preserve AndAlso Not SuppressRedimOperandRvalueOnPreserve Then
VisitRvalue(node.Operand)
End If
VisitLvalue(node.Operand)
For Each index In node.Indices
VisitRvalue(index)
Next
Return Nothing
End Function
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
If node.LeftOnTheRightOpt Is Nothing Then
VisitLvalue(node.Left)
Else
SetPlaceholderSubstitute(node.LeftOnTheRightOpt, node.Left)
End If
VisitRvalue(node.Right)
If node.LeftOnTheRightOpt IsNot Nothing Then
RemovePlaceholderSubstitute(node.LeftOnTheRightOpt)
End If
Return Nothing
End Function
Public Overrides Function VisitMidResult(node As BoundMidResult) As BoundNode
VisitRvalue(node.Original)
VisitRvalue(node.Start)
If node.LengthOpt IsNot Nothing Then
VisitRvalue(node.LengthOpt)
End If
VisitRvalue(node.Source)
Return Nothing
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
VisitRvalue(node.ByRefLocal)
VisitRvalue(node.LValue)
Return Nothing
End Function
Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Dim replacement As BoundExpression = GetPlaceholderSubstitute(node)
If replacement IsNot Nothing Then
VisitRvalue(replacement, ReadWriteContext.CompoundAssignmentTarget)
End If
Return Nothing
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
VisitFieldAccessInternal(node)
Return Nothing
End Function
Private Function VisitFieldAccessInternal(node As BoundFieldAccess) As BoundNode
Dim receiverOpt = node.ReceiverOpt
If FieldAccessMayRequireTracking(node) Then
VisitLvalue(receiverOpt)
ElseIf node.FieldSymbol.IsShared Then
VisitUnreachableReceiver(receiverOpt)
Else
VisitRvalue(receiverOpt)
End If
Return Nothing
End Function
''' <summary> Bound field access passed may require tracking if it is an access to a non-shared structure field </summary>
Protected Function FieldAccessMayRequireTracking(fieldAccess As BoundFieldAccess) As Boolean
If fieldAccess.FieldSymbol.IsShared Then
Return False
End If
Dim receiver = fieldAccess.ReceiverOpt
' Receiver must exist
If receiver Is Nothing Then
Return False
End If
' Receiver is of non-primitive structure type
Dim receiverType = receiver.Type
Return IsNonPrimitiveValueType(receiverType)
End Function
Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Dim propertyGroup As BoundPropertyGroup = node.PropertyGroupOpt
' if property group is present, check if we need to enter region
If propertyGroup IsNot Nothing AndAlso Me._firstInRegion Is propertyGroup AndAlso
Me._regionPlace = RegionPlace.Before Then
Me.EnterRegion()
End If
If node.ReceiverOpt IsNot Nothing Then
VisitRvalue(node.ReceiverOpt)
Else
' If receiver is nothing it means that the property being
' accessed is shared; we still want to visit the original receiver
' to handle shared properties accessed on instance receiver.
Dim originalReceiver As BoundExpression = If(propertyGroup IsNot Nothing, propertyGroup.ReceiverOpt, Nothing)
If originalReceiver IsNot Nothing AndAlso Not originalReceiver.WasCompilerGenerated Then
Debug.Assert(node.PropertySymbol.IsShared)
' Do not visit originalReceiver if it is Type/Namespace/TypeOrValueExpression and the property
' is shared, we want region flow analysis to return Succeeded = False in this case
Dim kind As BoundKind = originalReceiver.Kind
If (kind <> BoundKind.TypeExpression) AndAlso
(kind <> BoundKind.NamespaceExpression) AndAlso
(kind <> BoundKind.TypeOrValueExpression) Then
VisitUnreachableReceiver(originalReceiver)
End If
End If
End If
' if property group is present, check if we need to leave region
If propertyGroup IsNot Nothing AndAlso Me._lastInRegion Is propertyGroup AndAlso IsInside Then
Me.LeaveRegion()
End If
For Each argument In node.Arguments
VisitRvalue(argument)
Next
Return Nothing
End Function
''' <summary>
''' If a receiver is included in cases where the receiver will not be
''' evaluated (an instance for a shared method for instance), we
''' still want to visit the receiver but treat it as unreachable code.
''' </summary>
Private Sub VisitUnreachableReceiver(receiver As BoundExpression)
Debug.Assert(Not Me.IsConditionalState)
If receiver IsNot Nothing Then
Dim saved As LocalState = Me.State.Clone()
Me.SetUnreachable()
Me.VisitRvalue(receiver)
Me.SetState(saved)
End If
End Sub
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Visit(node.Initializer)
For Each v In node.LocalDeclarations
Visit(v)
Next
Return Nothing
End Function
Public Overrides Function VisitDimStatement(node As BoundDimStatement) As BoundNode
For Each v In node.LocalDeclarations
VisitStatement(v)
Next
Return Nothing
End Function
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
' while node.Condition node.Body node.ContinueLabel: node.BreakLabel:
LoopHead(node)
VisitCondition(node.Condition)
Dim bodyState As LocalState = Me.StateWhenTrue
Dim breakState As LocalState = Me.StateWhenFalse
Me.SetState(bodyState)
VisitStatement(node.Body)
ResolveContinues(node.ContinueLabel)
LoopTail(node)
ResolveBreaks(breakState, node.ExitLabel)
Return Nothing
End Function
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
VisitStatement(node.ExpressionStatement)
Dim caseBlocks = node.CaseBlocks
If caseBlocks.Any() Then
VisitCaseBlocks(caseBlocks)
ResolveBreaks(Me.State, node.ExitLabel)
End If
Return Nothing
End Function
Private Sub VisitCaseBlocks(caseBlocks As ImmutableArray(Of BoundCaseBlock))
Debug.Assert(caseBlocks.Any())
Dim caseBlockStateBuilder = ArrayBuilder(Of LocalState).GetInstance(caseBlocks.Length)
Dim hasCaseElse = False
Dim curIndex As Integer = 0
Dim lastIndex As Integer = caseBlocks.Length - 1
For Each caseBlock In caseBlocks
' Visit case statement
VisitStatement(caseBlock.CaseStatement)
' Case statement might have a non-null conditionOpt for the condition expression.
' However, conditionOpt cannot be a compile time constant expression.
' VisitCaseStatement must have unsplit the states into a non-conditional state for this scenario.
Debug.Assert(Not Me.IsConditionalState)
' save the current state for next case block.
Dim savedState As LocalState = Me.State.Clone()
' Visit case block body
VisitStatement(caseBlock.Body)
hasCaseElse = hasCaseElse OrElse caseBlock.Syntax.Kind = SyntaxKind.CaseElseBlock
' If the select statement had a case else block, then the state at the end
' of select statement is the merge of states at the end of all case blocks.
' Otherwise, the end state is merge of states at the end of all case blocks
' and saved state prior to visiting the last case block body (i.e. no matching case state)
If curIndex <> lastIndex OrElse Not hasCaseElse Then
caseBlockStateBuilder.Add(Me.State.Clone())
Me.SetState(savedState)
End If
curIndex = curIndex + 1
Next
For Each localState In caseBlockStateBuilder
Me.IntersectWith(Me.State, localState)
Next
caseBlockStateBuilder.Free()
End Sub
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function VisitCaseStatement(node As BoundCaseStatement) As BoundNode
If node.ConditionOpt IsNot Nothing Then
' Case clause expressions cannot be constant expression.
Debug.Assert(node.ConditionOpt.ConstantValueOpt Is Nothing)
VisitRvalue(node.ConditionOpt)
Else
For Each clause In node.CaseClauses
Select Case clause.Kind
Case BoundKind.RelationalCaseClause
VisitRelationalCaseClause(DirectCast(clause, BoundRelationalCaseClause))
Case BoundKind.SimpleCaseClause
VisitSimpleCaseClause(DirectCast(clause, BoundSimpleCaseClause))
Case BoundKind.RangeCaseClause
VisitRangeCaseClause(DirectCast(clause, BoundRangeCaseClause))
Case Else
Throw ExceptionUtilities.UnexpectedValue(clause.Kind)
End Select
Next
End If
Return Nothing
End Function
Public Overrides Function VisitRelationalCaseClause(node As BoundRelationalCaseClause) As BoundNode
' Exactly one of the operand or condition must be non-null
Debug.Assert(node.OperandOpt IsNot Nothing Xor node.ConditionOpt IsNot Nothing)
If node.OperandOpt IsNot Nothing Then
VisitRvalue(node.OperandOpt)
Else
VisitRvalue(node.ConditionOpt)
End If
Return Nothing
End Function
Public Overrides Function VisitSimpleCaseClause(node As BoundSimpleCaseClause) As BoundNode
' Exactly one of the value or condition must be non-null
Debug.Assert(node.ValueOpt IsNot Nothing Xor node.ConditionOpt IsNot Nothing)
If node.ValueOpt IsNot Nothing Then
VisitRvalue(node.ValueOpt)
Else
VisitRvalue(node.ConditionOpt)
End If
Return Nothing
End Function
Public Overrides Function VisitRangeCaseClause(node As BoundRangeCaseClause) As BoundNode
' Exactly one of the LowerBoundOpt or LowerBoundConditionOpt must be non-null
Debug.Assert(node.LowerBoundOpt IsNot Nothing Xor node.LowerBoundConditionOpt IsNot Nothing)
If node.LowerBoundOpt IsNot Nothing Then
VisitRvalue(node.LowerBoundOpt)
Else
VisitRvalue(node.LowerBoundConditionOpt)
End If
' Exactly one of the UpperBoundOpt or UpperBoundConditionOpt must be non-null
Debug.Assert(node.UpperBoundOpt IsNot Nothing Xor node.UpperBoundConditionOpt IsNot Nothing)
If node.UpperBoundOpt IsNot Nothing Then
VisitRvalue(node.UpperBoundOpt)
Else
VisitRvalue(node.UpperBoundConditionOpt)
End If
Return Nothing
End Function
Protected Overridable Sub VisitForControlInitialization(node As BoundForToStatement)
VisitLvalue(node.ControlVariable)
End Sub
Protected Overridable Sub VisitForControlInitialization(node As BoundForEachStatement)
VisitLvalue(node.ControlVariable)
End Sub
Protected Overridable Sub VisitForInitValues(node As BoundForToStatement)
VisitRvalue(node.InitialValue)
VisitRvalue(node.LimitValue)
VisitRvalue(node.StepValue)
End Sub
Protected Overridable Sub VisitForStatementVariableDeclaration(node As BoundForStatement)
End Sub
Public Overrides Function VisitForEachStatement(node As BoundForEachStatement) As BoundNode
' This is a bit subtle.
' initialization of For each control variable happens after the collection is evaluated.
' For example the following statement should give a warning:
' For each i As Object in Me.GetSomeCollection(i) ' <- use of uninitialized i
VisitForStatementVariableDeclaration(node)
VisitRvalue(node.Collection)
LoopHead(node)
Me.Split()
Dim bodyState As LocalState = Me.StateWhenTrue
Dim breakState As LocalState = Me.StateWhenFalse
Me.SetState(bodyState)
' The control Variable is only considered initialized if the body was entered.
VisitForControlInitialization(node)
VisitStatement(node.Body)
ResolveContinues(node.ContinueLabel)
LoopTail(node)
ResolveBreaks(breakState, node.ExitLabel)
Return Nothing
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
Debug.Assert(Not node.ResourceList.IsDefault OrElse node.ResourceExpressionOpt IsNot Nothing)
' A using statement can come in two flavors: using <expression> and using <variable declarations>
' visit possible resource expression
If node.ResourceExpressionOpt IsNot Nothing Then
VisitRvalue(node.ResourceExpressionOpt)
Else
' visit all declarations
For Each variableDeclaration In node.ResourceList
Visit(variableDeclaration)
Next
End If
VisitStatement(node.Body)
Return Nothing
End Function
Public Overrides Function VisitForToStatement(node As BoundForToStatement) As BoundNode
' This is a bit subtle.
' initialization of For control variable happens after initial value, limit and step are evaluated.
' For example the following statement should give a warning:
' For i As Object = 0 To i ' <- use of uninitialized i
VisitForStatementVariableDeclaration(node)
VisitForInitValues(node)
VisitForControlInitialization(node)
LoopHead(node)
Me.Split()
Dim bodyState As LocalState = Me.StateWhenTrue
Dim breakState As LocalState = Me.StateWhenFalse
Me.SetState(bodyState)
VisitStatement(node.Body)
ResolveContinues(node.ContinueLabel)
LoopTail(node)
ResolveBreaks(breakState, node.ExitLabel)
Return Nothing
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Dim oldPending = SavePending()
Dim level = IntroduceBlock()
Dim i As Integer = 0
Dim initialState = Me.State.Clone()
InitializeBlockStatement(level, i)
VisitTryBlock(node.TryBlock, node, initialState)
Dim finallyState = initialState.Clone()
Dim endState = Me.State
For Each catchBlock In node.CatchBlocks
Me.SetState(initialState.Clone())
InitializeBlockStatement(level, i)
VisitCatchBlock(catchBlock, finallyState)
IntersectWith(endState, Me.State)
Next
If node.FinallyBlockOpt IsNot Nothing Then
Dim tryAndCatchPending As SavedPending = SavePending()
Me.SetState(finallyState)
Dim unsetInFinally = AllBitsSet()
InitializeBlockStatement(level, i)
VisitFinallyBlock(node.FinallyBlockOpt, unsetInFinally)
For Each pend In tryAndCatchPending.PendingBranches
' Do not union if branch is a Yield statement
Dim unionBranchWithFinallyState As Boolean = pend.Branch.Kind <> BoundKind.YieldStatement
' or if the branch goes from Catch to Try block
If unionBranchWithFinallyState Then
If BothBranchAndLabelArePrefixedByNesting(pend, ignoreLast:=True) Then
unionBranchWithFinallyState = False
End If
End If
If unionBranchWithFinallyState Then
Me.UnionWith(pend.State, Me.State)
If Me.TrackUnassignments Then
Me.IntersectWith(pend.State, unsetInFinally)
End If
End If
Next
RestorePending(tryAndCatchPending)
Me.UnionWith(endState, Me.State)
If Me.TrackUnassignments Then
Me.IntersectWith(endState, unsetInFinally)
End If
End If
Me.SetState(endState)
FinalizeBlock(level)
If node.ExitLabelOpt IsNot Nothing Then
ResolveBreaks(endState, node.ExitLabelOpt)
End If
RestorePending(oldPending)
Return Nothing
End Function
Protected Overridable Sub VisitTryBlock(tryBlock As BoundStatement, node As BoundTryStatement, ByRef tryState As LocalState)
VisitStatement(tryBlock)
End Sub
Protected Overridable Overloads Sub VisitCatchBlock(catchBlock As BoundCatchBlock, ByRef finallyState As LocalState)
If catchBlock.ExceptionSourceOpt IsNot Nothing Then
VisitLvalue(catchBlock.ExceptionSourceOpt)
End If
If catchBlock.ErrorLineNumberOpt IsNot Nothing Then
VisitRvalue(catchBlock.ErrorLineNumberOpt)
End If
If catchBlock.ExceptionFilterOpt IsNot Nothing Then
VisitRvalue(catchBlock.ExceptionFilterOpt)
End If
VisitBlock(catchBlock.Body)
End Sub
Protected Overridable Sub VisitFinallyBlock(finallyBlock As BoundStatement, ByRef unsetInFinally As LocalState)
VisitStatement(finallyBlock)
End Sub
Public Overrides Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode
VisitRvalue(node.Expression)
For Each i In node.Indices
VisitRvalue(i)
Next
Return Nothing
End Function
Public NotOverridable Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode
Select Case node.OperatorKind And BinaryOperatorKind.OpMask
Case BinaryOperatorKind.AndAlso
VisitCondition(node.Left)
Dim leftTrue As LocalState = Me.StateWhenTrue
Dim leftFalse As LocalState = Me.StateWhenFalse
Me.SetState(leftTrue)
VisitCondition(node.Right)
Dim resultTrue As LocalState = Me.StateWhenTrue
Dim resultFalse As LocalState = leftFalse
IntersectWith(resultFalse, Me.StateWhenFalse)
Me.SetConditionalState(resultTrue, resultFalse)
Exit Select
Case BinaryOperatorKind.OrElse
VisitCondition(node.Left)
Dim leftTrue As LocalState = Me.StateWhenTrue
Dim leftFalse As LocalState = Me.StateWhenFalse
Me.SetState(leftFalse)
VisitCondition(node.Right)
Dim resultTrue As LocalState = Me.StateWhenTrue
IntersectWith(resultTrue, leftTrue)
Dim resultFalse As LocalState = Me.StateWhenFalse
Me.SetConditionalState(resultTrue, resultFalse)
Exit Select
Case BinaryOperatorKind.Concatenate
UnwindAndVisitConcatenationOperator(node)
Case Else
VisitRvalue(node.Left)
VisitRvalue(node.Right)
End Select
Return Nothing
End Function
Private Sub UnwindAndVisitConcatenationOperator(node As BoundBinaryOperator)
Debug.Assert((node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Concatenate)
' It is common in machine-generated code for there to be deep recursion on the left side of a binary
' operator, for example, if you have "a + b + c + ... " then the bound tree will be deep on the left
' hand side. To mitigate the risk of stack overflow we use an explicit stack.
'
' Of course we must ensure that we visit the left hand side before the right hand side.
Dim leftmostConcatExpressions = ArrayBuilder(Of BoundBinaryOperator).GetInstance()
leftmostConcatExpressions.Add(node)
' Collect all binary concatenation operators along the leftmost
' expression tree branch in leftmostConcatExpressions
Dim lastLeftOperand As BoundExpression = node.Left
Do
If lastLeftOperand.Kind = BoundKind.BinaryOperator Then
Dim binary = DirectCast(lastLeftOperand, BoundBinaryOperator)
If (binary.OperatorKind And BinaryOperatorKind.OpMask) <> BinaryOperatorKind.Concatenate Then
Exit Do
End If
' As we emulate visiting the concatenate operator: enter the region if needed
If binary Is Me._firstInRegion AndAlso Me._regionPlace = RegionPlace.Before Then
Me.EnterRegion()
End If
leftmostConcatExpressions.Push(binary)
lastLeftOperand = binary.Left
Else
Exit Do
End If
Loop
' Visit leftmost operand
VisitRvalue(lastLeftOperand)
' emulate visiting binary concat operators
While leftmostConcatExpressions.Count > 0
Dim concat As BoundBinaryOperator = leftmostConcatExpressions.Pop()
' Visit right operand
VisitRvalue(concat.Right)
' Don't leave region for the uppermost concat operator, it should be done by
' VisitBinaryOperator caller such as VisitRValue(...)
If concat IsNot node Then
' As we emulate visiting the concatenate operator: leave region if needed
Me.Unsplit()
If concat Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
End If
End While
leftmostConcatExpressions.Free()
End Sub
Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
If node.LeftOperand IsNot Nothing Then
VisitRvalue(node.LeftOperand)
End If
VisitRvalue(node.BitwiseOperator)
Return Nothing
End Function
Public Overrides Function VisitAddHandlerStatement(node As BoundAddHandlerStatement) As BoundNode
Return VisitAddRemoveHandlerStatement(node)
End Function
Public Overrides Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement) As BoundNode
Return VisitAddRemoveHandlerStatement(node)
End Function
Public Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Visit(node.MethodGroup)
Return Nothing
End Function
Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Visit(node.MemberAccess)
Return Nothing
End Function
Private Function VisitAddRemoveHandlerStatement(node As BoundAddRemoveHandlerStatement) As BoundNode
' from the data/control flow prospective AddRemoveHandler
' statement is just a trivial binary operator.
VisitRvalue(node.EventAccess)
VisitRvalue(node.Handler)
Return Nothing
End Function
Public Overrides Function VisitEventAccess(node As BoundEventAccess) As BoundNode
Dim receiver = node.ReceiverOpt
If receiver IsNot Nothing Then
VisitRvalue(node.ReceiverOpt)
End If
Return Nothing
End Function
Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode
Me.Visit(node.EventInvocation)
Return Nothing
End Function
Public Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode
VisitRvalue(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode
If node.OperatorKind = UnaryOperatorKind.Not Then
VisitCondition(node.Operand)
Me.SetConditionalState(Me.StateWhenFalse, Me.StateWhenTrue)
Else
VisitRvalue(node.Operand)
End If
Return Nothing
End Function
Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
VisitRvalue(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode
For Each e1 In node.Bounds
VisitRvalue(e1)
Next
If node.InitializerOpt IsNot Nothing AndAlso Not node.InitializerOpt.Initializers.IsDefault Then
For Each element In node.InitializerOpt.Initializers
VisitRvalue(element)
Next
End If
Return Nothing
End Function
Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode
For Each initializer In node.Initializers
VisitRvalue(initializer)
Next
Return Nothing
End Function
Public Overrides Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
For Each arrayBound In node.Bounds
VisitRvalue(arrayBound)
Next
VisitRvalue(node.Initializer)
Return Nothing
End Function
Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode
VisitRvalue(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode
VisitRvalue(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitTypeOf(node As BoundTypeOf) As BoundNode
VisitRvalue(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
VisitRvalue(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
VisitRvalue(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitGetType(node As BoundGetType) As BoundNode
VisitTypeExpression(node.SourceType)
Return Nothing
End Function
Public Overrides Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode
VisitStatement(node.StatementOpt)
Return Nothing
End Function
Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode
VisitStatement(node.StatementOpt)
Return Nothing
End Function
Public Overrides Function VisitStatementList(node As BoundStatementList) As BoundNode
For Each statement In node.Statements
Visit(statement)
Next
Return Nothing
End Function
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
' visit SyncLock expression
VisitRvalue(node.LockExpression)
' visit body
VisitStatement(node.Body)
Return Nothing
End Function
Public Overrides Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Dim boundLambda As BoundLambda = node.BindForErrorRecovery()
Debug.Assert(boundLambda IsNot Nothing)
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'boundLambda' is not nothing
If boundLambda Is Me._firstInRegion AndAlso Me._regionPlace = RegionPlace.Before Then
Me.EnterRegion()
End If
VisitLambda(node.BindForErrorRecovery())
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'boundLambda' is not nothing
If boundLambda Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
Return Nothing
End Function
Public Overrides Function VisitExitStatement(node As BoundExitStatement) As BoundNode
Me._pendingBranches.Add(New PendingBranch(node, Me.State, Me._nesting))
SetUnreachable()
Return Nothing
End Function
Public Overrides Function VisitContinueStatement(node As BoundContinueStatement) As BoundNode
Me._pendingBranches.Add(New PendingBranch(node, Me.State, Me._nesting))
SetUnreachable()
Return Nothing
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitDoLoopStatement(node As BoundDoLoopStatement) As BoundNode
If node.ConditionOpt IsNot Nothing Then
If node.ConditionIsTop Then
VisitDoLoopTopConditionStatement(node)
Else
VisitDoLoopBottomConditionStatement(node)
End If
Else
VisitUnconditionalDoLoopStatement(node)
End If
Return Nothing
End Function
Public Sub VisitDoLoopTopConditionStatement(node As BoundDoLoopStatement)
Debug.Assert(node.ConditionIsTop AndAlso node.ConditionOpt IsNot Nothing)
' do while | until node.Condition statements node.ContinueLabel: loop node.BreakLabel:
LoopHead(node)
VisitCondition(node.ConditionOpt)
Dim exitState As LocalState
If node.ConditionIsUntil Then
exitState = Me.StateWhenTrue
Me.SetState(Me.StateWhenFalse)
Else
exitState = Me.StateWhenFalse
Me.SetState(Me.StateWhenTrue)
End If
VisitStatement(node.Body)
ResolveContinues(node.ContinueLabel)
LoopTail(node)
ResolveBreaks(exitState, node.ExitLabel)
End Sub
Public Sub VisitDoLoopBottomConditionStatement(node As BoundDoLoopStatement)
Debug.Assert(Not node.ConditionIsTop AndAlso node.ConditionOpt IsNot Nothing)
' do statements node.ContinueLabel: loop while|until node.Condition node.ExitLabel:
LoopHead(node)
VisitStatement(node.Body)
ResolveContinues(node.ContinueLabel)
VisitCondition(node.ConditionOpt)
Dim exitState As LocalState
If node.ConditionIsUntil Then
exitState = Me.StateWhenTrue
Me.SetState(Me.StateWhenFalse)
Else
exitState = Me.StateWhenFalse
Me.SetState(Me.StateWhenTrue)
End If
LoopTail(node)
ResolveBreaks(exitState, node.ExitLabel)
End Sub
Private Overloads Sub VisitUnconditionalDoLoopStatement(node As BoundDoLoopStatement)
Debug.Assert(node.ConditionOpt Is Nothing)
' do statements; node.ContinueLabel: loop node.BreakLabel:
LoopHead(node)
VisitStatement(node.Body)
ResolveContinues(node.ContinueLabel)
Dim exitState = UnreachableState()
LoopTail(node)
ResolveBreaks(exitState, node.ExitLabel)
End Sub
Public Overrides Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode
Me._pendingBranches.Add(New PendingBranch(node, Me.State, Me._nesting))
SetUnreachable()
Return Nothing
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
If ResolveBranches(node) Then
Me.backwardBranchChanged = True
End If
Dim label As LabelSymbol = node.Label
Dim _state As LocalState = LabelState(label)
Me.IntersectWith(Me.State, _state)
Me._labels(label) = New LabelStateAndNesting(node, Me.State.Clone(), Me._nesting)
Me._labelsSeen.Add(label)
Return Nothing
End Function
Public Overrides Function VisitThrowStatement(node As BoundThrowStatement) As BoundNode
Dim expr As BoundExpression = node.ExpressionOpt
If expr IsNot Nothing Then
VisitRvalue(expr)
End If
SetUnreachable()
Return Nothing
End Function
Public Overrides Function VisitNoOpStatement(node As BoundNoOpStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitNamespaceExpression(node As BoundNamespaceExpression) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitFieldOrPropertyInitializer(node As BoundFieldOrPropertyInitializer) As BoundNode
VisitRvalue(node.InitialValue)
Return Nothing
End Function
Public Overrides Function VisitArrayLength(node As BoundArrayLength) As BoundNode
VisitRvalue(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode
VisitRvalue(node.Condition)
Me._pendingBranches.Add(New PendingBranch(node, Me.State, Me._nesting))
Return Nothing
End Function
Public Overrides Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
VisitRvalue(node.Declaration)
For Each child In node.ChildNodes
VisitRvalue(child)
Next
Return Nothing
End Function
Public Overrides Function VisitXmlElement(node As BoundXmlElement) As BoundNode
VisitRvalue(node.Argument)
For Each child In node.ChildNodes
VisitRvalue(child)
Next
Return Nothing
End Function
Public Overrides Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
VisitRvalue(node.Name)
VisitRvalue(node.Value)
Return Nothing
End Function
Public Overrides Function VisitXmlName(node As BoundXmlName) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
' VisitRvalue(node.XmlNamespace) is supposed to be included in node.ObjectCreation
VisitRvalue(node.ObjectCreation)
Return Nothing
End Function
Public Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
VisitRvalue(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Visit(node.MemberAccess)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement) As BoundNode
Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
Visit(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitNameOfOperator(node As BoundNameOfOperator) As BoundNode
Dim savedState As LocalState = Me.State.Clone()
SetUnreachable()
Visit(node.Argument)
Me.SetState(savedState)
Return Nothing
End Function
Public Overrides Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression) As BoundNode
Visit(node.Expression)
Return Nothing
End Function
#End Region
End Class
End Namespace
|
furesoft/roslyn
|
src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/AbstractFlowPass.vb
|
Visual Basic
|
apache-2.0
| 106,813
|
' 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
<WpfFact, 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
|
mseamari/Stuff
|
src/VisualStudio/Core/Test/Progression/ImplementedByGraphQueryTests.vb
|
Visual Basic
|
apache-2.0
| 3,024
|
' 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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.PreprocessorDirectives
Public Class EndRegionDirectiveKeywordRecommenderTests
Inherits RecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndRegionNotInFileTest()
VerifyRecommendationsMissing(<File>|</File>, "#End Region")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndRegionInFileAfterRegionTest()
VerifyRecommendationsContain(<File>
#Region "goo"
|</File>, "#End Region")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub RegionAfterHashEndEndTest()
VerifyRecommendationsContain(<File>
#Region "goo"
#End |</File>, "Region")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotHashEndRegionAfterHashEndTest()
VerifyRecommendationsMissing(<File>
#Region "goo"
#End |</File>, "#End Region")
End Sub
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/PreprocessorDirectives/EndRegionDirectiveKeywordRecommenderTests.vb
|
Visual Basic
|
mit
| 1,373
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp
Public Class CodeClassTests
Inherits AbstractCodeClassTests
#Region "GetStartPoint() tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint1()
Dim code =
<Code>
class $$C {}
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
ThrowsCOMException(E_FAIL)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=10)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=10)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=10)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=10)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint2()
Dim code =
<Code>
class $$C { }
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
ThrowsCOMException(E_FAIL)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint3()
Dim code =
<Code>
class $$C { }
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
ThrowsCOMException(E_FAIL)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=12)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=12)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=12)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=12)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint4()
Dim code =
<Code>
using System;
[CLSCompliant(true)] class $$C { }
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=32)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=31, absoluteOffset:=45, lineLength:=32)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=22, absoluteOffset:=36, lineLength:=32)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=28, absoluteOffset:=42, lineLength:=32)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=32)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint5()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C { }
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint6()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C {
}
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=1)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint7()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C {
}
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=0)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint8()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C
{
}
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=5, lineOffset:=1, absoluteOffset:=46, lineLength:=0)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=7)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=7)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint9()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C {void M() { }}
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=22)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=22)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=22)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint10()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C { void M() { } }
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint11()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C {
void M() { }
}
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint12()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C
{
void M() { }
}
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=5, lineOffset:=1, absoluteOffset:=46, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=7)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=7)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)))
End Sub
#End Region
#Region "GetEndPoint() tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint1()
Dim code =
<Code>
class $$C {}
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
ThrowsCOMException(E_FAIL)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=10)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=10)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=10)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint2()
Dim code =
<Code>
class $$C { }
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
ThrowsCOMException(E_FAIL)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint3()
Dim code =
<Code>
class $$C { }
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
ThrowsCOMException(E_FAIL)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=12)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=12)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=13, absoluteOffset:=13, lineLength:=12)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint4()
Dim code =
<Code>
using System;
[CLSCompliant(true)] class $$C { }
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=32)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=46, lineLength:=32)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=29, absoluteOffset:=43, lineLength:=32)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=33, absoluteOffset:=47, lineLength:=32)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint5()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C { }
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=11, absoluteOffset:=46, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=11)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=12, absoluteOffset:=47, lineLength:=11)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint6()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C {
}
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=1)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=4, lineOffset:=2, absoluteOffset:=47, lineLength:=1)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint7()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C {
}
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=5, lineOffset:=1, absoluteOffset:=47, lineLength:=1)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=5, lineOffset:=2, absoluteOffset:=48, lineLength:=1)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint8()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C
{
}
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=6, lineOffset:=1, absoluteOffset:=47, lineLength:=1)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=7)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=6, lineOffset:=2, absoluteOffset:=48, lineLength:=1)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint9()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C {void M() { }}
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=57, lineLength:=22)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=22)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=23, absoluteOffset:=58, lineLength:=22)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint10()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C { void M() { } }
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=24, absoluteOffset:=59, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=25, absoluteOffset:=60, lineLength:=24)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint11()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C {
void M() { }
}
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=5, lineOffset:=1, absoluteOffset:=63, lineLength:=1)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=5, lineOffset:=2, absoluteOffset:=64, lineLength:=1)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint12()
Dim code =
<Code>
using System;
[CLSCompliant(true)]
class $$C
{
void M() { }
}
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=6, lineOffset:=1, absoluteOffset:=63, lineLength:=1)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartName,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=7)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
ThrowsNotImplementedException),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=6, lineOffset:=2, absoluteOffset:=64, lineLength:=1)))
End Sub
#End Region
#Region "Access tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access1()
Dim code =
<Code>
class $$C { }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access2()
Dim code =
<Code>
internal class $$C { }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access3()
Dim code =
<Code>
public class $$C { }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access4()
Dim code =
<Code>
class C { class $$D { } }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access5()
Dim code =
<Code>
class C { private class $$D { } }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access6()
Dim code =
<Code>
class C { protected class $$D { } }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access7()
Dim code =
<Code>
class C { protected internal class $$D { } }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access8()
Dim code =
<Code>
class C { internal class $$D { } }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access9()
Dim code =
<Code>
class C { public class $$D { } }
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
#End Region
#Region "Attributes tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Attributes1()
Dim code =
<Code>
class $$C { }
</Code>
TestAttributes(code, NoElements)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Attributes2()
Dim code =
<Code>
using System;
[Serializable]
class $$C { }
</Code>
TestAttributes(code, IsElement("Serializable"))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Attributes3()
Dim code =
<Code>using System;
[Serializable]
[CLSCompliant(true)]
class $$C { }
</Code>
TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant"))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Attributes4()
Dim code =
<Code>using System;
[Serializable, CLSCompliant(true)]
class $$C { }
</Code>
TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant"))
End Sub
#End Region
#Region "Bases tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Bases1()
Dim code =
<Code>
class $$C { }
</Code>
TestBases(code, IsElement("Object"))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Bases2()
Dim code =
<Code>
class $$C : object { }
</Code>
TestBases(code, IsElement("Object"))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Bases3()
Dim code =
<Code>
class C { }
class $$D : C { }
</Code>
TestBases(code, IsElement("C"))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Bases4()
Dim code =
<Code>
interface I { }
class $$D : I { }
</Code>
TestBases(code, IsElement("Object"))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Bases5()
Dim code =
<Code>
class $$C : System.Collections.Generic.List<int> { }
</Code>
TestBases(code, IsElement("List"))
End Sub
#End Region
#Region "Children tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Children1()
Dim code =
<Code>
class $$C { }
</Code>
TestChildren(code, NoElements)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Children2()
Dim code =
<Code>
class $$C { void M() { } }
</Code>
TestChildren(code, IsElement("M"))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Children3()
Dim code =
<Code>
[Obsolete]
class $$C { void M() { } }
</Code>
TestChildren(code, IsElement("Obsolete"), IsElement("M"))
End Sub
#End Region
#Region "ClassKind tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub ClassKind_MainClass()
Dim code =
<Code>
class $$C
{
}
</Code>
TestClassKind(code, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub ClassKind_PartialClass()
Dim code =
<Code>
partial class $$C
{
}
</Code>
TestClassKind(code, EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass)
End Sub
#End Region
#Region "Comment tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment1()
Dim code =
<Code>
class $$C { }
</Code>
TestComment(code, String.Empty)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment2()
Dim code =
<Code>
// Foo
// Bar
class $$C { }
</Code>
TestComment(code, "Foo" & vbCrLf & "Bar" & vbCrLf)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment3()
Dim code =
<Code>
class B { } // Foo
// Bar
class $$C { }
</Code>
TestComment(code, "Bar" & vbCrLf)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment4()
Dim code =
<Code>
class B { } // Foo
/* Bar */
class $$C { }
</Code>
TestComment(code, "Bar" & vbCrLf)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment5()
Dim code =
<Code>
class B { } // Foo
/*
Bar
*/
class $$C { }
</Code>
TestComment(code, "Bar" & vbCrLf)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment6()
Dim code =
<Code>
class B { } // Foo
/*
Hello
World!
*/
class $$C { }
</Code>
TestComment(code, "Hello" & vbCrLf & "World!" & vbCrLf)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment7()
Dim code =
<Code>
class B { } // Foo
/*
Hello
World!
*/
class $$C { }
</Code>
TestComment(code, "Hello" & vbCrLf & vbCrLf & "World!" & vbCrLf)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment8()
Dim code =
<Code>
/* This
* is
* a
* multi-line
* comment!
*/
class $$C { }
</Code>
TestComment(code, "This" & vbCrLf & "is" & vbCrLf & "a" & vbCrLf & "multi-line" & vbCrLf & "comment!" & vbCrLf)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment9()
Dim code =
<Code>
// Foo
/// <summary>Bar</summary>
class $$C { }
</Code>
TestComment(code, String.Empty)
End Sub
#End Region
#Region "DocComment tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub DocComment1()
Dim code =
<Code>
/// <summary>Hello World</summary>
class $$C { }
</Code>
TestDocComment(code, "<doc>" & vbCrLf & "<summary>Hello World</summary>" & vbCrLf & "</doc>")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub DocComment2()
Dim code =
<Code>
/// <summary>
/// Hello World
/// </summary>
class $$C { }
</Code>
TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub DocComment3()
Dim code =
<Code>
/// <summary>
/// Hello World
///</summary>
class $$C { }
</Code>
TestDocComment(code, "<doc>" & vbCrLf & " <summary>" & vbCrLf & " Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub DocComment4()
Dim code =
<Code>
/// <summary>
/// Summary
/// </summary>
/// <remarks>Remarks</remarks>
class $$C { }
</Code>
TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Summary" & vbCrLf & "</summary>" & vbCrLf & "<remarks>Remarks</remarks>" & vbCrLf & "</doc>")
End Sub
#End Region
#Region "InheritanceKind tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub InheritanceKind_None()
Dim code =
<Code>
class $$C
{
}
</Code>
TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub InheritanceKind_Abstract()
Dim code =
<Code>
abstract class $$C
{
}
</Code>
TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub InheritanceKind_Sealed()
Dim code =
<Code>
sealed class $$C
{
}
</Code>
TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub InheritanceKind_New()
Dim code =
<Code>
class C
{
protected class Inner { }
}
class D
{
new protected class $$Inner { }
}
</Code>
TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub InheritanceKind_AbstractAndNew()
Dim code =
<Code>
class C
{
protected class Inner { }
}
class D
{
new protected abstract class $$Inner { }
}
</Code>
TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew)
End Sub
#End Region
#Region "IsAbstract tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsAbstract1()
Dim code =
<Code>
class $$C
{
}
</Code>
TestIsAbstract(code, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsAbstract2()
Dim code =
<Code>
abstract class $$C
{
}
</Code>
TestIsAbstract(code, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsAbstract3()
Dim code =
<Code>
abstract partial class $$C
{
}
partial class C
{
}
</Code>
TestIsAbstract(code, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsAbstract4()
Dim code =
<Code>
partial class $$C
{
}
abstract partial class C
{
}
</Code>
TestIsAbstract(code, False)
End Sub
#End Region
#Region "IsShared tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsShared1()
Dim code =
<Code>
class $$C
{
}
</Code>
TestIsShared(code, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsShared2()
Dim code =
<Code>
static class $$C
{
}
</Code>
TestIsShared(code, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsShared3()
Dim code =
<Code>
static partial class $$C
{
}
partial class C
{
}
</Code>
TestIsShared(code, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsShared4()
Dim code =
<Code>
partial class $$C
{
}
static partial class C
{
}
</Code>
TestIsShared(code, False)
End Sub
#End Region
#Region "IsDerivedFrom tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsDerivedFromObject_Explicit()
Dim code =
<Code>
class $$C : object { }
</Code>
TestIsDerivedFrom(code, "System.Object", True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsDerivedFrom_ObjectImplicit()
Dim code =
<Code>
class $$C { }
</Code>
TestIsDerivedFrom(code, "System.Object", True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsDerivedFrom_NotString()
Dim code =
<Code>
class $$C { }
</Code>
TestIsDerivedFrom(code, "System.String", False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsDerivedFrom_NotNonexistent()
Dim code =
<Code>
class $$C { }
</Code>
TestIsDerivedFrom(code, "System.ThisIsClearlyNotARealClassName", False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsDerivedFrom_UserClassInGlobalNamespace()
Dim code =
<Code>
class B { }
class $$C : B { }
</Code>
TestIsDerivedFrom(code, "B", True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsDerivedFrom_UserClassInSameNamespace()
Dim code =
<Code>
namespace NS
{
class B { }
class $$C : B { }
}
</Code>
TestIsDerivedFrom(code, "NS.B", True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsDerivedFrom_UserClassInDifferentNamespace()
Dim code =
<Code>
namespace NS1
{
class B { }
}
namespace NS2
{
class $$C : NS1.B { }
}
</Code>
TestIsDerivedFrom(code, "NS1.B", True)
End Sub
#End Region
#Region "Kind tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Kind()
Dim code =
<Code>
class $$C
{
}
</Code>
TestKind(code, EnvDTE.vsCMElement.vsCMElementClass)
End Sub
#End Region
#Region "Parts tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Parts1()
Dim code =
<Code>
class $$C
{
}
</Code>
TestParts(code, 1)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Parts2()
Dim code =
<Code>
partial class $$C
{
}
</Code>
TestParts(code, 1)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Parts3()
Dim code =
<Code>
partial class $$C
{
}
partial class C
{
}
</Code>
TestParts(code, 2)
End Sub
#End Region
#Region "AddAttribute tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddAttribute1()
Dim code =
<Code>
using System;
class $$C { }
</Code>
Dim expected =
<Code>
using System;
[Serializable()]
class C { }
</Code>
TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddAttribute2()
Dim code =
<Code>
using System;
[Serializable]
class $$C { }
</Code>
Dim expected =
<Code>
using System;
[Serializable]
[CLSCompliant(true)]
class C { }
</Code>
TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1})
End Sub
#End Region
#Region "AddBase tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddBase1()
Dim code =
<Code>
class $$C { }
</Code>
Dim expected =
<Code>
class C : B { }
</Code>
TestAddBase(code, "B", Nothing, expected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddBase2()
Dim code =
<Code>
class $$C : B { }
</Code>
Dim expected =
<Code>
class C : A, B { }
</Code>
TestAddBase(code, "A", Nothing, expected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddBase3()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C : B
{
}
</Code>
TestAddBase(code, "B", Nothing, expected)
End Sub
#End Region
#Region "AddEvent tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddEvent1()
Dim code =
<Code>
class C$$
{
}
</Code>
Dim expected =
<Code>
class C
{
event System.EventHandler E;
}
</Code>
TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddEvent2()
Dim code =
<Code>
class C$$
{
}
</Code>
Dim expected =
<Code>
class C
{
event System.EventHandler E
{
add
{
}
remove
{
}
}
}
</Code>
TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler", .CreatePropertyStyleEvent = True})
End Sub
#End Region
#Region "AddFunction tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction1()
Dim code =
<Code>
class $$C { }
</Code>
Dim expected =
<Code>
class C
{
void Foo()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "Foo", .Type = "void"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction2()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
void Foo()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "Foo", .Type = "void"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction3()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
void Foo()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "Foo", .Type = "System.Void"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction4()
Dim code =
<Code>
class $$C
{
int i;
}
</Code>
Dim expected =
<Code>
class C
{
void Foo()
{
}
int i;
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "Foo", .Type = "void"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction5()
Dim code =
<Code>
class $$C
{
int i;
}
</Code>
Dim expected =
<Code>
class C
{
int i;
void Foo()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "Foo", .Type = "void", .Position = 1})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction6()
Dim code =
<Code>
class $$C
{
int i;
}
</Code>
Dim expected =
<Code>
class C
{
int i;
void Foo()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "Foo", .Type = "void", .Position = "i"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction_Constructor1()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
C()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionConstructor})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction_Constructor2()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
public C()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionConstructor, .Access = EnvDTE.vsCMAccess.vsCMAccessPublic})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction_EscapedName()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
public void @as()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "@as", .Type = "void", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddFunction_Destructor()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
~C()
{
}
}
</Code>
TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionDestructor, .Type = "void", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic})
End Sub
#End Region
#Region "AddImplementedInterface tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddImplementedInterface1()
Dim code =
<Code>
class $$C { }
</Code>
TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", Nothing)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddImplementedInterface2()
Dim code =
<Code>
class $$C { }
interface I { }
</Code>
Dim expected =
<Code>
class C : I { }
interface I { }
</Code>
TestAddImplementedInterface(code, "I", -1, expected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddImplementedInterface3()
Dim code =
<Code>
class $$C : I { }
interface I { }
interface J { }
</Code>
Dim expected =
<Code>
class C : I, J { }
interface I { }
interface J { }
</Code>
TestAddImplementedInterface(code, "J", -1, expected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddImplementedInterface4()
Dim code =
<Code>
class $$C : I { }
interface I { }
interface J { }
</Code>
Dim expected =
<Code>
class C : J, I { }
interface I { }
interface J { }
</Code>
TestAddImplementedInterface(code, "J", 0, expected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddImplementedInterface5()
Dim code =
<Code>
class $$C : I, K { }
interface I { }
interface J { }
interface K { }
</Code>
Dim expected =
<Code>
class C : I, J, K { }
interface I { }
interface J { }
interface K { }
</Code>
TestAddImplementedInterface(code, "J", 1, expected)
End Sub
#End Region
#Region "AddProperty tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddProperty1()
Dim code =
<Code>
class C$$
{
}
</Code>
Dim expected =
<Code>
class C
{
string Name
{
get
{
return default(string);
}
set
{
}
}
}
</Code>
TestAddProperty(code, expected, New PropertyData With {.GetterName = "Name", .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddProperty2()
Dim code =
<Code>
class C$$
{
}
</Code>
Dim expected =
<Code>
class C
{
string Name
{
get
{
return default(string);
}
}
}
</Code>
TestAddProperty(code, expected, New PropertyData With {.GetterName = "Name", .PutterName = Nothing, .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddProperty3()
Dim code =
<Code>
class C$$
{
}
</Code>
Dim expected =
<Code>
class C
{
string Name
{
set
{
}
}
}
</Code>
TestAddProperty(code, expected, New PropertyData With {.GetterName = Nothing, .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString})
End Sub
#End Region
#Region "AddVariable tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable1()
Dim code =
<Code>
class $$C { }
</Code>
Dim expected =
<Code>
class C
{
int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable2()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable3()
Dim code =
<Code>
class $$C
{
void Foo() { }
}
</Code>
Dim expected =
<Code>
class C
{
void Foo() { }
int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "Foo"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable4()
Dim code =
<Code>
class $$C
{
int x;
void Foo() { }
}
</Code>
Dim expected =
<Code>
class C
{
int x;
int i;
void Foo() { }
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable5()
Dim code =
<Code>
class $$C
{
int x;
void Foo() { }
}
</Code>
Dim expected =
<Code>
class C
{
int x;
int i;
void Foo() { }
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable6()
Dim code =
<Code>
class $$C
{
int x, y;
void Foo() { }
}
</Code>
Dim expected =
<Code>
class C
{
int x, y;
int i;
void Foo() { }
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable7()
Dim code =
<Code>
class $$C
{
int x, y;
void Foo() { }
}
</Code>
Dim expected =
<Code>
class C
{
int x, y;
int i;
void Foo() { }
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "y"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable8()
Dim code =
<Code>
class $$C
{
void Foo() { }
}
</Code>
Dim expected =
<Code>
class C
{
int i;
void Foo() { }
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = 0})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable9()
Dim code =
<Code>
class $$C
{
void Foo() { }
}
</Code>
Dim expected =
<Code>
class C
{
void Foo() { }
int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = -1})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable10()
Dim code =
<Code>
class $$C
{
int x;
int y;
}
</Code>
Dim expected =
<Code>
class C
{
int x;
int i;
int y;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable11()
Dim code =
<Code>
class $$C
{
int x, y;
int z;
}
</Code>
Dim expected =
<Code>
class C
{
int x, y;
int i;
int z;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable12()
Dim code =
<Code>
class $$C
{
int x, y;
int z;
}
</Code>
Dim expected =
<Code>
class C
{
int x, y;
int i;
int z;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "y"})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable13()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
public int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic})
End Sub
<WorkItem(545238)>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable14()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
private int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessPrivate})
End Sub
<WorkItem(546556)>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable15()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
internal int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProject})
End Sub
<WorkItem(546556)>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable16()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
protected internal int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected})
End Sub
<WorkItem(546556)>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariable17()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
protected int i;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProtected})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariableOutsideOfRegion()
Dim code =
<Code>
class $$C
{
#region Foo
int i = 0;
#endregion
}
</Code>
Dim expected =
<Code>
class C
{
#region Foo
int i = 0;
#endregion
int j;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "j", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefInt, .Position = "i"})
End Sub
<WorkItem(529865)>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddVariableAfterComment()
Dim code =
<Code>
class $$C
{
int i = 0; // Foo
}
</Code>
Dim expected =
<Code>
class C
{
int i = 0; // Foo
int j;
}
</Code>
TestAddVariable(code, expected, New VariableData With {.Name = "j", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefInt, .Position = "i"})
End Sub
#End Region
#Region "RemoveBase tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub RemoveBase1()
Dim code =
<Code>
class $$C : B { }
</Code>
Dim expected =
<Code>
class C { }
</Code>
TestRemoveBase(code, "B", expected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub RemoveBase2()
Dim code =
<Code>
class $$C : A, B { }
</Code>
Dim expected =
<Code>
class C : B { }
</Code>
TestRemoveBase(code, "A", expected)
End Sub
#End Region
#Region "RemoveImplementedInterface tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub RemoveImplementedInterface1()
Dim code =
<Code>
class $$C : I { }
interface I { }
</Code>
Dim expected =
<Code>
class C { }
interface I { }
</Code>
TestRemoveImplementedInterface(code, "I", expected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub RemoveImplementedInterface2()
Dim code =
<Code>
class $$C : A, I { }
class A { }
interface I { }
</Code>
Dim expected =
<Code>
class C : A { }
class A { }
interface I { }
</Code>
TestRemoveImplementedInterface(code, "I", expected)
End Sub
#End Region
#Region "RemoveMember tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember1()
Dim code =
<Code>
class $$C
{
void Foo()
{
}
}
</Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestRemoveChild(code, expected, "Foo")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember2()
Dim code =
<Code><![CDATA[
class $$C
{
/// <summary>
/// Doc comment.
/// </summary>
void Foo()
{
}
}
]]></Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestRemoveChild(code, expected, "Foo")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember3()
Dim code =
<Code><![CDATA[
class $$C
{
// Comment comment comment
void Foo()
{
}
}
]]></Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestRemoveChild(code, expected, "Foo")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember4()
Dim code =
<Code><![CDATA[
class $$C
{
// Comment comment comment
void Foo()
{
}
}
]]></Code>
Dim expected =
<Code>
class C
{
// Comment comment comment
}
</Code>
TestRemoveChild(code, expected, "Foo")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember5()
Dim code =
<Code><![CDATA[
class $$C
{
#region A region
int a;
#endregion
/// <summary>
/// Doc comment.
/// </summary>
void Foo()
{
}
}
]]></Code>
Dim expected =
<Code>
class C
{
#region A region
int a;
#endregion
}
</Code>
TestRemoveChild(code, expected, "Foo")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember6()
Dim code =
<Code><![CDATA[
class $$C
{
// This comment remains.
// This comment is deleted.
/// <summary>
/// This comment is deleted.
/// </summary>
void Foo()
{
}
}
]]></Code>
Dim expected =
<Code>
class C
{
// This comment remains.
}
</Code>
TestRemoveChild(code, expected, "Foo")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember7()
Dim code =
<Code><![CDATA[
class $$C
{
int a;
int b;
int d;
}
]]></Code>
Dim expected =
<Code>
class C
{
int a;
int d;
}
</Code>
TestRemoveChild(code, expected, "b")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember8()
Dim code =
<Code>
class $$C
{
void Alpha()
{
}
void Foo()
{
}
void Beta()
{
}
}
</Code>
Dim expected =
<Code>
class C
{
void Alpha()
{
}
void Beta()
{
}
}
</Code>
TestRemoveChild(code, expected, "Foo")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember_Event1()
Dim code =
<Code>
class $$C
{
event System.EventHandler E;
}
</Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestRemoveChild(code, expected, "E")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember_Event2()
Dim code =
<Code>
class $$C
{
event System.EventHandler E, F, G;
}
</Code>
Dim expected =
<Code>
class C
{
event System.EventHandler F, G;
}
</Code>
TestRemoveChild(code, expected, "E")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember_Event3()
Dim code =
<Code>
class $$C
{
event System.EventHandler E, F, G;
}
</Code>
Dim expected =
<Code>
class C
{
event System.EventHandler E, G;
}
</Code>
TestRemoveChild(code, expected, "F")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember_Event4()
Dim code =
<Code>
class $$C
{
event System.EventHandler E, F, G;
}
</Code>
Dim expected =
<Code>
class C
{
event System.EventHandler E, F;
}
</Code>
TestRemoveChild(code, expected, "G")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub RemoveMember_Event5()
Dim code =
<Code>
class $$C
{
event System.EventHandler E
{
add { }
remove { }
}
}
</Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestRemoveChild(code, expected, "E")
End Sub
#End Region
#Region "Set Access tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess1()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
public class C
{
}
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess2()
Dim code =
<Code>
public class $$C
{
}
</Code>
Dim expected =
<Code>
internal class C
{
}
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProject)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess3()
Dim code =
<Code>
protected internal class $$C
{
}
</Code>
Dim expected =
<Code>
public class C
{
}
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess4()
Dim code =
<Code>
public class $$C
{
}
</Code>
Dim expected =
<Code>
public class C
{
}
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected, ThrowsArgumentException(Of EnvDTE.vsCMAccess)())
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess5()
Dim code =
<Code>
public class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess6()
Dim code =
<Code>
public class $$C
{
}
</Code>
Dim expected =
<Code>
public class C
{
}
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)())
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess7()
Dim code =
<Code>
class C
{
class $$D
{
}
}
</Code>
Dim expected =
<Code>
class C
{
private class D
{
}
}
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate)
End Sub
#End Region
#Region "Set ClassKind tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetClassKind1()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetClassKind2()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
partial class C
{
}
</Code>
TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetClassKind3()
Dim code =
<Code>
partial class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass)
End Sub
#End Region
#Region "Set Comment tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetComment1()
Dim code =
<Code>
// Foo
// Bar
class $$C { }
</Code>
Dim expected =
<Code>
class C { }
</Code>
TestSetComment(code, expected, Nothing)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetComment2()
Dim code =
<Code>
// Foo
/// <summary>Bar</summary>
class $$C { }
</Code>
Dim expected =
<Code>
// Foo
/// <summary>Bar</summary>
// Bar
class C { }
</Code>
TestSetComment(code, expected, "Bar")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetComment3()
Dim code =
<Code>
// Foo
// Bar
class $$C { }
</Code>
Dim expected =
<Code>
// Blah
class C { }
</Code>
TestSetComment(code, expected, "Blah")
End Sub
#End Region
#Region "Set DocComment tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetDocComment_Nothing()
Dim code =
<Code>
class $$C { }
</Code>
Dim expected =
<Code>
class C { }
</Code>
TestSetDocComment(code, expected, Nothing, ThrowsArgumentException(Of String))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetDocComment_InvalidXml1()
Dim code =
<Code>
class $$C { }
</Code>
Dim expected =
<Code>
class C { }
</Code>
TestSetDocComment(code, expected, "<doc><summary>Blah</doc>", ThrowsArgumentException(Of String))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetDocComment_InvalidXml2()
Dim code =
<Code>
class $$C { }
</Code>
Dim expected =
<Code>
class C { }
</Code>
TestSetDocComment(code, expected, "<doc___><summary>Blah</summary></doc___>", ThrowsArgumentException(Of String))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetDocComment1()
Dim code =
<Code>
class $$C { }
</Code>
Dim expected =
<Code>
/// <summary>Hello World</summary>
class C { }
</Code>
TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetDocComment2()
Dim code =
<Code>
/// <summary>Hello World</summary>
class $$C { }
</Code>
Dim expected =
<Code>
/// <summary>Blah</summary>
class C { }
</Code>
TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetDocComment3()
Dim code =
<Code>
// Foo
class $$C { }
</Code>
Dim expected =
<Code>
// Foo
/// <summary>Blah</summary>
class C { }
</Code>
TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetDocComment4()
Dim code =
<Code>
/// <summary>FogBar</summary>
// Foo
class $$C { }
</Code>
Dim expected =
<Code>
/// <summary>Blah</summary>
// Foo
class C { }
</Code>
TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetDocComment5()
Dim code =
<Code>
namespace N
{
class $$C { }
}
</Code>
Dim expected =
<Code>
namespace N
{
/// <summary>Hello World</summary>
class C { }
}
</Code>
TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>")
End Sub
#End Region
#Region "Set InheritanceKind tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInheritanceKind1()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
abstract class C
{
}
</Code>
TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInheritanceKind2()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
sealed class C
{
}
</Code>
TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInheritanceKind3()
Dim code =
<Code>
class C
{
class $$D
{
}
}
</Code>
Dim expected =
<Code>
class C
{
abstract class D
{
}
}
</Code>
TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInheritanceKind4()
Dim code =
<Code>
class C
{
class $$D
{
}
}
</Code>
Dim expected =
<Code>
class C
{
new sealed class D
{
}
}
</Code>
TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew)
End Sub
#End Region
#Region "Set IsAbstract tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsAbstract1()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
abstract class C
{
}
</Code>
TestSetIsAbstract(code, expected, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsAbstract2()
Dim code =
<Code>
abstract class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestSetIsAbstract(code, expected, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsAbstract3()
Dim code =
<Code>
class C
{
new class $$D
{
}
}
</Code>
Dim expected =
<Code>
class C
{
abstract new class D
{
}
}
</Code>
TestSetIsAbstract(code, expected, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsAbstract4()
Dim code =
<Code>
class C
{
abstract new class $$D
{
}
}
</Code>
Dim expected =
<Code>
class C
{
new class D
{
}
}
</Code>
TestSetIsAbstract(code, expected, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsAbstract5()
' Note: In Dev11 the C# Code Model will happily include an abstract modifier
' on a sealed class. This differs from VB Code Model where the NotInheritable
' modifier will be removed when adding MustInherit. In Roslyn, we take the Dev11
' VB behavior for both C# and VB since it produces more correct code.
Dim code =
<Code>
sealed class $$C
{
}
</Code>
Dim expected =
<Code>
abstract class C
{
}
</Code>
TestSetIsAbstract(code, expected, True)
End Sub
#End Region
#Region "Set IsShared tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsShared1()
Dim code =
<Code>
class $$C
{
}
</Code>
Dim expected =
<Code>
static class C
{
}
</Code>
TestSetIsShared(code, expected, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsShared2()
Dim code =
<Code>
static class $$C
{
}
</Code>
Dim expected =
<Code>
class C
{
}
</Code>
TestSetIsShared(code, expected, False)
End Sub
#End Region
#Region "Set Name tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub SetName1()
Dim code =
<Code>
class $$Foo
{
}
</Code>
Dim expected =
<Code>
class Bar
{
}
</Code>
TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub SetName2()
Dim code =
<Code>
class $$Foo
{
Foo()
{
}
}
</Code>
Dim expected =
<Code>
class Bar
{
Bar()
{
}
}
</Code>
TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub SetName3()
Dim code =
<Code>
partial class $$Foo
{
}
partial class Foo
{
}
</Code>
Dim expected =
<Code>
partial class Bar
{
}
partial class Foo
{
}
</Code>
TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Sub
#End Region
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub ExternalClass_ImplementedInterfaces()
Dim code =
<Code>
class $$Foo : System.Collections.Generic.List<int>
{
}
</Code>
TestElement(code,
Sub(codeClass)
Dim listType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2)
Assert.NotNull(listType)
Assert.Equal(8, listType.ImplementedInterfaces.Count)
End Sub)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub ExternalFunction_Overloads()
Dim code =
<Code>
class $$Derived : System.Console
{
}
</Code>
TestElement(
code,
Sub(codeClass)
Dim baseType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2)
Assert.NotNull(baseType)
Dim method1 = TryCast(baseType.Members.Item("WriteLine"), EnvDTE80.CodeFunction2)
Assert.NotNull(method1)
Assert.Equal(True, method1.IsOverloaded)
Assert.Equal(19, method1.Overloads.Count)
End Sub)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub ExternalFunction_Overloads_NotOverloaded()
Dim code =
<Code>
class $$Derived : System.Console
{
}
</Code>
TestElement(
code,
Sub(codeClass)
Dim baseType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2)
Assert.NotNull(baseType)
Dim method2 = TryCast(baseType.Members.Item("Clear"), EnvDTE80.CodeFunction2)
Assert.NotNull(method2)
Assert.Equal(1, method2.Overloads.Count)
Assert.Equal("System.Console.Clear", TryCast(method2.Overloads.Item(1), EnvDTE80.CodeFunction2).FullName)
End Sub)
End Sub
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.CSharp
End Get
End Property
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/VisualStudio/Core/Test/CodeModel/CSharp/CodeClassTests.vb
|
Visual Basic
|
apache-2.0
| 96,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.Collections.Immutable
Imports System.Reflection
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend MustInherit Class PEAssemblyBuilderBase
Inherits PEModuleBuilder
Implements Cci.IAssembly
Protected ReadOnly m_SourceAssembly As SourceAssemblySymbol
Private ReadOnly _additionalTypes As ImmutableArray(Of NamedTypeSymbol)
Private _lazyFiles As ImmutableArray(Of Cci.IFileReference)
''' <summary>
''' This value will override m_SourceModule.MetadataName.
''' </summary>
''' <remarks>
''' This functionality exists for parity with C#, which requires it for
''' legacy reasons (see Microsoft.CodeAnalysis.CSharp.Emit.PEAssemblyBuilderBase.metadataName).
''' </remarks>
Private ReadOnly _metadataName As String
Public Sub New(sourceAssembly As SourceAssemblySymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
assemblySymbolMapper As Func(Of AssemblySymbol, AssemblyIdentity),
additionalTypes As ImmutableArray(Of NamedTypeSymbol))
MyBase.New(DirectCast(sourceAssembly.Modules(0), SourceModuleSymbol),
emitOptions,
outputKind,
serializationProperties,
manifestResources,
assemblySymbolMapper)
Debug.Assert(sourceAssembly IsNot Nothing)
Debug.Assert(manifestResources IsNot Nothing)
Me.m_SourceAssembly = sourceAssembly
Me._additionalTypes = additionalTypes.NullToEmpty()
Me._metadataName = If(emitOptions.OutputNameOverride Is Nothing, sourceAssembly.MetadataName, FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension:=Nothing))
m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, Me)
End Sub
Public Overrides Sub Dispatch(visitor As Cci.MetadataVisitor)
visitor.Visit(DirectCast(Me, Cci.IAssembly))
End Sub
Friend Overrides Function GetAdditionalTopLevelTypes() As ImmutableArray(Of NamedTypeSymbol)
Return Me._additionalTypes
End Function
Private Function IAssemblyGetFiles(context As EmitContext) As IEnumerable(Of Cci.IFileReference) Implements Cci.IAssembly.GetFiles
If _lazyFiles.IsDefault Then
Dim builder = ArrayBuilder(Of Cci.IFileReference).GetInstance()
Try
Dim modules = m_SourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1
builder.Add(DirectCast(Translate(modules(i), context.Diagnostics), Cci.IFileReference))
Next
For Each resource In ManifestResources
If Not resource.IsEmbedded Then
builder.Add(resource)
End If
Next
' Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed.
If ImmutableInterlocked.InterlockedInitialize(_lazyFiles, builder.ToImmutable()) AndAlso _lazyFiles.Length > 0 Then
If Not CryptographicHashProvider.IsSupportedAlgorithm(m_SourceAssembly.AssemblyHashAlgorithm) Then
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_CryptoHashFailed), NoLocation.Singleton))
End If
End If
Finally
' Clean up so we don't get a leak report from the unit tests.
builder.Free()
End Try
End If
Return _lazyFiles
End Function
Private Shared Function Free(builder As ArrayBuilder(Of Cci.IFileReference)) As Boolean
builder.Free()
Return False
End Function
Private ReadOnly Property IAssemblyFlags As UInteger Implements Cci.IAssembly.Flags
Get
Dim result As System.Reflection.AssemblyNameFlags = m_SourceAssembly.Flags And Not System.Reflection.AssemblyNameFlags.PublicKey
If Not m_SourceAssembly.PublicKey.IsDefaultOrEmpty Then
result = result Or System.Reflection.AssemblyNameFlags.PublicKey
End If
Return CUInt(result)
End Get
End Property
Private ReadOnly Property IAssemblySignatureKey As String Implements Cci.IAssembly.SignatureKey
Get
Return m_SourceAssembly.AssemblySignatureKeyAttributeSetting
End Get
End Property
Private ReadOnly Property IAssemblyPublicKey As ImmutableArray(Of Byte) Implements Cci.IAssembly.PublicKey
Get
Return m_SourceAssembly.Identity.PublicKey
End Get
End Property
Protected Overrides Sub AddEmbeddedResourcesFromAddedModules(builder As ArrayBuilder(Of Cci.ManagedResource), diagnostics As DiagnosticBag)
Dim modules = m_SourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1
Dim file = DirectCast(Translate(modules(i), diagnostics), Cci.IFileReference)
Try
For Each resource In DirectCast(modules(i), Symbols.Metadata.PE.PEModuleSymbol).Module.GetEmbeddedResourcesOrThrow()
builder.Add(New Cci.ManagedResource(
resource.Name,
(resource.Attributes And ManifestResourceAttributes.Public) <> 0,
Nothing,
file,
resource.Offset))
Next
Catch mrEx As BadImageFormatException
diagnostics.Add(ERRID.ERR_UnsupportedModule1, NoLocation.Singleton, modules(i))
End Try
Next
End Sub
Private ReadOnly Property IAssemblyReferenceCulture As String Implements Cci.IAssemblyReference.Culture
Get
Return m_SourceAssembly.Identity.CultureName
End Get
End Property
Private ReadOnly Property IAssemblyReferenceIsRetargetable As Boolean Implements Cci.IAssemblyReference.IsRetargetable
Get
Return m_SourceAssembly.Identity.IsRetargetable
End Get
End Property
Private ReadOnly Property IAssemblyReferenceContentType As AssemblyContentType Implements Cci.IAssemblyReference.ContentType
Get
Return m_SourceAssembly.Identity.ContentType
End Get
End Property
Private ReadOnly Property IAssemblyReferencePublicKeyToken As ImmutableArray(Of Byte) Implements Cci.IAssemblyReference.PublicKeyToken
Get
Return m_SourceAssembly.Identity.PublicKeyToken
End Get
End Property
Private ReadOnly Property IAssemblyReferenceVersion As Version Implements Cci.IAssemblyReference.Version
Get
Return m_SourceAssembly.Identity.Version
End Get
End Property
Private Function IAssemblyReferenceGetDisplayName() As String Implements Cci.IAssemblyReference.GetDisplayName
Return m_SourceAssembly.Identity.GetDisplayName()
End Function
Friend Overrides ReadOnly Property Name As String
Get
Return _metadataName
End Get
End Property
Private ReadOnly Property IAssemblyHashAlgorithm As AssemblyHashAlgorithm Implements Cci.IAssembly.HashAlgorithm
Get
Return m_SourceAssembly.AssemblyHashAlgorithm
End Get
End Property
End Class
Friend NotInheritable Class PEAssemblyBuilder
Inherits PEAssemblyBuilderBase
Public Sub New(sourceAssembly As SourceAssemblySymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
Optional assemblySymbolMapper As Func(Of AssemblySymbol, AssemblyIdentity) = Nothing,
Optional additionalTypes As ImmutableArray(Of NamedTypeSymbol) = Nothing)
MyBase.New(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, assemblySymbolMapper, additionalTypes)
End Sub
Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property CurrentGenerationOrdinal As Integer
Get
Return 0
End Get
End Property
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/PEAssemblyBuilder.vb
|
Visual Basic
|
apache-2.0
| 9,464
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SymbolId
Public Class SymbolKeyTestBase
Inherits BasicTestBase
<Flags>
Friend Enum SymbolIdComparison
None = 0
CaseSensitive = 1
CaseInsensitive = 2
IgnoreAssemblyIds = 4
End Enum
<Flags>
Friend Enum SymbolCategory
All = 0
DeclaredNamespace = 1
DeclaredType = 2
NonTypeMember = 4
Parameter = 16
Local = 32
End Enum
#Region "Verification"
Friend Shared Sub ResolveAndVerifySymbolList(newSymbols As IEnumerable(Of ISymbol), newCompilation As Compilation, originalSymbols As IEnumerable(Of ISymbol), originalCompilation As Compilation)
Dim newlist = newSymbols.OrderBy(Function(s) s.Name).ToList()
Dim origlist = originalSymbols.OrderBy(Function(s) s.Name).ToList()
Assert.Equal(origlist.Count, newlist.Count)
For i = 0 To newlist.Count - 1
ResolveAndVerifySymbol(newlist(i), newCompilation, origlist(i), originalCompilation)
Next
End Sub
Friend Shared Sub ResolveAndVerifyTypeSymbol(node As ExpressionSyntax, sourceSymbol As ITypeSymbol, model As SemanticModel, sourceComp As Compilation)
Dim typeinfo = model.GetTypeInfo(node)
ResolveAndVerifySymbol(If(typeinfo.Type, typeinfo.ConvertedType), model.Compilation, sourceSymbol, sourceComp)
End Sub
Friend Shared Sub ResolveAndVerifySymbol(node As ExpressionSyntax, sourceSymbol As ISymbol, model As SemanticModel, sourceComp As Compilation, Optional comparison As SymbolIdComparison = SymbolIdComparison.None)
Dim syminfo = model.GetSymbolInfo(node)
Dim symbol = syminfo.Symbol
If symbol Is Nothing Then
symbol = syminfo.CandidateSymbols.Single()
End If
ResolveAndVerifySymbol(symbol, model.Compilation, sourceSymbol, sourceComp, comparison)
End Sub
Friend Shared Sub ResolveAndVerifySymbol(symbol1 As ISymbol, compilation1 As Compilation, symbol2 As ISymbol, compilation2 As Compilation, Optional comparison As SymbolIdComparison = SymbolIdComparison.None)
AssertSymbolsIdsEqual(symbol1, compilation1, symbol2, compilation2, comparison)
Dim resolvedSymbol = ResolveSymbol(symbol1, compilation1, compilation2, comparison)
Assert.NotNull(resolvedSymbol)
Assert.Equal(symbol2, resolvedSymbol)
Assert.Equal(symbol2.GetHashCode(), resolvedSymbol.GetHashCode())
End Sub
Friend Shared Function ResolveSymbol(originalSymbol As ISymbol, originalCompilation As Compilation, targetCompilation As Compilation, comparision As SymbolIdComparison) As ISymbol
Dim sid = SymbolKey.Create(originalSymbol, originalCompilation, CancellationToken.None)
Dim symInfo = sid.Resolve(targetCompilation, (comparision And SymbolIdComparison.IgnoreAssemblyIds) = SymbolIdComparison.IgnoreAssemblyIds)
Return symInfo.Symbol
End Function
Friend Shared Sub AssertSymbolsIdsEqual(symbol1 As ISymbol, compilation1 As Compilation, symbol2 As ISymbol, compilation2 As Compilation, comparision As SymbolIdComparison, Optional expectEqual As Boolean = True)
Dim sid1 = SymbolKey.Create(symbol1, compilation1, CancellationToken.None)
Dim sid2 = SymbolKey.Create(symbol2, compilation2, CancellationToken.None)
Dim isCaseSensitive = (comparision And SymbolIdComparison.CaseSensitive) = SymbolIdComparison.CaseSensitive
Dim ignoreAssemblyIds = (comparision And SymbolIdComparison.IgnoreAssemblyIds) = SymbolIdComparison.IgnoreAssemblyIds
Dim message = String.Concat(
If(isCaseSensitive, "SymbolID CaseSensitive", "SymbolID CaseInsensitive"),
If(ignoreAssemblyIds, " IgnoreAssemblyIds ", " "),
"Compare")
If expectEqual Then
Assert.[True](CodeAnalysis.SymbolKey.GetComparer(isCaseSensitive, ignoreAssemblyIds).Equals(sid2, sid1), message)
Else
Assert.[False](CodeAnalysis.SymbolKey.GetComparer(isCaseSensitive, ignoreAssemblyIds).Equals(sid2, sid1), message)
End If
End Sub
#End Region
#Region "Utilities"
Friend Shared Function GetBindNodes(Of T As VisualBasicSyntaxNode)(comp As VisualBasicCompilation, fileName As String, count As Integer) As IList(Of T)
Dim list = New List(Of T)()
' 1 based - BIND#:
For i = 1 To count
Try
Dim node = CompilationUtils.FindBindingText(Of T)(comp, fileName, i)
list.Add(node)
Catch ex As Exception
Exit For
End Try
Next
Return list
End Function
Friend Shared Function GetSourceSymbols(comp As VisualBasicCompilation, category As SymbolCategory) As IEnumerable(Of ISymbol)
Dim list = GetSourceSymbols(comp, includeLocals:=(category And SymbolCategory.Local) <> 0)
Dim kinds = New List(Of SymbolKind)()
If (category And SymbolCategory.DeclaredNamespace) <> 0 Then
kinds.Add(SymbolKind.Namespace)
End If
If (category And SymbolCategory.DeclaredType) <> 0 Then
kinds.Add(SymbolKind.NamedType)
kinds.Add(SymbolKind.TypeParameter)
End If
If (category And SymbolCategory.NonTypeMember) <> 0 Then
kinds.Add(SymbolKind.Field)
kinds.Add(SymbolKind.Event)
kinds.Add(SymbolKind.Property)
kinds.Add(SymbolKind.Method)
End If
If (category And SymbolCategory.Parameter) <> 0 Then
kinds.Add(SymbolKind.Parameter)
End If
If (category And SymbolCategory.Local) <> 0 Then
kinds.Add(SymbolKind.Local)
kinds.Add(SymbolKind.Label)
kinds.Add(SymbolKind.RangeVariable)
' TODO: anonymous type & func
End If
Return list.Where(Function(s)
If s.IsImplicitlyDeclared Then
Return False
End If
For Each k In kinds
If s.Kind = k Then
Return True
End If
Next
Return False
End Function)
End Function
Friend Shared Function GetSourceSymbols(compilation As VisualBasicCompilation, includeLocals As Boolean) As IList(Of ISymbol)
Dim list = New List(Of ISymbol)()
Dim localDumper As LocalSymbolDumper = If(includeLocals, New LocalSymbolDumper(compilation), Nothing)
GetSourceMemberSymbols(compilation.SourceModule.GlobalNamespace, list, localDumper)
GetSourceAliasSymbols(compilation, list)
list.Add(compilation.Assembly)
list.AddRange(compilation.Assembly.Modules)
Return list
End Function
Private Shared Sub GetSourceAliasSymbols(comp As VisualBasicCompilation, list As List(Of ISymbol))
For Each tree In comp.SyntaxTrees
Dim aliases = tree.GetRoot().DescendantNodes().OfType(Of ImportAliasClauseSyntax)()
Dim model = comp.GetSemanticModel(tree)
For Each a In aliases
Dim sym = model.GetDeclaredSymbol(a)
If sym IsNot Nothing AndAlso Not list.Contains(sym) Then
list.Add(sym)
End If
Next
Next
End Sub
Private Shared Sub GetSourceMemberSymbols(symbol As INamespaceOrTypeSymbol, list As List(Of ISymbol), localDumper As LocalSymbolDumper)
For Each member In symbol.GetMembers()
list.Add(member)
Select Case member.Kind
Case SymbolKind.NamedType, SymbolKind.Namespace
GetSourceMemberSymbols(DirectCast(member, INamespaceOrTypeSymbol), list, localDumper)
Case SymbolKind.Method
Dim method = DirectCast(member, IMethodSymbol)
For Each parameter In method.Parameters
list.Add(parameter)
Next
If localDumper IsNot Nothing Then
localDumper.GetLocalSymbols(method, list)
End If
Case SymbolKind.Field
If localDumper IsNot Nothing Then
localDumper.GetLocalSymbols(DirectCast(member, IFieldSymbol), list)
End If
End Select
Next
End Sub
#End Region
End Class
Friend Class LocalSymbolDumper
Private _comp As VisualBasicCompilation
Public Sub New(comp As VisualBasicCompilation)
Me._comp = comp
End Sub
Public Sub GetLocalSymbols(symbol As IFieldSymbol, list As List(Of ISymbol))
For Each node In symbol.DeclaringSyntaxReferences.Select(Function(d) d.GetSyntax())
Dim declarator = TryCast(node.Parent, VariableDeclaratorSyntax)
If declarator IsNot Nothing AndAlso declarator.Initializer IsNot Nothing Then
Dim model = _comp.GetSemanticModel(declarator.SyntaxTree)
Dim df = model.AnalyzeDataFlow(declarator.Initializer.Value)
GetLocalAndType(df, list)
GetAnonymousExprSymbols(declarator.Initializer.Value, model, list)
End If
Next
End Sub
Public Sub GetLocalSymbols(symbol As IMethodSymbol, list As List(Of ISymbol))
' Delaration statement is child of Block
For Each n In symbol.DeclaringSyntaxReferences.Select(Function(d) d.GetSyntax())
Dim body = TryCast(n.Parent, MethodBlockSyntax)
' interface method
If body IsNot Nothing Then
If body.Statements <> Nothing AndAlso body.Statements.Count > 0 Then
Dim model = _comp.GetSemanticModel(body.SyntaxTree)
Dim df As DataFlowAnalysis = Nothing
If body.Statements.Count = 1 Then
df = model.AnalyzeDataFlow(body.Statements.First)
Else
df = model.AnalyzeDataFlow(body.Statements.First, body.Statements.Last)
End If
GetLocalAndType(df, list)
GetLabelSymbols(body, model, list)
GetAnonymousTypeAndFuncSymbols(body, model, list)
End If
End If
Next
End Sub
Private Sub GetLocalAndType(df As DataFlowAnalysis, list As List(Of ISymbol))
' add local symbols to list
For Each v As ISymbol In df.VariablesDeclared
list.Add(v)
Dim local = TryCast(v, ILocalSymbol)
If local IsNot Nothing AndAlso local.Type.Kind = SymbolKind.ArrayType Then
list.Add(local.Type)
End If
Next
End Sub
Private Sub GetLabelSymbols(body As MethodBlockSyntax, model As SemanticModel, list As List(Of ISymbol))
Dim labels = body.DescendantNodes().OfType(Of LabelStatementSyntax)()
For Each lb As LabelStatementSyntax In labels
Dim sym = model.GetDeclaredSymbol(lb)
list.Add(sym)
Next
' VB has not SwitchLabel; it's CaseStatement
End Sub
Private Sub GetAnonymousTypeAndFuncSymbols(body As MethodBlockSyntax, model As SemanticModel, list As List(Of ISymbol))
Dim exprs As IEnumerable(Of ExpressionSyntax), tmp As IEnumerable(Of ExpressionSyntax)
exprs = body.DescendantNodes().OfType(Of AnonymousObjectCreationExpressionSyntax)()
tmp = body.DescendantNodes().OfType(Of SingleLineLambdaExpressionSyntax)()
exprs = exprs.Concat(tmp)
tmp = body.DescendantNodes().OfType(Of MultiLineLambdaExpressionSyntax)()
exprs = exprs.Concat(tmp)
For Each expr As ExpressionSyntax In exprs
GetAnonymousExprSymbols(expr, model, list)
Next
End Sub
Private Sub GetAnonymousExprSymbols(expr As ExpressionSyntax, model As SemanticModel, list As List(Of ISymbol))
Dim kind = expr.Kind
If kind <> SyntaxKind.AnonymousObjectCreationExpression AndAlso
kind <> SyntaxKind.SingleLineSubLambdaExpression AndAlso
kind <> SyntaxKind.SingleLineFunctionLambdaExpression AndAlso
kind <> SyntaxKind.MultiLineSubLambdaExpression AndAlso
kind <> SyntaxKind.MultiLineFunctionLambdaExpression Then
Return
End If
Dim tinfo = model.GetTypeInfo(expr)
Dim tconv = model.GetConversion(expr)
' lambda has NO type
' Bug#13362 - Lambda
If tconv.IsAnonymousDelegate OrElse tconv.IsLambda Then
Dim sinfo = model.GetSymbolInfo(expr)
' SymbolInfo should NOT be null
list.Add(sinfo.Symbol)
' Error case might be Nothing
ElseIf tinfo.Type IsNot Nothing Then
list.Add(tinfo.Type)
For Each m In tinfo.Type.GetMembers
list.Add(m)
Next
End If
End Sub
End Class
End Namespace
|
paladique/roslyn
|
src/EditorFeatures/VisualBasicTest/SymbolId/SymbolKeyTestBase.vb
|
Visual Basic
|
apache-2.0
| 14,442
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
'-----------------------------------------------------------------------------
' Contains the definition of the Scanner, which produces tokens from text
'-----------------------------------------------------------------------------
Option Compare Binary
Option Strict On
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Scanner
Private Function ScanXmlTrivia(c As Char) As SyntaxList(Of VisualBasicSyntaxNode)
Debug.Assert(Not IsScanningXmlDoc)
Debug.Assert(c = CARRIAGE_RETURN OrElse c = LINE_FEED OrElse c = " "c OrElse c = CHARACTER_TABULATION)
Dim builder = _triviaListPool.Allocate
Dim len = 0
Do
If c = " "c OrElse c = CHARACTER_TABULATION Then
len += 1
ElseIf c = CARRIAGE_RETURN OrElse c = LINE_FEED Then
If len > 0 Then
builder.Add(MakeWhiteSpaceTrivia(GetText(len)))
len = 0
End If
builder.Add(ScanNewlineAsTrivia(c))
Else
Exit Do
End If
If Not CanGet(len) Then
Exit Do
End If
c = Peek(len)
Loop
If len > 0 Then
builder.Add(MakeWhiteSpaceTrivia(GetText(len)))
len = 0
End If
Debug.Assert(builder.Count > 0)
Dim result = builder.ToList
_triviaListPool.Free(builder)
Return result
End Function
Friend Function ScanXmlElement(Optional state As ScannerState = ScannerState.Element) As SyntaxToken
Debug.Assert(state = ScannerState.Element OrElse state = ScannerState.EndElement OrElse state = ScannerState.DocType)
' SHIM
If IsScanningXmlDoc Then
Return ScanXmlElementInXmlDoc(state)
End If
' // Only legal tokens
' // QName
' // /
' // >
' // =
' // Whitespace
Dim leadingTrivia As SyntaxList(Of VisualBasicSyntaxNode) = Nothing
While CanGet()
Dim c As Char = Peek()
Select Case (c)
' // Whitespace
' // S ::= (#x20 | #x9 | #xD | #xA)+
Case CARRIAGE_RETURN, LINE_FEED
' we should not visit this place twice
Debug.Assert(leadingTrivia.Node Is Nothing)
Dim offsets = CreateOffsetRestorePoint()
leadingTrivia = ScanXmlTrivia(c)
If ScanXmlForPossibleStatement(state) Then
offsets.Restore()
Return SyntaxFactory.Token(Nothing, SyntaxKind.EndOfXmlToken, Nothing, String.Empty)
End If
Case " "c, CHARACTER_TABULATION
' we should not visit this place twice
Debug.Assert(leadingTrivia.Node Is Nothing)
leadingTrivia = ScanXmlTrivia(c)
Case "/"c
If CanGet(1) AndAlso Peek(1) = ">" Then
Return XmlMakeEndEmptyElementToken(leadingTrivia)
End If
Return XmlMakeDivToken(leadingTrivia)
Case ">"c
' TODO: this will not consume trailing trivia
' consider cases where this is the last element in the literal.
Return XmlMakeGreaterToken(leadingTrivia)
Case "="c
Return XmlMakeEqualsToken(leadingTrivia)
Case "'"c, LEFT_SINGLE_QUOTATION_MARK, RIGHT_SINGLE_QUOTATION_MARK
Return XmlMakeSingleQuoteToken(leadingTrivia, c, isOpening:=True)
Case """"c, LEFT_DOUBLE_QUOTATION_MARK, RIGHT_DOUBLE_QUOTATION_MARK
Return XmlMakeDoubleQuoteToken(leadingTrivia, c, isOpening:=True)
Case "<"c
If CanGet(1) Then
Dim ch As Char = Peek(1)
Select Case ch
Case "!"c
If CanGet(2) Then
Select Case (Peek(2))
Case "-"c
If NextIs(3, "-"c) Then
Return XmlMakeBeginCommentToken(leadingTrivia, s_scanNoTriviaFunc)
End If
Case "["c
If NextAre(3, "CDATA[") Then
Return XmlMakeBeginCDataToken(leadingTrivia, s_scanNoTriviaFunc)
End If
Case "D"c
If Nextare(3, "OCTYPE") Then
Return XmlMakeBeginDTDToken(leadingTrivia)
End If
End Select
End If
Return XmlLessThanExclamationToken(state, leadingTrivia)
Case "%"c
If NextIs(2, "="c) Then
Return XmlMakeBeginEmbeddedToken(leadingTrivia)
End If
Case "?"c
Return XmlMakeBeginProcessingInstructionToken(leadingTrivia, s_scanNoTriviaFunc)
Case "/"c
Return XmlMakeBeginEndElementToken(leadingTrivia, s_scanNoTriviaFunc)
End Select
End If
Return XmlMakeLessToken(leadingTrivia)
Case "?"c
If NextIs(1, ">"c) Then
' // Create token for the '?>' termination sequence
Return XmlMakeEndProcessingInstructionToken(leadingTrivia)
End If
Return XmlMakeBadToken(leadingTrivia, 1, ERRID.ERR_IllegalXmlNameChar)
Case "("c
Return XmlMakeLeftParenToken(leadingTrivia)
Case ")"c
Return XmlMakeRightParenToken(leadingTrivia)
Case "!"c, ";"c, "#"c, ","c, "}"c
Return XmlMakeBadToken(leadingTrivia, 1, ERRID.ERR_IllegalXmlNameChar)
Case ":"c
Return XmlMakeColonToken(leadingTrivia)
Case "["c
Return XmlMakeOpenBracketToken(state, leadingTrivia)
Case "]"c
Return XmlMakeCloseBracketToken(state, leadingTrivia)
Case Else
' // Because of weak scanning of QName, this state must always handle
' // '=' | '\'' | '"'| '/' | '>' | '<' | '?'
Return ScanXmlNcName(leadingTrivia)
End Select
End While
Return MakeEofToken(leadingTrivia)
End Function
'//
'// This is used to detect a VB statement on the next line
'//
'// NL WS* KW WS* ID | KW
'// Example Dim x
'//
'// For EndElement state only, </x followed by Sub
'// NL WS* KW | ID
'// Example Sub
'//
'// NL WS* ID WS* (
'// Example Console.WriteLine (
'//
'// NL WS* < ID WS* (
'// Example <ClsCompliant(
'//
'// NL WS* # WS* KW
'// Example #END
'//
'// NL WS* '
'// Example ' This is a comment
Private Function ScanXmlForPossibleStatement(state As ScannerState) As Boolean
If Not CanGet() Then
Return False
End If
Dim token As SyntaxToken
Dim possibleStatement As Boolean = False
Dim offsets = CreateOffsetRestorePoint()
Dim c As Char = Peek()
Select Case c
Case "#"c,
FULLWIDTH_NUMBER_SIGN
' Check for preprocessor statement, i.e. # if
AdvanceChar(1)
token = ScanNextToken(allowLeadingMultilineTrivia:=False)
possibleStatement = token.IsKeyword
Case "<"c,
FULLWIDTH_LESS_THAN_SIGN
' Check for code attribute, i.e < clscompliant (
AdvanceChar(1)
Dim leadingTrivia = ScanSingleLineTrivia()
' Use ScanXmlNcName instead of ScanToken because it won't stop on "."
token = ScanXmlNcName(leadingTrivia)
Dim name As XmlNameTokenSyntax = TryCast(token, XmlNameTokenSyntax)
If name IsNot Nothing AndAlso Not name.IsMissing Then
If name.PossibleKeywordKind <> SyntaxKind.XmlNameToken Then
leadingTrivia = ScanSingleLineTrivia()
c = Peek()
possibleStatement =
c = "("c OrElse c = FULLWIDTH_LEFT_PARENTHESIS
End If
End If
Case Else
If IsSingleQuote(c) AndAlso LastToken.Kind <> SyntaxKind.EqualsToken Then
' Check for comment
possibleStatement = True
Else
' Check for statement or call
Dim leadingTrivia = ScanSingleLineTrivia()
' Use ScanXmlNcName instead of ScanToken because it won't stop on "."
token = ScanXmlNcName(leadingTrivia)
Dim name As XmlNameTokenSyntax = TryCast(token, XmlNameTokenSyntax)
If name IsNot Nothing AndAlso Not token.IsMissing Then
If state = ScannerState.EndElement Then
possibleStatement = token.Kind = SyntaxKind.XmlNameToken OrElse
LastToken.Kind = SyntaxKind.XmlNameToken
Exit Select
End If
' If there was leading trivia, it must be trivia recognized by VB but not XML.
Debug.Assert(Not leadingTrivia.Any() OrElse
(IsNewLine(c) AndAlso (c <> CARRIAGE_RETURN) AndAlso (c <> LINE_FEED)) OrElse
(IsWhitespace(c) AndAlso Not IsXmlWhitespace(c)))
token = ScanNextToken(allowLeadingMultilineTrivia:=False)
If name.PossibleKeywordKind = SyntaxKind.XmlNameToken Then
possibleStatement =
token.Kind = SyntaxKind.OpenParenToken
Else
possibleStatement =
(token.Kind = SyntaxKind.IdentifierToken) OrElse token.IsKeyword
End If
End If
End If
End Select
offsets.Restore()
Return possibleStatement
End Function
Friend Function ScanXmlContent() As SyntaxToken
' SHIM
If Me.IsScanningXmlDoc Then
Return ScanXmlContentInXmlDoc()
End If
' // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
Dim Here As Integer = 0
Dim IsAllWhitespace As Boolean = True
' lets do an unusual peek-behind to make sure we are not restarting after a non-Ws char.
If _lineBufferOffset > 0 Then
Dim prevChar = Peek(-1)
If prevChar <> ">"c AndAlso Not XmlCharType.IsWhiteSpace(prevChar) Then
IsAllWhitespace = False
End If
End If
Dim scratch = GetScratch()
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
Here = SkipLineBreak(c, Here)
scratch.Append(LINE_FEED)
Case " "c, CHARACTER_TABULATION
scratch.Append(c)
Here += 1
Case "&"c
If Here <> 0 Then
Return XmlMakeTextLiteralToken(Nothing, Here, scratch)
End If
' TODO: the entity could be whitespace, do we want to report it as WS?
Return ScanXmlReference(Nothing)
Case "<"c
Dim precedingTrivia As SyntaxList(Of VisualBasicSyntaxNode) = Nothing
If Here <> 0 Then
If Not IsAllWhitespace Then
Return XmlMakeTextLiteralToken(Nothing, Here, scratch)
Else
scratch.Clear() ' will not use this
Here = 0 ' consumed chars.
precedingTrivia = ScanXmlTrivia(Peek)
End If
End If
Debug.Assert(Here = 0)
If CanGet(1) Then
Dim ch As Char = Peek(1)
Select Case ch
Case "!"c
If CanGet(2) Then
Select Case (Peek(2))
Case "-"c
If NextIs(3, "-"c) Then
Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "["c
If NextAre(3, "CDATA[") Then
Return XmlMakeBeginCDataToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "D"c
If NextAre(3, "OCTYPE") Then
Return XmlMakeBeginDTDToken(precedingTrivia)
End If
End Select
End If
Case "%"c
If NextIs(2, "="c) Then
Return XmlMakeBeginEmbeddedToken(precedingTrivia)
End If
Case "?"c
Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc)
Case "/"c
Return XmlMakeBeginEndElementToken(precedingTrivia, s_scanNoTriviaFunc)
End Select
End If
Return XmlMakeLessToken(precedingTrivia)
Case "]"c
If NextAre(Here + 1, "]>") Then
' // If valid characters found then return them.
If Here <> 0 Then
Return XmlMakeTextLiteralToken(Nothing, Here, scratch)
End If
' // Create an invalid character data token for the illegal ']]>' sequence
Return XmlMakeTextLiteralToken(Nothing, 3, ERRID.ERR_XmlEndCDataNotAllowedInContent)
End If
GoTo ScanChars
Case "#"c
' // Even though # is valid in content, abort xml scanning if the m_State shows and error
' // and the line begins with NL WS* # WS* KW
'TODO: error recovery - how can we do this?
'If m_State.m_IsXmlError Then
' MakeXmlCharToken(tokens.tkXmlCharData, Here - m_InputStreamPosition, IsAllWhitespace)
' m_InputStreamPosition = Here
' Dim sharp As Token = MakeToken(tokens.tkSharp, 1)
' m_InputStreamPosition += 1
' While (m_InputStream(m_InputStreamPosition) = " "c OrElse m_InputStream(m_InputStreamPosition) = CHARACTER_TABULATION)
' m_InputStreamPosition += 1
' End While
' ScanXmlQName()
' Dim restart As Token = CheckXmlForStatement()
' If restart IsNot Nothing Then
' ' // Abort Xml - Found Keyword space at the beginning of the line
' AbandonTokens(restart)
' m_State.Init(LexicalState.VB)
' MakeToken(tokens.tkXmlAbort, 0)
' Return
' End If
' AbandonTokens(sharp)
' Here = m_InputStreamPosition
'End If
GoTo ScanChars
Case "%"c
'TODO: error recovery. We cannot do this.
'If there is all whitespace after ">", it will be scanned as insignificant,
'but in this case it is significant.
'Also as far as I can see Dev10 does not resync on "%>" text anyways.
'' // Even though %> is valid in pcdata. When inside of an embedded expression
'' // return this sequence separately so that the xml literal completion code can
'' // easily detect the end of an embedded expression that may be temporarily hidden
'' // by a new element. i.e. <%= <a> %>
'If CanGetCharAtOffset(Here + 1) AndAlso _
' PeekAheadChar(Here + 1) = ">"c Then
' ' // If valid characters found then return them.
' If Here <> 0 Then
' Return XmlMakeCharDataToken(Nothing, Here, New String(value.ToArray))
' End If
' ' // Create a special pcdata token for the possible tkEndXmlEmbedded
' Return XmlMakeCharDataToken(Nothing, 2, "%>")
'Else
' IsAllWhitespace = False
' value.Add("%"c)
' Here += 1
'End If
'Continue While
GoTo ScanChars
Case Else
ScanChars:
' // Check characters are valid
IsAllWhitespace = False
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length = 0 Then
' bad char
If Here > 0 Then
Return XmlMakeTextLiteralToken(Nothing, Here, scratch)
Else
Return XmlMakeBadToken(Nothing, 1, ERRID.ERR_IllegalChar)
End If
End If
xmlCh.AppendTo(scratch)
Here += xmlCh.Length
End Select
End While
' no more chars
If Here > 0 Then
Return XmlMakeTextLiteralToken(Nothing, Here, scratch)
Else
Return MakeEofToken()
End If
End Function
Friend Function ScanXmlComment() As SyntaxToken
' // [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
Dim precedingTrivia As SyntaxList(Of VisualBasicSyntaxNode) = Nothing
If IsScanningXmlDoc AndAlso IsAtNewLine() Then
Dim xDocTrivia = ScanXmlDocTrivia()
If xDocTrivia Is Nothing Then
Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
End If
precedingTrivia = xDocTrivia
End If
Dim Here = 0
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
Return XmlMakeCommentToken(precedingTrivia, Here + LengthOfLineBreak(c, Here))
Case "-"c
If NextIs(Here + 1, "-"c) Then
' // --> terminates an Xml comment but otherwise -- is an illegal character sequence.
' // The scanner will always returns "--" as a separate comment data string and the
' // the semantics will error if '--' is ever found.
' // Return valid characters up to the --
If Here > 0 Then
Return XmlMakeCommentToken(precedingTrivia, Here)
End If
If CanGet(Here + 2) Then
c = Peek(Here + 2)
Here += 2
' // if > is not found then this is an error. Return the -- string
If c <> ">"c Then
Return XmlMakeCommentToken(precedingTrivia, 2)
' TODO: we cannot do the following
' // For better error recovery, allow -> to terminate the comment.
' // This works because the -> terminates only when the invalid --
' // is returned.
'If Here + 1 < m_InputStreamEnd AndAlso _
' m_InputStream(Here) = "-"c AndAlso _
' m_InputStream(Here + 1) = ">"c Then
' Here += 1
'Else
' Continue While
'End If
Else
Return XmlMakeEndCommentToken(precedingTrivia)
End If
End If
End If
GoTo ScanChars
Case Else
ScanChars:
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length <> 0 Then
Here += xmlCh.Length
Continue While
End If
' bad char
If Here > 0 Then
Return XmlMakeCommentToken(precedingTrivia, Here)
Else
Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar)
End If
End Select
End While
' no more chars
If Here > 0 Then
Return XmlMakeCommentToken(precedingTrivia, Here)
Else
Return MakeEofToken(precedingTrivia)
End If
End Function
Friend Function ScanXmlCData() As SyntaxToken
' // [18] CDSect ::= CDStart CData CDEnd
' // [19] CDStart ::= '<![CDATA['
' // [20] CData ::= (Char* - (Char* ']]>' Char*))
' // [21] CDEnd ::= ']]>'
Dim precedingTrivia As SyntaxList(Of VisualBasicSyntaxNode) = Nothing
If IsScanningXmlDoc AndAlso IsAtNewLine() Then
Dim xDocTrivia = ScanXmlDocTrivia()
If xDocTrivia Is Nothing Then
Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
End If
precedingTrivia = xDocTrivia
End If
Dim scratch = GetScratch()
Dim Here = 0
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
Here = SkipLineBreak(c, Here)
scratch.Append(LINE_FEED)
Return XmlMakeCDataToken(precedingTrivia, Here, scratch)
Case "]"c
If NextAre(Here + 1, "]>") Then
'// If valid characters found then return them.
If Here <> 0 Then
Return XmlMakeCDataToken(precedingTrivia, Here, scratch)
End If
' // Create token for ']]>' sequence
Return XmlMakeEndCDataToken(precedingTrivia)
End If
GoTo ScanChars
Case Else
ScanChars:
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length = 0 Then
' bad char
If Here > 0 Then
Return XmlMakeCDataToken(precedingTrivia, Here, scratch)
Else
Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar)
End If
End If
xmlCh.AppendTo(scratch)
Here += xmlCh.Length
End Select
End While
' no more chars
If Here > 0 Then
Return XmlMakeCDataToken(precedingTrivia, Here, scratch)
Else
Return MakeEofToken(precedingTrivia)
End If
End Function
Friend Function ScanXmlPIData(state As ScannerState) As SyntaxToken
' SHIM
If IsScanningXmlDoc Then
Return ScanXmlPIDataInXmlDoc(state)
End If
' // Scan the PI data after the white space
' // [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
' // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
Debug.Assert(state = ScannerState.StartProcessingInstruction OrElse
state = ScannerState.ProcessingInstruction)
Dim precedingTrivia = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)()
Dim result As SyntaxToken
If state = ScannerState.StartProcessingInstruction AndAlso CanGet() Then
' // Whitespace
' // S ::= (#x20 | #x9 | #xD | #xA)+
Dim c = Peek()
Select Case c
Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION
Dim wsTrivia = ScanXmlTrivia(c)
precedingTrivia.AddRange(wsTrivia)
End Select
End If
Dim Here = 0
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here + LengthOfLineBreak(c, Here))
GoTo CleanUp
Case "?"c
If NextIs(Here + 1, ">"c) Then
'// If valid characters found then return them.
If Here <> 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
GoTo CleanUp
End If
' // Create token for the '?>' termination sequence
result = XmlMakeEndProcessingInstructionToken(precedingTrivia.ToList)
GoTo CleanUp
End If
GoTo ScanChars
Case Else
ScanChars:
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length > 0 Then
Here += xmlCh.Length
Continue While
End If
' bad char
If Here <> 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
GoTo CleanUp
Else
result = XmlMakeBadToken(precedingTrivia.ToList, 1, ERRID.ERR_IllegalChar)
GoTo CleanUp
End If
End Select
End While
' no more chars
If Here > 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
Else
result = MakeEofToken(precedingTrivia.ToList)
End If
CleanUp:
_triviaListPool.Free(precedingTrivia)
Return result
End Function
Friend Function ScanXmlMisc() As SyntaxToken
Debug.Assert(Not IsScanningXmlDoc)
' // Misc ::= Comment | PI | S
Dim precedingTrivia As SyntaxList(Of VisualBasicSyntaxNode) = Nothing
While CanGet()
Dim c As Char = Peek()
Select Case (c)
' // Whitespace
' // S ::= (#x20 | #x9 | #xD | #xA)+
Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION
' we should not visit this place twice
Debug.Assert(Not precedingTrivia.Any)
precedingTrivia = ScanXmlTrivia(c)
Case "<"c
If CanGet(1) Then
Dim ch As Char = Peek(1)
Select Case ch
Case "!"c
If NextAre(2, "--") Then
Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc)
ElseIf NextAre(2, "DOCTYPE") Then
Return XmlMakeBeginDTDToken(precedingTrivia)
End If
Case "%"c
If NextIs(2, "="c) Then
Return XmlMakeBeginEmbeddedToken(precedingTrivia)
End If
Case "?"c
Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc)
End Select
End If
Return XmlMakeLessToken(precedingTrivia)
' TODO: review
' If Not m_State.m_ScannedElement OrElse c = "?"c OrElse c = "!"c Then
' ' // Remove tEOL from token ring if any exists
' If tEOL IsNot Nothing Then
' m_FirstFreeToken = tEOL
' End If
' m_State.m_LexicalState = LexicalState.XmlMarkup
' MakeToken(tokens.tkLT, 1)
' m_InputStreamPosition += 1
' Return
' End If
'End If
'm_State.EndXmlState()
'If tEOL IsNot Nothing Then
' tEOL.m_EOL.m_NextLineAlreadyScanned = True
'Else
' MakeToken(tokens.tkLT, 1)
' m_InputStreamPosition += 1
'End If
'Return
Case Else
Return SyntaxFactory.Token(precedingTrivia.Node, SyntaxKind.EndOfXmlToken, Nothing, String.Empty)
End Select
End While
Return MakeEofToken(precedingTrivia)
End Function
Friend Function ScanXmlStringUnQuoted() As SyntaxToken
If Not CanGet() Then
Return MakeEofToken()
End If
' This can never happen as this token cannot cross lines.
Debug.Assert(Not (IsScanningXmlDoc AndAlso IsAtNewLine()))
Dim Here = 0
Dim scratch = GetScratch()
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION
If Here > 0 Then
Return XmlMakeAttributeDataToken(Nothing, Here, scratch)
Else
Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken)
End If
Case "<"c, ">"c, "?"c
' This cannot be in a string. terminate the string.
If Here <> 0 Then
Return XmlMakeAttributeDataToken(Nothing, Here, scratch)
Else
Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken)
End If
Case "&"c
If Here > 0 Then
Return XmlMakeAttributeDataToken(Nothing, Here, scratch)
Else
Return ScanXmlReference(Nothing)
End If
Case "/"c
If NextIs(Here + 1, ">"c) Then
If Here <> 0 Then
Return XmlMakeAttributeDataToken(Nothing, Here, scratch)
Else
Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken)
End If
End If
GoTo ScanChars
Case Else
ScanChars:
' // Check characters are valid
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length = 0 Then
' bad char
If Here > 0 Then
Return XmlMakeAttributeDataToken(Nothing, Here, scratch)
Else
Return XmlMakeBadToken(Nothing, 1, ERRID.ERR_IllegalChar)
End If
End If
xmlCh.AppendTo(scratch)
Here += xmlCh.Length
End Select
End While
' no more chars
Return XmlMakeAttributeDataToken(Nothing, Here, scratch)
End Function
Friend Function ScanXmlStringSingle() As SyntaxToken
Return ScanXmlString("'"c, "'"c, True)
End Function
Friend Function ScanXmlStringDouble() As SyntaxToken
Return ScanXmlString(""""c, """"c, False)
End Function
Friend Function ScanXmlStringSmartSingle() As SyntaxToken
Return ScanXmlString(RIGHT_SINGLE_QUOTATION_MARK, LEFT_SINGLE_QUOTATION_MARK, True)
End Function
Friend Function ScanXmlStringSmartDouble() As SyntaxToken
Return ScanXmlString(RIGHT_DOUBLE_QUOTATION_MARK, LEFT_DOUBLE_QUOTATION_MARK, False)
End Function
Friend Function ScanXmlString(terminatingChar As Char, altTerminatingChar As Char, isSingle As Boolean) As SyntaxToken
' TODO: this trivia is used only in XmlDoc. May split the function?
Dim precedingTrivia = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)()
Dim result As SyntaxToken
If IsScanningXmlDoc AndAlso IsAtNewLine() Then
Dim xDocTrivia = ScanXmlDocTrivia()
If xDocTrivia Is Nothing Then
result = MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
GoTo CleanUp
End If
precedingTrivia.Add(xDocTrivia)
End If
Dim Here = 0
Dim scratch = GetScratch()
While CanGet(Here)
Dim c As Char = Peek(Here)
If c = terminatingChar Or c = altTerminatingChar Then
If Here > 0 Then
result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch)
GoTo CleanUp
Else
If isSingle Then
result = XmlMakeSingleQuoteToken(precedingTrivia, c, isOpening:=False)
Else
result = XmlMakeDoubleQuoteToken(precedingTrivia, c, isOpening:=False)
End If
GoTo CleanUp
End If
End If
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
Here = SkipLineBreak(c, Here)
scratch.Append(SPACE)
result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch)
GoTo CleanUp
Case CHARACTER_TABULATION
scratch.Append(SPACE)
Here += 1
Case "<"c
' This cannot be in a string. terminate the string.
If Here > 0 Then
result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch)
GoTo CleanUp
Else
' report unexpected <%= in a special way.
If NextAre(1, "%=") Then
Dim errEmbedStart = XmlMakeAttributeDataToken(precedingTrivia, 3, "<%=")
Dim errEmbedInfo = ErrorFactory.ErrorInfo(ERRID.ERR_QuotedEmbeddedExpression)
result = DirectCast(errEmbedStart.SetDiagnostics({errEmbedInfo}), SyntaxToken)
GoTo CleanUp
End If
Dim data = SyntaxFactory.MissingToken(SyntaxKind.SingleQuoteToken)
If precedingTrivia.Count > 0 Then
data = DirectCast(data.WithLeadingTrivia(precedingTrivia.ToList.Node), SyntaxToken)
End If
Dim errInfo = ErrorFactory.ErrorInfo(If(isSingle, ERRID.ERR_ExpectedSQuote, ERRID.ERR_ExpectedQuote))
result = DirectCast(data.SetDiagnostics({errInfo}), SyntaxToken)
GoTo CleanUp
End If
Case "&"c
If Here > 0 Then
result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch)
GoTo CleanUp
Else
result = ScanXmlReference(precedingTrivia)
GoTo CleanUp
End If
Case Else
ScanChars:
' // Check characters are valid
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length = 0 Then
' bad char
If Here > 0 Then
result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch)
GoTo CleanUp
Else
result = XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar)
GoTo CleanUp
End If
End If
xmlCh.AppendTo(scratch)
Here += xmlCh.Length
End Select
End While
' no more chars
If Here > 0 Then
result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch)
GoTo CleanUp
Else
result = MakeEofToken(precedingTrivia)
GoTo CleanUp
End If
CleanUp:
_triviaListPool.Free(precedingTrivia)
Return result
End Function
''' <summary>
''' 0 - not a surrogate, 2 - is valid surrogate
''' 1 is an error
''' </summary>
Private Function ScanSurrogatePair(c1 As Char, Here As Integer) As XmlCharResult
Debug.Assert(Here >= 0)
Debug.Assert(CanGet(Here))
Debug.Assert(Peek(Here) = c1)
If IsHighSurrogate(c1) AndAlso CanGet(Here + 1) Then
Dim c2 = Peek(Here + 1)
If IsLowSurrogate(c2) Then
Return New XmlCharResult(c1, c2)
End If
End If
Return Nothing
End Function
' contains result of Xml char scanning.
Friend Structure XmlCharResult
Friend ReadOnly Length As Integer
Friend ReadOnly Char1 As Char
Friend ReadOnly Char2 As Char
Friend Sub New(ch As Char)
Length = 1
Char1 = ch
End Sub
Friend Sub New(ch1 As Char, ch2 As Char)
Length = 2
Char1 = ch1
Char2 = ch2
End Sub
Friend Sub AppendTo(list As StringBuilder)
Debug.Assert(list IsNot Nothing)
Debug.Assert(Length <> 0)
list.Append(Char1)
If Length = 2 Then
list.Append(Char2)
End If
End Sub
End Structure
Private Function ScanXmlChar(Here As Integer) As XmlCharResult
Debug.Assert(Here >= 0)
Debug.Assert(CanGet(Here))
Dim c = Peek(Here)
If Not isValidUtf16(c) Then
Return Nothing
End If
If Not IsSurrogate(c) Then
Return New XmlCharResult(c)
End If
Return ScanSurrogatePair(c, Here)
End Function
Private Function ScanXmlNcName(precedingTrivia As SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken
' // Scan a non qualified name per Xml Namespace 1.0
' // [4] NCName ::= (Letter | '_') (NCNameChar)* /* An XML Name, minus the ":" */
' // This scanner is much looser than a pure Xml scanner.
' // Names are any character up to a separator character from
' // ':' | ' ' | '\t' | '\n' | '\r' | '=' | '\'' | '"'| '/' | '<' | '>' | EOF
' // Each name token will be marked as to whether it contains only valid Xml name characters.
Dim Here As Integer = 0
Dim IsIllegalChar As Boolean = False
Dim isFirst As Boolean = True
Dim err As ERRID = ERRID.ERR_None
Dim errUnicode As Integer = 0
Dim errChar As String = Nothing
'TODO - Fix ScanXmlNCName to conform to XML spec instead of old loose scanning.
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case ":"c, " "c, CHARACTER_TABULATION, LINE_FEED, CARRIAGE_RETURN,
"="c, "'"c, """"c, "/"c,
">"c, "<"c, "("c, ")"c,
"?"c, ";"c, ","c, "}"c
GoTo CreateNCNameToken
Case Else
' // Invalid Xml name but scan as Xml name anyway
' // Check characters are valid name chars
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length = 0 Then
IsIllegalChar = True
GoTo CreateNCNameToken
Else
If err = ERRID.ERR_None Then
If xmlCh.Length = 1 Then
' Non surrogate check
If isFirst Then
err = If(Not isStartNameChar(xmlCh.Char1), ERRID.ERR_IllegalXmlStartNameChar, ERRID.ERR_None)
isFirst = False
Else
err = If(Not isNameChar(xmlCh.Char1), ERRID.ERR_IllegalXmlNameChar, ERRID.ERR_None)
End If
If err <> ERRID.ERR_None Then
errChar = Convert.ToString(xmlCh.Char1)
errUnicode = Convert.ToInt32(xmlCh.Char1)
End If
Else
' Surrogate check
Dim unicode = UTF16ToUnicode(xmlCh)
If Not (unicode >= &H10000 AndAlso unicode <= &HEFFFF) Then
err = ERRID.ERR_IllegalXmlNameChar
errChar = {xmlCh.Char1, xmlCh.Char2}
errUnicode = unicode
End If
End If
End If
Here += xmlCh.Length
End If
End Select
End While
CreateNCNameToken:
If Here <> 0 Then
Dim name = XmlMakeXmlNCNameToken(precedingTrivia, Here)
If err <> ERRID.ERR_None Then
name = name.WithDiagnostics(ErrorFactory.ErrorInfo(err, errChar, String.Format("&H{0:X}", errUnicode)))
End If
Return name
ElseIf IsIllegalChar Then
Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar)
End If
Return MakeMissingToken(precedingTrivia, SyntaxKind.XmlNameToken)
End Function
Private Function ScanXmlReference(precedingTrivia As SyntaxList(Of VisualBasicSyntaxNode)) As XmlTextTokenSyntax
Debug.Assert(CanGet)
Debug.Assert(Peek() = "&"c)
' skip 1 char for "&"
If CanGet(1) Then
Dim c As Char = Peek(1)
Select Case (c)
Case "#"c
Dim Here = 2 ' skip "&#"
Dim result = ScanXmlCharRef(Here)
If result.Length <> 0 Then
Dim value As String = Nothing
If result.Length = 1 Then
value = Intern(result.Char1)
ElseIf result.Length = 2 Then
value = Intern({result.Char1, result.Char2})
End If
If CanGet(Here) AndAlso Peek(Here) = ";"c Then
Return XmlMakeEntityLiteralToken(precedingTrivia, Here + 1, value)
Else
Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, Here, value)
Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon)
Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax)
End If
End If
Case "a"c
' // &
' // '
If CanGet(4) AndAlso NextAre(2, "mp") Then
If Peek(4) = ";"c Then
Return XmlMakeAmpLiteralToken(precedingTrivia)
Else
Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 4, "&")
Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon)
Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax)
End If
ElseIf CanGet(5) AndAlso NextAre(2, "pos") Then
If Peek(5) = ";"c Then
Return XmlMakeAposLiteralToken(precedingTrivia)
Else
Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 5, "'")
Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon)
Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax)
End If
End If
Case "l"c
' // <
If CanGet(3) AndAlso NextIs(2, "t"c) Then
If Peek(3) = ";"c Then
Return XmlMakeLtLiteralToken(precedingTrivia)
Else
Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 3, "<")
Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon)
Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax)
End If
End If
Case "g"c
' // >
If CanGet(3) AndAlso NextIs(2, "t"c) Then
If Peek(3) = ";"c Then
Return XmlMakeGtLiteralToken(precedingTrivia)
Else
Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 3, ">")
Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon)
Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax)
End If
End If
Case "q"c
' // "
If CanGet(5) AndAlso NextAre(2, "uot") Then
If Peek(5) = ";"c Then
Return XmlMakeQuotLiteralToken(precedingTrivia)
Else
Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 5, """")
Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon)
Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax)
End If
End If
End Select
End If
Dim badEntity = XmlMakeEntityLiteralToken(precedingTrivia, 1, "")
Dim errInfo = ErrorFactory.ErrorInfo(ERRID.ERR_XmlEntityReference)
Return DirectCast(badEntity.SetDiagnostics({errInfo}), XmlTextTokenSyntax)
End Function
Private Function ScanXmlCharRef(ByRef index As Integer) As XmlCharResult
Debug.Assert(index >= 0)
If Not CanGet(index) Then
Return Nothing
End If
' cannot reuse Scratch as this can be used in a nested call.
Dim charRefSb As New StringBuilder
Dim Here = index
Dim ch = Peek(Here)
If ch = "x"c Then
Here += 1
While CanGet(Here)
ch = Peek(Here)
If XmlCharType.IsHexDigit(ch) Then
charRefSb.Append(ch)
Else
Exit While
End If
Here += 1
End While
If charRefSb.Length > 0 Then
Dim result = HexToUTF16(charRefSb)
If result.Length <> 0 Then
index = Here
End If
Return result
End If
Else
While CanGet(Here)
ch = Peek(Here)
If XmlCharType.IsDigit(ch) Then
charRefSb.Append(ch)
Else
Exit While
End If
Here += 1
End While
If charRefSb.Length > 0 Then
Dim result = DecToUTF16(charRefSb)
If result.Length <> 0 Then
index = Here
End If
Return result
End If
End If
Return Nothing
End Function
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Portable/Scanner/ScannerXml.vb
|
Visual Basic
|
apache-2.0
| 55,011
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Preview
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(Preview))
Me.PrintPreviewControl1 = New System.Windows.Forms.PrintPreviewControl()
Me.ToolStrip1 = New System.Windows.Forms.ToolStrip()
Me.PrevButton = New System.Windows.Forms.ToolStripButton()
Me.ToolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator()
Me.NextButton = New System.Windows.Forms.ToolStripButton()
Me.Panel1 = New System.Windows.Forms.Panel()
Me.ToolStrip1.SuspendLayout()
Me.Panel1.SuspendLayout()
Me.SuspendLayout()
'
'PrintPreviewControl1
'
Me.PrintPreviewControl1.Dock = System.Windows.Forms.DockStyle.Fill
Me.PrintPreviewControl1.Location = New System.Drawing.Point(0, 0)
Me.PrintPreviewControl1.Name = "PrintPreviewControl1"
Me.PrintPreviewControl1.Size = New System.Drawing.Size(488, 540)
Me.PrintPreviewControl1.TabIndex = 0
'
'ToolStrip1
'
Me.ToolStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.PrevButton, Me.ToolStripSeparator1, Me.NextButton})
Me.ToolStrip1.Location = New System.Drawing.Point(0, 0)
Me.ToolStrip1.Name = "ToolStrip1"
Me.ToolStrip1.Size = New System.Drawing.Size(488, 25)
Me.ToolStrip1.TabIndex = 1
Me.ToolStrip1.Text = "ToolStrip1"
'
'PrevButton
'
Me.PrevButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text
Me.PrevButton.Image = CType(resources.GetObject("PrevButton.Image"), System.Drawing.Image)
Me.PrevButton.ImageTransparentColor = System.Drawing.Color.Magenta
Me.PrevButton.Name = "PrevButton"
Me.PrevButton.Size = New System.Drawing.Size(34, 22)
Me.PrevButton.Text = "Prev"
'
'ToolStripSeparator1
'
Me.ToolStripSeparator1.Name = "ToolStripSeparator1"
Me.ToolStripSeparator1.Size = New System.Drawing.Size(6, 25)
'
'NextButton
'
Me.NextButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text
Me.NextButton.Image = CType(resources.GetObject("NextButton.Image"), System.Drawing.Image)
Me.NextButton.ImageTransparentColor = System.Drawing.Color.Magenta
Me.NextButton.Name = "NextButton"
Me.NextButton.Size = New System.Drawing.Size(35, 22)
Me.NextButton.Text = "Next"
'
'Panel1
'
Me.Panel1.Controls.Add(Me.PrintPreviewControl1)
Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
Me.Panel1.Location = New System.Drawing.Point(0, 25)
Me.Panel1.Name = "Panel1"
Me.Panel1.Size = New System.Drawing.Size(488, 540)
Me.Panel1.TabIndex = 2
'
'Preview
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(488, 565)
Me.Controls.Add(Me.Panel1)
Me.Controls.Add(Me.ToolStrip1)
Me.Name = "Preview"
Me.Text = "Preview"
Me.WindowState = System.Windows.Forms.FormWindowState.Maximized
Me.ToolStrip1.ResumeLayout(False)
Me.ToolStrip1.PerformLayout()
Me.Panel1.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents PrintPreviewControl1 As System.Windows.Forms.PrintPreviewControl
Friend WithEvents ToolStrip1 As System.Windows.Forms.ToolStrip
Friend WithEvents PrevButton As System.Windows.Forms.ToolStripButton
Friend WithEvents ToolStripSeparator1 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents NextButton As System.Windows.Forms.ToolStripButton
Friend WithEvents Panel1 As System.Windows.Forms.Panel
End Class
|
pagotti/vrx
|
Sample/Preview.Designer.vb
|
Visual Basic
|
mit
| 4,818
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
<Global.System.Configuration.ApplicationScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("c:\Program Files (x86)\ProcessControl\ProcessControlParams.xml")> _
Public ReadOnly Property sProcessControlXMLPath() As String
Get
Return CType(Me("sProcessControlXMLPath"),String)
End Get
End Property
<Global.System.Configuration.ApplicationScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("15")> _
Public ReadOnly Property iTimerInterval() As Integer
Get
Return CType(Me("iTimerInterval"),Integer)
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.ProcessControl.My.MySettings
Get
Return Global.ProcessControl.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
md-schneider/ProcessControl
|
ProcessControl/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 3,810
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class AboutDSGM
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(AboutDSGM))
Me.DSGMTopPanel = New System.Windows.Forms.Panel()
Me.MainPanel = New System.Windows.Forms.Panel()
Me.AdditionalCreditsLabel = New System.Windows.Forms.Label()
Me.WebAddressLabel = New System.Windows.Forms.Label()
Me.MainInfoLabel = New System.Windows.Forms.Label()
Me.WrittenByLabel = New System.Windows.Forms.Label()
Me.VersionLabel = New System.Windows.Forms.Label()
Me.DOkayButton = New System.Windows.Forms.Button()
Me.Label1 = New System.Windows.Forms.Label()
Me.MainPanel.SuspendLayout()
Me.SuspendLayout()
'
'DSGMTopPanel
'
Me.DSGMTopPanel.BackgroundImage = Global.DS_Game_Maker.My.Resources.Resources.DSGMTopBanner
Me.DSGMTopPanel.Location = New System.Drawing.Point(0, 0)
Me.DSGMTopPanel.Name = "DSGMTopPanel"
Me.DSGMTopPanel.Size = New System.Drawing.Size(338, 130)
Me.DSGMTopPanel.TabIndex = 0
'
'MainPanel
'
Me.MainPanel.BackColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer))
Me.MainPanel.Controls.Add(Me.Label1)
Me.MainPanel.Controls.Add(Me.AdditionalCreditsLabel)
Me.MainPanel.Controls.Add(Me.WebAddressLabel)
Me.MainPanel.Controls.Add(Me.MainInfoLabel)
Me.MainPanel.Controls.Add(Me.WrittenByLabel)
Me.MainPanel.Location = New System.Drawing.Point(0, 130)
Me.MainPanel.Name = "MainPanel"
Me.MainPanel.Size = New System.Drawing.Size(338, 235)
Me.MainPanel.TabIndex = 1
'
'AdditionalCreditsLabel
'
Me.AdditionalCreditsLabel.Font = New System.Drawing.Font("Tahoma", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.AdditionalCreditsLabel.ForeColor = System.Drawing.Color.Silver
Me.AdditionalCreditsLabel.Location = New System.Drawing.Point(8, 60)
Me.AdditionalCreditsLabel.Name = "AdditionalCreditsLabel"
Me.AdditionalCreditsLabel.Size = New System.Drawing.Size(314, 67)
Me.AdditionalCreditsLabel.TabIndex = 3
Me.AdditionalCreditsLabel.Text = "Additional components and assistance contributed by Dave J Murphy, Michael Noland" & _
", Jason Rogers, Gregory Potdevin, Chris Rickard, Nick Thissen, Robert Dixon, Dav" & _
"e Tabba, Cilein Kearns and Baron Khan."
'
'WebAddressLabel
'
Me.WebAddressLabel.AutoSize = True
Me.WebAddressLabel.Cursor = System.Windows.Forms.Cursors.Hand
Me.WebAddressLabel.Font = New System.Drawing.Font("Tahoma", 9.0!, CType((System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Underline), System.Drawing.FontStyle), System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.WebAddressLabel.ForeColor = System.Drawing.Color.White
Me.WebAddressLabel.Location = New System.Drawing.Point(8, 207)
Me.WebAddressLabel.Name = "WebAddressLabel"
Me.WebAddressLabel.Size = New System.Drawing.Size(157, 14)
Me.WebAddressLabel.TabIndex = 2
Me.WebAddressLabel.Text = "www.dsgamemaker.com"
'
'MainInfoLabel
'
Me.MainInfoLabel.Font = New System.Drawing.Font("Tahoma", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.MainInfoLabel.ForeColor = System.Drawing.Color.White
Me.MainInfoLabel.Location = New System.Drawing.Point(8, 127)
Me.MainInfoLabel.Name = "MainInfoLabel"
Me.MainInfoLabel.Size = New System.Drawing.Size(314, 80)
Me.MainInfoLabel.TabIndex = 1
Me.MainInfoLabel.Text = "Copyright James Garner, Invisionsoft 2008-2011" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "For DS Game Maker updates, rela" & _
"ted products (such as DS Homebrew Kits), more information, discussion and games," & _
" visit our website:"
'
'WrittenByLabel
'
Me.WrittenByLabel.AutoSize = True
Me.WrittenByLabel.Font = New System.Drawing.Font("Tahoma", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.WrittenByLabel.ForeColor = System.Drawing.Color.White
Me.WrittenByLabel.Location = New System.Drawing.Point(8, 12)
Me.WrittenByLabel.Name = "WrittenByLabel"
Me.WrittenByLabel.Size = New System.Drawing.Size(158, 14)
Me.WrittenByLabel.TabIndex = 0
Me.WrittenByLabel.Text = "Written by James Garner"
'
'VersionLabel
'
Me.VersionLabel.Font = New System.Drawing.Font("Tahoma", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.VersionLabel.ForeColor = System.Drawing.Color.Gray
Me.VersionLabel.Location = New System.Drawing.Point(6, 375)
Me.VersionLabel.Name = "VersionLabel"
Me.VersionLabel.Size = New System.Drawing.Size(200, 18)
Me.VersionLabel.TabIndex = 3
Me.VersionLabel.Text = "..."
'
'DOkayButton
'
Me.DOkayButton.Location = New System.Drawing.Point(234, 369)
Me.DOkayButton.Name = "DOkayButton"
Me.DOkayButton.Size = New System.Drawing.Size(100, 28)
Me.DOkayButton.TabIndex = 2
Me.DOkayButton.Text = "OK"
Me.DOkayButton.UseVisualStyleBackColor = True
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Tahoma", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.ForeColor = System.Drawing.Color.White
Me.Label1.Location = New System.Drawing.Point(12, 35)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(277, 14)
Me.Label1.TabIndex = 4
Me.Label1.Text = "Updates (version 5.2+) written by Chris Ertl"
'
'AboutDSGM
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(338, 402)
Me.Controls.Add(Me.VersionLabel)
Me.Controls.Add(Me.DOkayButton)
Me.Controls.Add(Me.MainPanel)
Me.Controls.Add(Me.DSGMTopPanel)
Me.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "AboutDSGM"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
Me.Text = "About DS Game Maker"
Me.MainPanel.ResumeLayout(False)
Me.MainPanel.PerformLayout()
Me.ResumeLayout(False)
End Sub
Friend WithEvents DSGMTopPanel As System.Windows.Forms.Panel
Friend WithEvents MainPanel As System.Windows.Forms.Panel
Friend WithEvents DOkayButton As System.Windows.Forms.Button
Friend WithEvents WrittenByLabel As System.Windows.Forms.Label
Friend WithEvents MainInfoLabel As System.Windows.Forms.Label
Friend WithEvents WebAddressLabel As System.Windows.Forms.Label
Friend WithEvents VersionLabel As System.Windows.Forms.Label
Friend WithEvents AdditionalCreditsLabel As System.Windows.Forms.Label
Friend WithEvents Label1 As System.Windows.Forms.Label
End Class
|
cfwprpht/dsgamemaker
|
AboutDSGM.Designer.vb
|
Visual Basic
|
mit
| 8,911
|
Public Class NuevaListaPrecios
Dim ControlesConErrores As List(Of Control) = New List(Of Control)
Dim idSeleccionado As Integer = -1
#Region "Botones"
Private Sub btn_Cancelar_Click(sender As Object, e As EventArgs) Handles btn_Cancelar.Click
idSeleccionado = -1
tbLista.Text = ""
btn_Actualizar.Enabled = False
btn_Guardar.Enabled = True
End Sub
Private Sub btn_Guardar_Click(sender As Object, e As EventArgs) Handles btn_Guardar.Click
'Verificacion de campos obligatorios completos
If tbLista.Text = "" Then
formMain.ErrorProvider.SetError(tbLista, "Debe completar el campo")
If Not ControlesConErrores.Contains(tbLista) Then
ControlesConErrores.Add(tbLista)
End If
Else
formMain.ErrorProvider.SetError(tbLista, "")
ControlesConErrores.Remove(tbLista)
End If
'Verificamos que todos los campos hayan pasado las validaciones
If ControlesConErrores.Count > 0 Then
MsgBox("Por favor revise los campos ingresados", MsgBoxStyle.Exclamation, "Error")
Exit Sub
End If
' GUARDAR
If (MsgBox("Está seguro?", MsgBoxStyle.OkCancel, "Guardar?") = MsgBoxResult.Ok) Then
If (NuevaListaPrecio(
tbLista.Text
) = True) Then
PreciosNuevaLista(obtenerID("ListaPrecios", "nombre", tbLista.Text))
MsgBox("Guardada correctamente.", MsgBoxStyle.Information, "Guardado")
idSeleccionado = -1
tbLista.Text = ""
btn_Guardar.Enabled = True
btn_Actualizar.Enabled = False
cargarListaPrecios(dgvGrid)
Else
MsgBox("Ocurrió un problema al guardar", MsgBoxStyle.Critical, "Error")
End If
End If
End Sub
Private Sub btn_Actualizar_Click(sender As Object, e As EventArgs) Handles btn_Actualizar.Click
' Verificacion de campos obligatorios completos
If tbLista.Text = "" Then
formMain.ErrorProvider.SetError(tbLista, "Debe completar el campo")
If Not ControlesConErrores.Contains(tbLista) Then
ControlesConErrores.Add(tbLista)
End If
Else
formMain.ErrorProvider.SetError(tbLista, "")
ControlesConErrores.Remove(tbLista)
End If
If idSeleccionado = -1 Then
MsgBox("Error al obtener el ítem seleccionado." & vbCrLf &
"Intente seleccionarlo nuevamente.", MsgBoxStyle.Exclamation, "Error")
Exit Sub
End If
'Verificamos que todos los campos hayan pasado las validaciones
If ControlesConErrores.Count > 0 Then
MsgBox("Por favor revise los campos ingresados", MsgBoxStyle.Exclamation, "Error")
Exit Sub
End If
'Verificación de item Repetido
If existActualizar("ListaPrecios", "nombre", tbLista.Text, idSeleccionado) Then
MsgBox("Ya existe una lista de precios con ese nombre", MsgBoxStyle.Exclamation, "Error")
Exit Sub
End If
' ACTUALIZAR
If (MsgBox("Está seguro?", MsgBoxStyle.OkCancel, "Guardar?") = MsgBoxResult.Ok) Then
If (EditarListaPrecio(
idSeleccionado,
tbLista.Text
) = True) Then
MsgBox("Guardado correctamente", MsgBoxStyle.Information, "Guardado")
tbLista.Text = ""
idSeleccionado = -1
btn_Actualizar.Enabled = False
btn_Guardar.Enabled = True
cargarListaPrecios(dgvGrid)
Else
MsgBox("Ocurrió un problema al editar el ítem", MsgBoxStyle.Critical, "Error")
End If
End If
End Sub
Private Sub btn_Eliminar_Click(sender As Object, e As EventArgs) Handles btn_Eliminar.Click
If dgvGrid.SelectedRows.Count = 0 Then
MsgBox("Error al obtener la lista seleccionado." & vbCrLf &
"Intente seleccionarlo nuevamente.", MsgBoxStyle.Exclamation, "Error")
Exit Sub
End If
' ELIMINAR
If (MsgBox("Está seguro?", MsgBoxStyle.OkCancel, "Eliminar?") = MsgBoxResult.Ok) Then
If (EliminarListaPrecio(dgvGrid.CurrentRow.Cells("id").Value) = True) Then
MsgBox("Eliminado Correctamente", MsgBoxStyle.Information, "Eliminado")
tbLista.Text = ""
idSeleccionado = -1
btn_Actualizar.Enabled = False
btn_Guardar.Enabled = True
cargarListaPrecios(dgvGrid)
Else
MsgBox("Ocurrió un problema al eliminar el ítem", MsgBoxStyle.Critical, "Error")
End If
End If
End Sub
#End Region
#Region "Eventos"
Private Sub NuevaListaPrecios_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cargarListaPrecios(dgvGrid)
End Sub
Private Sub dgvGrid_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvGrid.CellMouseDoubleClick
If e.RowIndex >= 0 Then
idSeleccionado = CInt(dgvGrid.Rows(e.RowIndex).Cells("id").Value)
tbLista.Text = dgvGrid.Rows(e.RowIndex).Cells("nombre").Value
btn_Guardar.Enabled = False
btn_Actualizar.Enabled = True
End If
End Sub
#End Region
#Region "Validaciones"
Private Sub tbLista_KeyPress(sender As Object, e As KeyPressEventArgs) Handles tbLista.KeyPress
keyverify(e, numeros:=True, letras:=True, espacios:=True, comas:=True)
End Sub
#End Region
End Class
|
MontiQt/SaavedraSystem
|
Formularios Saavedra/Vistas/NuevaListaPrecios.vb
|
Visual Basic
|
mit
| 5,796
|
Module ModulatorX
#Region "ListBox to Array String"
Friend Function ListBoxToArray(ListBoxer As ListBox) As String()
Dim arr As String() = {"*"}
If ListBoxer.Items.Count > 0 Then
arr = New String(ListBoxer.Items.Count - 1) {}
For i As Integer = 0 To ListBoxer.Items.Count - 1
arr(i) = ListBoxer.Items(i).ToString
Next
End If
Return arr
End Function
#End Region
#Region "File Size"
Function GetFileSize(ByVal byteLength As Long) As String
Dim sizer As String = Nothing
If byteLength >= 1048576 And byteLength <= 1073741823 Then
sizer = FormatNumber(byteLength / 1048576, 2).ToString & "MB"
ElseIf byteLength >= 1024 And byteLength <= 1048575 Then
sizer = FormatNumber(byteLength / 1024, 2) & "KB"
Else
sizer = FormatNumber(byteLength, 0) & "B"
End If
Return sizer
End Function
#End Region
#Region "DoubleBuffered Buff // Use Buff.DoubleBuff(<Control>)"
Friend NotInheritable Class Buff
Friend Shared Sub DoubleBuff(Contt As Control)
Dim ConttType As Type = Contt.[GetType]()
Dim propInfo As System.Reflection.PropertyInfo = ConttType.GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.NonPublic)
propInfo.SetValue(Contt, True, Nothing)
End Sub
End Class
#End Region
#Region "Text Search"
'www.dotnetcurry.com/ShowArticle.aspx?ID=146
Friend start As Integer = 0
Friend indexOfSearchText As Integer = 0
Public Function FindMyText(ByVal txtToSearch As String, ByVal searchStart As Integer, ByVal searchEnd As Integer, rtb As RichTextBox) As Integer
' Unselect the previously searched string
If searchStart > 0 AndAlso searchEnd > 0 AndAlso indexOfSearchText >= 0 Then
rtb.SelectionBackColor = Color.White
End If
' Set the return value to -1 by default.
Dim retVal As Integer = -1
' A valid starting index should be specified.
' if indexOfSearchText = -1, the end of search
If searchStart >= 0 AndAlso indexOfSearchText >= 0 Then
' A valid ending index
If searchEnd > searchStart OrElse searchEnd = -1 Then
' Find the position of search string in RichTextBox
indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None)
' Determine whether the text was found in richTextBox1.
If indexOfSearchText <> -1 Then
' Return the index to the specified search text.
retVal = indexOfSearchText
Else
start = 0
indexOfSearchText = 0
MessageBox.Show("End of Search!", "End of the Line~", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End If
End If
Return retVal
End Function
#End Region
End Module
|
Laicure/HostsX
|
HostsX/Modules/ModulatorX.vb
|
Visual Basic
|
mit
| 3,071
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmPrintGroup
#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 _txtInteger_0 As System.Windows.Forms.TextBox
Public WithEvents _txtFields_0 As System.Windows.Forms.TextBox
Public WithEvents cmdCancel As System.Windows.Forms.Button
Public WithEvents cmdClose As System.Windows.Forms.Button
Public WithEvents picButtons As System.Windows.Forms.Panel
Public WithEvents _lblLabels_0 As System.Windows.Forms.Label
Public WithEvents _lblLabels_38 As System.Windows.Forms.Label
Public WithEvents _Shape1_2 As Microsoft.VisualBasic.PowerPacks.RectangleShape
Public WithEvents _lbl_5 As System.Windows.Forms.Label
'Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
'Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
'Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
'Public WithEvents txtInteger As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
Public WithEvents Shape1 As RectangleShapeArray
Public WithEvents ShapeContainer1 As Microsoft.VisualBasic.PowerPacks.ShapeContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmPrintGroup))
Me.components = New System.ComponentModel.Container()
Me.ToolTip1 = New System.Windows.Forms.ToolTip(components)
Me.ShapeContainer1 = New Microsoft.VisualBasic.PowerPacks.ShapeContainer
Me._txtInteger_0 = New System.Windows.Forms.TextBox
Me._txtFields_0 = New System.Windows.Forms.TextBox
Me.picButtons = New System.Windows.Forms.Panel
Me.cmdCancel = New System.Windows.Forms.Button
Me.cmdClose = New System.Windows.Forms.Button
Me._lblLabels_0 = New System.Windows.Forms.Label
Me._lblLabels_38 = New System.Windows.Forms.Label
Me._Shape1_2 = New Microsoft.VisualBasic.PowerPacks.RectangleShape
Me._lbl_5 = New System.Windows.Forms.Label
'Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
'Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
'Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
'Me.txtInteger = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
Me.Shape1 = New RectangleShapeArray(components)
Me.picButtons.SuspendLayout()
Me.SuspendLayout()
Me.ToolTip1.Active = True
'CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
'CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit()
'CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit()
'CType(Me.txtInteger, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Shape1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.BackColor = System.Drawing.Color.FromARGB(224, 224, 224)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.Text = "Edit Print Group Item"
Me.ClientSize = New System.Drawing.Size(455, 109)
Me.Location = New System.Drawing.Point(73, 22)
Me.ControlBox = False
Me.KeyPreview = True
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.Enabled = True
Me.Cursor = System.Windows.Forms.Cursors.Default
Me.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.ShowInTaskbar = True
Me.HelpButton = False
Me.WindowState = System.Windows.Forms.FormWindowState.Normal
Me.Name = "frmPrintGroup"
Me._txtInteger_0.AutoSize = False
Me._txtInteger_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
Me._txtInteger_0.Size = New System.Drawing.Size(64, 19)
Me._txtInteger_0.Location = New System.Drawing.Point(375, 66)
Me._txtInteger_0.TabIndex = 3
Me._txtInteger_0.Text = "9,999.99"
Me._txtInteger_0.AcceptsReturn = True
Me._txtInteger_0.BackColor = System.Drawing.SystemColors.Window
Me._txtInteger_0.CausesValidation = True
Me._txtInteger_0.Enabled = True
Me._txtInteger_0.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtInteger_0.HideSelection = True
Me._txtInteger_0.ReadOnly = False
Me._txtInteger_0.Maxlength = 0
Me._txtInteger_0.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtInteger_0.MultiLine = False
Me._txtInteger_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtInteger_0.ScrollBars = System.Windows.Forms.ScrollBars.None
Me._txtInteger_0.TabStop = True
Me._txtInteger_0.Visible = True
Me._txtInteger_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtInteger_0.Name = "_txtInteger_0"
Me._txtFields_0.AutoSize = False
Me._txtFields_0.Size = New System.Drawing.Size(195, 19)
Me._txtFields_0.Location = New System.Drawing.Point(114, 66)
Me._txtFields_0.TabIndex = 1
Me._txtFields_0.AcceptsReturn = True
Me._txtFields_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Left
Me._txtFields_0.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_0.CausesValidation = True
Me._txtFields_0.Enabled = True
Me._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_0.HideSelection = True
Me._txtFields_0.ReadOnly = False
Me._txtFields_0.Maxlength = 0
Me._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_0.MultiLine = False
Me._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_0.ScrollBars = System.Windows.Forms.ScrollBars.None
Me._txtFields_0.TabStop = True
Me._txtFields_0.Visible = True
Me._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_0.Name = "_txtFields_0"
Me.picButtons.Dock = System.Windows.Forms.DockStyle.Top
Me.picButtons.BackColor = System.Drawing.Color.Blue
Me.picButtons.Size = New System.Drawing.Size(455, 39)
Me.picButtons.Location = New System.Drawing.Point(0, 0)
Me.picButtons.TabIndex = 6
Me.picButtons.TabStop = False
Me.picButtons.CausesValidation = True
Me.picButtons.Enabled = True
Me.picButtons.ForeColor = System.Drawing.SystemColors.ControlText
Me.picButtons.Cursor = System.Windows.Forms.Cursors.Default
Me.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.picButtons.Visible = True
Me.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.picButtons.Name = "picButtons"
Me.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdCancel.Text = "&Undo"
Me.cmdCancel.Size = New System.Drawing.Size(73, 29)
Me.cmdCancel.Location = New System.Drawing.Point(5, 3)
Me.cmdCancel.TabIndex = 5
Me.cmdCancel.TabStop = False
Me.cmdCancel.BackColor = System.Drawing.SystemColors.Control
Me.cmdCancel.CausesValidation = True
Me.cmdCancel.Enabled = True
Me.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdCancel.Name = "cmdCancel"
Me.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdClose.Text = "E&xit"
Me.cmdClose.Size = New System.Drawing.Size(73, 29)
Me.cmdClose.Location = New System.Drawing.Point(372, 3)
Me.cmdClose.TabIndex = 4
Me.cmdClose.TabStop = False
Me.cmdClose.BackColor = System.Drawing.SystemColors.Control
Me.cmdClose.CausesValidation = True
Me.cmdClose.Enabled = True
Me.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdClose.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdClose.Name = "cmdClose"
Me._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lblLabels_0.Text = "Order:"
Me._lblLabels_0.Size = New System.Drawing.Size(29, 13)
Me._lblLabels_0.Location = New System.Drawing.Point(341, 69)
Me._lblLabels_0.TabIndex = 2
Me._lblLabels_0.BackColor = System.Drawing.Color.Transparent
Me._lblLabels_0.Enabled = True
Me._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default
Me._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblLabels_0.UseMnemonic = True
Me._lblLabels_0.Visible = True
Me._lblLabels_0.AutoSize = True
Me._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lblLabels_0.Name = "_lblLabels_0"
Me._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lblLabels_38.Text = "Print Group Name:"
Me._lblLabels_38.Size = New System.Drawing.Size(87, 13)
Me._lblLabels_38.Location = New System.Drawing.Point(22, 69)
Me._lblLabels_38.TabIndex = 0
Me._lblLabels_38.BackColor = System.Drawing.Color.Transparent
Me._lblLabels_38.Enabled = True
Me._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default
Me._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblLabels_38.UseMnemonic = True
Me._lblLabels_38.Visible = True
Me._lblLabels_38.AutoSize = True
Me._lblLabels_38.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lblLabels_38.Name = "_lblLabels_38"
Me._Shape1_2.BackColor = System.Drawing.Color.FromARGB(192, 192, 255)
Me._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque
Me._Shape1_2.Size = New System.Drawing.Size(430, 31)
Me._Shape1_2.Location = New System.Drawing.Point(15, 60)
Me._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText
Me._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid
Me._Shape1_2.BorderWidth = 1
Me._Shape1_2.FillColor = System.Drawing.Color.Black
Me._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent
Me._Shape1_2.Visible = True
Me._Shape1_2.Name = "_Shape1_2"
Me._lbl_5.BackColor = System.Drawing.Color.Transparent
Me._lbl_5.Text = "&1. General"
Me._lbl_5.Size = New System.Drawing.Size(60, 13)
Me._lbl_5.Location = New System.Drawing.Point(15, 45)
Me._lbl_5.TabIndex = 7
Me._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lbl_5.Enabled = True
Me._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_5.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_5.UseMnemonic = True
Me._lbl_5.Visible = True
Me._lbl_5.AutoSize = True
Me._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_5.Name = "_lbl_5"
Me.Controls.Add(_txtInteger_0)
Me.Controls.Add(_txtFields_0)
Me.Controls.Add(picButtons)
Me.Controls.Add(_lblLabels_0)
Me.Controls.Add(_lblLabels_38)
Me.ShapeContainer1.Shapes.Add(_Shape1_2)
Me.Controls.Add(_lbl_5)
Me.Controls.Add(ShapeContainer1)
Me.picButtons.Controls.Add(cmdCancel)
Me.picButtons.Controls.Add(cmdClose)
'Me.lbl.SetIndex(_lbl_5, CType(5, Short))
'Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short))
'Me.lblLabels.SetIndex(_lblLabels_38, CType(38, Short))
'Me.txtFields.SetIndex(_txtFields_0, CType(0, Short))
'Me.txtInteger.SetIndex(_txtInteger_0, CType(0, Short))
Me.Shape1.SetIndex(_Shape1_2, CType(2, Short))
CType(Me.Shape1, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.txtInteger, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
Me.picButtons.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
#End Region
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmPrintGroup.Designer.vb
|
Visual Basic
|
mit
| 12,882
|
Imports BurnSoft.Universal
Imports System.Windows.Forms
Imports MySql.Data.MySqlClient
Imports System.Data.SQLite
Imports System.IO
Module modMain
Dim _sessionId As Long
Dim _appProjectMainProcessId As Long
Dim _appPath As String
Dim _uselocal As Boolean
Dim _offline as Boolean
Dim _param As string
Private _updatedsession As Boolean
#Region "SQLite Database Function and Sub"
''' <summary>
''' Get the Application Project Main Process ID and also return if the application has logs or not
''' </summary>
''' <param name="processName">process name</param>
''' <param name="hasLogs">Pass to check for logs or not</param>
''' <returns>id</returns>
Function GetAppProjectMainProcessSqlIte(processName As String, Optional ByRef hasLogs As Boolean = False) As Long
Dim lAns As Long = 0
Try
Dim sql As String = "Select id, haslogs from app_project_main_process where process_name='" & processName & "' COLLATE NOCASE"
Dim obj As New BurnSoft.BSSqliteDatabase
If obj.ConnectDB = 0 Then
Dim cmd As New SQLiteCommand(sql, obj.Conn)
Dim rs As SQLiteDataReader
rs = cmd.ExecuteReader
While rs.Read
lAns = rs("id")
HasLogs = Convert10ToBool(rs("haslogs"))
End While
rs.Close()
rs = Nothing
cmd = Nothing
obj.CloseDB()
End If
obj = Nothing
Catch ex As Exception
Call LogError("modMain.getAppProjectMainProcessSQLite", ex.Message.ToString)
End Try
Return lAns
End Function
''' <summary>
''' Gets the Log file name and path from the database for this main process
''' </summary>
''' <param name="apid">Application ID</param>
''' <returns>The Path of the logfile for that process</returns>
Function GetLogPathSqLite(apid As Long) As String
Dim sAns As String = ""
Try
Dim obj As New BurnSoft.BSSqliteDatabase
If obj.ConnectDB() = 0 Then
Dim sql As String = "select * from app_project_main_log where apmid=" & APID
Dim cmd As New SQLiteCommand(sql, obj.Conn)
Dim rs As SQLiteDataReader
rs = cmd.ExecuteReader
While rs.Read
sAns = rs("logpath") & "\" & rs("logname")
End While
rs.Close()
rs = Nothing
cmd = Nothing
obj.CloseDB()
End If
obj = Nothing
Catch ex As Exception
Call LogError("modMain.GetLogPathSQLite", ex.Message.ToString)
End Try
Return sAns
End Function
''' <summary>
''' Get the latest session that was just entered into the database
''' </summary>
''' <returns>id</returns>
Function GetSessionIdsqLite() As Long
Dim lAns As Long = 0
Try
Dim sql As String = "SELECT id from monitoring_session where APNID=" & PROCESS_ID & " and AID=" & AGENT_ID &
" order by id desc limit 1"
Dim obj As New BurnSoft.BSSqliteDatabase
If obj.ConnectDB = 0 Then
Dim cmd As New SQLiteCommand(sql, obj.Conn)
Dim rs As SQLiteDataReader
rs = cmd.ExecuteReader
While rs.Read
lAns = rs("id")
End While
rs.Close()
rs = Nothing
cmd = Nothing
obj.CloseDB()
obj = Nothing
End If
Catch ex As Exception
Call LogError("modmain.getSessionIDSQLite", ex.Message.ToString)
End Try
Return lAns
End Function
#End Region
#Region "MySQL Database Functions and Subs"
''' <summary>
''' Get the Application Project Main Process ID and also return if the application has logs or not
''' </summary>
''' <param name="processName"></param>
''' <param name="hasLogs"></param>
''' <returns>id</returns>
Function GetAppProjectMainProcessMySql(processName As String, Optional ByRef hasLogs As Boolean = False) As Long
Dim lAns As Long = 0
Try
Dim sql As String = "Select id, haslogs from app_project_main_process where process_name='" & processName & "'"
Dim obj As New BurnSoft.BSDatabase
If obj.ConnectDB = 0 Then
Dim cmd As New MySqlCommand(sql, obj.Conn)
Dim rs As MySqlDataReader
rs = cmd.ExecuteReader
While rs.Read
lAns = rs("id")
hasLogs = Convert10ToBool(rs("haslogs"))
End While
rs.Close()
rs = Nothing
cmd = Nothing
obj.CloseDB()
End If
obj = Nothing
Catch ex As Exception
Call LogError("modMain.getAppProjectMainProcessMySQL", ex.Message.ToString)
End Try
Return lAns
End Function
''' <summary>
''' Gets the Log file name and path from the database for this main process
''' </summary>
''' <param name="apid"></param>
''' <returns></returns>
Function GetLogPathMySql(apid As Long) As String
Dim sAns As String = ""
Try
Dim obj As New BurnSoft.BSDatabase
If obj.ConnectDB() = 0 Then
Dim sql As String = "select * from app_project_main_log where apmid=" & APID
Dim cmd As New MySqlCommand(sql, obj.Conn)
Dim rs As MySqlDataReader
rs = cmd.ExecuteReader
While rs.Read
sAns = rs("logpath") & "\" & rs("logname")
End While
rs.Close()
rs = Nothing
cmd = Nothing
obj.CloseDB()
End If
obj = Nothing
Catch ex As Exception
Call LogError("modMain.GetLogPathMySQL", ex.Message.ToString)
End Try
Return sAns
End Function
''' <summary>
''' Get the latest session that was just entered into the database
''' </summary>
''' <returns>id</returns>
Function GetSessionIdmySql() As Long
Dim lAns As Long = 0
Try
Dim sql As String = "SELECT id from monitoring_session where APNID=" & PROCESS_ID & " and AID=" & AGENT_ID &
" order by id desc limit 1"
Dim obj As New BurnSoft.BSDatabase
If obj.ConnectDB = 0 Then
Dim cmd As New MySqlCommand(sql, obj.Conn)
Dim rs As MySqlDataReader
rs = cmd.ExecuteReader
While rs.Read
lAns = rs("id")
End While
rs.Close()
rs = Nothing
cmd = Nothing
obj.CloseDB()
obj = Nothing
End If
Catch ex As Exception
Call LogError("modmain.getSessionIDMySQL", ex.Message.ToString)
End Try
Return lAns
End Function
#End Region
#Region "Database Functions and Subs"
''' <summary>
''' Create a new Session Marker in the database and set the Global
''' variable SESSIOn_ID
''' </summary>
Sub StartSessionDetails()
Call CreateNewSession()
_UPDATEDSESSION = False
_sessionId = getSessionID()
End Sub
''' <summary>
''' Mark the database that the process has exist the system to close to capture project
''' </summary>
Sub EndSession()
Dim sql As String = "UPDATE monitoring_session set sessionend=CURRENT_TIMESTAMP where ID=" & _sessionId
Call ConnExec(sql)
End Sub
''' <summary>
''' Get the main application ID doem the database based on the name of the process
''' </summary>
''' <param name="processName"></param>
''' <param name="hasLogs"></param>
''' <returns></returns>
Function GetAppProjectMainProcess(processName As String, Optional ByRef hasLogs As Boolean = False) As Long
Dim lAns As Long = 0
If Not _uselocal Then
lAns = getAppProjectMainProcessMySQL(processName, hasLogs)
Else
lAns = GetAppProjectMainProcessSqlIte(processName, hasLogs)
End If
Return lAns
End Function
''' <summary>
''' Get the Log Path and details based on the main application ID
''' </summary>
''' <param name="apid"></param>
''' <returns></returns>
Function GetLogPath(apid As Long) As String
Dim sAns As String = ""
If Not _uselocal Then
sAns = GetLogPathMySQL(apid)
Else
sAns = GetLogPathSQLite(apid)
End If
Return sAns
End Function
''' <summary>
''' Move between the main database and the local database to execute sql statements
''' </summary>
''' <param name="SQL"></param>
Sub ConnExec(SQL As String)
If Not _uselocal Then
Dim Obj As New BurnSoft.BSDatabase
Obj.ConnExe(SQL)
Obj = Nothing
Else
Dim Obj As New BurnSoft.BSSqliteDatabase
Obj.ConnExe(SQL)
Obj = Nothing
End If
End Sub
''' <summary>
''' Get the latest session that was just entered into the database
''' </summary>
''' <returns>id</returns>
Function getSessionID() As Long
Dim lAns As Long = 0
If Not _uselocal Then
lAns = getSessionIDMySQL()
Else
lAns = getSessionIDSQLite()
End If
Return lAns
End Function
''' <summary>
''' Create a new sessiont in the database
''' </summary>
Sub CreateNewSession()
Dim SQL As String = "INSERT INTO monitoring_session (APNID, AID) VALUES (" & PROCESS_ID & "," & AGENT_ID & ")"
Call ConnExec(SQL)
End Sub
''' <summary>
''' Update the Current Session with Details from the app such as version, company and dates that are in the application details.
''' </summary>
''' <param name="SID"></param>
''' <param name="appversion"></param>
''' <param name="appcomany"></param>
''' <param name="applastaccess"></param>
''' <param name="applastwrite"></param>
''' <param name="createddatetime"></param>
Sub UpdateSessionWithAppDetails(SID As Long, appversion As String, appcomany As String, applastaccess As String, applastwrite As String, createddatetime As String)
Try
If Not _UPDATEDSESSION Then
Dim SQL As String = "UPDATE monitoring_session set appversion='" & appversion & "', appcomany='" & appcomany & "', applastaccess='" & applastaccess &
"', applastwrite='" & applastwrite & "', createddatetime='" & createddatetime & "' where ID=" & SID
Call ConnExec(SQL)
_UPDATEDSESSION = True
End If
Catch ex As Exception
_UPDATEDSESSION = True
End Try
End Sub
''' <summary>
''' Insert the information gathered about the process into the database
''' </summary>
''' <param name="SessionID"></param>
''' <param name="apnid"></param>
''' <param name="apmpid"></param>
''' <param name="aid"></param>
''' <param name="imagename"></param>
''' <param name="username"></param>
''' <param name="cpu"></param>
''' <param name="memoryused"></param>
''' <param name="ihandles"></param>
''' <param name="threads"></param>
''' <param name="commandline"></param>
Sub InsertIntoProcessStats(SessionID As String, apnid As String, apmpid As String, aid As String, imagename As String,
username As String, cpu As String, memoryused As String, ihandles As String, threads As String,
commandline As String)
Try
Dim SQL As String = "INSERT INTO process_stats_main (SessionID,apnid,apmpid,AID,imagename," &
"username,`cpu`,memoryused,handles,threads,commandline) VALUES(" & SessionID & "," &
apnid & "," & apmpid & "," & aid & ",'" & imagename & "','" & username & "'," &
cpu & "," & memoryused & "," & ihandles & "," & threads & ",'" & commandline & "')"
Call BuggerMe(SQL, "modMain.InsertIntoProcessStats", "high")
Call ConnExec(SQL)
Catch ex As Exception
Call LogError("modMain.InsertIntoProcessStats", ex.Message.ToString)
End Try
End Sub
#End Region
#Region "Other Subs and Functions"
''' <summary>
''' Go through the log file and insert the lines from the log file into the database
''' </summary>
''' <param name="sFile"></param>
''' <param name="FileName"></param>
''' <param name="APID"></param>
''' <param name="SID"></param>
Sub ProcessLogFile(sFile As String, FileName As String, APID As Long, SID As Long)
Dim fr As StreamReader = New StreamReader(sFile)
Dim ObjOF As New BSOtherObjects
Dim SQL As String = ""
Do Until fr.EndOfStream
Dim sLine As String = ObjOF.FC(fr.ReadLine)
SQL = "INSERT INTO logs_main (sessionid,APNID,filename,logdetails) VALUES (" & SID &
"," & APID & ",'" & FileName & "','" & sLine & "')"
Call ConnExec(SQL)
Loop
fr.Close()
fr = Nothing
ObjOF = Nothing
End Sub
''' <summary>
''' Quickly Convert a 1 or 0 value to true or false
''' </summary>
''' <param name="iValue"></param>
''' <returns></returns>
Function Convert10ToBool(iValue As Integer) As Boolean
Dim bAns As Boolean = False
If iValue = 1 Then bAns = True
Return bAns
End Function
''' <summary>
''' Start the BSAP_SubAppMonior to look for any sub/child processes that may result from this main application
''' </summary>
Sub StartSubProcessMonitor()
'TODO: Need to work this into running the subapp
Dim subApp As String = "BSAP_SubAppMonitor.exe"
'Need to Pass Time_interval Process_ID and Main AgentID to Process
End Sub
''' <summary>
''' Set Global Vars
''' </summary>
Sub Init()
If Not USE_TEST_INIT Then
Dim objO As New BSOtherObjects
PROCESS_NAME = objO.GetCommand("name", "")
PROCESS_ID = objO.GetCommand("pid", 0)
AGENT_ID = objO.GetCommand("aid", 0)
_param = objO.GetCommand("param","")
_offline = objO.GetCommand("offline",False)
TIMER_INTERVAL = objO.GetCommand("interval", 0) * 60000
If TIMER_INTERVAL = 0 Then
TIMER_INTERVAL = System.Configuration.ConfigurationManager.AppSettings("TIMER_INTERVAL")
End If
objO = Nothing
If Len(System.Configuration.ConfigurationManager.AppSettings("APP_PATH")) = 0 Then
_appPath = Application.StartupPath
Else
_appPath = System.Configuration.ConfigurationManager.AppSettings("APP_PATH")
End If
BUGFILE_LEVEL = System.Configuration.ConfigurationManager.AppSettings("BUGFILE_LEVEL")
DO_DEBUG = CBool(System.Configuration.ConfigurationManager.AppSettings("DEBUG"))
DEBUG_LOGFILE = _appPath & "\" & System.Configuration.ConfigurationManager.AppSettings("BUGFILE")
MyLogFile = _appPath & "\" & System.Configuration.ConfigurationManager.AppSettings("LOGFILE")
CONSOLEMODE = CBool(System.Configuration.ConfigurationManager.AppSettings("CONSOLE"))
USE_LOGFILE = CBool(System.Configuration.ConfigurationManager.AppSettings("USE_LOGFILE"))
DBHOST = System.Configuration.ConfigurationManager.AppSettings("DB_HOST")
Else
PROCESS_NAME = "BSMyGunCollection.exe"
PROCESS_ID = 2
AGENT_ID = 1
TIMER_INTERVAL = 1 * 60000
End If
If (Not _offline) Then
If PROCESS_ID = 0 Or AGENT_ID = 0 Then
LogError("modMail.Init", "Missing Agent ID or Process ID")
Call ExitApp()
End If
Else
If PROCESS_ID = 0 Then
LogError("modMail.Init", "Missing Process ID")
Call ExitApp()
End If
End If
End Sub
''' <summary>
''' Properly exit the application
''' </summary>
''' <param name="exitValue"></param>
Sub ExitApp(Optional ByVal exitValue As Integer = 0)
Application.Exit()
Environment.Exit(ExitValue)
End Sub
Sub GetExeDetails(fullAppPath As String)
Try
If Not _UPDATEDSESSION Then
Dim objFs As New FileIO
Dim appVersion As String = objFs.GetFileVersion(FullAppPath)
Dim appComp As String = objFs.GetFileCompany(FullAppPath)
Dim appLastAccess As String = objFs.GetLastAccessDateTime(FullAppPath)
Dim appGetLastWrite As String = objFs.GetLastWriteDateTime(FullAppPath)
Dim createdDateTime As String = objFs.GetCreationDateTime(FullAppPath)
Call UpdateSessionWithAppDetails(_sessionId, appVersion, appComp, appLastAccess, appGetLastWrite, createdDateTime)
End If
Catch ex As Exception
Dim sMsg As String = ex.Message.ToString
Dim errorNum As Long = Err.Number
Select Case errorNum
Case 5
sMsg &= " ( " & FullAppPath & " )"
End Select
sMsg = Err.Number & "::" & sMsg
_UPDATEDSESSION = True
LogError("modMain.GetExeDetails", sMsg)
End Try
End Sub
''' <summary>
''' Collect the information needed to monitor the process
''' </summary>
''' <param name="myProcess"></param>
''' <param name="processActive"></param>
Sub CollectData(myProcess As String, ByRef processActive As Boolean)
Try
Dim myPid As String = ""
Dim processCount As Integer = 0
Dim cpu As Double = 0
Dim objP As New BurnSoft.BSProcessInfo
Dim username As String = objP.GetProcessOwner(MyProcess)
BuggerMe("username=" & username)
ProcessActive = objP.ProcessExists(MyProcess, myPid, processCount)
If ProcessActive Then
Dim activePath As String = Replace(objP.GetProcessCommandLine(myPid), "\", "//")
BuggerMe("Full Active Path: " & activePath)
Dim fullAppPath As String = ""
If IsDBNull(activePath) Then
fullAppPath = activePath.Replace(Chr(34), "")
End If
BuggerMe("FullPath Formated: " & fullAppPath)
If not _offline Then If Not _UPDATEDSESSION Then Call GetExeDetails(fullAppPath)
If LAST_CPU_VALUE = 0 Then
cpu = objP.GetCPUProcessStarting(Replace(MyProcess, ".exe", ""), LAST_CPU_VALUE)
Else
cpu = objP.GetProcessCPUTime(Replace(MyProcess, ".exe", ""), LAST_CPU_VALUE, LAST_CPU_VALUE)
End If
If not _offline Then
Call InsertIntoProcessStats(_sessionId, PROCESS_ID, _appProjectMainProcessId, AGENT_ID, MyProcess, username,
cpu, objP.GetProcessMemoryUseage(Replace(MyProcess, ".exe", "")),
objP.GetProccessHandleCount(myPid), objP.GetProcessThreadCount(myPid), activePath)
Else
Call InsertIntoFile( MyProcess, username,
cpu, objP.GetProcessMemoryUseage(Replace(MyProcess, ".exe", "")),
objP.GetProccessHandleCount(myPid), objP.GetProcessThreadCount(myPid), activePath)
End If
End If
Catch ex As Exception
LogError("modMain.CollectData", ex.Message.ToString)
End Try
End Sub
Sub InsertIntoFile (imagename As String,
username As String, cpu As String, memoryused As String, ihandles As String, threads As String,
commandline As String)
Try
Dim logName as String = String.Format("{0}-{1}.csv",imagename,DateTime.Now.ToString("yyyMMdd"))
Dim obj as New FileIO
Dim fullPath as String = _appPath & "\logs\" & logName
If ( Not obj.FileExists(fullPath))
'Dim sHeader = "User Name" & vbTab & "CPU" & vbTab & "Memory Used" & vbTab & "Handles" & vbTab & "Threads" & vbTab & "Command Line"
Dim sHeader = "," & "User Name" & "," & "CPU" & "," & "Memory Used" & "," & "Handles" & "," & "Threads" & "," & "Command Line"
obj.LogFile(fullPath,sHeader)
End If
'Dim sLine as String = username & vbTab & cpu & vbTab & memoryused & vbTab & ihandles & vbTab & threads & vbTab & commandline
Dim sLine as String = "," & username & "," & cpu & "," & memoryused & "," & ihandles & "," & threads & "," & commandline
obj.LogFile(fullPath,sLine)
Catch ex As Exception
LogError("modMain.InsertIntoFile", ex.Message.ToString)
End Try
End Sub
#End Region
''' <summary>
''' Starting Point for application
''' </summary>
Sub Main()
Try
Call INIT()
if Not _offline Then
Dim objN As New BSNetwork
If objN.DeviceIsUp(DBHOST) Then
_uselocal = False
Else
_uselocal = True
End If
objN = Nothing
If _uselocal Then
Call LogError("modMain.Main", "Unabled to connnect to database host " & DBHOST)
Call BuggerMe("Using Local Database", "modMain.Main")
Else
Call BuggerMe("Using Remote Database " & DBHOST, "modMain.Main")
End If
Dim hasLogs As Boolean = False
_appProjectMainProcessId = GetAppProjectMainProcess(PROCESS_NAME, hasLogs)
BuggerMe("_appProjectMainProcessId=" & _appProjectMainProcessId)
'Start up a session in the database
Call StartSessionDetails()
'Start Watching the process for details
LAST_CPU_VALUE = 0
Dim processActive As Boolean = True
Do While processActive
Call BuggerMe("Starting Data Collection at " & Now, "modMain.Main", "medium")
Call CollectData(PROCESS_NAME, processActive)
Call BuggerMe("Ending Data Collection at " & Now, "modMain.Main", "medium")
If processActive Then Threading.Thread.Sleep(TIMER_INTERVAL)
Loop
'Check to see if there was any log files left by the application after it exit the system
If hasLogs Then
BuggerMe("Looking for Logs!", "modMain.Main", "medium")
Dim logLocation As String = GetLogPath(_appProjectMainProcessId)
BuggerMe("LogFile: " & logLocation)
Dim objF As New FileIO
If objF.FileExists(logLocation) Then
BuggerMe("Processing Logs!", "modMain.Main", "medium")
Call ProcessLogFile(logLocation, objF.GetNameOfFile(logLocation), PROCESS_ID, _sessionId)
BuggerMe("Deleting log file!")
objF.DeleteFile(logLocation)
Else
BuggerMe(logLocation & " not found!", "modMain.Main", "medium")
End If
BuggerMe("End of looking for Logs!", "modMain.Main", "medium")
End If
'Mark the recording secction as ended in the database
Call EndSession()
Else
Call BuggerMe("OFFLINE MODE WRITING TO FLAT FILES", "modMain.Main")
LAST_CPU_VALUE = 0
Dim processActive As Boolean = True
Do While processActive
Call BuggerMe("Starting Data Collection at " & Now, "modMain.Main", "medium")
Call CollectData(PROCESS_NAME, processActive)
Call BuggerMe("Ending Data Collection at " & Now, "modMain.Main", "medium")
If processActive Then Threading.Thread.Sleep(TIMER_INTERVAL)
Loop
End If
Catch ex As Exception
LogError("modMain.Main", ex.Message.ToString)
End Try
End Sub
End Module
|
burnsoftnet/BSApplicationProfiler
|
BSAP_AppMonitor/modMain.vb
|
Visual Basic
|
mit
| 25,587
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.EasyNotepad.Form1
End Sub
End Class
End Namespace
|
ZetkoOfficial/EasyNotepad
|
Application/EasyNotepad/EasyNotepad/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,477
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34209
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.Network_Search.Form1
End Sub
End Class
End Namespace
|
codingeass/Shared-Network-Files
|
Network Search/My Project/Application.Designer.vb
|
Visual Basic
|
apache-2.0
| 1,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.Collections.Immutable
Imports System.Globalization
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The VisualBasicCommandLineParser class contains members used to perform various Visual Basic command line parsing operations.
''' </summary>
Public Class VisualBasicCommandLineParser
Inherits CommandLineParser
''' <summary>
''' Gets the current command line parser.
''' </summary>
Public Shared ReadOnly Property [Default] As VisualBasicCommandLineParser = New VisualBasicCommandLineParser()
''' <summary>
''' Gets the current interactive command line parser.
''' </summary>
Public Shared ReadOnly Property Interactive As VisualBasicCommandLineParser = New VisualBasicCommandLineParser(isInteractive:=True)
''' <summary>
''' Creates a new command line parser.
''' </summary>
''' <param name="isInteractive">An optional parameter indicating indicating whether to create a interactive command line parser.</param>
Public Sub New(Optional isInteractive As Boolean = False)
MyBase.New(VisualBasic.MessageProvider.Instance, isInteractive)
End Sub
Private Const s_win32Manifest As String = "win32manifest"
Private Const s_win32Icon As String = "win32icon"
Private Const s_win32Res As String = "win32resource"
''' <summary>
''' Gets the standard Visual Basic source file extension
''' </summary>
''' <returns>A string representing the standard Visual Basic source file extension.</returns>
Protected Overrides ReadOnly Property RegularFileExtension As String
Get
Return ".vb"
End Get
End Property
''' <summary>
''' Gets the standard Visual Basic script file extension.
''' </summary>
''' <returns>A string representing the standard Visual Basic script file extension.</returns>
Protected Overrides ReadOnly Property ScriptFileExtension As String
Get
Return ".vbx"
End Get
End Property
Friend NotOverridable Overrides Function CommonParse(args As IEnumerable(Of String), baseDirectory As String, sdkDirectory As String, additionalReferenceDirectories As String) As CommandLineArguments
Return Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories)
End Function
''' <summary>
''' Parses a command line.
''' </summary>
''' <param name="args">A collection of strings representing the command line arguments.</param>
''' <param name="baseDirectory">The base directory used for qualifying file locations.</param>
''' <param name="sdkDirectory">The directory to search for mscorlib.</param>
''' <param name="additionalReferenceDirectories">A string representing additional reference paths.</param>
''' <returns>A CommandLineArguments object representing the parsed command line.</returns>
Public Shadows Function Parse(args As IEnumerable(Of String), baseDirectory As String, sdkDirectory As String, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments
Const GenerateFileNameForDocComment As String = "USE-OUTPUT-NAME"
Dim diagnostics As List(Of Diagnostic) = New List(Of Diagnostic)()
Dim flattenedArgs As List(Of String) = New List(Of String)()
Dim scriptArgs As List(Of String) = If(IsInteractive, New List(Of String)(), Nothing)
' normalized paths to directories containing response files:
Dim responsePaths As New List(Of String)
FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory, responsePaths)
Dim displayLogo As Boolean = True
Dim displayHelp As Boolean = False
Dim outputLevel As OutputLevel = OutputLevel.Normal
Dim optimize As Boolean = False
Dim checkOverflow As Boolean = True
Dim concurrentBuild As Boolean = True
Dim emitPdb As Boolean = False
Dim noStdLib As Boolean = False
Dim utf8output As Boolean = False
Dim outputFileName As String = Nothing
Dim outputDirectory As String = baseDirectory
Dim documentationPath As String = Nothing
Dim errorLogPath As String = Nothing
Dim parseDocumentationComments As Boolean = False ' Don't just null check documentationFileName because we want to do this even if the file name is invalid.
Dim outputKind As OutputKind = OutputKind.ConsoleApplication
Dim ssVersion As SubsystemVersion = SubsystemVersion.None
Dim languageVersion As LanguageVersion = LanguageVersion.VisualBasic14
Dim mainTypeName As String = Nothing
Dim win32ManifestFile As String = Nothing
Dim win32ResourceFile As String = Nothing
Dim win32IconFile As String = Nothing
Dim noWin32Manifest As Boolean = False
Dim managedResources = New List(Of ResourceDescription)()
Dim sourceFiles = New List(Of CommandLineSourceFile)()
Dim hasSourceFiles = False
Dim additionalFiles = New List(Of CommandLineSourceFile)()
Dim codepage As Encoding = Nothing
Dim checksumAlgorithm = SourceHashAlgorithm.Sha1
Dim defines As IReadOnlyDictionary(Of String, Object) = Nothing
Dim metadataReferences = New List(Of CommandLineReference)()
Dim analyzers = New List(Of CommandLineAnalyzerReference)()
Dim sdkPaths As New List(Of String)()
Dim libPaths As New List(Of String)()
Dim keyFileSearchPaths = New List(Of String)()
Dim globalImports = New List(Of GlobalImport)
Dim rootNamespace As String = ""
Dim optionStrict As OptionStrict = OptionStrict.Off
Dim optionInfer As Boolean = False ' MSDN says: ...The compiler default for this option is /optioninfer-.
Dim optionExplicit As Boolean = True
Dim optionCompareText As Boolean = False
Dim embedVbCoreRuntime As Boolean = False
Dim platform As Platform = Platform.AnyCpu
Dim preferredUILang As CultureInfo = Nothing
Dim fileAlignment As Integer = 0
Dim baseAddress As ULong = 0
Dim highEntropyVA As Boolean = False
Dim vbRuntimePath As String = Nothing
Dim includeVbRuntimeReference As Boolean = True
Dim generalDiagnosticOption As ReportDiagnostic = ReportDiagnostic.Default
' Diagnostic ids specified via /nowarn /warnaserror must be processed in case-insensitive fashion.
Dim specificDiagnosticOptionsFromRuleSet = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer)
Dim specificDiagnosticOptionsFromGeneralArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer)
Dim specificDiagnosticOptionsFromSpecificArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer)
Dim specificDiagnosticOptionsFromNoWarnArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer)
Dim keyFileSetting As String = Nothing
Dim keyContainerSetting As String = Nothing
Dim delaySignSetting As Boolean? = Nothing
Dim moduleAssemblyName As String = Nothing
Dim moduleName As String = Nothing
Dim sqmsessionguid As Guid = Nothing
Dim touchedFilesPath As String = Nothing
Dim features = New List(Of String)()
Dim reportAnalyzer As Boolean = False
' Process ruleset files first so that diagnostic severity settings specified on the command line via
' /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file.
If Not IsInteractive Then
For Each arg In flattenedArgs
Dim name As String = Nothing
Dim value As String = Nothing
If TryParseOption(arg, name, value) AndAlso (name = "ruleset") Then
Dim unquoted = RemoveAllQuotes(value)
If String.IsNullOrEmpty(unquoted) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file>")
Continue For
End If
generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(specificDiagnosticOptionsFromRuleSet, diagnostics, unquoted, baseDirectory)
End If
Next
End If
For Each arg In flattenedArgs
Debug.Assert(Not arg.StartsWith("@", StringComparison.Ordinal))
Dim name As String = Nothing
Dim value As String = Nothing
If Not TryParseOption(arg, name, value) Then
sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics))
hasSourceFiles = True
Continue For
End If
Select Case name
Case "?", "help"
If value IsNot Nothing Then
Exit Select
End If
displayHelp = True
Continue For
Case "r", "reference"
metadataReferences.AddRange(ParseAssemblyReferences(name, value, diagnostics, embedInteropTypes:=False))
Continue For
Case "a", "analyzer"
analyzers.AddRange(ParseAnalyzers(name, value, diagnostics))
Continue For
Case "d", "define"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<symbol_list>")
Continue For
End If
Dim conditionalCompilationDiagnostics As IEnumerable(Of Diagnostic) = Nothing
defines = ParseConditionalCompilationSymbols(value, conditionalCompilationDiagnostics, defines)
diagnostics.AddRange(conditionalCompilationDiagnostics)
Continue For
Case "imports", "import"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, If(name = "import", ":<str>", ":<import_list>"))
Continue For
End If
ParseGlobalImports(value, globalImports, diagnostics)
Continue For
Case "optionstrict"
If value Is Nothing Then
optionStrict = VisualBasic.OptionStrict.On
ElseIf String.Equals(value, "custom", StringComparison.OrdinalIgnoreCase) Then
optionStrict = VisualBasic.OptionStrict.Custom
Else
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "optionstrict", ":custom")
End If
Continue For
Case "optionstrict+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionstrict")
Continue For
End If
optionStrict = VisualBasic.OptionStrict.On
Continue For
Case "optionstrict-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionstrict")
Continue For
End If
optionStrict = VisualBasic.OptionStrict.Off
Continue For
Case "optioncompare"
If value Is Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "optioncompare", ":binary|text")
ElseIf String.Equals(value, "text", StringComparison.OrdinalIgnoreCase) Then
optionCompareText = True
ElseIf String.Equals(value, "binary", StringComparison.OrdinalIgnoreCase) Then
optionCompareText = False
Else
AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "optioncompare", value)
End If
Continue For
Case "optionexplicit", "optionexplicit+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionexplicit")
Continue For
End If
optionExplicit = True
Continue For
Case "optionexplicit-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionexplicit")
Continue For
End If
optionExplicit = False
Continue For
Case "optioninfer", "optioninfer+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optioninfer")
Continue For
End If
optionInfer = True
Continue For
Case "optioninfer-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optioninfer")
Continue For
End If
optionInfer = False
Continue For
Case "codepage"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "codepage", ":<number>")
Continue For
End If
Dim encoding = TryParseEncodingName(value)
If encoding Is Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_BadCodepage, value)
Continue For
End If
codepage = encoding
Continue For
Case "checksumalgorithm"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "checksumalgorithm", ":<algorithm>")
Continue For
End If
Dim newChecksumAlgorithm = TryParseHashAlgorithmName(value)
If newChecksumAlgorithm = SourceHashAlgorithm.None Then
AddDiagnostic(diagnostics, ERRID.ERR_BadChecksumAlgorithm, value)
Continue For
End If
checksumAlgorithm = newChecksumAlgorithm
Continue For
Case "removeintchecks", "removeintchecks+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "removeintchecks")
Continue For
End If
checkOverflow = False
Continue For
Case "removeintchecks-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "removeintchecks")
Continue For
End If
checkOverflow = True
Continue For
Case "sqmsessionguid"
If String.IsNullOrWhiteSpace(value) = True Then
AddDiagnostic(diagnostics, ERRID.ERR_MissingGuidForOption, value, name)
Else
If Not Guid.TryParse(value, sqmsessionguid) Then
AddDiagnostic(diagnostics, ERRID.ERR_InvalidFormatForGuidForOption, value, name)
End If
End If
Continue For
Case "preferreduilang"
If (String.IsNullOrEmpty(value)) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<string>")
Continue For
End If
Try
preferredUILang = New CultureInfo(value)
If (CorLightup.Desktop.IsUserCustomCulture(preferredUILang)) Then
' Do not use user custom cultures.
preferredUILang = Nothing
End If
Catch ex As CultureNotFoundException
End Try
If preferredUILang Is Nothing Then
AddDiagnostic(diagnostics, ERRID.WRN_BadUILang, value)
End If
Continue For
#If DEBUG Then
Case "attachdebugger"
Debugger.Launch()
Continue For
#End If
End Select
If IsInteractive Then
Select Case name
Case "rp", "referencepath"
' TODO: should it really go to /libpath?
libPaths.AddRange(ParseSeparatedPaths(value))
Continue For
End Select
Else
Select Case name
Case "out"
If String.IsNullOrWhiteSpace(value) Then
' When the value has " " (e.g., "/out: ")
' the Roslyn VB compiler reports "BC 2006 : option 'out' requires ':<file>',
' While the Dev11 VB compiler reports "BC2012 : can't open ' ' for writing,
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file>")
Else
' Even when value is neither null or whitespace, the output file name still could be invalid. (e.g., "/out:sub\ ")
' While the Dev11 VB compiler reports "BC2012: can't open 'sub\ ' for writing,
' the Roslyn VB compiler reports "BC2032: File name 'sub\ ' is empty, contains invalid characters, ..."
' which is generated by the following ParseOutputFile.
ParseOutputFile(value, diagnostics, baseDirectory, outputFileName, outputDirectory)
End If
Continue For
Case "t", "target"
outputKind = ParseTarget(name, value, diagnostics)
Continue For
Case "moduleassemblyname"
value = If(value IsNot Nothing, value.Unquote(), Nothing)
Dim identity As AssemblyIdentity = Nothing
' Note that native compiler also extracts public key, but Roslyn doesn't use it.
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "moduleassemblyname", ":<string>")
ElseIf Not AssemblyIdentity.TryParseDisplayName(value, identity) OrElse
Not MetadataHelpers.IsValidAssemblyOrModuleName(identity.Name) Then
AddDiagnostic(diagnostics, ERRID.ERR_InvalidAssemblyName, value, arg)
Else
moduleAssemblyName = identity.Name
End If
Continue For
Case "rootnamespace"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "rootnamespace", ":<string>")
Continue For
End If
rootNamespace = value
Continue For
Case "doc"
parseDocumentationComments = True
If value Is Nothing Then
' Illegal in C#, but works in VB
documentationPath = GenerateFileNameForDocComment
Continue For
End If
Dim unquoted = RemoveAllQuotes(value)
If unquoted.Length = 0 Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "doc", ":<file>")
Else
documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory, generateDiagnostic:=False)
If String.IsNullOrWhiteSpace(documentationPath) Then
AddDiagnostic(diagnostics, ERRID.WRN_XMLCannotWriteToXMLDocFile2, unquoted, New LocalizableErrorArgument(ERRID.IDS_TheSystemCannotFindThePathSpecified))
documentationPath = Nothing
End If
End If
Continue For
Case "doc+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "doc")
End If
' Seems redundant with default values, but we need to clobber any preceding /doc switches
documentationPath = GenerateFileNameForDocComment
parseDocumentationComments = True
Continue For
Case "doc-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "doc")
End If
' Seems redundant with default values, but we need to clobber any preceding /doc switches
documentationPath = Nothing
parseDocumentationComments = False
Continue For
Case "errorlog"
Dim unquoted = RemoveAllQuotes(value)
If String.IsNullOrEmpty(unquoted) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "errorlog", ":<file>")
Else
errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory)
End If
Continue For
Case "netcf"
' Do nothing as we no longer have any use for implementing this switch and
' want to avoid failing with any warnings/errors
Continue For
Case "libpath"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "libpath", ":<path_list>")
Continue For
End If
libPaths.AddRange(ParseSeparatedPaths(RemoveAllQuotes(value)))
Continue For
Case "sdkpath"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "sdkpath", ":<path>")
Continue For
End If
sdkPaths.Clear()
sdkPaths.AddRange(ParseSeparatedPaths(RemoveAllQuotes(value)))
Continue For
Case "recurse"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "recurse", ":<wildcard>")
Continue For
End If
Dim before As Integer = sourceFiles.Count
sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics))
If sourceFiles.Count > before Then
hasSourceFiles = True
End If
Continue For
Case "addmodule"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "addmodule", ":<file_list>")
Continue For
End If
' NOTE(tomat): Dev10 reports "Command line error BC2017 : could not find library."
' Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
' An error will be reported by the assembly manager anyways.
metadataReferences.AddRange(
ParseSeparatedPaths(value).Select(
Function(path) New CommandLineReference(path, New MetadataReferenceProperties(MetadataImageKind.Module))))
Continue For
Case "l", "link"
metadataReferences.AddRange(ParseAssemblyReferences(name, value, diagnostics, embedInteropTypes:=True))
Continue For
Case "win32resource"
win32ResourceFile = GetWin32Setting(s_win32Res, value, diagnostics)
Continue For
Case "win32icon"
win32IconFile = GetWin32Setting(s_win32Icon, value, diagnostics)
Continue For
Case "win32manifest"
win32ManifestFile = GetWin32Setting(s_win32Manifest, value, diagnostics)
Continue For
Case "nowin32manifest"
If value IsNot Nothing Then
Exit Select
End If
noWin32Manifest = True
Continue For
Case "res", "resource"
Dim embeddedResource = ParseResourceDescription(name, value, baseDirectory, diagnostics, embedded:=True)
If embeddedResource IsNot Nothing Then
managedResources.Add(embeddedResource)
End If
Continue For
Case "linkres", "linkresource"
Dim linkedResource = ParseResourceDescription(name, value, baseDirectory, diagnostics, embedded:=False)
If linkedResource IsNot Nothing Then
managedResources.Add(linkedResource)
End If
Continue For
Case "debug"
' parse only for backwards compat
If value IsNot Nothing Then
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "debug", ":pdbonly|full")
ElseIf Not String.Equals(value, "full", StringComparison.OrdinalIgnoreCase) AndAlso
Not String.Equals(value, "pdbonly", StringComparison.OrdinalIgnoreCase) Then
AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "debug", value)
End If
End If
emitPdb = True
Continue For
Case "debug+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "debug")
End If
emitPdb = True
Continue For
Case "debug-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "debug")
End If
emitPdb = False
Continue For
Case "optimize", "optimize+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optimize")
Continue For
End If
optimize = True
Continue For
Case "optimize-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optimize")
Continue For
End If
optimize = False
Continue For
Case "parallel", "p"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name)
Continue For
End If
concurrentBuild = True
Continue For
Case "parallel+", "p+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1))
Continue For
End If
concurrentBuild = True
Continue For
Case "parallel-", "p-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1))
Continue For
End If
concurrentBuild = False
Continue For
Case "warnaserror", "warnaserror+"
If value Is Nothing Then
generalDiagnosticOption = ReportDiagnostic.Error
specificDiagnosticOptionsFromGeneralArguments.Clear()
For Each pair In specificDiagnosticOptionsFromRuleSet
If pair.Value = ReportDiagnostic.Warn Then
specificDiagnosticOptionsFromGeneralArguments.Add(pair.Key, ReportDiagnostic.Error)
End If
Next
Continue For
End If
AddWarnings(specificDiagnosticOptionsFromSpecificArguments, ReportDiagnostic.Error, ParseWarnings(value))
Continue For
Case "warnaserror-"
If value Is Nothing Then
If generalDiagnosticOption <> ReportDiagnostic.Suppress Then
generalDiagnosticOption = ReportDiagnostic.Default
End If
specificDiagnosticOptionsFromGeneralArguments.Clear()
Continue For
End If
For Each id In ParseWarnings(value)
Dim ruleSetValue As ReportDiagnostic
If specificDiagnosticOptionsFromRuleSet.TryGetValue(id, ruleSetValue) Then
specificDiagnosticOptionsFromSpecificArguments(id) = ruleSetValue
Else
specificDiagnosticOptionsFromSpecificArguments(id) = ReportDiagnostic.Default
End If
Next
Continue For
Case "nowarn"
If value Is Nothing Then
generalDiagnosticOption = ReportDiagnostic.Suppress
specificDiagnosticOptionsFromGeneralArguments.Clear()
For Each pair In specificDiagnosticOptionsFromRuleSet
If pair.Value <> ReportDiagnostic.Error Then
specificDiagnosticOptionsFromGeneralArguments.Add(pair.Key, ReportDiagnostic.Suppress)
End If
Next
Continue For
End If
AddWarnings(specificDiagnosticOptionsFromNoWarnArguments, ReportDiagnostic.Suppress, ParseWarnings(value))
Continue For
Case "langversion"
If value Is Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "langversion", ":<number>")
Continue For
End If
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "langversion", ":<number>")
Else
Select Case value.ToLowerInvariant()
Case "9", "9.0"
languageVersion = LanguageVersion.VisualBasic9
Case "10", "10.0"
languageVersion = LanguageVersion.VisualBasic10
Case "11", "11.0"
languageVersion = LanguageVersion.VisualBasic11
Case "12", "12.0"
languageVersion = LanguageVersion.VisualBasic12
Case "14", "14.0"
languageVersion = LanguageVersion.VisualBasic14
Case Else
AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "langversion", value)
End Select
End If
Continue For
Case "delaysign", "delaysign+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "delaysign")
Continue For
End If
delaySignSetting = True
Continue For
Case "delaysign-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "delaysign")
Continue For
End If
delaySignSetting = False
Continue For
Case "keycontainer"
' NOTE: despite what MSDN says, Dev11 resets '/keyfile' in this case:
'
' MSDN: In case both /keyfile and /keycontainer are specified (either by command-line
' MSDN: option or by custom attribute) in the same compilation, the compiler first tries
' MSDN: the key container. If that succeeds, then the assembly is signed with the
' MSDN: information in the key container. If the compiler does not find the key container,
' MSDN: it tries the file specified with /keyfile. If this succeeds, the assembly is
' MSDN: signed with the information in the key file, and the key information is installed
' MSDN: in the key container (similar to sn -i) so that on the next compilation,
' MSDN: the key container will be valid.
keyFileSetting = Nothing
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "keycontainer", ":<string>")
Else
keyContainerSetting = value
End If
Continue For
Case "keyfile"
' NOTE: despite what MSDN says, Dev11 resets '/keycontainer' in this case:
'
' MSDN: In case both /keyfile and /keycontainer are specified (either by command-line
' MSDN: option or by custom attribute) in the same compilation, the compiler first tries
' MSDN: the key container. If that succeeds, then the assembly is signed with the
' MSDN: information in the key container. If the compiler does not find the key container,
' MSDN: it tries the file specified with /keyfile. If this succeeds, the assembly is
' MSDN: signed with the information in the key file, and the key information is installed
' MSDN: in the key container (similar to sn -i) so that on the next compilation,
' MSDN: the key container will be valid.
keyContainerSetting = Nothing
If String.IsNullOrWhiteSpace(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "keyfile", ":<file>")
Else
keyFileSetting = RemoveAllQuotes(value)
End If
Continue For
Case "highentropyva", "highentropyva+"
If value IsNot Nothing Then
Exit Select
End If
highEntropyVA = True
Continue For
Case "highentropyva-"
If value IsNot Nothing Then
Exit Select
End If
highEntropyVA = False
Continue For
Case "nologo", "nologo+"
If value IsNot Nothing Then
Exit Select
End If
displayLogo = False
Continue For
Case "nologo-"
If value IsNot Nothing Then
Exit Select
End If
displayLogo = True
Continue For
Case "quiet+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "quiet")
Continue For
End If
outputLevel = VisualBasic.OutputLevel.Quiet
Continue For
Case "quiet"
If value IsNot Nothing Then
Exit Select
End If
outputLevel = VisualBasic.OutputLevel.Quiet
Continue For
Case "verbose"
If value IsNot Nothing Then
Exit Select
End If
outputLevel = VisualBasic.OutputLevel.Verbose
Continue For
Case "verbose+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "verbose")
Continue For
End If
outputLevel = VisualBasic.OutputLevel.Verbose
Continue For
Case "quiet-", "verbose-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1))
Continue For
End If
outputLevel = VisualBasic.OutputLevel.Normal
Continue For
Case "utf8output", "utf8output+"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "utf8output")
End If
utf8output = True
Continue For
Case "utf8output-"
If value IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "utf8output")
End If
utf8output = False
Continue For
Case "noconfig"
' It is already handled (see CommonCommandLineCompiler.cs).
Continue For
Case "bugreport"
' Do nothing as we no longer have any use for implementing this switch and
' want to avoid failing with any warnings/errors
' We do no further checking as to a value provided or not and '
' this will cause no diagnostics for invalid values.
Continue For
Case "errorreport"
' Allows any value to be entered and will just silently do nothing
' previously we would validate value for prompt, send Or Queue
' This will cause no diagnostics for invalid values.
Continue For
Case "novbruntimeref"
' The switch is no longer supported and for backwards compat ignored.
Continue For
Case "m", "main"
' MSBuild can result in maintypename being passed in quoted when cyrillic namespace was being used resulting
' in ERRID.ERR_StartupCodeNotFound1 diagnostic. The additional quotes cause problems and quotes are not a
' valid character in typename.
value = RemoveAllQuotes(value)
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<class>")
Continue For
End If
mainTypeName = value
Continue For
Case "subsystemversion"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<version>")
Continue For
End If
Dim version As SubsystemVersion = Nothing
If SubsystemVersion.TryParse(value, version) Then
ssVersion = version
Else
AddDiagnostic(diagnostics, ERRID.ERR_InvalidSubsystemVersion, value)
End If
Continue For
Case "touchedfiles"
Dim unquoted = RemoveAllQuotes(value)
If (String.IsNullOrEmpty(unquoted)) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<touchedfiles>")
Continue For
Else
touchedFilesPath = unquoted
End If
Continue For
Case "fullpaths", "errorendlocation"
UnimplementedSwitch(diagnostics, name)
Continue For
Case "reportanalyzer"
reportAnalyzer = True
Continue For
Case "nostdlib"
If value IsNot Nothing Then
Exit Select
End If
noStdLib = True
Continue For
Case "vbruntime"
If value Is Nothing Then
GoTo lVbRuntimePlus
End If
' NOTE: that Dev11 does not report errors on empty or invalid file specified
vbRuntimePath = RemoveAllQuotes(value)
includeVbRuntimeReference = True
embedVbCoreRuntime = False
Continue For
Case "vbruntime+"
If value IsNot Nothing Then
Exit Select
End If
lVbRuntimePlus:
vbRuntimePath = Nothing
includeVbRuntimeReference = True
embedVbCoreRuntime = False
Continue For
Case "vbruntime-"
If value IsNot Nothing Then
Exit Select
End If
vbRuntimePath = Nothing
includeVbRuntimeReference = False
embedVbCoreRuntime = False
Continue For
Case "vbruntime*"
If value IsNot Nothing Then
Exit Select
End If
vbRuntimePath = Nothing
includeVbRuntimeReference = False
embedVbCoreRuntime = True
Continue For
Case "platform"
If value IsNot Nothing Then
platform = ParsePlatform(name, value, diagnostics)
Else
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "platform", ":<string>")
End If
Continue For
Case "filealign"
fileAlignment = ParseFileAlignment(name, value, diagnostics)
Continue For
Case "baseaddress"
baseAddress = ParseBaseAddress(name, value, diagnostics)
Continue For
Case "ruleset"
' The ruleset arg has already been processed in a separate pass above.
Continue For
Case "features"
If value Is Nothing Then
features.Clear()
Else
features.Add(value)
End If
Continue For
Case "additionalfile"
If String.IsNullOrEmpty(value) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>")
Continue For
End If
additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics))
Continue For
End Select
End If
AddDiagnostic(diagnostics, ERRID.WRN_BadSwitch, arg)
Next
Dim specificDiagnosticOptions = New Dictionary(Of String, ReportDiagnostic)(specificDiagnosticOptionsFromRuleSet, CaseInsensitiveComparison.Comparer)
For Each item In specificDiagnosticOptionsFromGeneralArguments
specificDiagnosticOptions(item.Key) = item.Value
Next
For Each item In specificDiagnosticOptionsFromSpecificArguments
specificDiagnosticOptions(item.Key) = item.Value
Next
For Each item In specificDiagnosticOptionsFromNoWarnArguments
specificDiagnosticOptions(item.Key) = item.Value
Next
If Not IsInteractive AndAlso Not hasSourceFiles AndAlso managedResources.IsEmpty() AndAlso outputKind.IsApplication Then
' VB displays help when there is nothing specified on the command line
If flattenedArgs.Any Then
AddDiagnostic(diagnostics, ERRID.ERR_NoSources)
Else
displayHelp = True
End If
End If
' Prepare SDK PATH
If sdkPaths.Count = 0 Then
sdkPaths.Add(sdkDirectory)
End If
' Locate default 'mscorlib.dll' or 'System.Runtime.dll', if any.
Dim defaultCoreLibraryReference As CommandLineReference? = LoadCoreLibraryReference(sdkPaths, baseDirectory, sdkDirectory)
' If /nostdlib is not specified, load System.dll
' Dev12 does it through combination of CompilerHost::InitStandardLibraryList and CompilerProject::AddStandardLibraries.
If Not noStdLib Then
Dim systemDllPath As String = FindFileInSdkPath(sdkPaths, "System.dll", baseDirectory, sdkDirectory)
If systemDllPath Is Nothing Then
AddDiagnostic(diagnostics, ERRID.WRN_CannotFindStandardLibrary1, "System.dll")
Else
metadataReferences.Add(
New CommandLineReference(systemDllPath, New MetadataReferenceProperties(MetadataImageKind.Assembly)))
End If
' Dev11 also adds System.Core.dll in VbHostedCompiler::CreateCompilerProject()
End If
' Add reference to 'Microsoft.VisualBasic.dll' if needed
If includeVbRuntimeReference Then
If vbRuntimePath Is Nothing Then
Dim msVbDllPath As String = FindFileInSdkPath(sdkPaths, "Microsoft.VisualBasic.dll", baseDirectory, sdkDirectory)
If msVbDllPath Is Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_LibNotFound, "Microsoft.VisualBasic.dll")
Else
metadataReferences.Add(
New CommandLineReference(msVbDllPath, New MetadataReferenceProperties(MetadataImageKind.Assembly)))
End If
Else
metadataReferences.Add(New CommandLineReference(vbRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly)))
End If
End If
' add additional reference paths if specified
If Not String.IsNullOrWhiteSpace(additionalReferenceDirectories) Then
libPaths.AddRange(ParseSeparatedPaths(additionalReferenceDirectories))
End If
' Build search path
Dim searchPaths As ImmutableArray(Of String) = BuildSearchPaths(baseDirectory, sdkPaths, responsePaths, libPaths)
ValidateWin32Settings(noWin32Manifest, win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics)
' Validate root namespace if specified
Debug.Assert(rootNamespace IsNot Nothing)
' NOTE: empty namespace is a valid option
If Not String.Empty.Equals(rootNamespace) Then
rootNamespace = rootNamespace.Unquote()
If String.IsNullOrWhiteSpace(rootNamespace) OrElse Not OptionsValidator.IsValidNamespaceName(rootNamespace) Then
AddDiagnostic(diagnostics, ERRID.ERR_BadNamespaceName1, rootNamespace)
rootNamespace = "" ' To make it pass compilation options' check
End If
End If
' Dev10 searches for the keyfile in the current directory and assembly output directory.
' We always look to base directory and then examine the search paths.
keyFileSearchPaths.Add(baseDirectory)
If baseDirectory <> outputDirectory Then
keyFileSearchPaths.Add(outputDirectory)
End If
Dim compilationName As String = Nothing
GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, moduleAssemblyName, outputFileName, moduleName, compilationName)
If Not IsInteractive AndAlso
Not hasSourceFiles AndAlso
Not managedResources.IsEmpty() AndAlso
outputFileName = Nothing AndAlso
Not flattenedArgs.IsEmpty() Then
AddDiagnostic(diagnostics, ERRID.ERR_NoSourcesOut)
End If
Dim parseOptions = New VisualBasicParseOptions(
languageVersion:=languageVersion,
documentationMode:=If(parseDocumentationComments, DocumentationMode.Diagnose, DocumentationMode.None),
kind:=SourceCodeKind.Regular,
preprocessorSymbols:=AddPredefinedPreprocessorSymbols(outputKind, defines.AsImmutableOrEmpty()),
features:=CompilerOptionParseUtilities.ParseFeatures(features))
Dim scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script)
Dim options = New VisualBasicCompilationOptions(
outputKind:=outputKind,
moduleName:=moduleName,
mainTypeName:=mainTypeName,
scriptClassName:=WellKnownMemberNames.DefaultScriptClassName,
globalImports:=globalImports,
rootNamespace:=rootNamespace,
optionStrict:=optionStrict,
optionInfer:=optionInfer,
optionExplicit:=optionExplicit,
optionCompareText:=optionCompareText,
embedVbCoreRuntime:=embedVbCoreRuntime,
checkOverflow:=checkOverflow,
concurrentBuild:=concurrentBuild,
cryptoKeyContainer:=keyContainerSetting,
cryptoKeyFile:=keyFileSetting,
delaySign:=delaySignSetting,
platform:=platform,
generalDiagnosticOption:=generalDiagnosticOption,
specificDiagnosticOptions:=specificDiagnosticOptions,
optimizationLevel:=If(optimize, OptimizationLevel.Release, OptimizationLevel.Debug),
parseOptions:=parseOptions)
Dim emitOptions = New EmitOptions(
metadataOnly:=False,
debugInformationFormat:=DebugInformationFormat.Pdb,
pdbFilePath:=Nothing, ' to be determined later
outputNameOverride:=Nothing, ' to be determined later
fileAlignment:=fileAlignment,
baseAddress:=baseAddress,
highEntropyVirtualAddressSpace:=highEntropyVA,
subsystemVersion:=ssVersion,
runtimeMetadataVersion:=Nothing)
' add option incompatibility errors if any
diagnostics.AddRange(options.Errors)
If documentationPath Is GenerateFileNameForDocComment Then
documentationPath = PathUtilities.CombineAbsoluteAndRelativePaths(outputDirectory, PathUtilities.RemoveExtension(outputFileName))
documentationPath = documentationPath + ".xml"
End If
Return New VisualBasicCommandLineArguments With
{
.IsInteractive = IsInteractive,
.BaseDirectory = baseDirectory,
.Errors = diagnostics.AsImmutable(),
.Utf8Output = utf8output,
.CompilationName = compilationName,
.OutputFileName = outputFileName,
.OutputDirectory = outputDirectory,
.DocumentationPath = documentationPath,
.ErrorLogPath = errorLogPath,
.SourceFiles = sourceFiles.AsImmutable(),
.Encoding = codepage,
.ChecksumAlgorithm = checksumAlgorithm,
.MetadataReferences = metadataReferences.AsImmutable(),
.AnalyzerReferences = analyzers.AsImmutable(),
.AdditionalFiles = additionalFiles.AsImmutable(),
.ReferencePaths = searchPaths,
.KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(),
.Win32ResourceFile = win32ResourceFile,
.Win32Icon = win32IconFile,
.Win32Manifest = win32ManifestFile,
.NoWin32Manifest = noWin32Manifest,
.DisplayLogo = displayLogo,
.DisplayHelp = displayHelp,
.ManifestResources = managedResources.AsImmutable(),
.CompilationOptions = options,
.ParseOptions = If(IsInteractive, scriptParseOptions, parseOptions),
.EmitOptions = emitOptions,
.ScriptArguments = scriptArgs.AsImmutableOrEmpty(),
.TouchedFilesPath = touchedFilesPath,
.OutputLevel = outputLevel,
.EmitPdb = emitPdb,
.DefaultCoreLibraryReference = defaultCoreLibraryReference,
.PreferredUILang = preferredUILang,
.SqmSessionGuid = sqmsessionguid,
.ReportAnalyzer = reportAnalyzer
}
End Function
Private Function LoadCoreLibraryReference(sdkPaths As List(Of String), baseDirectory As String, sdkDirectory As String) As CommandLineReference?
' Load Core library in Dev11:
' Traditionally VB compiler has hard-coded the name of mscorlib.dll. In the Immersive profile the
' library is called System.Runtime.dll. Ideally we should get rid of the dependency on the name and
' identify the core library as the assembly that contains System.Object. At this point in the compiler,
' it is too early though as we haven't loaded any types or assemblies. Changing this now is a deep
' change. So the workaround here is to allow mscorlib or system.runtime and prefer system.runtime if present.
' There is an extra check to only pick an assembly with no other assembly refs. This is so that is an
' user drops a user-defined binary called System.runtime.dll into the fx directory we still want to pick
' mscorlib.
Dim msCorLibPath As String = FindFileInSdkPath(sdkPaths, "mscorlib.dll", baseDirectory, sdkDirectory)
Dim systemRuntimePath As String = FindFileInSdkPath(sdkPaths, "System.Runtime.dll", baseDirectory, sdkDirectory)
If systemRuntimePath IsNot Nothing Then
If msCorLibPath Is Nothing Then
Return New CommandLineReference(systemRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly))
End If
' Load System.Runtime.dll and see if it has any references
Try
Using metadata = AssemblyMetadata.CreateFromFile(systemRuntimePath)
' Prefer 'System.Runtime.dll' if it does not have any references
If metadata.GetModules()(0).Module.IsLinkedModule AndAlso
metadata.GetAssembly().AssemblyReferences.Length = 0 Then
Return New CommandLineReference(systemRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly))
End If
End Using
Catch
' If we caught anything, there is something wrong with System.Runtime.dll and we fall back to mscorlib.dll
End Try
' Otherwise prefer 'mscorlib.dll'
Return New CommandLineReference(msCorLibPath, New MetadataReferenceProperties(MetadataImageKind.Assembly))
End If
If msCorLibPath IsNot Nothing Then
' We return a reference to 'mscorlib.dll'
Return New CommandLineReference(msCorLibPath, New MetadataReferenceProperties(MetadataImageKind.Assembly))
End If
Return Nothing
End Function
Private Function FindFileInSdkPath(sdkPaths As List(Of String), fileName As String, baseDirectory As String, sdkDirectory As String) As String
For Each path In sdkPaths
Dim absolutePath = FileUtilities.ResolveRelativePath(If(path, sdkDirectory), baseDirectory)
If absolutePath IsNot Nothing Then
Dim filePath = PathUtilities.CombineAbsoluteAndRelativePaths(absolutePath, fileName)
If PortableShim.File.Exists(filePath) Then
Return filePath
End If
End If
Next
Return Nothing
End Function
Private Function GetWin32Setting(arg As String, value As String, diagnostics As List(Of Diagnostic)) As String
If (value = Nothing) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, arg, ":<file>")
Else
Dim noQuotes As String = RemoveAllQuotes(value)
If (String.IsNullOrWhiteSpace(noQuotes)) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, arg, ":<file>")
Else
Return noQuotes
End If
End If
Return Nothing
End Function
Private Shared Function BuildSearchPaths(baseDirectory As String, sdkPaths As List(Of String), responsePaths As List(Of String), libPaths As List(Of String)) As ImmutableArray(Of String)
Dim builder = ArrayBuilder(Of String).GetInstance()
' Match how Dev11 builds the list of search paths
' see void GetSearchPath(CComBSTR& strSearchPath)
' current folder -- base directory is searched by default by the FileResolver
' SDK path is specified or current runtime directory
AddNormalizedPaths(builder, sdkPaths, baseDirectory)
' Response file path, see the following comment from Dev11:
' // .NET FX 3.5 will have response file in the FX 3.5 directory but SdkPath will still be in 2.0 directory.
' // Therefore we need to make sure the response file directories are also on the search path
' // so response file authors can continue to use relative paths in the response files.
builder.AddRange(responsePaths)
' libpath
AddNormalizedPaths(builder, libPaths, baseDirectory)
Return builder.ToImmutableAndFree()
End Function
Private Shared Sub AddNormalizedPaths(builder As ArrayBuilder(Of String), paths As List(Of String), baseDirectory As String)
For Each path In paths
Dim normalizedPath = FileUtilities.NormalizeRelativePath(path, basePath:=Nothing, baseDirectory:=baseDirectory)
If normalizedPath Is Nothing Then
' just ignore invalid paths, native compiler doesn't report any errors
Continue For
End If
builder.Add(normalizedPath)
Next
End Sub
Private Shared Sub ValidateWin32Settings(noWin32Manifest As Boolean, win32ResSetting As String, win32IconSetting As String, win32ManifestSetting As String, outputKind As OutputKind, diagnostics As List(Of Diagnostic))
If noWin32Manifest AndAlso (win32ManifestSetting IsNot Nothing) Then
AddDiagnostic(diagnostics, ERRID.ERR_ConflictingManifestSwitches)
End If
If win32ResSetting IsNot Nothing Then
If win32IconSetting IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_IconFileAndWin32ResFile)
End If
If win32ManifestSetting IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_CantHaveWin32ResAndManifest)
End If
End If
If win32ManifestSetting IsNot Nothing AndAlso outputKind.IsNetModule() Then
AddDiagnostic(diagnostics, ERRID.WRN_IgnoreModuleManifest)
End If
End Sub
Private Shared Function ParseTarget(optionName As String, value As String, diagnostics As IList(Of Diagnostic)) As OutputKind
Select Case If(value, "").ToLowerInvariant()
Case "exe"
Return OutputKind.ConsoleApplication
Case "winexe"
Return OutputKind.WindowsApplication
Case "library"
Return OutputKind.DynamicallyLinkedLibrary
Case "module"
Return OutputKind.NetModule
Case "appcontainerexe"
Return OutputKind.WindowsRuntimeApplication
Case "winmdobj"
Return OutputKind.WindowsRuntimeMetadata
Case ""
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, optionName, ":exe|winexe|library|module|appcontainerexe|winmdobj")
Return OutputKind.ConsoleApplication
Case Else
AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, optionName, value)
Return OutputKind.ConsoleApplication
End Select
End Function
Private Function ParseAssemblyReferences(name As String, value As String, diagnostics As IList(Of Diagnostic), embedInteropTypes As Boolean) As IEnumerable(Of CommandLineReference)
If String.IsNullOrEmpty(value) Then
' TODO: localize <file_list>?
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>")
Return SpecializedCollections.EmptyEnumerable(Of CommandLineReference)()
End If
' TODO: how does VB handle quotes, separators, ...?
' /r:"reference"
' /r:reference;reference
' /r:"path;containing;semicolons"
' /r:"unterminated_quotes
' /r:"quotes"in"the"middle
Return ParseSeparatedPaths(value).
Select(Function(path) New CommandLineReference(path, New MetadataReferenceProperties(MetadataImageKind.Assembly, embedInteropTypes:=embedInteropTypes)))
End Function
Private Function ParseAnalyzers(name As String, value As String, diagnostics As IList(Of Diagnostic)) As IEnumerable(Of CommandLineAnalyzerReference)
If String.IsNullOrEmpty(value) Then
' TODO: localize <file_list>?
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>")
Return SpecializedCollections.EmptyEnumerable(Of CommandLineAnalyzerReference)()
End If
Return ParseSeparatedPaths(value).
Select(Function(path)
Return New CommandLineAnalyzerReference(path)
End Function)
End Function
' See ParseCommandLine in vbc.cpp.
Friend Overloads Shared Function ParseResourceDescription(name As String, resourceDescriptor As String, baseDirectory As String, diagnostics As IList(Of Diagnostic), embedded As Boolean) As ResourceDescription
If String.IsNullOrEmpty(resourceDescriptor) Then
AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<resinfo>")
Return Nothing
End If
' NOTE: these are actually passed to out parameters of .ParseResourceDescription.
Dim filePath As String = Nothing
Dim fullPath As String = Nothing
Dim fileName As String = Nothing
Dim resourceName As String = Nothing
Dim accessibility As String = Nothing
ParseResourceDescription(
resourceDescriptor,
baseDirectory,
True,
filePath,
fullPath,
fileName,
resourceName,
accessibility)
If String.IsNullOrWhiteSpace(filePath) Then
AddInvalidSwitchValueDiagnostic(diagnostics, name, filePath)
Return Nothing
End If
If fullPath Is Nothing OrElse fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 Then
AddDiagnostic(diagnostics, ERRID.FTL_InputFileNameTooLong, filePath)
Return Nothing
End If
Dim isPublic As Boolean
If String.IsNullOrEmpty(accessibility) Then
' If no accessibility is given, we default to "public".
' NOTE: Dev10 treats empty the same as null (the difference being that empty indicates a comma after the resource name).
' NOTE: Dev10 distinguishes between empty and whitespace-only.
isPublic = True
ElseIf String.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase) Then
isPublic = True
ElseIf String.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase) Then
isPublic = False
Else
AddInvalidSwitchValueDiagnostic(diagnostics, name, accessibility)
Return Nothing
End If
Dim dataProvider As Func(Of Stream) = Function()
' Use FileShare.ReadWrite because the file could be opened by the current process.
' For example, it Is an XML doc file produced by the build.
Return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite)
End Function
Return New ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs:=False)
End Function
Private Shared Sub AddInvalidSwitchValueDiagnostic(diagnostics As IList(Of Diagnostic), ByVal name As String, ByVal nullStringText As String)
If String.IsNullOrEmpty(name) Then
' NOTE: "(null)" to match Dev10.
' CONSIDER: should this be a resource string?
name = "(null)"
End If
AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, name, nullStringText)
End Sub
Private Shared Sub ParseGlobalImports(value As String, globalImports As List(Of GlobalImport), errors As List(Of Diagnostic))
Dim importsArray As String() = value.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
For Each importNamespace In importsArray
Dim importDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
Dim import = GlobalImport.Parse(importNamespace, importDiagnostics)
errors.AddRange(importDiagnostics)
globalImports.Add(import)
Next
End Sub
''' <summary>
''' Converts a sequence of definitions provided by a caller (public API) into map
''' of definitions used internally.
''' </summary>
''' <exception cref="ArgumentException">Invalid value provided.</exception>
Private Shared Function PublicSymbolsToInternalDefines(symbols As IEnumerable(Of KeyValuePair(Of String, Object)),
parameterName As String) As ImmutableDictionary(Of String, InternalSyntax.CConst)
Dim result = ImmutableDictionary.CreateBuilder(Of String, InternalSyntax.CConst)(CaseInsensitiveComparison.Comparer)
If symbols IsNot Nothing Then
For Each symbol In symbols
Dim constant = InternalSyntax.CConst.TryCreate(symbol.Value)
If constant Is Nothing Then
Throw New ArgumentException(String.Format(ErrorFactory.IdToString(ERRID.IDS_InvalidPreprocessorConstantType, Culture), symbol.Key, symbol.Value.GetType()), parameterName)
End If
result(symbol.Key) = constant
Next
End If
Return result.ToImmutable()
End Function
''' <summary>
''' Converts ImmutableDictionary of definitions used internallyinto IReadOnlyDictionary of definitions
''' returned to a caller (of public API)
''' </summary>
Private Shared Function InternalDefinesToPublicSymbols(defines As ImmutableDictionary(Of String, InternalSyntax.CConst)) As IReadOnlyDictionary(Of String, Object)
Dim result = ImmutableDictionary.CreateBuilder(Of String, Object)(CaseInsensitiveComparison.Comparer)
For Each kvp In defines
result(kvp.Key) = kvp.Value.ValueAsObject
Next
Return result.ToImmutable()
End Function
''' <summary>
''' Parses Conditional Compilations Symbols. Given the string of conditional compilation symbols from the project system, parse them and merge them with an IReadOnlyDictionary
''' ready to be given to the compilation.
''' </summary>
''' <param name="symbolList">
''' The conditional compilation string. This takes the form of a comma delimited list
''' of NAME=Value pairs, where Value may be a quoted string or integer.
''' </param>
''' <param name="diagnostics">A collection of reported diagnostics during parsing of symbolList, can be empty IEnumerable.</param>
''' <param name="symbols">A collection representing existing symbols. Symbols parsed from <paramref name="symbolList"/> will be merged with this dictionary. </param>
''' <exception cref="ArgumentException">Invalid value provided.</exception>
Public Shared Function ParseConditionalCompilationSymbols(
symbolList As String,
<Out> ByRef diagnostics As IEnumerable(Of Diagnostic),
Optional symbols As IEnumerable(Of KeyValuePair(Of String, Object)) = Nothing
) As IReadOnlyDictionary(Of String, Object)
Dim diagnosticBuilder = ArrayBuilder(Of Diagnostic).GetInstance()
Dim parsedTokensAsString As New StringBuilder
Dim defines As ImmutableDictionary(Of String, InternalSyntax.CConst) = PublicSymbolsToInternalDefines(symbols, "symbols")
' remove quotes around the whole /define argument (incl. nested)
Dim unquotedString As String
Do
unquotedString = symbolList
symbolList = symbolList.Unquote()
Loop While Not String.Equals(symbolList, unquotedString, StringComparison.Ordinal)
' unescape quotes \" -> "
symbolList = symbolList.Replace("\""", """")
Dim trimmedSymbolList As String = symbolList.TrimEnd(Nothing)
If trimmedSymbolList.Length > 0 AndAlso IsConnectorPunctuation(trimmedSymbolList(trimmedSymbolList.Length - 1)) Then
' In case the symbol list ends with '_' we add ',' to the end of the list which in some
' cases will produce an error 30999 to match Dev11 behavior
symbolList = symbolList + ","
End If
' In order to determine our conditional compilation symbols, we must parse the string we get from the
' project system. We take a cue from the legacy language services and use the VB scanner, since this string
' apparently abides by the same tokenization rules
Dim tokenList = SyntaxFactory.ParseTokens(symbolList)
Using tokens = tokenList.GetEnumerator()
If tokens.MoveNext() Then
Do
' This is the beginning of declaration like 'A' or 'A=123' with optional extra
' separators (',' or ':') in the beginning, if this is NOT the first declaration,
' the tokens.Current should be either separator or EOF
If tokens.Current.Position > 0 AndAlso Not IsSeparatorOrEndOfFile(tokens.Current) Then
parsedTokensAsString.Append(" ^^ ^^ ")
' Complete parsedTokensAsString until the next comma or end of stream
While Not IsSeparatorOrEndOfFile(tokens.Current)
parsedTokensAsString.Append(tokens.Current.ToFullString())
tokens.MoveNext()
End While
diagnosticBuilder.Add(
New DiagnosticWithInfo(
ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1,
ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedEOS),
parsedTokensAsString.ToString),
Location.None))
Exit Do
End If
Dim lastSeparatorToken As SyntaxToken = Nothing
' If we're on a comma, it means there was an empty item in the list (item1,,item2),
' so just eat it and move on...
While tokens.Current.Kind = SyntaxKind.CommaToken OrElse tokens.Current.Kind = SyntaxKind.ColonToken
If lastSeparatorToken.Kind = SyntaxKind.None Then
' accept multiple : or ,
lastSeparatorToken = tokens.Current
ElseIf lastSeparatorToken.Kind <> tokens.Current.Kind Then
' but not mixing them, e.g. ::,,::
GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString, stopTokenKind:=lastSeparatorToken.Kind, includeCurrentToken:=True)
diagnosticBuilder.Add(
New DiagnosticWithInfo(
ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1,
ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier),
parsedTokensAsString.ToString),
Location.None))
End If
parsedTokensAsString.Append(tokens.Current.ToString)
' this can happen when the while loop above consumed all tokens for the diagnostic message
If tokens.Current.Kind <> SyntaxKind.EndOfFileToken Then
Dim moveNextResult = tokens.MoveNext
Debug.Assert(moveNextResult)
End If
End While
parsedTokensAsString.Clear()
' If we're at the end of the list, we're done
If tokens.Current.Kind = SyntaxKind.EndOfFileToken Then
Dim eof = tokens.Current
If eof.FullWidth > 0 Then
If Not eof.LeadingTrivia.All(Function(t) t.Kind = SyntaxKind.WhitespaceTrivia) Then
' This is an invalid line like "'Blah'"
GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString, True)
diagnosticBuilder.Add(
New DiagnosticWithInfo(
ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1,
ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier),
parsedTokensAsString.ToString),
Location.None))
End If
End If
Exit Do
End If
parsedTokensAsString.Append(tokens.Current.ToFullString())
If Not tokens.Current.Kind = SyntaxKind.IdentifierToken Then
GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString)
diagnosticBuilder.Add(
New DiagnosticWithInfo(
ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1,
ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier),
parsedTokensAsString.ToString),
Location.None))
Exit Do
End If
Dim symbolName = tokens.Current.ValueText
' there should at least be a end of file token
Dim moveResult As Boolean = tokens.MoveNext
Debug.Assert(moveResult)
If tokens.Current.Kind = SyntaxKind.EqualsToken Then
parsedTokensAsString.Append(tokens.Current.ToFullString())
' there should at least be a end of file token
moveResult = tokens.MoveNext
Debug.Assert(moveResult)
' Parse expression starting with the offset
Dim offset As Integer = tokens.Current.SpanStart
Dim expression As ExpressionSyntax = ParseConditionalCompilationExpression(symbolList, offset)
Dim parsedEnd As Integer = offset + expression.Span.End
Dim atTheEndOrSeparator As Boolean = IsSeparatorOrEndOfFile(tokens.Current)
' Consume tokens that are supposed to belong to the expression; we loop
' until the token's end position is the end of the expression, but not consume
' the last token as it will be consumed in uppermost While
While tokens.Current.Kind <> SyntaxKind.EndOfFileToken AndAlso tokens.Current.Span.End <= parsedEnd
parsedTokensAsString.Append(tokens.Current.ToFullString())
moveResult = tokens.MoveNext
Debug.Assert(moveResult)
atTheEndOrSeparator = IsSeparatorOrEndOfFile(tokens.Current)
End While
If expression.ContainsDiagnostics Then
' Dev11 reports syntax errors in not consistent way, sometimes errors are not reported by
' command line utility at all; this implementation tries to repro Dev11 when possible
parsedTokensAsString.Append(" ^^ ^^ ")
' Compete parsedTokensAsString until the next comma or end of stream
While Not IsSeparatorOrEndOfFile(tokens.Current)
parsedTokensAsString.Append(tokens.Current.ToFullString())
tokens.MoveNext()
End While
' NOTE: Dev11 reports ERR_ExpectedExpression and ERR_BadCCExpression in different
' cases compared to what ParseConditionalCompilationExpression(...) generates,
' so we have to use different criteria here; if we don't want to match Dev11
' errors we may simplify the code below
Dim errorSkipped As Boolean = False
For Each diag In expression.VbGreen.GetSyntaxErrors
If diag.Code <> ERRID.ERR_ExpectedExpression AndAlso diag.Code <> ERRID.ERR_BadCCExpression Then
diagnosticBuilder.Add(New DiagnosticWithInfo(ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1, diag, parsedTokensAsString.ToString), Location.None))
Else
errorSkipped = True
End If
Next
If errorSkipped Then
diagnosticBuilder.Add(
New DiagnosticWithInfo(
ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1,
ErrorFactory.ErrorInfo(If(atTheEndOrSeparator, ERRID.ERR_ExpectedExpression, ERRID.ERR_BadCCExpression)),
parsedTokensAsString.ToString),
Location.None))
End If
Exit Do
End If
' Expression parsed successfully --> evaluate it
Dim value As InternalSyntax.CConst =
InternalSyntax.ExpressionEvaluator.EvaluateExpression(
DirectCast(expression.Green, InternalSyntax.ExpressionSyntax), defines)
Dim err As ERRID = value.ErrorId
If err <> 0 Then
GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString)
diagnosticBuilder.Add(
New DiagnosticWithInfo(
ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1,
ErrorFactory.ErrorInfo(err, value.ErrorArgs),
parsedTokensAsString.ToString),
Location.None))
Exit Do
End If
' Expression evaluated successfully --> add to 'defines'
If defines.ContainsKey(symbolName) Then
defines = defines.Remove(symbolName)
End If
defines = defines.Add(symbolName, value)
ElseIf tokens.Current.Kind = SyntaxKind.CommaToken OrElse
tokens.Current.Kind = SyntaxKind.ColonToken OrElse
tokens.Current.Kind = SyntaxKind.EndOfFileToken Then
' We have no value being assigned, so we'll just assign it to true
If defines.ContainsKey(symbolName) Then
defines = defines.Remove(symbolName)
End If
defines = defines.Add(symbolName, InternalSyntax.CConst.Create(True))
ElseIf tokens.Current.Kind = SyntaxKind.BadToken Then
GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString)
diagnosticBuilder.Add(
New DiagnosticWithInfo(
ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1,
ErrorFactory.ErrorInfo(ERRID.ERR_IllegalChar),
parsedTokensAsString.ToString),
Location.None))
Exit Do
Else
GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString)
diagnosticBuilder.Add(
New DiagnosticWithInfo(
ErrorFactory.ErrorInfo(ERRID.ERR_ProjectCCError1,
ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedEOS),
parsedTokensAsString.ToString),
Location.None))
Exit Do
End If
Loop
End If
End Using
diagnostics = diagnosticBuilder.ToArrayAndFree()
Return InternalDefinesToPublicSymbols(defines)
End Function
''' <summary>
''' NOTE: implicit line continuation will not be handled here and an error will be generated,
''' but explicit one (like ".... _\r\n ....") should work fine
''' </summary>
Private Shared Function ParseConditionalCompilationExpression(symbolList As String, offset As Integer) As ExpressionSyntax
Using p = New InternalSyntax.Parser(SyntaxFactory.MakeSourceText(symbolList, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
Return DirectCast(p.ParseConditionalCompilationExpression().CreateRed(Nothing, 0), ExpressionSyntax)
End Using
End Function
Private Shared Function IsSeparatorOrEndOfFile(token As SyntaxToken) As Boolean
Return token.Kind = SyntaxKind.EndOfFileToken OrElse token.Kind = SyntaxKind.ColonToken OrElse token.Kind = SyntaxKind.CommaToken
End Function
Private Shared Sub GetErrorStringForRemainderOfConditionalCompilation(
tokens As IEnumerator(Of SyntaxToken),
remainderErrorLine As StringBuilder,
Optional includeCurrentToken As Boolean = False,
Optional stopTokenKind As SyntaxKind = SyntaxKind.CommaToken
)
If includeCurrentToken Then
remainderErrorLine.Append(" ^^ ")
If tokens.Current.Kind = SyntaxKind.ColonToken AndAlso tokens.Current.FullWidth = 0 Then
remainderErrorLine.Append(SyntaxFacts.GetText(SyntaxKind.ColonToken))
Else
remainderErrorLine.Append(tokens.Current.ToFullString())
End If
remainderErrorLine.Append(" ^^ ")
Else
remainderErrorLine.Append(" ^^ ^^ ")
End If
While tokens.MoveNext AndAlso Not tokens.Current.Kind = stopTokenKind
remainderErrorLine.Append(tokens.Current.ToFullString())
End While
End Sub
''' <summary>
''' Parses the given platform option. Legal strings are "anycpu", "x64", "x86", "itanium", "anycpu32bitpreferred", "arm".
''' In case an invalid value was passed, anycpu is returned.
''' </summary>
''' <param name="value">The value for platform.</param>
''' <param name="errors">The error bag.</param>
Private Shared Function ParsePlatform(name As String, value As String, errors As List(Of Diagnostic)) As Platform
If value.IsEmpty Then
AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<string>")
Else
Select Case value.ToLowerInvariant()
Case "x86"
Return Platform.X86
Case "x64"
Return Platform.X64
Case "itanium"
Return Platform.Itanium
Case "anycpu"
Return Platform.AnyCpu
Case "anycpu32bitpreferred"
Return Platform.AnyCpu32BitPreferred
Case "arm"
Return Platform.Arm
Case Else
AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value)
End Select
End If
Return Platform.AnyCpu
End Function
''' <summary>
''' Parses the file alignment option.
''' In case an invalid value was passed, nothing is returned.
''' </summary>
''' <param name="name">The name of the option.</param>
''' <param name="value">The value for the option.</param>
''' <param name="errors">The error bag.</param><returns></returns>
Private Shared Function ParseFileAlignment(name As String, value As String, errors As List(Of Diagnostic)) As Integer
Dim alignment As UShort
If String.IsNullOrEmpty(value) Then
AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<number>")
ElseIf Not TryParseUInt16(value, alignment) Then
AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value)
ElseIf Not Microsoft.CodeAnalysis.CompilationOptions.IsValidFileAlignment(alignment) Then
AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value)
Else
Return alignment
End If
Return 0
End Function
''' <summary>
''' Parses the base address option.
''' In case an invalid value was passed, nothing is returned.
''' </summary>
''' <param name="name">The name of the option.</param>
''' <param name="value">The value for the option.</param>
''' <param name="errors">The error bag.</param><returns></returns>
Private Shared Function ParseBaseAddress(name As String, value As String, errors As List(Of Diagnostic)) As ULong
If String.IsNullOrEmpty(value) Then
AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<number>")
Else
Dim baseAddress As ULong
Dim parseValue As String = value
If value.StartsWith("0x", StringComparison.OrdinalIgnoreCase) Then
parseValue = value.Substring(2) ' UInt64.TryParse does not accept hex format strings
End If
' always treat the base address string as being a hex number, regardless of the given format.
' This handling was hardcoded in the command line option parsing of Dev10 and Dev11.
If Not ULong.TryParse(parseValue,
NumberStyles.HexNumber,
CultureInfo.InvariantCulture,
baseAddress) Then
AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value.ToString())
Else
Return baseAddress
End If
End If
Return 0
End Function
''' <summary>
''' Parses the warning option.
''' </summary>
''' <param name="value">The value for the option.</param>
Private Shared Function ParseWarnings(value As String) As IEnumerable(Of String)
Dim values = value.Split(","c)
Dim results = New List(Of String)()
For Each id In values
Dim number As UShort
If UShort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, number) AndAlso
(VisualBasic.MessageProvider.Instance.GetSeverity(number) = DiagnosticSeverity.Warning) AndAlso
(VisualBasic.MessageProvider.Instance.GetWarningLevel(number) = 1) Then
' The id refers to a compiler warning.
' Only accept real warnings from the compiler not including the command line warnings.
' Also only accept the numbers that are actually declared in the enum.
results.Add(VisualBasic.MessageProvider.Instance.GetIdForErrorCode(CInt(number)))
Else
' Previous versions of the compiler used to report warnings (BC2026, BC2014)
' whenever unrecognized warning codes were supplied in /nowarn or
' /warnaserror. We no longer generate a warning in such cases.
' Instead we assume that the unrecognized id refers to a custom diagnostic.
results.Add(id)
End If
Next
Return results
End Function
Private Shared Sub AddWarnings(d As IDictionary(Of String, ReportDiagnostic), kind As ReportDiagnostic, items As IEnumerable(Of String))
For Each id In items
Dim existing As ReportDiagnostic
If d.TryGetValue(id, existing) Then
' Rewrite the existing value with the latest one unless it is for /nowarn.
If existing <> ReportDiagnostic.Suppress Then
d(id) = kind
End If
Else
d.Add(id, kind)
End If
Next
End Sub
Private Shared Sub UnimplementedSwitch(diagnostics As IList(Of Diagnostic), switchName As String)
AddDiagnostic(diagnostics, ERRID.WRN_UnimplementedCommandLineSwitch, "/" + switchName)
End Sub
Friend Overrides Sub GenerateErrorForNoFilesFoundInRecurse(path As String, errors As IList(Of Diagnostic))
AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, "recurse", path)
End Sub
Private Shared Sub AddDiagnostic(diagnostics As IList(Of Diagnostic), errorCode As ERRID, ParamArray arguments As Object())
diagnostics.Add(Diagnostic.Create(VisualBasic.MessageProvider.Instance, CInt(errorCode), arguments))
End Sub
''' <summary>
''' In VB, if the output file name isn't specified explicitly, then it is derived from the name of the
''' first input file.
''' </summary>
''' <remarks>
''' http://msdn.microsoft.com/en-us/library/std9609e(v=vs.110)
''' Specify the full name and extension of the file to create. If you do not, the .exe file takes
''' its name from the source-code file containing the Sub Main procedure, and the .dll file takes
''' its name from the first source-code file.
'''
''' However, vbc.cpp has:
''' <![CDATA[
''' // Calculate the output name and directory
''' dwCharCount = GetFullPathName(pszOut ? pszOut : g_strFirstFile, &wszFileName);
''' ]]>
''' </remarks>
Private Sub GetCompilationAndModuleNames(diagnostics As List(Of Diagnostic),
kind As OutputKind,
sourceFiles As List(Of CommandLineSourceFile),
moduleAssemblyName As String,
ByRef outputFileName As String,
ByRef moduleName As String,
<Out> ByRef compilationName As String)
Dim simpleName As String = Nothing
If outputFileName Is Nothing Then
Dim first = sourceFiles.FirstOrDefault()
If first.Path IsNot Nothing Then
simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(first.Path))
outputFileName = simpleName & kind.GetDefaultExtension()
If simpleName.Length = 0 AndAlso Not kind.IsNetModule() Then
AddDiagnostic(diagnostics, ERRID.FTL_InputFileNameTooLong, outputFileName)
simpleName = Nothing
outputFileName = Nothing
End If
End If
Else
Dim ext As String = PathUtilities.GetExtension(outputFileName)
If kind.IsNetModule() Then
If ext.Length = 0 Then
outputFileName = outputFileName & ".netmodule"
End If
Else
Dim defaultExtension As String = kind.GetDefaultExtension()
If Not String.Equals(ext, defaultExtension, StringComparison.OrdinalIgnoreCase) Then
simpleName = outputFileName
outputFileName = outputFileName & defaultExtension
End If
If simpleName Is Nothing Then
simpleName = PathUtilities.RemoveExtension(outputFileName)
' /out:".exe"
' Dev11 emits assembly with an empty name, we don't
If simpleName.Length = 0 Then
AddDiagnostic(diagnostics, ERRID.FTL_InputFileNameTooLong, outputFileName)
simpleName = Nothing
outputFileName = Nothing
End If
End If
End If
End If
If kind.IsNetModule() Then
Debug.Assert(Not IsInteractive)
compilationName = moduleAssemblyName
Else
If moduleAssemblyName IsNot Nothing Then
AddDiagnostic(diagnostics, ERRID.ERR_NeedModule)
End If
compilationName = simpleName
End If
If moduleName Is Nothing Then
moduleName = outputFileName
End If
End Sub
End Class
End Namespace
|
cybernet14/roslyn
|
src/Compilers/VisualBasic/Portable/CommandLine/CommandLineParser.vb
|
Visual Basic
|
apache-2.0
| 106,167
|
' 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
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A class representing Visual Basic compilation Options.
''' </summary>
Public NotInheritable Class VisualBasicCompilationOptions
Inherits CompilationOptions
Implements IEquatable(Of VisualBasicCompilationOptions)
Private Const s_globalImportsString = "GlobalImports"
Private Const s_rootNamespaceString = "RootNamespace"
Private Const s_optionStrictString = "OptionStrict"
Private Const s_optionInferString = "OptionInfer"
Private Const s_optionExplicitString = "OptionExplicit"
Private Const s_optionCompareTextString = "OptionCompareText"
Private Const s_embedVbCoreRuntimeString = "EmbedVbCoreRuntime"
Private Const s_parseOptionsString = "ParseOptions"
Private _globalImports As ImmutableArray(Of GlobalImport)
Private _rootNamespace As String
Private _optionStrict As OptionStrict
Private _optionInfer As Boolean
Private _optionExplicit As Boolean
Private _optionCompareText As Boolean
Private _embedVbCoreRuntime As Boolean
Private _parseOptions As VisualBasicParseOptions
' The assemblies emitted by the expression compiler should never contain embedded declarations -
' those should come from the user's code.
Private _suppressEmbeddedDeclarations As Boolean
''' <summary>
''' Initializes a new instance of the VisualBasicCompilationOptions type with various options.
''' </summary>
''' <param name="outputKind">The compilation output kind. <see cref="CodeAnalysis.OutputKind"/></param>
''' <param name="moduleName">An optional parameter to specify the name of the assembly that this module will be a part of.</param>
''' <param name="mainTypeName">An optional parameter to specify the class or module that contains the Sub Main procedure.</param>
''' <param name="scriptClassName">An optional parameter to specify an alternate DefaultScriptClassName object to be used.</param>
''' <param name="globalImports">An optional collection of GlobalImports <see cref="GlobalImports"/> .</param>
''' <param name="rootNamespace">An optional parameter to specify the name of the default root namespace.</param>
''' <param name="optionStrict">An optional parameter to specify the default Option Strict behavior. <see cref="VisualBasic.OptionStrict"/></param>
''' <param name="optionInfer">An optional parameter to specify default Option Infer behavior.</param>
''' <param name="optionExplicit">An optional parameter to specify the default Option Explicit behavior.</param>
''' <param name="optionCompareText">An optional parameter to specify the default Option Compare Text behavior.</param>
''' <param name="embedVbCoreRuntime">An optional parameter to specify the embedded Visual Basic Core Runtime behavior.</param>
''' <param name="checkOverflow">An optional parameter to specify enabling/disabling overflow checking.</param>
''' <param name="concurrentBuild">An optional parameter to specify enabling/disabling concurrent build.</param>
''' <param name="cryptoKeyContainer">An optional parameter to specify a key container name for a key pair to give an assembly a strong name.</param>
''' <param name="cryptoKeyFile">An optional parameter to specify a file containing a key or key pair to give an assembly a strong name.</param>
''' <param name="cryptoPublicKey">An optional parameter to specify a public key used to give an assembly a strong name.</param>
''' <param name="delaySign">An optional parameter to specify whether the assembly will be fully or partially signed.</param>
''' <param name="platform">An optional parameter to specify which platform version of common language runtime (CLR) can run compilation. <see cref="CodeAnalysis.Platform"/></param>
''' <param name="generalDiagnosticOption">An optional parameter to specify the general warning level.</param>
''' <param name="specificDiagnosticOptions">An optional collection representing specific warnings that differ from general warning behavior.</param>
''' <param name="optimizationLevel">An optional parameter to enabled/disable optimizations. </param>
''' <param name="parseOptions">An optional parameter to specify the parse options. <see cref="VisualBasicParseOptions"/></param>
''' <param name="xmlReferenceResolver">An optional parameter to specify the XML file resolver.</param>
''' <param name="sourceReferenceResolver">An optional parameter to specify the source file resolver.</param>
''' <param name="metadataReferenceResolver">An optional parameter to specify <see cref="CodeAnalysis.MetadataReferenceResolver"/>.</param>
''' <param name="assemblyIdentityComparer">An optional parameter to specify <see cref="CodeAnalysis.AssemblyIdentityComparer"/>.</param>
''' <param name="strongNameProvider">An optional parameter to specify <see cref="CodeAnalysis.StrongNameProvider"/>.</param>
''' <param name="publicSign">An optional parameter to specify whether the assembly will be public signed.</param>
''' <param name="reportSuppressedDiagnostics">An optional parameter to specify whether or not suppressed diagnostics should be reported.</param>
Public Sub New(
outputKind As OutputKind,
Optional moduleName As String = Nothing,
Optional mainTypeName As String = Nothing,
Optional scriptClassName As String = WellKnownMemberNames.DefaultScriptClassName,
Optional globalImports As IEnumerable(Of GlobalImport) = Nothing,
Optional rootNamespace As String = Nothing,
Optional optionStrict As OptionStrict = OptionStrict.Off,
Optional optionInfer As Boolean = True,
Optional optionExplicit As Boolean = True,
Optional optionCompareText As Boolean = False,
Optional parseOptions As VisualBasicParseOptions = Nothing,
Optional embedVbCoreRuntime As Boolean = False,
Optional optimizationLevel As OptimizationLevel = OptimizationLevel.Debug,
Optional checkOverflow As Boolean = True,
Optional cryptoKeyContainer As String = Nothing,
Optional cryptoKeyFile As String = Nothing,
Optional cryptoPublicKey As ImmutableArray(Of Byte) = Nothing,
Optional delaySign As Boolean? = Nothing,
Optional platform As Platform = Platform.AnyCpu,
Optional generalDiagnosticOption As ReportDiagnostic = ReportDiagnostic.Default,
Optional specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic)) = Nothing,
Optional concurrentBuild As Boolean = True,
Optional deterministic As Boolean = False,
Optional xmlReferenceResolver As XmlReferenceResolver = Nothing,
Optional sourceReferenceResolver As SourceReferenceResolver = Nothing,
Optional metadataReferenceResolver As MetadataReferenceResolver = Nothing,
Optional assemblyIdentityComparer As AssemblyIdentityComparer = Nothing,
Optional strongNameProvider As StrongNameProvider = Nothing,
Optional publicSign As Boolean = False,
Optional reportSuppressedDiagnostics As Boolean = False)
MyClass.New(
outputKind,
reportSuppressedDiagnostics,
moduleName,
mainTypeName,
scriptClassName,
globalImports,
rootNamespace,
optionStrict,
optionInfer,
optionExplicit,
optionCompareText,
parseOptions,
embedVbCoreRuntime,
optimizationLevel,
checkOverflow,
cryptoKeyContainer,
cryptoKeyFile,
cryptoPublicKey,
delaySign,
publicSign,
platform,
generalDiagnosticOption,
specificDiagnosticOptions,
concurrentBuild,
deterministic:=deterministic,
suppressEmbeddedDeclarations:=False,
extendedCustomDebugInformation:=True,
debugPlusMode:=False,
xmlReferenceResolver:=xmlReferenceResolver,
sourceReferenceResolver:=sourceReferenceResolver,
metadataReferenceResolver:=metadataReferenceResolver,
assemblyIdentityComparer:=assemblyIdentityComparer,
strongNameProvider:=strongNameProvider,
metadataImportOptions:=MetadataImportOptions.Public)
End Sub
Friend Sub New(
outputKind As OutputKind,
reportSuppressedDiagnostics As Boolean,
ModuleName As String,
mainTypeName As String,
scriptClassName As String,
globalImports As IEnumerable(Of GlobalImport),
rootNamespace As String,
optionStrict As OptionStrict,
optionInfer As Boolean,
optionExplicit As Boolean,
optionCompareText As Boolean,
parseOptions As VisualBasicParseOptions,
embedVbCoreRuntime As Boolean,
optimizationLevel As OptimizationLevel,
checkOverflow As Boolean,
cryptoKeyContainer As String,
cryptoKeyFile As String,
cryptoPublicKey As ImmutableArray(Of Byte),
delaySign As Boolean?,
publicSign As Boolean,
platform As Platform,
generalDiagnosticOption As ReportDiagnostic,
specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic)),
concurrentBuild As Boolean,
deterministic As Boolean,
suppressEmbeddedDeclarations As Boolean,
extendedCustomDebugInformation As Boolean,
debugPlusMode As Boolean,
xmlReferenceResolver As XmlReferenceResolver,
sourceReferenceResolver As SourceReferenceResolver,
metadataReferenceResolver As MetadataReferenceResolver,
assemblyIdentityComparer As AssemblyIdentityComparer,
strongNameProvider As StrongNameProvider,
metadataImportOptions As MetadataImportOptions)
MyBase.New(
outputKind:=outputKind,
reportSuppressedDiagnostics:=reportSuppressedDiagnostics,
moduleName:=ModuleName,
mainTypeName:=mainTypeName,
scriptClassName:=scriptClassName,
cryptoKeyContainer:=cryptoKeyContainer,
cryptoKeyFile:=cryptoKeyFile,
cryptoPublicKey:=cryptoPublicKey,
delaySign:=delaySign,
publicSign:=publicSign,
optimizationLevel:=optimizationLevel,
checkOverflow:=checkOverflow,
platform:=platform,
generalDiagnosticOption:=generalDiagnosticOption,
warningLevel:=1,
specificDiagnosticOptions:=specificDiagnosticOptions.ToImmutableDictionaryOrEmpty(CaseInsensitiveComparison.Comparer), ' Diagnostic ids must be processed in case-insensitive fashion.
concurrentBuild:=concurrentBuild,
deterministic:=deterministic,
extendedCustomDebugInformation:=extendedCustomDebugInformation,
debugPlusMode:=debugPlusMode,
xmlReferenceResolver:=xmlReferenceResolver,
sourceReferenceResolver:=sourceReferenceResolver,
metadataReferenceResolver:=metadataReferenceResolver,
assemblyIdentityComparer:=assemblyIdentityComparer,
strongNameProvider:=strongNameProvider,
metadataImportOptions:=metadataImportOptions)
_globalImports = globalImports.AsImmutableOrEmpty()
_rootNamespace = If(rootNamespace, String.Empty)
_optionStrict = optionStrict
_optionInfer = optionInfer
_optionExplicit = optionExplicit
_optionCompareText = optionCompareText
_embedVbCoreRuntime = embedVbCoreRuntime
_suppressEmbeddedDeclarations = suppressEmbeddedDeclarations
_parseOptions = parseOptions
Debug.Assert(Not (_embedVbCoreRuntime AndAlso _suppressEmbeddedDeclarations),
"_embedVbCoreRuntime and _suppressEmbeddedDeclarations are mutually exclusive")
End Sub
Private Sub New(other As VisualBasicCompilationOptions)
MyClass.New(
outputKind:=other.OutputKind,
reportSuppressedDiagnostics:=other.ReportSuppressedDiagnostics,
ModuleName:=other.ModuleName,
mainTypeName:=other.MainTypeName,
scriptClassName:=other.ScriptClassName,
globalImports:=other.GlobalImports,
rootNamespace:=other.RootNamespace,
optionStrict:=other.OptionStrict,
optionInfer:=other.OptionInfer,
optionExplicit:=other.OptionExplicit,
optionCompareText:=other.OptionCompareText,
parseOptions:=other.ParseOptions,
embedVbCoreRuntime:=other.EmbedVbCoreRuntime,
suppressEmbeddedDeclarations:=other.SuppressEmbeddedDeclarations,
optimizationLevel:=other.OptimizationLevel,
checkOverflow:=other.CheckOverflow,
cryptoKeyContainer:=other.CryptoKeyContainer,
cryptoKeyFile:=other.CryptoKeyFile,
cryptoPublicKey:=other.CryptoPublicKey,
delaySign:=other.DelaySign,
Platform:=other.Platform,
GeneralDiagnosticOption:=other.GeneralDiagnosticOption,
SpecificDiagnosticOptions:=other.SpecificDiagnosticOptions,
concurrentBuild:=other.ConcurrentBuild,
deterministic:=other.Deterministic,
extendedCustomDebugInformation:=other.ExtendedCustomDebugInformation,
debugPlusMode:=other.DebugPlusMode,
xmlReferenceResolver:=other.XmlReferenceResolver,
sourceReferenceResolver:=other.SourceReferenceResolver,
metadataReferenceResolver:=other.MetadataReferenceResolver,
assemblyIdentityComparer:=other.AssemblyIdentityComparer,
strongNameProvider:=other.StrongNameProvider,
metadataImportOptions:=other.MetadataImportOptions,
publicSign:=other.PublicSign)
End Sub
Friend Overrides Function GetImports() As ImmutableArray(Of String)
' TODO: implement (only called from VBI) https://github.com/dotnet/roslyn/issues/5854
Dim importNames = ArrayBuilder(Of String).GetInstance(GlobalImports.Length)
For Each globalImport In GlobalImports
If Not globalImport.IsXmlClause Then
importNames.Add(globalImport.Name)
End If
Next
Return importNames.ToImmutableAndFree()
End Function
''' <summary>
''' Gets the global imports collection.
''' </summary>
''' <returns>The global imports.</returns>
Public ReadOnly Property GlobalImports As ImmutableArray(Of GlobalImport)
Get
Return _globalImports
End Get
End Property
''' <summary>
''' Gets the default namespace for all source code in the project. Corresponds to the
''' "RootNamespace" project option or the "/rootnamespace" command line option.
''' </summary>
''' <returns>The default namespace.</returns>
Public ReadOnly Property RootNamespace As String
Get
Return _rootNamespace
End Get
End Property
Friend Function GetRootNamespaceParts() As ImmutableArray(Of String)
If String.IsNullOrEmpty(_rootNamespace) OrElse Not OptionsValidator.IsValidNamespaceName(_rootNamespace) Then
Return ImmutableArray(Of String).Empty
End If
Return MetadataHelpers.SplitQualifiedName(_rootNamespace)
End Function
''' <summary>
''' Gets the Option Strict Setting.
''' </summary>
''' <returns>The Option Strict setting.</returns>
Public ReadOnly Property OptionStrict As OptionStrict
Get
Return _optionStrict
End Get
End Property
''' <summary>
''' Gets the Option Infer setting.
''' </summary>
''' <returns>The Option Infer setting. True if Option Infer On is in effect by default. False if Option Infer Off is on effect by default. </returns>
Public ReadOnly Property OptionInfer As Boolean
Get
Return _optionInfer
End Get
End Property
''' <summary>
''' Gets the Option Explicit setting.
''' </summary>
''' <returns>The Option Explicit setting. True if Option Explicit On is in effect by default. False if Option Explicit Off is on by default.</returns>
Public ReadOnly Property OptionExplicit As Boolean
Get
Return _optionExplicit
End Get
End Property
''' <summary>
''' Gets the Option Compare Text setting.
''' </summary>
''' <returns>
''' The Option Compare Text Setting, True if Option Compare Text is in effect by default. False if Option Compare Binary is
''' in effect by default.
''' </returns>
Public ReadOnly Property OptionCompareText As Boolean
Get
Return _optionCompareText
End Get
End Property
''' <summary>
''' Gets the Embed Visual Basic Core Runtime setting.
''' </summary>
''' <returns>
''' The EmbedVbCoreRuntime setting, True if VB core runtime should be embedded in the compilation. Equal to '/vbruntime*'
''' </returns>
Public ReadOnly Property EmbedVbCoreRuntime As Boolean
Get
Return _embedVbCoreRuntime
End Get
End Property
''' <summary>
''' Gets the embedded declaration suppression setting.
''' </summary>
''' <returns>
''' The embedded declaration suppression setting.
''' </returns>
Friend ReadOnly Property SuppressEmbeddedDeclarations As Boolean
Get
Return _suppressEmbeddedDeclarations
End Get
End Property
''' <summary>
''' Gets the Parse Options setting.
''' Compilation level parse options. Used when compiling synthetic embedded code such as My template
''' </summary>
''' <returns>The Parse Options Setting.</returns>
Friend ReadOnly Property ParseOptions As VisualBasicParseOptions
Get
Return _parseOptions
End Get
End Property
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different OutputKind specified.
''' </summary>
''' <param name="kind">The Output Kind.</param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the output kind is different; otherwise current instance.</returns>
Public Shadows Function WithOutputKind(kind As OutputKind) As VisualBasicCompilationOptions
If kind = Me.OutputKind Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.OutputKind = kind}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance With a different ModuleName specified.
''' </summary>
''' <param name="moduleName">The moduleName.</param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the module name is different; otherwise current instance.</returns>
Public Function WithModuleName(moduleName As String) As VisualBasicCompilationOptions
If String.Equals(moduleName, Me.ModuleName, StringComparison.Ordinal) Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.ModuleName = moduleName}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a Script Class Name specified.
''' </summary>
''' <param name="name">The name for the ScriptClassName.</param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the script class name is different; otherwise current instance.</returns>
Public Shadows Function WithScriptClassName(name As String) As VisualBasicCompilationOptions
If String.Equals(name, Me.ScriptClassName, StringComparison.Ordinal) Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.ScriptClassName = name}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different Main Type name specified.
''' </summary>
''' <param name="name">The name for the MainType .</param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the main type name is different; otherwise current instance.</returns>
Public Shadows Function WithMainTypeName(name As String) As VisualBasicCompilationOptions
If String.Equals(name, Me.MainTypeName, StringComparison.Ordinal) Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.MainTypeName = name}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different global imports specified.
''' </summary>
''' <param name="globalImports">A collection of Global Imports <see cref="GlobalImport"/>.</param>
''' <returns>A new instance of VisualBasicCompilationOptions.</returns>
Public Function WithGlobalImports(globalImports As ImmutableArray(Of GlobalImport)) As VisualBasicCompilationOptions
If Me.GlobalImports.Equals(globalImports) Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._globalImports = globalImports}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different global imports specified.
''' </summary>
''' <param name="globalImports">A collection of Global Imports <see cref="GlobalImport"/>.</param>
''' <returns>A new instance of VisualBasicCompilationOptions.</returns>
Public Function WithGlobalImports(globalImports As IEnumerable(Of GlobalImport)) As VisualBasicCompilationOptions
Return New VisualBasicCompilationOptions(Me) With {._globalImports = globalImports.AsImmutableOrEmpty()}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different global imports specified.
''' </summary>
''' <param name="globalImports">A collection of Global Imports <see cref="GlobalImport"/>.</param>
''' <returns>A new instance of VisualBasicCompilationOptions.</returns>
Public Function WithGlobalImports(ParamArray globalImports As GlobalImport()) As VisualBasicCompilationOptions
Return WithGlobalImports(DirectCast(globalImports, IEnumerable(Of GlobalImport)))
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different root namespace specified.
''' </summary>
''' <param name="rootNamespace">The root namespace.</param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the root namespace is different; otherwise current instance.</returns>
Public Function WithRootNamespace(rootNamespace As String) As VisualBasicCompilationOptions
If String.Equals(rootNamespace, Me.RootNamespace, StringComparison.Ordinal) Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._rootNamespace = rootNamespace}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different option strict specified.
''' </summary>
''' <param name="value">The Option Strict setting. <see cref="Microsoft.CodeAnalysis.VisualBasic.OptionStrict"/></param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the option strict is different; otherwise current instance.</returns>
Public Shadows Function WithOptionStrict(value As OptionStrict) As VisualBasicCompilationOptions
If value = Me.OptionStrict Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._optionStrict = value}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different option infer specified.
''' </summary>
''' <param name="value">The Option infer setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the option infer is different; otherwise current instance.</returns>
Public Shadows Function WithOptionInfer(value As Boolean) As VisualBasicCompilationOptions
If value = Me.OptionInfer Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._optionInfer = value}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different option explicit specified.
''' </summary>
''' <param name="value">The Option Explicit setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the option explicit is different; otherwise current instance.</returns>
Public Shadows Function WithOptionExplicit(value As Boolean) As VisualBasicCompilationOptions
If value = Me.OptionExplicit Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._optionExplicit = value}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different Option Compare Text specified.
''' </summary>
''' <param name="value">The Option Compare Text setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the option compare text is different; otherwise current instance.</returns>
Public Shadows Function WithOptionCompareText(value As Boolean) As VisualBasicCompilationOptions
If value = Me.OptionCompareText Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._optionCompareText = value}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different Embed VB Core Runtime specified.
''' </summary>
''' <param name="value">The Embed VB Core Runtime setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the embed vb core runtime is different; otherwise current instance.</returns>
Public Shadows Function WithEmbedVbCoreRuntime(value As Boolean) As VisualBasicCompilationOptions
If value = Me.EmbedVbCoreRuntime Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._embedVbCoreRuntime = value}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different Overflow checks specified.
''' </summary>
''' <param name="enabled">The overflow check setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the overflow check is different; otherwise current instance.</returns>
Public Shadows Function WithOverflowChecks(enabled As Boolean) As VisualBasicCompilationOptions
If enabled = Me.CheckOverflow Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.CheckOverflow = enabled}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different concurrent build specified.
''' </summary>
''' <param name="concurrentBuild">The concurrent build setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the concurrent build is different; otherwise current instance.</returns>
Public Shadows Function WithConcurrentBuild(concurrentBuild As Boolean) As VisualBasicCompilationOptions
If concurrentBuild = Me.ConcurrentBuild Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.ConcurrentBuild = concurrentBuild}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different deterministic mode specified.
''' <param name="deterministic"> The deterministic mode. </param>
''' <returns> A new instance of VisualBasicCompilationOptions, if the concurrent build is different; otherwise the current instance.</returns>
''' </summary>
Public Shadows Function WithDeterministic(deterministic As Boolean) As VisualBasicCompilationOptions
If deterministic = Me.Deterministic Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.Deterministic = deterministic}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different extended custom debug information specified.
''' </summary>
''' <param name="extendedCustomDebugInformation">The extended custom debug information setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the extended custom debug information is different; otherwise current instance.</returns>
Friend Function WithExtendedCustomDebugInformation(extendedCustomDebugInformation As Boolean) As VisualBasicCompilationOptions
If extendedCustomDebugInformation = Me.ExtendedCustomDebugInformation Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.ExtendedCustomDebugInformation_internal_protected_set = extendedCustomDebugInformation}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different extended custom debug information specified.
''' </summary>
''' <param name="debugPlusMode">The extended custom debug information setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the extended custom debug information is different; otherwise current instance.</returns>
Friend Function WithDebugPlusMode(debugPlusMode As Boolean) As VisualBasicCompilationOptions
If debugPlusMode = Me.DebugPlusMode Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.DebugPlusMode_internal_protected_set = debugPlusMode}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with different embedded declaration suppression setting specified.
''' </summary>
''' <param name="suppressEmbeddedDeclarations">The embedded declaration suppression setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the embedded declaration suppression setting is different; otherwise current instance.</returns>
''' <remarks>Only expected to be called from the expression compiler.</remarks>
Friend Function WithSuppressEmbeddedDeclarations(suppressEmbeddedDeclarations As Boolean) As VisualBasicCompilationOptions
If suppressEmbeddedDeclarations = _suppressEmbeddedDeclarations Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._suppressEmbeddedDeclarations = suppressEmbeddedDeclarations}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different cryptography key container specified
''' </summary>
''' <param name="name">The name of the cryptography key container. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the cryptography key container name is different; otherwise current instance.</returns>
Public Shadows Function WithCryptoKeyContainer(name As String) As VisualBasicCompilationOptions
If String.Equals(name, Me.CryptoKeyContainer, StringComparison.Ordinal) Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.CryptoKeyContainer = name}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different cryptography key file path specified.
''' </summary>
''' <param name="path">The cryptography key file path. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the cryptography key path is different; otherwise current instance.</returns>
Public Shadows Function WithCryptoKeyFile(path As String) As VisualBasicCompilationOptions
If String.Equals(path, Me.CryptoKeyFile, StringComparison.Ordinal) Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.CryptoKeyFile = path}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different public key.
''' </summary>
''' <param name="value">The cryptography key file path. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the public key is different; otherwise current instance.</returns>
Public Shadows Function WithCryptoPublicKey(value As ImmutableArray(Of Byte)) As VisualBasicCompilationOptions
If value.IsDefault Then
value = ImmutableArray(Of Byte).Empty
End If
If value = Me.CryptoPublicKey Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.CryptoPublicKey = value}
End Function
''' <summary>
''' Creates a new VisualBasicCompilationOptions instance with a different delay signing specified.
''' </summary>
''' <param name="value">The delay signing setting. </param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the delay sign is different; otherwise current instance.</returns>
Public Shadows Function WithDelaySign(value As Boolean?) As VisualBasicCompilationOptions
If value = Me.DelaySign Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.DelaySign = value}
End Function
''' <summary>
''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with a different platform specified.
''' </summary>
''' <param name="value">The platform setting. <see cref="Microsoft.CodeAnalysis.Platform"/></param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the platform is different; otherwise current instance.</returns>
Public Shadows Function WithPlatform(value As Platform) As VisualBasicCompilationOptions
If value = Me.Platform Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.Platform = value}
End Function
Public Shadows Function WithPublicSign(value As Boolean) As VisualBasicCompilationOptions
If value = Me.PublicSign Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.PublicSign = value}
End Function
Protected Overrides Function CommonWithDeterministic(deterministic As Boolean) As CompilationOptions
Return Me.WithDeterministic(deterministic)
End Function
Protected Overrides Function CommonWithGeneralDiagnosticOption(value As ReportDiagnostic) As CompilationOptions
Return Me.WithGeneralDiagnosticOption(value)
End Function
Protected Overrides Function CommonWithSpecificDiagnosticOptions(specificDiagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic)) As CompilationOptions
Return Me.WithSpecificDiagnosticOptions(specificDiagnosticOptions)
End Function
Protected Overrides Function CommonWithSpecificDiagnosticOptions(specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic))) As CompilationOptions
Return Me.WithSpecificDiagnosticOptions(specificDiagnosticOptions)
End Function
Protected Overrides Function CommonWithReportSuppressedDiagnostics(reportSuppressedDiagnostics As Boolean) As CompilationOptions
Return Me.WithReportSuppressedDiagnostics(reportSuppressedDiagnostics)
End Function
<Obsolete>
Protected Overrides Function CommonWithFeatures(features As ImmutableArray(Of String)) As CompilationOptions
Throw New NotImplementedException()
End Function
''' <summary>
''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with a different report warning specified.
''' </summary>
''' <param name="value">The Report Warning setting. <see cref="Microsoft.CodeAnalysis.ReportDiagnostic"/></param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the report warning is different; otherwise current instance.</returns>
Public Shadows Function WithGeneralDiagnosticOption(value As ReportDiagnostic) As VisualBasicCompilationOptions
If value = Me.GeneralDiagnosticOption Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.GeneralDiagnosticOption = value}
End Function
''' <summary>
''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with different specific warnings specified.
''' </summary>
''' <param name="value">Specific report warnings. <see cref="Microsoft.CodeAnalysis.ReportDiagnostic"/></param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the dictionary of report warning is different; otherwise current instance.</returns>
Public Shadows Function WithSpecificDiagnosticOptions(value As ImmutableDictionary(Of String, ReportDiagnostic)) As VisualBasicCompilationOptions
If value Is Nothing Then
value = ImmutableDictionary(Of String, ReportDiagnostic).Empty
End If
If value Is Me.SpecificDiagnosticOptions Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.SpecificDiagnosticOptions = value}
End Function
''' <summary>
''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with different specific warnings specified.
''' </summary>
''' <param name="value">Specific report warnings. <see cref="Microsoft.CodeAnalysis.ReportDiagnostic"/></param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the dictionary of report warning is different; otherwise current instance.</returns>
Public Shadows Function WithSpecificDiagnosticOptions(value As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic))) As VisualBasicCompilationOptions
Return New VisualBasicCompilationOptions(Me) With {.SpecificDiagnosticOptions = value.ToImmutableDictionaryOrEmpty()}
End Function
''' <summary>
''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with specified suppress diagnostics reporting option.
''' </summary>
''' <param name="value">Report suppressed diagnostics setting.</param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the value is different from the current value; otherwise current instance.</returns>
Public Shadows Function WithReportSuppressedDiagnostics(value As Boolean) As VisualBasicCompilationOptions
If value = Me.ReportSuppressedDiagnostics Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.ReportSuppressedDiagnostics = value}
End Function
''' <summary>
''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with a specified <see cref="VisualBasicCompilationOptions.OptimizationLevel"/>.
''' </summary>
''' <returns>A new instance of <see cref="VisualBasicCompilationOptions"/>, if the value is different; otherwise the current instance.</returns>
Public Shadows Function WithOptimizationLevel(value As OptimizationLevel) As VisualBasicCompilationOptions
If value = Me.OptimizationLevel Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.OptimizationLevel = value}
End Function
Friend Function WithMetadataImportOptions(value As MetadataImportOptions) As VisualBasicCompilationOptions
If value = Me.MetadataImportOptions Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.MetadataImportOptions_internal_protected_set = value}
End Function
''' <summary>
''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with a different parse option specified.
''' </summary>
''' <param name="options">The parse option setting. <see cref="Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions"/></param>
''' <returns>A new instance of VisualBasicCompilationOptions, if the parse options is different; otherwise current instance.</returns>
Public Function WithParseOptions(options As VisualBasicParseOptions) As VisualBasicCompilationOptions
If options Is Me.ParseOptions Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {._parseOptions = options}
End Function
Public Shadows Function WithXmlReferenceResolver(resolver As XmlReferenceResolver) As VisualBasicCompilationOptions
If resolver Is Me.XmlReferenceResolver Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.XmlReferenceResolver = resolver}
End Function
Public Shadows Function WithSourceReferenceResolver(resolver As SourceReferenceResolver) As VisualBasicCompilationOptions
If resolver Is Me.SourceReferenceResolver Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.SourceReferenceResolver = resolver}
End Function
Public Shadows Function WithMetadataReferenceResolver(resolver As MetadataReferenceResolver) As VisualBasicCompilationOptions
If resolver Is Me.MetadataReferenceResolver Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.MetadataReferenceResolver = resolver}
End Function
Public Shadows Function WithAssemblyIdentityComparer(comparer As AssemblyIdentityComparer) As VisualBasicCompilationOptions
comparer = If(comparer, AssemblyIdentityComparer.Default)
If comparer Is Me.AssemblyIdentityComparer Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.AssemblyIdentityComparer = comparer}
End Function
Public Shadows Function WithStrongNameProvider(provider As StrongNameProvider) As VisualBasicCompilationOptions
If provider Is Me.StrongNameProvider Then
Return Me
End If
Return New VisualBasicCompilationOptions(Me) With {.StrongNameProvider = provider}
End Function
Protected Overrides Function CommonWithOutputKind(kind As OutputKind) As CompilationOptions
Return WithOutputKind(kind)
End Function
Protected Overrides Function CommonWithPlatform(platform As Platform) As CompilationOptions
Return WithPlatform(platform)
End Function
Protected Overrides Function CommonWithPublicSign(publicSign As Boolean) As CompilationOptions
Return WithPublicSign(publicSign)
End Function
Protected Overrides Function CommonWithOptimizationLevel(value As OptimizationLevel) As CompilationOptions
Return WithOptimizationLevel(value)
End Function
Protected Overrides Function CommonWithAssemblyIdentityComparer(comparer As AssemblyIdentityComparer) As CompilationOptions
Return WithAssemblyIdentityComparer(comparer)
End Function
Protected Overrides Function CommonWithXmlReferenceResolver(resolver As XmlReferenceResolver) As CompilationOptions
Return WithXmlReferenceResolver(resolver)
End Function
Protected Overrides Function CommonWithSourceReferenceResolver(resolver As SourceReferenceResolver) As CompilationOptions
Return WithSourceReferenceResolver(resolver)
End Function
Protected Overrides Function CommonWithMetadataReferenceResolver(resolver As MetadataReferenceResolver) As CompilationOptions
Return WithMetadataReferenceResolver(resolver)
End Function
Protected Overrides Function CommonWithStrongNameProvider(provider As StrongNameProvider) As CompilationOptions
Return WithStrongNameProvider(provider)
End Function
Friend Overrides Sub ValidateOptions(builder As ArrayBuilder(Of Diagnostic))
If Me.EmbedVbCoreRuntime AndAlso Me.OutputKind.IsNetModule() Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_VBCoreNetModuleConflict))
End If
If Not Platform.IsValid() Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(Platform), Platform.ToString()))
End If
If ModuleName IsNot Nothing Then
Dim e As Exception = MetadataHelpers.CheckAssemblyOrModuleName(ModuleName, NameOf(ModuleName))
If e IsNot Nothing Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_BadCompilationOption, e.Message))
End If
End If
If Not OutputKind.IsValid() Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(OutputKind), OutputKind.ToString()))
End If
If Not OptimizationLevel.IsValid() Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(OptimizationLevel), OptimizationLevel.ToString()))
End If
If ScriptClassName Is Nothing OrElse Not ScriptClassName.IsValidClrTypeName() Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(ScriptClassName), If(ScriptClassName, "Nothing")))
End If
If MainTypeName IsNot Nothing AndAlso Not MainTypeName.IsValidClrTypeName() Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(MainTypeName), MainTypeName))
End If
If Not String.IsNullOrEmpty(RootNamespace) AndAlso Not OptionsValidator.IsValidNamespaceName(RootNamespace) Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(RootNamespace), RootNamespace))
End If
If Not OptionStrict.IsValid Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(OptionStrict), OptionStrict.ToString()))
End If
If Platform = Platform.AnyCpu32BitPreferred AndAlso OutputKind.IsValid() AndAlso
Not (OutputKind = OutputKind.ConsoleApplication OrElse OutputKind = OutputKind.WindowsApplication OrElse OutputKind = OutputKind.WindowsRuntimeApplication) Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_LibAnycpu32bitPreferredConflict, NameOf(Platform), Platform.ToString()))
End If
' TODO: add check for
' (kind == 'arm' || kind == 'appcontainer' || kind == 'winmdobj') &&
' (version >= "6.2")
If Not CryptoPublicKey.IsEmpty Then
If CryptoKeyFile IsNot Nothing Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_MutuallyExclusiveOptions, NameOf(CryptoPublicKey), NameOf(CryptoKeyFile)))
End If
If CryptoKeyContainer IsNot Nothing Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_MutuallyExclusiveOptions, NameOf(CryptoPublicKey), NameOf(CryptoKeyContainer)))
End If
End If
If PublicSign AndAlso DelaySign.HasValue Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_MutuallyExclusiveOptions, NameOf(PublicSign), NameOf(DelaySign)))
End If
End Sub
''' <summary>
''' Determines whether the current object is equal to another object of the same type.
''' </summary>
''' <param name="other">A VisualBasicCompilationOptions to compare with this object</param>
''' <returns>A boolean value. True if the current object is equal to the other parameter; otherwise, False.</returns>
Public Overloads Function Equals(other As VisualBasicCompilationOptions) As Boolean Implements IEquatable(Of VisualBasicCompilationOptions).Equals
If Me Is other Then
Return True
End If
If Not MyBase.EqualsHelper(other) Then
Return False
End If
Return If(Me.GlobalImports.IsDefault, other.GlobalImports.IsDefault, Me.GlobalImports.SequenceEqual(other.GlobalImports)) AndAlso
String.Equals(Me.RootNamespace, other.RootNamespace, StringComparison.Ordinal) AndAlso
Me.OptionStrict = other.OptionStrict AndAlso
Me.OptionInfer = other.OptionInfer AndAlso
Me.OptionExplicit = other.OptionExplicit AndAlso
Me.OptionCompareText = other.OptionCompareText AndAlso
Me.EmbedVbCoreRuntime = other.EmbedVbCoreRuntime AndAlso
Me.SuppressEmbeddedDeclarations = other.SuppressEmbeddedDeclarations AndAlso
If(Me.ParseOptions Is Nothing, other.ParseOptions Is Nothing, Me.ParseOptions.Equals(other.ParseOptions))
End Function
''' <summary>
''' Indicates whether the current object is equal to another object.
''' </summary>
''' <param name="obj">A object to compare with this object</param>
''' <returns>A boolean value. True if the current object is equal to the other parameter; otherwise, False.</returns>
Public Overrides Function Equals(obj As Object) As Boolean
Return Me.Equals(TryCast(obj, VisualBasicCompilationOptions))
End Function
''' <summary>
''' Creates a hashcode for this instance.
''' </summary>
''' <returns>A hashcode representing this instance.</returns>
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(MyBase.GetHashCodeHelper(),
Hash.Combine(Hash.CombineValues(Me.GlobalImports),
Hash.Combine(If(Me.RootNamespace IsNot Nothing, StringComparer.Ordinal.GetHashCode(Me.RootNamespace), 0),
Hash.Combine(Me.OptionStrict,
Hash.Combine(Me.OptionInfer,
Hash.Combine(Me.OptionExplicit,
Hash.Combine(Me.OptionCompareText,
Hash.Combine(Me.EmbedVbCoreRuntime,
Hash.Combine(Me.SuppressEmbeddedDeclarations,
Hash.Combine(Me.ParseOptions, 0))))))))))
End Function
Friend Overrides Function FilterDiagnostic(diagnostic As Diagnostic) As Diagnostic
Return VisualBasicDiagnosticFilter.Filter(diagnostic, GeneralDiagnosticOption, SpecificDiagnosticOptions)
End Function
'' 1.1 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
Public Sub New(
outputKind As OutputKind,
moduleName As String,
mainTypeName As String,
scriptClassName As String,
globalImports As IEnumerable(Of GlobalImport),
rootNamespace As String,
optionStrict As OptionStrict,
optionInfer As Boolean,
optionExplicit As Boolean,
optionCompareText As Boolean,
parseOptions As VisualBasicParseOptions,
embedVbCoreRuntime As Boolean,
optimizationLevel As OptimizationLevel,
checkOverflow As Boolean,
cryptoKeyContainer As String,
cryptoKeyFile As String,
cryptoPublicKey As ImmutableArray(Of Byte),
delaySign As Boolean?,
platform As Platform,
generalDiagnosticOption As ReportDiagnostic,
specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic)),
concurrentBuild As Boolean,
deterministic As Boolean,
xmlReferenceResolver As XmlReferenceResolver,
sourceReferenceResolver As SourceReferenceResolver,
metadataReferenceResolver As MetadataReferenceResolver,
assemblyIdentityComparer As AssemblyIdentityComparer,
strongNameProvider As StrongNameProvider)
MyClass.New(
outputKind,
moduleName,
mainTypeName,
scriptClassName,
globalImports,
rootNamespace,
optionStrict,
optionInfer,
optionExplicit,
optionCompareText,
parseOptions,
embedVbCoreRuntime,
optimizationLevel,
checkOverflow,
cryptoKeyContainer,
cryptoKeyFile,
cryptoPublicKey,
delaySign,
platform,
generalDiagnosticOption,
specificDiagnosticOptions,
concurrentBuild,
deterministic:=False,' TODO: fix this
xmlReferenceResolver:=xmlReferenceResolver,
sourceReferenceResolver:=sourceReferenceResolver,
metadataReferenceResolver:=metadataReferenceResolver,
assemblyIdentityComparer:=assemblyIdentityComparer,
strongNameProvider:=strongNameProvider,
publicSign:=False)
End Sub
' 1.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
Public Sub New(
outputKind As OutputKind,
moduleName As String,
mainTypeName As String,
scriptClassName As String,
globalImports As IEnumerable(Of GlobalImport),
rootNamespace As String,
optionStrict As OptionStrict,
optionInfer As Boolean,
optionExplicit As Boolean,
optionCompareText As Boolean,
parseOptions As VisualBasicParseOptions,
embedVbCoreRuntime As Boolean,
optimizationLevel As OptimizationLevel,
checkOverflow As Boolean,
cryptoKeyContainer As String,
cryptoKeyFile As String,
cryptoPublicKey As ImmutableArray(Of Byte),
delaySign As Boolean?,
platform As Platform,
generalDiagnosticOption As ReportDiagnostic,
specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic)),
concurrentBuild As Boolean,
xmlReferenceResolver As XmlReferenceResolver,
sourceReferenceResolver As SourceReferenceResolver,
metadataReferenceResolver As MetadataReferenceResolver,
assemblyIdentityComparer As AssemblyIdentityComparer,
strongNameProvider As StrongNameProvider)
MyClass.New(
outputKind,
moduleName,
mainTypeName,
scriptClassName,
globalImports,
rootNamespace,
optionStrict,
optionInfer,
optionExplicit,
optionCompareText,
parseOptions,
embedVbCoreRuntime,
optimizationLevel,
checkOverflow,
cryptoKeyContainer,
cryptoKeyFile,
cryptoPublicKey,
delaySign,
platform,
generalDiagnosticOption,
specificDiagnosticOptions,
concurrentBuild,
deterministic:=False,
xmlReferenceResolver:=xmlReferenceResolver,
sourceReferenceResolver:=sourceReferenceResolver,
metadataReferenceResolver:=metadataReferenceResolver,
assemblyIdentityComparer:=assemblyIdentityComparer,
strongNameProvider:=strongNameProvider)
End Sub
'' Bad constructor, do not use!
'' Violates the rules for optional parameter overloads detailed at
'' https://github.com/dotnet/roslyn/blob/e8fdb391703dcb5712ff6a5b83d768d784cba4cf/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md
Public Sub New(
outputKind As OutputKind,
reportSuppressedDiagnostics As Boolean,
Optional moduleName As String = Nothing,
Optional mainTypeName As String = Nothing,
Optional scriptClassName As String = WellKnownMemberNames.DefaultScriptClassName,
Optional globalImports As IEnumerable(Of GlobalImport) = Nothing,
Optional rootNamespace As String = Nothing,
Optional optionStrict As OptionStrict = OptionStrict.Off,
Optional optionInfer As Boolean = True,
Optional optionExplicit As Boolean = True,
Optional optionCompareText As Boolean = False,
Optional parseOptions As VisualBasicParseOptions = Nothing,
Optional embedVbCoreRuntime As Boolean = False,
Optional optimizationLevel As OptimizationLevel = OptimizationLevel.Debug,
Optional checkOverflow As Boolean = True,
Optional cryptoKeyContainer As String = Nothing,
Optional cryptoKeyFile As String = Nothing,
Optional cryptoPublicKey As ImmutableArray(Of Byte) = Nothing,
Optional delaySign As Boolean? = Nothing,
Optional platform As Platform = Platform.AnyCpu,
Optional generalDiagnosticOption As ReportDiagnostic = ReportDiagnostic.Default,
Optional specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic)) = Nothing,
Optional concurrentBuild As Boolean = True,
Optional deterministic As Boolean = False,
Optional xmlReferenceResolver As XmlReferenceResolver = Nothing,
Optional sourceReferenceResolver As SourceReferenceResolver = Nothing,
Optional metadataReferenceResolver As MetadataReferenceResolver = Nothing,
Optional assemblyIdentityComparer As AssemblyIdentityComparer = Nothing,
Optional strongNameProvider As StrongNameProvider = Nothing)
MyClass.New(
outputKind,
reportSuppressedDiagnostics,
moduleName,
mainTypeName,
scriptClassName,
globalImports,
rootNamespace,
optionStrict,
optionInfer,
optionExplicit,
optionCompareText,
parseOptions,
embedVbCoreRuntime,
optimizationLevel,
checkOverflow,
cryptoKeyContainer,
cryptoKeyFile,
cryptoPublicKey,
delaySign,
publicSign:=False,
Platform:=platform,
GeneralDiagnosticOption:=generalDiagnosticOption,
SpecificDiagnosticOptions:=specificDiagnosticOptions,
concurrentBuild:=concurrentBuild,
deterministic:=deterministic,
suppressEmbeddedDeclarations:=False,
extendedCustomDebugInformation:=True,
debugPlusMode:=False,
xmlReferenceResolver:=xmlReferenceResolver,
sourceReferenceResolver:=sourceReferenceResolver,
metadataReferenceResolver:=metadataReferenceResolver,
assemblyIdentityComparer:=assemblyIdentityComparer,
strongNameProvider:=strongNameProvider,
metadataImportOptions:=MetadataImportOptions.Public)
End Sub
End Class
End Namespace
|
HellBrick/roslyn
|
src/Compilers/VisualBasic/Portable/VisualBasicCompilationOptions.vb
|
Visual Basic
|
apache-2.0
| 63,167
|
''' <summary>
''' 脚本生成
''' </summary>
''' <remarks></remarks>
Public Class ScriptHelper
''' <summary>
''' DHCP脚本
''' </summary>
''' <remarks></remarks>
Public Class DHCP
''' <summary>
''' 根据MAC地址创建HDCP Lease的删除脚本
''' </summary>
''' <param name="mac">MAC地址</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function Lease_RemoveByMacAddress(ByVal mac As String) As String
mac = mac.Replace("-", ":")
Return vbNewLine & "/ip dhcp-server lease {:foreach i in=[find mac-address=" & mac & "] do={remove $i}}"
End Function
End Class
''' <summary>
''' ARP脚本
''' </summary>
''' <remarks></remarks>
Public Class ARP
''' <summary>
''' 根据MAC地址创建arp的删除脚本
''' </summary>
''' <param name="mac">MAC地址</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function RemoveByMacAddress(ByVal mac As String) As String
mac = mac.Replace("-", ":")
Return vbNewLine & "/ip arp {:foreach i in=[find mac-address=" & mac & "] do={remove $i}}"
End Function
End Class
''' <summary>
''' 热点
''' </summary>
''' <remarks></remarks>
Public Class Hotspot
''' <summary>
''' 根据MAC地址创建/ip hotspot ip-binding的删除脚本
''' </summary>
''' <param name="mac">MAC地址</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function IPBinding_RemoveByMacAddress(ByVal mac As String) As String
mac = mac.Replace("-", ":")
Return vbNewLine & "/ip hotspot ip-binding {:foreach i in=[find mac-address=" & mac & "] do={remove $i}}"
End Function
End Class
End Class
|
sugartomato/AllProjects
|
ZS.RouterOS/ZS.RouterOS/ScriptHelper.vb
|
Visual Basic
|
apache-2.0
| 1,919
|
' ******************************************************************************
' **
' ** Yahoo! Managed
' ** Written by Marius Häusler 2011
' ** It would be pleasant, if you contact me when you are using this code.
' ** Contact: YahooFinanceManaged@gmail.com
' ** Project Home: http://code.google.com/p/yahoo-finance-managed/
' **
' ******************************************************************************
' **
' ** Copyright 2011 Marius Häusler
' **
' ** Licensed under the Apache License, Version 2.0 (the "License");
' ** you may not use this file except in compliance with the License.
' ** You may obtain a copy of the License at
' **
' ** http://www.apache.org/licenses/LICENSE-2.0
' **
' ** Unless required by applicable law or agreed to in writing, software
' ** distributed under the License is distributed on an "AS IS" BASIS,
' ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' ** See the License for the specific language governing permissions and
' ** limitations under the License.
' **
' ******************************************************************************
Namespace Base
''' <summary>
''' Describes the end state of a connection.
''' </summary>
''' <remarks></remarks>
Public Enum ConnectionState
''' <summary>
''' Download process completed successfully without timeout, errors or cancelations
''' </summary>
''' <remarks></remarks>
Success
''' <summary>
''' Download process was canceled by user interaction
''' </summary>
''' <remarks></remarks>
Canceled
''' <summary>
''' Download process reached the setted timeout span
''' </summary>
''' <remarks></remarks>
Timeout
''' <summary>
''' An Error occured during download process
''' </summary>
''' <remarks></remarks>
ErrorOccured
End Enum
End Namespace
|
agassan/YahooManaged
|
MaasOne.YahooManaged/Base/Enums.vb
|
Visual Basic
|
apache-2.0
| 1,990
|
Imports BVSoftware.Bvc5.Core
Imports System.Collections.ObjectModel
Partial Class BVAdmin_Configuration_Workflow_Edit
Inherits BaseAdminPage
Protected Sub Page_PreInit1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Me.PageTitle = "Edit Workflow"
Me.CurrentTab = AdminTabType.Configuration
ValidateCurrentUserHasPermission(Membership.SystemPermissions.SettingsView)
End Sub
Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Request.QueryString("id") IsNot Nothing Then
Me.BvinField.Value = Request.QueryString("id")
End If
LoadWorkflow()
End If
End Sub
Private Sub LoadStepList(ByVal flowType As BusinessRules.WorkFlowType)
Me.lstSteps.Items.Clear()
Select Case flowType
Case BusinessRules.WorkFlowType.OrderWorkFlow
For i As Integer = 0 To BusinessRules.AvailableTasks.OrderTasks.Count - 1
lstSteps.Items.Add(New ListItem(BusinessRules.AvailableTasks.OrderTasks(i).TaskName, BusinessRules.AvailableTasks.OrderTasks(i).TaskId))
Next
Case BusinessRules.WorkFlowType.ProductWorkFlow
For i As Integer = 0 To BusinessRules.AvailableTasks.ProductTasks.Count - 1
lstSteps.Items.Add(New ListItem(BusinessRules.AvailableTasks.ProductTasks(i).TaskName, BusinessRules.AvailableTasks.ProductTasks(i).TaskId))
Next
Case BusinessRules.WorkFlowType.ShippingWorkFlow
For i As Integer = 0 To BusinessRules.AvailableTasks.ShippingTasks.Count - 1
lstSteps.Items.Add(New ListItem(BusinessRules.AvailableTasks.ShippingTasks(i).TaskName, BusinessRules.AvailableTasks.ShippingTasks(i).TaskId))
Next
Case BusinessRules.WorkFlowType.Uknown
' Do Nothing
End Select
If Me.lstSteps.Items.Count < 1 Then
Me.lstSteps.Items.Add("- No Tasks Found -")
End If
End Sub
Private Sub LoadWorkflow()
Dim w As BusinessRules.Workflow = BusinessRules.Workflow.FindByBvin(Me.BvinField.Value)
LoadStepList(w.ContextType)
Me.lblTitle.Text = w.Name
Me.GridView1.DataSource = w.Steps
Me.GridView1.DataBind()
Me.GridView1.UpdateAfterCallBack = True
End Sub
Protected Sub btnNew_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNew.Click
Me.msg.ClearMessage()
Dim s As New BusinessRules.WorkFlowStep
s.ControlName = Me.lstSteps.SelectedValue
s.DisplayName = Me.lstSteps.SelectedItem.Text
s.WorkFlowBvin = Me.BvinField.Value
BusinessRules.WorkFlowStep.Insert(s)
LoadWorkflow()
End Sub
Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit
Me.msg.ClearMessage()
Dim bvin As String = String.Empty
bvin = CType(sender, GridView).DataKeys(e.RowIndex).Value.ToString
BusinessRules.WorkFlowStep.MoveDown(bvin, Me.BvinField.Value)
LoadWorkflow()
End Sub
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ws As BusinessRules.WorkFlowStep = CType(e.Row.DataItem, BusinessRules.WorkFlowStep)
Dim controlFound As Boolean = False
Dim editControl As System.Web.UI.UserControl
Dim t As BusinessRules.Task = FindAvailableTask(ws.ControlName)
If TypeOf t Is BusinessRules.OrderTask Then
' Order Task
editControl = Content.ModuleController.LoadOrderTaskEditor(t.TaskName, Me)
Else
' Product Task
editControl = Content.ModuleController.LoadProductTaskEditor(t.TaskName, Me)
End If
If TypeOf editControl Is Content.BVModule Then
CType(editControl, Content.BVModule).BlockId = ws.Bvin
controlFound = True
End If
' Check for Editor
Dim lnkEdit As HyperLink = e.Row.FindControl("lnkEdit")
If lnkEdit IsNot Nothing Then
lnkEdit.Visible = controlFound
End If
End If
End Sub
Private Function FindAvailableTask(ByVal bvin As String) As BusinessRules.Task
Dim result As BusinessRules.Task = New BusinessRules.NullTask
Dim found As Boolean = False
For i As Integer = 0 To BusinessRules.AvailableTasks.OrderTasks.Count - 1
If BusinessRules.AvailableTasks.OrderTasks(i).TaskId = bvin Then
result = BusinessRules.AvailableTasks.OrderTasks(i)
found = True
Exit For
End If
Next
For i As Integer = 0 To BusinessRules.AvailableTasks.ProductTasks.Count - 1
If BusinessRules.AvailableTasks.ProductTasks(i).TaskId = bvin Then
result = BusinessRules.AvailableTasks.ProductTasks(i)
found = True
Exit For
End If
Next
For i As Integer = 0 To BusinessRules.AvailableTasks.ShippingTasks.Count - 1
If BusinessRules.AvailableTasks.ShippingTasks(i).TaskId = bvin Then
result = BusinessRules.AvailableTasks.ShippingTasks(i)
found = True
Exit For
End If
Next
Return result
End Function
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Me.msg.ClearMessage()
Dim bvin As String = String.Empty
bvin = CType(sender, GridView).DataKeys(e.RowIndex).Value.ToString
BusinessRules.WorkFlowStep.Delete(bvin)
LoadWorkflow()
End Sub
Protected Sub btnOk_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnOk.Click
Response.Redirect("Workflow.aspx")
End Sub
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Me.msg.ClearMessage()
Dim bvin As String = String.Empty
bvin = CType(sender, GridView).DataKeys(e.RowIndex).Value.ToString
BusinessRules.WorkFlowStep.MoveUp(bvin, Me.BvinField.Value)
LoadWorkflow()
End Sub
End Class
|
ajaydex/Scopelist_2015
|
BVAdmin/Configuration/Workflow_Edit.aspx.vb
|
Visual Basic
|
apache-2.0
| 6,765
|
Dim impressora = new System.IO.StreamWriter(@"\\.\COM1");
impressora.Write("Teste");
impressora.Flush();
impressora.Close();
//http://pt.stackoverflow.com/q/15287/101
|
maniero/SOpt
|
VB.NET/PrinterPort.vb
|
Visual Basic
|
mit
| 168
|
Imports System.Web
Imports System.Web.Services
Imports System
Imports System.IO
Imports System.Net
Public Class feedproxy1
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'Address of URL
'Dim URL As String = "http://www.jackslocum.com/yui/feed/"
Dim URL As String = context.Request.Form("feed")
'Only allow http:// prefix
If IsNothing(URL) Then
Exit Sub
End If
If URL.Substring(0, 7) = "http://" Then
Try
'Dim enc As Encoding = Encoding.GetEncoding("UTF-8")
Dim enc As Encoding = Encoding.GetEncoding("ISO-8859-1")
Dim request As HttpWebRequest = WebRequest.Create(URL)
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As StreamReader = New StreamReader(response.GetResponseStream(), enc)
Dim str As String '= reader.ReadLine()
Dim reply As String = ""
'Do While str.Length > 0 And Not reader.EndOfStream
Do While Not reader.EndOfStream
str = reader.ReadLine()
reply &= str & vbCrLf
'Console.WriteLine(str)
Loop
context.Response.ContentType = "text/xml"
context.Response.ContentEncoding = enc
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
context.Response.Cache.SetCacheability(HttpCacheability.Public)
context.Response.Write(reply)
Catch ex As Exception
End Try
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
|
grasscrm/gdesigner
|
editor/lib/sources/ext-2.0.2/examples/feed-viewer/feed-proxy.ashx.vb
|
Visual Basic
|
apache-2.0
| 1,671
|
Imports System.Collections.Generic
Namespace Objects
Public Class GlobalPermissions
Private Shared m_Permissions As New Dictionary(Of String, IPermissionObject)
Public Sub Add(ByVal permission As IPermissionObject)
If m_Permissions.ContainsKey(permission.Name) Then
m_Permissions(permission.Name).Select = m_Permissions(permission.Name).Select Or permission.Select
m_Permissions(permission.Name).Insert = m_Permissions(permission.Name).Insert Or permission.Insert
m_Permissions(permission.Name).Update = m_Permissions(permission.Name).Update Or permission.Update
m_Permissions(permission.Name).Delete = m_Permissions(permission.Name).Delete Or permission.Delete
m_Permissions(permission.Name).Execute = m_Permissions(permission.Name).Execute Or permission.Execute
Else
m_Permissions.Add(permission.Name, permission)
End If
End Sub
Public Sub Remove(ByVal permissionObjectName As String)
If m_Permissions.ContainsKey(permissionObjectName) Then
m_Permissions.Remove(permissionObjectName)
End If
End Sub
Public Shared Sub Clear()
m_Permissions.Clear()
End Sub
Public Shared ReadOnly Property Permissions() As IDictionary(Of String, IPermissionObject)
Get
Return m_Permissions
End Get
End Property
End Class
End Namespace
|
EIDSS/EIDSS-Legacy
|
EIDSS v6/vb/Shared/bv_common/Objects/Permisions/GlobalPermissions.vb
|
Visual Basic
|
bsd-2-clause
| 1,554
|
' 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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class AttributeScopeKeywordRecommenderTests
Inherits RecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileTest()
VerifyRecommendationsContain(<File><|</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileAfterImportsTest()
VerifyRecommendationsContain(<File>
Imports Goo
<|</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileBeforeClassTest()
VerifyRecommendationsContain(<File>
<|
Class Goo
End Class</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileInsideClassTest()
VerifyRecommendationsAreExactly(<File>
Class Goo
<|
End Class</File>, {"Global"})
End Sub
<WorkItem(542207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542207")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileAtStartOfMalformedAttributeTest()
VerifyRecommendationsContain(<File><![CDATA[<|Assembly: AssemblyDelaySignAttribute(True)>]]></File>,
"Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesAtEndOfFileTest()
VerifyRecommendationsContain(<File>
Class goo
End Class
<|
</File>, "Assembly", "Module")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesAfterEolTest()
VerifyRecommendationsContain(<File>
Class goo
End Class
<
|
</File>, "Assembly", "Module")
End Sub
End Class
End Namespace
|
mavasani/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/AttributeScopesKeywordRecommenderTests.vb
|
Visual Basic
|
mit
| 2,459
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.InlineTemporary
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InlineMethod
Public Class VisualBasicInlineMethodTests_CrossLanguage
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Dim testWorkspace = DirectCast(workspace, TestWorkspace)
Return testWorkspace.ExportProvider.GetExportedValue(Of VisualBasicInlineMethodRefactoringProvider)
End Function
Private Async Function TestNoActionIsProvided(initialMarkup As String) As Task
Dim workspace = CreateWorkspaceFromOptions(initialMarkup, Nothing)
Dim actions = Await GetCodeActionsAsync(workspace, Nothing).ConfigureAwait(False)
Assert.True(actions.Item1.IsEmpty())
End Function
' Because this issue: https://github.com/dotnet/roslyn-sdk/issues/464
' it is hard to test cross language scenario.
' After it is resolved then this test should be merged to the other test class
<Fact>
Public Async Function TestCrossLanguageInline() As Task
Dim input = "
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document>
public class TestClass
{
private void Callee()
{
}
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<ProjectReference>CSAssembly</ProjectReference>
<Document>
Public Class VBClass
Private Sub Caller()
Dim x = new TestClass()
x.Cal[||]lee()
End Sub
End Class
</Document>
</Project>
</Workspace>"
Await TestNoActionIsProvided(input).ConfigureAwait(False)
End Function
End Class
End Namespace
|
brettfo/roslyn
|
src/EditorFeatures/VisualBasicTest/InlineMethod/VisualBasicInlineMethodTests_CrossLanguage.vb
|
Visual Basic
|
apache-2.0
| 2,501
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.GoToAdjacentMember
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GoToAdjacentMember
Public Class VisualBasicGoToAdjacentMemberTests
Inherits AbstractGoToAdjacentMemberTests
Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic
Protected Overrides ReadOnly Property DefaultParseOptions As ParseOptions = VisualBasicParseOptions.Default
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function EmptyFile() As Task
Assert.Null(Await GetTargetPositionAsync("$$", next:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function ClassWithNoMembers() As Task
Dim code = "Class C
$$
End Class"
Assert.Null(Await GetTargetPositionAsync(code, next:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function BeforeClassWithMember() As Task
Dim code = "$$
Class C
[||]Sub M()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function AfterClassWithMember() As Task
Dim code = "
Class C
[||]Sub M()
End Sub
End Class
$$"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function BetweenClasses() As Task
Dim code = "
Class C1
Sub M()
End Sub
End Class
$$
Class C2
[||]Sub M()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function BetweenClassesPrevious() As Task
Dim code = "
Class C1
[||]Sub M()
End Sub
End Class
$$
Class C2
Sub M()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function FromFirstMemberToSecond() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function FromSecondToFirst() As Task
Dim code = "
Class C
[||]Sub M1()
End Sub
$$Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function NextWraps() As Task
Dim code = "
Class C
[||]Sub M1()
End Sub
$$Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function PreviousWraps() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function DescendsIntoNestedType() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
Class N
[||]Sub M2()
End Sub
End Class
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function StopsAtConstructor() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Public Sub New()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function StopsAtOperator() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Shared Operator +(left As C, right As C) As C
Throw New System.NotImplementedException()
End Operator
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
Shared Operator +(left As VisualBasicGoToAdjacentMemberTests, right As VisualBasicGoToAdjacentMemberTests) As VisualBasicGoToAdjacentMemberTests
Throw New System.NotImplementedException()
End Operator
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function StopsAtField() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Dim f as Integer
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function StopsAtFieldlikeEvent() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Event E As System.EventHandler
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function StopsAtAutoProperty() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Property P As Integer
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function StopsAtPropertyWithAccessors() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Property P As Integer
Get
Return 42
End Get
Set(value As Integer)
End Set
End Property
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function SkipsPropertyAccessors() As Task
Dim code = "
Class C
Sub M1()
End Sub
$$Property P As Integer
Get
Return 42
End Get
Set(value As Integer)
End Set
End Property
[||]Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function FromInsidePropertyAccessor() As Task
Dim code = "
Class C
Sub M1()
End Sub
Property P As Integer
Get
Return $$42
End Get
Set(value As Integer)
End Set
End Property
[||]Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function StopsAtEventWithAddRemove() As Task
Dim code = "
Class C
$$Sub M1()
End Sub
[||]Custom Event E As EventHandler
AddHandler(value As EventHandler)
End AddHandler
RemoveHandler(value As EventHandler)
End RemoveHandler
RaiseEvent(sender As Object, e As EventArgs)
End RaiseEvent
End Event
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function SkipsEventAddRemove() As Task
Dim code = "
Class C
Sub M1()
End Sub
$$Custom Event E As EventHandler
AddHandler(value As EventHandler)
End AddHandler
RemoveHandler(value As EventHandler)
End RemoveHandler
RaiseEvent(sender As Object, e As EventArgs)
End RaiseEvent
End Event
[||]Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function FromInsideMethod() As Task
Dim code = "
Class C
Sub M1()
$$System.Console.WriteLine()
End Sub
[||]Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function NextFromBetweenMethods() As Task
Dim code = "
Class C
Sub M1()
End Sub
$$
[||]Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function PreviousFromBetweenMethods() As Task
Dim code = "
Class C
[||]Sub M1()
End Sub
$$
Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function NextFromBetweenMethodsInTrailingTrivia() As Task
Dim code = "
Class C
Sub M1()
End Sub $$
[||]Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
<WorkItem(10588, "https://github.com/dotnet/roslyn/issues/10588")>
Public Async Function PreviousFromInsideCurrent() As Task
Dim code = "
class C
[||]Sub M1()
Console.WriteLine($$)
End Sub
Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function PreviousFromBetweenMethodsInTrailingTrivia() As Task
Dim code = "
Class C
[||]Sub M1()
End Sub $$
Sub M2()
End Sub
End Class"
Await AssertNavigatedAsync(code, next:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function NextInScript() As Task
Dim code = "
$$Sub M1()
End Sub
[||]Sub M2()
End Sub"
Await AssertNavigatedAsync(code, next:=True, sourceCodeKind:=SourceCodeKind.Script)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
<WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
Public Async Function PrevInScript() As Task
Dim code = "
[||]Sub M1()
End Sub
$$Sub M2()
End Sub"
Await AssertNavigatedAsync(code, next:=False, sourceCodeKind:=SourceCodeKind.Script)
End Function
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/EditorFeatures/VisualBasicTest/GoToAdjacentMember/VisualBasicGoToAdjacentMemberTests.vb
|
Visual Basic
|
apache-2.0
| 13,232
|
'////////////////////////////////////////////////////////////////////////
' 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
Imports System.IO
Imports Aspose.Words
Imports Aspose.Words.Layout
Public Class PageNumbersOfNodes
Public Shared Sub Run()
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir_WorkingWithDocument()
Dim doc As New Document(dataDir & "TestFile.docx")
' Create and attach collector before the document before page layout is built.
Dim layoutCollector As New LayoutCollector(doc)
' This will build layout model and collect necessary information.
doc.UpdatePageLayout()
' Print the details of each document node including the page numbers.
For Each node As Node In doc.FirstSection.Body.GetChildNodes(NodeType.Any, True)
Console.WriteLine(" --------- ")
Console.WriteLine("NodeType: " & node.NodeTypeToString(node.NodeType))
Console.WriteLine("Text: """ & node.ToString(SaveFormat.Text).Trim() & """")
Console.WriteLine("Page Start: " & layoutCollector.GetStartPageIndex(node))
Console.WriteLine("Page End: " & layoutCollector.GetEndPageIndex(node))
Console.WriteLine(" --------- ")
Console.WriteLine()
Next node
' Detatch the collector from the document.
layoutCollector.Document = Nothing
Console.WriteLine(vbNewLine & "Found the page numbers of all nodes successfully")
End Sub
End Class
|
dtscal/Aspose_Words_NET
|
Examples/VisualBasic/Programming-Documents/Document/PageNumbersOfNodes.vb
|
Visual Basic
|
mit
| 1,901
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class SplashScreen1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
Friend WithEvents ApplicationTitle As System.Windows.Forms.Label
Friend WithEvents Version As System.Windows.Forms.Label
Friend WithEvents Copyright As System.Windows.Forms.Label
Friend WithEvents MainLayoutPanel As System.Windows.Forms.TableLayoutPanel
Friend WithEvents DetailsLayoutPanel As System.Windows.Forms.TableLayoutPanel
'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(SplashScreen1))
Me.MainLayoutPanel = New System.Windows.Forms.TableLayoutPanel
Me.DetailsLayoutPanel = New System.Windows.Forms.TableLayoutPanel
Me.Version = New System.Windows.Forms.Label
Me.Copyright = New System.Windows.Forms.Label
Me.ApplicationTitle = New System.Windows.Forms.Label
Me.MainLayoutPanel.SuspendLayout()
Me.DetailsLayoutPanel.SuspendLayout()
Me.SuspendLayout()
'
'MainLayoutPanel
'
Me.MainLayoutPanel.BackgroundImage = CType(resources.GetObject("MainLayoutPanel.BackgroundImage"), System.Drawing.Image)
Me.MainLayoutPanel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch
Me.MainLayoutPanel.ColumnCount = 2
Me.MainLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 243.0!))
Me.MainLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!))
Me.MainLayoutPanel.Controls.Add(Me.DetailsLayoutPanel, 1, 1)
Me.MainLayoutPanel.Controls.Add(Me.ApplicationTitle, 1, 0)
Me.MainLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.MainLayoutPanel.Location = New System.Drawing.Point(0, 0)
Me.MainLayoutPanel.Name = "MainLayoutPanel"
Me.MainLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 218.0!))
Me.MainLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 38.0!))
Me.MainLayoutPanel.Size = New System.Drawing.Size(536, 349)
Me.MainLayoutPanel.TabIndex = 0
'
'DetailsLayoutPanel
'
Me.DetailsLayoutPanel.Anchor = System.Windows.Forms.AnchorStyles.None
Me.DetailsLayoutPanel.BackColor = System.Drawing.Color.Transparent
Me.DetailsLayoutPanel.ColumnCount = 1
Me.DetailsLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 247.0!))
Me.DetailsLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 142.0!))
Me.DetailsLayoutPanel.Controls.Add(Me.Version, 0, 0)
Me.DetailsLayoutPanel.Controls.Add(Me.Copyright, 0, 1)
Me.DetailsLayoutPanel.Location = New System.Drawing.Point(266, 244)
Me.DetailsLayoutPanel.Name = "DetailsLayoutPanel"
Me.DetailsLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.0!))
Me.DetailsLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.0!))
Me.DetailsLayoutPanel.Size = New System.Drawing.Size(247, 79)
Me.DetailsLayoutPanel.TabIndex = 1
'
'Version
'
Me.Version.Anchor = System.Windows.Forms.AnchorStyles.None
Me.Version.BackColor = System.Drawing.Color.Transparent
Me.Version.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Version.Location = New System.Drawing.Point(3, 9)
Me.Version.Name = "Version"
Me.Version.Size = New System.Drawing.Size(241, 20)
Me.Version.TabIndex = 1
Me.Version.Text = "Version {0}.{1:00}"
'
'Copyright
'
Me.Copyright.Anchor = System.Windows.Forms.AnchorStyles.None
Me.Copyright.BackColor = System.Drawing.Color.Transparent
Me.Copyright.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Copyright.Location = New System.Drawing.Point(3, 39)
Me.Copyright.Name = "Copyright"
Me.Copyright.Size = New System.Drawing.Size(241, 40)
Me.Copyright.TabIndex = 2
Me.Copyright.Text = "Copyright"
'
'ApplicationTitle
'
Me.ApplicationTitle.Anchor = System.Windows.Forms.AnchorStyles.None
Me.ApplicationTitle.BackColor = System.Drawing.Color.Transparent
Me.ApplicationTitle.Font = New System.Drawing.Font("Microsoft Sans Serif", 18.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.ApplicationTitle.Location = New System.Drawing.Point(266, 3)
Me.ApplicationTitle.Name = "ApplicationTitle"
Me.ApplicationTitle.Size = New System.Drawing.Size(247, 212)
Me.ApplicationTitle.TabIndex = 0
Me.ApplicationTitle.Text = "Application Title"
Me.ApplicationTitle.TextAlign = System.Drawing.ContentAlignment.BottomLeft
'
'SplashScreen1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(536, 349)
Me.ControlBox = False
Me.Controls.Add(Me.MainLayoutPanel)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "SplashScreen1"
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.MainLayoutPanel.ResumeLayout(False)
Me.DetailsLayoutPanel.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
End Class
|
hhaslam11/Visual-Basic-Projects
|
Profit and Loss/Profit and Loss/SplashScreen1.Designer.vb
|
Visual Basic
|
mit
| 6,855
|
Sub TurnFilterOff()
'removes AutoFilter if one exists
Worksheets("Data").AutoFilterMode = False
End Sub
|
Jonnokc/Excel_VBA
|
Validation_Form/Other/Turn_Off_AutoFilter.vb
|
Visual Basic
|
mit
| 113
|
Option Strict Off
Option Explicit On
Module basCryptoProcs
Public g_blnCaseSensitiveUserID As Boolean
Public g_blnCaseSensitivePWord As Boolean
Public g_blnEnhancedProvider As Boolean
Public g_intHashType As Short
Public Const PGM_NAME As String = "4LIQ Serials"
Public Const MAX_PATH As Integer = 260
Public Const APP_NAME As String = "PWDTest"
Public Const APP_SECTION As String = "Settings"
Public Const MYNAME As String = "4LIQ"
Public strCDKey As String
Public Function ConvertToArray(ByRef strInput As String) As Byte()
'UPGRADE_ISSUE: clsCryptoAPI object was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6B85A2A7-FE9F-4FBE-AA0C-CF11AC86A305"'
Dim cCrypto As clsCryptoAPI
cCrypto = New clsCryptoAPI
'UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.StringToByteArray. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
ConvertToArray = cCrypto.StringToByteArray(strInput)
'UPGRADE_NOTE: Object cCrypto may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cCrypto = Nothing
End Function
Public Function Correct_Password_Length(ByRef arPWord() As Byte) As Boolean
Dim intLength As Short
Dim strPWord As String
'UPGRADE_ISSUE: clsCryptoAPI object was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6B85A2A7-FE9F-4FBE-AA0C-CF11AC86A305"'
Dim cCrypto As clsCryptoAPI
cCrypto = New clsCryptoAPI
'UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.ByteArrayToString. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
strPWord = cCrypto.ByteArrayToString(arPWord)
intLength = Len(strPWord)
'UPGRADE_NOTE: Object cCrypto may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cCrypto = Nothing
If intLength = 0 Then
MsgBox("A Password / Passphrase must be entered.", MsgBoxStyle.Information Or MsgBoxStyle.OKOnly, "Password / Passphrase missing")
Correct_Password_Length = False
'UPGRADE_NOTE: Object cCrypto may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cCrypto = Nothing
Exit Function
End If
If intLength < 8 Then
' If not a valid length
MsgBox("Password / Passphrase must be a minimum length of eight(8) characters.", MsgBoxStyle.Information Or MsgBoxStyle.OKOnly, "Invalid Password / Passphrase length")
Correct_Password_Length = False
'UPGRADE_NOTE: Object cCrypto may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cCrypto = Nothing
Exit Function
End If
Correct_Password_Length = True
'UPGRADE_NOTE: Object cCrypto may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cCrypto = Nothing
End Function
Public Function CurrentSettings_Get(ByRef strKey As String) As Object
CurrentSettings_Get = GetSetting(APP_NAME, APP_SECTION, strKey)
End Function
Public Function CurrentSettings_Save(ByRef strKey As String, ByRef varValue As Object) As String
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
SaveSetting(APP_NAME, APP_SECTION, strKey, varValue)
End Function
Public Sub Initial_settings()
Dim varValue As Object
' ---------------------------------------------------------------------------
' Case sensitive User ID setting (Default = True)
' ---------------------------------------------------------------------------
'UPGRADE_WARNING: Couldn't resolve default property of object CurrentSettings_Get(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
varValue = CurrentSettings_Get("UserID")
' if nothing of file, write default to the registry
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
If Len(Trim(varValue)) = 0 Then
g_blnCaseSensitiveUserID = True
CurrentSettings_Save("UserID", g_blnCaseSensitiveUserID)
Else
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
g_blnCaseSensitiveUserID = CBool(varValue)
End If
' ---------------------------------------------------------------------------
' Case sensitive Password / Passphrase setting (Default = True)
' ---------------------------------------------------------------------------
'UPGRADE_WARNING: Couldn't resolve default property of object CurrentSettings_Get(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
varValue = CurrentSettings_Get("Password")
' if nothing of file, write default to the registry
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
If Len(Trim(varValue)) = 0 Then
g_blnCaseSensitivePWord = True
CurrentSettings_Save("Password", g_blnCaseSensitivePWord)
Else
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
g_blnCaseSensitivePWord = CBool(varValue)
End If
' ---------------------------------------------------------------------------
' Whether or not to use the Enhanced Provider
' ---------------------------------------------------------------------------
'UPGRADE_WARNING: Couldn't resolve default property of object CurrentSettings_Get(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
varValue = CurrentSettings_Get("EnhancedProvider")
' if nothing of file, write default to the registry
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
If Len(Trim(varValue)) = 0 Then
g_blnEnhancedProvider = False
CurrentSettings_Save("EnhancedProvider", g_blnEnhancedProvider)
Else
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
g_blnEnhancedProvider = CBool(varValue)
End If
' ---------------------------------------------------------------------------
' Hash method (Default = MD5)
' ---------------------------------------------------------------------------
'UPGRADE_WARNING: Couldn't resolve default property of object CurrentSettings_Get(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
varValue = CurrentSettings_Get("HashMethod")
' if nothing of file, write default to the registry
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
If Len(Trim(varValue)) = 0 Then
g_intHashType = 2
CurrentSettings_Save("HashMethod", g_intHashType)
Else
'UPGRADE_WARNING: Couldn't resolve default property of object varValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
g_intHashType = CShort(varValue)
End If
End Sub
Public Function Same_As_Previous(ByRef arByte1() As Byte, ByRef arByte2() As Byte) As Boolean
Dim strTmp1 As String
Dim strTmp2 As String
'UPGRADE_ISSUE: clsCryptoAPI object was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6B85A2A7-FE9F-4FBE-AA0C-CF11AC86A305"'
Dim cCrypto As clsCryptoAPI
cCrypto = New clsCryptoAPI
' ---------------------------------------------------------------------------
' Convert byte arrays to string data
' ---------------------------------------------------------------------------
'UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.ByteArrayToString. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
strTmp1 = cCrypto.ByteArrayToString(arByte1)
'UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.ByteArrayToString. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
strTmp2 = cCrypto.ByteArrayToString(arByte2)
' ---------------------------------------------------------------------------
' Make the comparisons to see if these two arrays are the same
' ---------------------------------------------------------------------------
If StrComp(strTmp1, strTmp2, CompareMethod.Binary) = 0 Then
Same_As_Previous = True
Else
Same_As_Previous = False
End If
' ---------------------------------------------------------------------------
' Empty data strings
' ---------------------------------------------------------------------------
strTmp1 = New String(Chr(0), 250)
strTmp2 = New String(Chr(0), 250)
'UPGRADE_NOTE: Object cCrypto may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cCrypto = Nothing
End Function
End Module
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/basCryptoProcs.vb
|
Visual Basic
|
mit
| 11,282
|
' 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.
Option Strict Off
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.InvertIf
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InvertIf
Public Class InvertSingleLineIfTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicInvertSingleLineIfCodeRefactoringProvider()
End Function
Public Async Function TestFixOneAsync(initial As String, expected As String) As Task
Await TestInRegularAndScriptAsync(CreateTreeText(initial), CreateTreeText(expected))
End Function
Public Shared Function CreateTreeText(initial As String) As String
Return "
Module Module1
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Boolean = True
Dim d As Boolean = True
" + initial + "
End Sub
Private Sub aMethod()
End Sub
Private Sub bMethod()
End Sub
Private Sub cMethod()
End Sub
Private Sub dMethod()
End Sub
End Module
"
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestAnd() As Task
Await TestFixOneAsync(
"
[||]If a And b Then aMethod() Else bMethod()
",
"
If Not a Or Not b Then bMethod() Else aMethod()
")
End Function
<WorkItem(545700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545700")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestAddEmptyArgumentListIfNeeded() As Task
Dim markup =
<File>
Module A
Sub Main()
[||]If True Then : Goo : Goo
Else
End If
End Sub
Sub Goo()
End Sub
End Module
</File>
Await TestMissingAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestAndAlso() As Task
Await TestFixOneAsync(
"
[||]If a AndAlso b Then aMethod() Else bMethod()
",
"
If Not a OrElse Not b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestCall() As Task
Await TestFixOneAsync(
"
[||]If a.Goo() Then aMethod() Else bMethod()
",
"
If Not a.Goo() Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestNotIdentifier() As Task
Await TestFixOneAsync(
"
[||]If Not a Then aMethod() Else bMethod()
",
"
If a Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestTrueLiteral() As Task
Await TestFixOneAsync(
"
[||]If True Then aMethod() Else bMethod()
",
"
If False Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestFalseLiteral() As Task
Await TestFixOneAsync(
"
[||]If False Then aMethod() Else bMethod()
",
"
If True Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestEquals() As Task
Await TestFixOneAsync(
"
[||]If a = b Then aMethod() Else bMethod()
",
"
If a <> b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestNotEquals() As Task
Await TestFixOneAsync(
"
[||]If a <> b Then aMethod() Else bMethod()
",
"
If a = b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestLessThan() As Task
Await TestFixOneAsync(
"
[||]If a < b Then aMethod() Else bMethod()
",
"
If a >= b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestLessThanOrEqual() As Task
Await TestFixOneAsync(
"
[||]If a <= b Then aMethod() Else bMethod()
",
"
If a > b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestGreaterThan() As Task
Await TestFixOneAsync(
"
[||]If a > b Then aMethod() Else bMethod()
",
"
If a <= b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestGreaterThanOrEqual() As Task
Await TestFixOneAsync(
"
[||]If a >= b Then aMethod() Else bMethod()
",
"
If a < b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestIs() As Task
Await TestFixOneAsync(
"
Dim myObject As New Object
Dim thisObject = myObject
[||]If thisObject Is myObject Then aMethod() Else bMethod()
",
"
Dim myObject As New Object
Dim thisObject = myObject
If thisObject IsNot myObject Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestIsNot() As Task
Await TestFixOneAsync(
"
Dim myObject As New Object
Dim thisObject = myObject
[||]If thisObject IsNot myObject Then aMethod() Else bMethod()
",
"
Dim myObject As New Object
Dim thisObject = myObject
If thisObject Is myObject Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestOr() As Task
Await TestFixOneAsync(
"
[||]If a Or b Then aMethod() Else bMethod()
",
"
If Not a And Not b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestOrElse() As Task
Await TestFixOneAsync(
"
[||]If a OrElse b Then aMethod() Else bMethod()
",
"
If Not a AndAlso Not b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestOr2() As Task
Await TestFixOneAsync(
"
I[||]f Not a Or Not b Then aMethod() Else bMethod()
",
"
If a And b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestOrElse2() As Task
Await TestFixOneAsync(
"
I[||]f Not a OrElse Not b Then aMethod() Else bMethod()
",
"
If a AndAlso b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestAnd2() As Task
Await TestFixOneAsync(
"
[||]If Not a And Not b Then aMethod() Else bMethod()
",
"
If a Or b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestAndAlso2() As Task
Await TestFixOneAsync(
"
[||]If Not a AndAlso Not b Then aMethod() Else bMethod()
",
"
If a OrElse b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestXor() As Task
Await TestFixOneAsync(
"
I[||]f a Xor b Then aMethod() Else bMethod()
",
"
If Not (a Xor b) Then bMethod() Else aMethod()
")
End Function
<WorkItem(545411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545411")>
<WpfFact(Skip:="545411"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestXor2() As Task
Await TestFixOneAsync(
"
I[||]f Not (a Xor b) Then aMethod() Else bMethod()
",
"
If (a Xor b) Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestNested() As Task
Await TestFixOneAsync(
"
[||]If (((a = b) AndAlso (c <> d)) OrElse ((e < f) AndAlso (Not g))) Then aMethod() Else bMethod()
",
"
If (a <> b OrElse c = d) AndAlso (e >= f OrElse g) Then bMethod() Else aMethod()
")
End Function
<WorkItem(529746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529746")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestEscapeKeywordsIfNeeded1() As Task
Dim markup =
<File>
Imports System.Linq
Module Program
Sub Main()
[||]If True Then Dim q = From x In "" Else Console.WriteLine()
Take()
End Sub
Sub Take()
End Sub
End Module
</File>
Await TestMissingAsync(markup)
End Function
<WorkItem(531471, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531471")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestEscapeKeywordsIfNeeded2() As Task
Dim markup =
<File>
Imports System.Linq
Module Program
Sub Main()
[||]If True Then Dim q = From x In "" Else Console.WriteLine()
Ascending()
End Sub
Sub Ascending()
End Sub
End Module
</File>
Await TestMissingAsync(markup)
End Function
<WorkItem(531471, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531471")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestEscapeKeywordsIfNeeded3() As Task
Dim markup =
<File>
Imports System.Linq
Module Program
Sub Main()
[||]If True Then Dim q = From x In "" Order By x Else Console.WriteLine()
Ascending()
End Sub
Sub Ascending()
End Sub
End Module
</File>
Await TestMissingAsync(markup)
End Function
<WorkItem(531472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531472")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestEscapeKeywordsIfNeeded4() As Task
Dim markup =
<File>
Imports System.Linq
Module Program
Sub Main()
[||]If True Then Dim q = From x In "" Else Console.WriteLine()
Take: Return
End Sub
End Module
</File>
Dim expected =
<File>
Imports System.Linq
Module Program
Sub Main()
If False Then Console.WriteLine() Else Dim q = From x In ""
[Take]: Return
End Sub
End Module
</File>
Await TestMissingAsync(markup)
End Function
<WorkItem(531475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531475")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestEscapeKeywordsIfNeeded5() As Task
Dim markup =
<File>
Imports System.Linq
Module Program
Sub Main()
Dim a = Sub() [||]If True Then Dim q = From x In "" Else Console.WriteLine()
Take()
End Sub
Sub Take()
End Sub
End Module
</File>
Await TestMissingAsync(markup)
End Function
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestSelection() As Task
Await TestFixOneAsync(
"
[|If a And b Then aMethod() Else bMethod()|]
",
"
If Not a Or Not b Then bMethod() Else aMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestMultipleStatementsSingleLineIfStatement() As Task
Await TestFixOneAsync(
"
If[||] a Then aMethod() : bMethod() Else cMethod() : d()
",
"
If Not a Then cMethod() : d() Else aMethod() : bMethod()
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestTriviaAfterSingleLineIfStatement() As Task
Await TestFixOneAsync(
"
[||]If a Then aMethod() Else bMethod() ' I will stay put
",
"
If Not a Then bMethod() Else aMethod() ' I will stay put
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestParenthesizeForLogicalExpressionPrecedence() As Task
Await TestInRegularAndScriptAsync(
"Sub Main()
I[||]f a AndAlso b Or c Then aMethod() Else bMethod()
End Sub
End Module",
"Sub Main()
If (Not a OrElse Not b) And Not c Then bMethod() Else aMethod()
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestParenthesizeComparisonOperands() As Task
Await TestFixOneAsync(
"
[||]If 0 <= <x/>.GetHashCode Then aMethod() Else bMethod()
",
"
If 0 > (<x/>.GetHashCode) Then bMethod() Else aMethod()
")
End Function
<WorkItem(529749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529749")>
<WorkItem(530593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530593")>
<WpfFact(Skip:="Bug 530593"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestNestedSingleLineIfs() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main()
' Invert the 1st If
I[||]f True Then Console.WriteLine(1) Else If True Then Return
End Sub
End Module",
"Module Program
Sub Main()
' Invert the 1st If
If False Then If True Then Return Else : Else Console.WriteLine(1)
End Sub
End Module")
End Function
<WorkItem(529747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529747")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestTryToParenthesizeAwkwardSyntaxInsideSingleLineLambdaMethod() As Task
Await TestMissingAsync(
"Module Program
Sub Main()
' Invert If
Dim x = Sub() I[||]f True Then Dim y Else Console.WriteLine(), z = 1
End Sub
End Module")
End Function
<WorkItem(529756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529756")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestOnCoditionOfSingleLineIf() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
If T[||]rue Then Return Else Console.WriteLine(""a"")
End Sub
End Module",
"Module Program
Sub Main(args As String())
If False Then Console.WriteLine(""a"") Else Return
End Sub
End Module")
End Function
<WorkItem(531101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531101")>
<WpfFact(Skip:="531101"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestImplicitLineContinuationBeforeClosingParenIsRemoved() As Task
Dim markup =
<MethodBody>
[||]If (True OrElse True
) Then
Else
End If
</MethodBody>
Dim expected =
<MethodBody>
If False AndAlso False Then
Else
End If
</MethodBody>
Await TestAsync(markup, expected)
End Function
<WorkItem(530758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530758")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestParenthesizeToKeepParseTheSame1() As Task
Dim markup =
<File>
Module Program
Sub Main()
[||]If 0 >= <x/>.GetHashCode Then Console.WriteLine(1) Else Console.WriteLine(2)
End Sub
End Module
</File>
Dim expected =
<File>
Module Program
Sub Main()
If 0 < (<x/>.GetHashCode) Then Console.WriteLine(2) Else Console.WriteLine(1)
End Sub
End Module
</File>
Await TestAsync(markup, expected)
End Function
<WorkItem(607862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607862")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestParenthesizeToKeepParseTheSame2() As Task
Dim markup =
<File>
Module Program
Sub Main()
Select Nothing
Case Sub() [||]If True Then Dim x Else Return, Nothing
End Select
End Sub
End Module
</File>
Await TestMissingAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)>
Public Async Function TestSingleLineIdentifier() As Task
Await TestFixOneAsync(
"
[||]If a Then aMethod() Else bMethod()
",
"
If Not a Then bMethod() Else aMethod()
")
End Function
End Class
End Namespace
|
diryboy/roslyn
|
src/EditorFeatures/VisualBasicTest/InvertIf/InvertSingleLineIfTests.vb
|
Visual Basic
|
mit
| 17,982
|
Attribute VB_Name = "testVBA"
Public Sub test()
MsgBox "Hello from vba!"
End Sub
|
tafia/xl2txt
|
tests/.issues.xlsb/vba/testVBA.vb
|
Visual Basic
|
mit
| 89
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.3625
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.LearningFluentMigrator.My.MySettings
Get
Return Global.LearningFluentMigrator.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
takas-ho/LearningFluentMigrator.2008
|
LearningFluentMigrator/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,991
|
Imports YamlDotNet.Serialization
Imports System.IO
Public Class YAMLinvTypeReactions
Inherits YAMLFilesBase
Public Const invTypeReactionsFile As String = "invTypeReactions.yaml"
Public Sub New(ByVal YAMLFileName As String, ByVal YAMLFilePath As String, ByRef DatabaseRef As Object, ByRef TranslationRef As YAMLTranslations)
MyBase.New(YAMLFileName, YAMLFilePath, DatabaseRef, TranslationRef)
End Sub
''' <summary>
''' Imports the yaml file into the database set in the constructor
''' </summary>
''' <param name="Params">What the row location is and whether to insert the data or not (for bulk import)</param>
Public Sub ImportFile(ByVal Params As ImportParameters)
Dim DSB = New DeserializerBuilder()
If Not TestForSDEChanges Then
DSB.IgnoreUnmatchedProperties()
End If
DSB = DSB.WithNamingConvention(New NamingConventions.NullNamingConvention)
Dim DS As New Deserializer
DS = DSB.Build
Dim YAMLRecords As New List(Of invTypeReaction)
Dim DataFields As List(Of DBField)
Dim SQL As String = ""
Dim Count As Long = 0
Dim TotalRecords As Long = 0
' Build table
Dim Table As New List(Of DBTableField)
Table.Add(New DBTableField("reactionTypeID", FieldType.int_type, 0, False, True))
Table.Add(New DBTableField("input", FieldType.bit_type, 0, False, True))
Table.Add(New DBTableField("typeID", FieldType.int_type, 0, False, True))
Table.Add(New DBTableField("quantity", FieldType.smallint_type, 0, True))
Call UpdateDB.CreateTable(TableName, Table)
' See if we only want to build the table and indexes
If Not Params.InsertRecords Then
Exit Sub
End If
' Start processing
Call InitGridRow(Params.RowLocation)
Try
' Parse the input text
YAMLRecords = DS.Deserialize(Of List(Of invTypeReaction))(New StringReader(File.ReadAllText(YAMLFile)))
Catch ex As Exception
Call ShowErrorMessage(ex)
End Try
TotalRecords = YAMLRecords.Count
' Process Data
For Each DataField In YAMLRecords
DataFields = New List(Of DBField)
' Build the insert list
DataFields.Add(UpdateDB.BuildDatabaseField("reactionTypeID", DataField.reactionTypeID, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("input", DataField.input, FieldType.bit_type))
DataFields.Add(UpdateDB.BuildDatabaseField("typeID", DataField.typeID, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("quantity", DataField.quantity, FieldType.smallint_type))
Call UpdateDB.InsertRecord(TableName, DataFields)
' Update grid progress
Call UpdateGridRowProgress(Params.RowLocation, Count, TotalRecords)
Count += 1
Next
Call FinalizeGridRow(Params.RowLocation)
End Sub
End Class
Public Class invTypeReaction
Public Property reactionTypeID As Object
Public Property input As Object
Public Property typeID As Object
Public Property quantity As Object
End Class
|
EVEIPH/EVE-SDE-Database-Builder
|
EVE SDE Database Builder/SDE YAML Classses/YAMLinvTypeReactions.vb
|
Visual Basic
|
mit
| 3,232
|
#Region "Microsoft.VisualBasic::9dbe31e5fdb38cb861d6a19f24e201d6, src\mzkit\mzkit\pages\dockWindow\documents\frmHtmlViewer.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Class frmHtmlViewer
'
' Sub: CopyFullPath, frmHtmlViewer_Load, LoadHtml, OpenContainingFolder, PDF
' SaveDocument, WebBrowser1_DocumentCompleted
'
' /********************************************************************************/
#End Region
Imports Microsoft.VisualBasic.ApplicationServices
Imports mzkit.My
Imports WkHtmlToPdf.Arguments
Public Class frmHtmlViewer
Dim url As String
Public Sub PDF(filepath As String)
Static bin As String = Nothing
If bin.StringEmpty Then
bin = $"{App.HOME}/tools/wkhtmltopdf.exe"
If Not bin.FileExists Then
bin = $"{App.HOME}/wkhtmltopdf.exe"
End If
End If
If bin.FileExists Then
Dim env As New PdfConvertEnvironment With {
.Debug = False,
.TempFolderPath = TempFileSystem.GetAppSysTempFile,
.Timeout = 60000,
.WkHtmlToPdfPath = bin
}
Dim content As New PdfDocument With {.Url = {WebBrowser1.Url.OriginalString}}
Dim pdfFile As New PdfOutput With {.OutputFilePath = filepath}
Call WkHtmlToPdf.PdfConvert.ConvertHtmlToPdf(content, pdfFile, env)
Else
Call MyApplication.host.showStatusMessage("'wkhtmltopdf' tool is missing for generate PDF file...", My.Resources.StatusAnnotations_Warning_32xLG_color)
End If
End Sub
Public Sub LoadHtml(url As String)
Me.WebBrowser1.Navigate(url)
Me.url = url
End Sub
Protected Overrides Sub CopyFullPath()
Call Clipboard.SetText(url)
End Sub
Protected Overrides Sub OpenContainingFolder()
Try
If url.FileExists Then
Call Process.Start(url.ParentPath)
End If
Catch ex As Exception
End Try
End Sub
Protected Overrides Sub SaveDocument() Handles SavePDFToolStripMenuItem.Click
Using file As New SaveFileDialog With {
.Title = "Export page as pdf file.",
.Filter = "PDF file(*.pdf)|*.pdf"
}
If file.ShowDialog = DialogResult.OK Then
Call PDF(file.FileName)
Call Process.Start(file.FileName)
End If
End Using
End Sub
Private Sub frmHtmlViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
Call ApplyVsTheme(ContextMenuStrip1)
TabText = "Document Viewer"
Icon = My.Resources.IE
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
TabText = WebBrowser1.DocumentTitle
End Sub
End Class
|
xieguigang/MassSpectrum-toolkits
|
src/mzkit/mzkit/pages/dockWindow/documents/frmHtmlViewer.vb
|
Visual Basic
|
mit
| 4,317
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmCompanyEmails
#Region "Windows Form Designer generated code "
<System.Diagnostics.DebuggerNonUserCode()> Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
If Disposing Then
If Not components Is Nothing Then
components.Dispose()
End If
End If
MyBase.Dispose(Disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
Public ToolTip1 As System.Windows.Forms.ToolTip
Public WithEvents _txtFields_7 As System.Windows.Forms.TextBox
Public WithEvents _txtFields_6 As System.Windows.Forms.TextBox
Public WithEvents _txtFields_5 As System.Windows.Forms.TextBox
Public WithEvents _txtFields_4 As System.Windows.Forms.TextBox
Public WithEvents cmdClose As System.Windows.Forms.Button
Public WithEvents cmdCancel As System.Windows.Forms.Button
Public WithEvents picButtons As System.Windows.Forms.Panel
Public WithEvents _txtFields_3 As System.Windows.Forms.TextBox
Public WithEvents _txtFields_2 As System.Windows.Forms.TextBox
Public WithEvents _txtFields_1 As System.Windows.Forms.TextBox
Public WithEvents _txtFields_0 As System.Windows.Forms.TextBox
Public WithEvents Label10 As System.Windows.Forms.Label
Public WithEvents Label9 As System.Windows.Forms.Label
Public WithEvents Shape1 As Microsoft.VisualBasic.PowerPacks.RectangleShape
Public WithEvents Label8 As System.Windows.Forms.Label
Public WithEvents Label7 As System.Windows.Forms.Label
Public WithEvents Label5 As System.Windows.Forms.Label
Public WithEvents Label4 As System.Windows.Forms.Label
Public WithEvents Label3 As System.Windows.Forms.Label
Public WithEvents Label2 As System.Windows.Forms.Label
Public WithEvents Label1 As System.Windows.Forms.Label
Public WithEvents Shape2 As Microsoft.VisualBasic.PowerPacks.RectangleShape
Public WithEvents Label6 As System.Windows.Forms.Label
'Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
Public WithEvents ShapeContainer1 As Microsoft.VisualBasic.PowerPacks.ShapeContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
Me.ShapeContainer1 = New Microsoft.VisualBasic.PowerPacks.ShapeContainer()
Me.Shape1 = New Microsoft.VisualBasic.PowerPacks.RectangleShape()
Me.Shape2 = New Microsoft.VisualBasic.PowerPacks.RectangleShape()
Me._txtFields_7 = New System.Windows.Forms.TextBox()
Me._txtFields_6 = New System.Windows.Forms.TextBox()
Me._txtFields_5 = New System.Windows.Forms.TextBox()
Me._txtFields_4 = New System.Windows.Forms.TextBox()
Me.picButtons = New System.Windows.Forms.Panel()
Me.cmdClose = New System.Windows.Forms.Button()
Me.cmdCancel = New System.Windows.Forms.Button()
Me._txtFields_3 = New System.Windows.Forms.TextBox()
Me._txtFields_2 = New System.Windows.Forms.TextBox()
Me._txtFields_1 = New System.Windows.Forms.TextBox()
Me._txtFields_0 = New System.Windows.Forms.TextBox()
Me.Label10 = New System.Windows.Forms.Label()
Me.Label9 = New System.Windows.Forms.Label()
Me.Label8 = New System.Windows.Forms.Label()
Me.Label7 = New System.Windows.Forms.Label()
Me.Label5 = New System.Windows.Forms.Label()
Me.Label4 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label6 = New System.Windows.Forms.Label()
Me.picButtons.SuspendLayout()
Me.SuspendLayout()
'
'ShapeContainer1
'
Me.ShapeContainer1.Location = New System.Drawing.Point(0, 0)
Me.ShapeContainer1.Margin = New System.Windows.Forms.Padding(0)
Me.ShapeContainer1.Name = "ShapeContainer1"
Me.ShapeContainer1.Shapes.AddRange(New Microsoft.VisualBasic.PowerPacks.Shape() {Me.Shape1, Me.Shape2})
Me.ShapeContainer1.Size = New System.Drawing.Size(298, 282)
Me.ShapeContainer1.TabIndex = 21
Me.ShapeContainer1.TabStop = False
'
'Shape1
'
Me.Shape1.BackColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer))
Me.Shape1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque
Me.Shape1.BorderColor = System.Drawing.SystemColors.WindowText
Me.Shape1.FillColor = System.Drawing.Color.Black
Me.Shape1.Location = New System.Drawing.Point(6, 236)
Me.Shape1.Name = "Shape1"
Me.Shape1.Size = New System.Drawing.Size(287, 31)
'
'Shape2
'
Me.Shape2.BackColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer))
Me.Shape2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque
Me.Shape2.BorderColor = System.Drawing.SystemColors.WindowText
Me.Shape2.FillColor = System.Drawing.Color.Black
Me.Shape2.Location = New System.Drawing.Point(6, 52)
Me.Shape2.Name = "Shape2"
Me.Shape2.Size = New System.Drawing.Size(287, 165)
'
'_txtFields_7
'
Me._txtFields_7.AcceptsReturn = True
Me._txtFields_7.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_7.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_7.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_7.Location = New System.Drawing.Point(228, 240)
Me._txtFields_7.MaxLength = 0
Me._txtFields_7.Name = "_txtFields_7"
Me._txtFields_7.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_7.Size = New System.Drawing.Size(59, 20)
Me._txtFields_7.TabIndex = 19
Me._txtFields_7.Text = "0"
Me._txtFields_7.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
'
'_txtFields_6
'
Me._txtFields_6.AcceptsReturn = True
Me._txtFields_6.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_6.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_6.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_6.Location = New System.Drawing.Point(76, 192)
Me._txtFields_6.MaxLength = 0
Me._txtFields_6.Name = "_txtFields_6"
Me._txtFields_6.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_6.Size = New System.Drawing.Size(214, 20)
Me._txtFields_6.TabIndex = 16
'
'_txtFields_5
'
Me._txtFields_5.AcceptsReturn = True
Me._txtFields_5.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_5.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_5.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_5.Location = New System.Drawing.Point(76, 170)
Me._txtFields_5.MaxLength = 0
Me._txtFields_5.Name = "_txtFields_5"
Me._txtFields_5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_5.Size = New System.Drawing.Size(214, 20)
Me._txtFields_5.TabIndex = 14
'
'_txtFields_4
'
Me._txtFields_4.AcceptsReturn = True
Me._txtFields_4.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_4.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_4.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_4.Location = New System.Drawing.Point(76, 148)
Me._txtFields_4.MaxLength = 0
Me._txtFields_4.Name = "_txtFields_4"
Me._txtFields_4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_4.Size = New System.Drawing.Size(214, 20)
Me._txtFields_4.TabIndex = 12
'
'picButtons
'
Me.picButtons.BackColor = System.Drawing.Color.Blue
Me.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.picButtons.Controls.Add(Me.cmdClose)
Me.picButtons.Controls.Add(Me.cmdCancel)
Me.picButtons.Cursor = System.Windows.Forms.Cursors.Default
Me.picButtons.Dock = System.Windows.Forms.DockStyle.Top
Me.picButtons.ForeColor = System.Drawing.SystemColors.ControlText
Me.picButtons.Location = New System.Drawing.Point(0, 0)
Me.picButtons.Name = "picButtons"
Me.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.picButtons.Size = New System.Drawing.Size(298, 33)
Me.picButtons.TabIndex = 9
'
'cmdClose
'
Me.cmdClose.BackColor = System.Drawing.SystemColors.Control
Me.cmdClose.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdClose.Location = New System.Drawing.Point(216, 2)
Me.cmdClose.Name = "cmdClose"
Me.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdClose.Size = New System.Drawing.Size(73, 23)
Me.cmdClose.TabIndex = 11
Me.cmdClose.TabStop = False
Me.cmdClose.Text = "E&xit"
Me.cmdClose.UseVisualStyleBackColor = False
'
'cmdCancel
'
Me.cmdCancel.BackColor = System.Drawing.SystemColors.Control
Me.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdCancel.Location = New System.Drawing.Point(4, 2)
Me.cmdCancel.Name = "cmdCancel"
Me.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdCancel.Size = New System.Drawing.Size(73, 23)
Me.cmdCancel.TabIndex = 10
Me.cmdCancel.TabStop = False
Me.cmdCancel.Text = "&Undo"
Me.cmdCancel.UseVisualStyleBackColor = False
'
'_txtFields_3
'
Me._txtFields_3.AcceptsReturn = True
Me._txtFields_3.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_3.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_3.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_3.Location = New System.Drawing.Point(76, 126)
Me._txtFields_3.MaxLength = 0
Me._txtFields_3.Name = "_txtFields_3"
Me._txtFields_3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_3.Size = New System.Drawing.Size(214, 20)
Me._txtFields_3.TabIndex = 4
'
'_txtFields_2
'
Me._txtFields_2.AcceptsReturn = True
Me._txtFields_2.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_2.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_2.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_2.Location = New System.Drawing.Point(76, 104)
Me._txtFields_2.MaxLength = 0
Me._txtFields_2.Name = "_txtFields_2"
Me._txtFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_2.Size = New System.Drawing.Size(214, 20)
Me._txtFields_2.TabIndex = 3
'
'_txtFields_1
'
Me._txtFields_1.AcceptsReturn = True
Me._txtFields_1.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_1.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_1.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_1.Location = New System.Drawing.Point(76, 82)
Me._txtFields_1.MaxLength = 0
Me._txtFields_1.Name = "_txtFields_1"
Me._txtFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_1.Size = New System.Drawing.Size(214, 20)
Me._txtFields_1.TabIndex = 2
'
'_txtFields_0
'
Me._txtFields_0.AcceptsReturn = True
Me._txtFields_0.BackColor = System.Drawing.SystemColors.Window
Me._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam
Me._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText
Me._txtFields_0.Location = New System.Drawing.Point(76, 60)
Me._txtFields_0.MaxLength = 0
Me._txtFields_0.Name = "_txtFields_0"
Me._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._txtFields_0.Size = New System.Drawing.Size(214, 20)
Me._txtFields_0.TabIndex = 1
'
'Label10
'
Me.Label10.AutoSize = True
Me.Label10.BackColor = System.Drawing.Color.Transparent
Me.Label10.Cursor = System.Windows.Forms.Cursors.Default
Me.Label10.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label10.Location = New System.Drawing.Point(138, 242)
Me.Label10.Name = "Label10"
Me.Label10.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label10.Size = New System.Drawing.Size(94, 13)
Me.Label10.TabIndex = 20
Me.Label10.Text = "Company Number:"
Me.Label10.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Label9
'
Me.Label9.BackColor = System.Drawing.Color.Transparent
Me.Label9.Cursor = System.Windows.Forms.Cursors.Default
Me.Label9.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(178, Byte))
Me.Label9.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label9.Location = New System.Drawing.Point(10, 220)
Me.Label9.Name = "Label9"
Me.Label9.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label9.Size = New System.Drawing.Size(121, 15)
Me.Label9.TabIndex = 18
Me.Label9.Text = "2. Company Number"
'
'Label8
'
Me.Label8.BackColor = System.Drawing.Color.Transparent
Me.Label8.Cursor = System.Windows.Forms.Cursors.Default
Me.Label8.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label8.Location = New System.Drawing.Point(10, 194)
Me.Label8.Name = "Label8"
Me.Label8.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label8.Size = New System.Drawing.Size(63, 17)
Me.Label8.TabIndex = 17
Me.Label8.Text = "Email No 7:"
Me.Label8.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Label7
'
Me.Label7.BackColor = System.Drawing.Color.Transparent
Me.Label7.Cursor = System.Windows.Forms.Cursors.Default
Me.Label7.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label7.Location = New System.Drawing.Point(10, 172)
Me.Label7.Name = "Label7"
Me.Label7.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label7.Size = New System.Drawing.Size(63, 17)
Me.Label7.TabIndex = 15
Me.Label7.Text = "Email No 6:"
Me.Label7.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Label5
'
Me.Label5.BackColor = System.Drawing.Color.Transparent
Me.Label5.Cursor = System.Windows.Forms.Cursors.Default
Me.Label5.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label5.Location = New System.Drawing.Point(10, 150)
Me.Label5.Name = "Label5"
Me.Label5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label5.Size = New System.Drawing.Size(63, 17)
Me.Label5.TabIndex = 13
Me.Label5.Text = "Email No 5:"
Me.Label5.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Label4
'
Me.Label4.BackColor = System.Drawing.Color.Transparent
Me.Label4.Cursor = System.Windows.Forms.Cursors.Default
Me.Label4.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label4.Location = New System.Drawing.Point(10, 130)
Me.Label4.Name = "Label4"
Me.Label4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label4.Size = New System.Drawing.Size(63, 17)
Me.Label4.TabIndex = 8
Me.Label4.Text = "Email No 4:"
Me.Label4.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Label3
'
Me.Label3.BackColor = System.Drawing.Color.Transparent
Me.Label3.Cursor = System.Windows.Forms.Cursors.Default
Me.Label3.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label3.Location = New System.Drawing.Point(10, 108)
Me.Label3.Name = "Label3"
Me.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label3.Size = New System.Drawing.Size(63, 17)
Me.Label3.TabIndex = 7
Me.Label3.Text = "Email No 3:"
Me.Label3.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.BackColor = System.Drawing.Color.Transparent
Me.Label2.Cursor = System.Windows.Forms.Cursors.Default
Me.Label2.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label2.Location = New System.Drawing.Point(19, 84)
Me.Label2.Name = "Label2"
Me.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label2.Size = New System.Drawing.Size(61, 13)
Me.Label2.TabIndex = 6
Me.Label2.Text = "Email No 2:"
Me.Label2.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.BackColor = System.Drawing.Color.Transparent
Me.Label1.Cursor = System.Windows.Forms.Cursors.Default
Me.Label1.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label1.Location = New System.Drawing.Point(19, 64)
Me.Label1.Name = "Label1"
Me.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label1.Size = New System.Drawing.Size(61, 13)
Me.Label1.TabIndex = 5
Me.Label1.Text = "Email No 1:"
Me.Label1.TextAlign = System.Drawing.ContentAlignment.TopRight
'
'Label6
'
Me.Label6.BackColor = System.Drawing.Color.Transparent
Me.Label6.Cursor = System.Windows.Forms.Cursors.Default
Me.Label6.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(178, Byte))
Me.Label6.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label6.Location = New System.Drawing.Point(8, 36)
Me.Label6.Name = "Label6"
Me.Label6.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label6.Size = New System.Drawing.Size(161, 15)
Me.Label6.TabIndex = 0
Me.Label6.Text = "1. Email For Remote Office"
'
'frmCompanyEmails
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.SystemColors.Control
Me.ClientSize = New System.Drawing.Size(298, 282)
Me.ControlBox = False
Me.Controls.Add(Me._txtFields_7)
Me.Controls.Add(Me._txtFields_6)
Me.Controls.Add(Me._txtFields_5)
Me.Controls.Add(Me._txtFields_4)
Me.Controls.Add(Me.picButtons)
Me.Controls.Add(Me._txtFields_3)
Me.Controls.Add(Me._txtFields_2)
Me.Controls.Add(Me._txtFields_1)
Me.Controls.Add(Me._txtFields_0)
Me.Controls.Add(Me.Label10)
Me.Controls.Add(Me.Label9)
Me.Controls.Add(Me.Label8)
Me.Controls.Add(Me.Label7)
Me.Controls.Add(Me.Label5)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.Label6)
Me.Controls.Add(Me.ShapeContainer1)
Me.Cursor = System.Windows.Forms.Cursors.Default
Me.KeyPreview = True
Me.Location = New System.Drawing.Point(4, 23)
Me.Name = "frmCompanyEmails"
Me.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
Me.Text = "Edit Store Emails"
Me.picButtons.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
#End Region
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmCompanyEmails.Designer.vb
|
Visual Basic
|
mit
| 21,958
|
Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.DataTableExtensions
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Math
Imports System.IO
Imports System.Text
Imports System.Threading.Tasks
'Imports PdfSharp.Pdf
'Imports PdfSharp.Pdf.IO
'Imports org.pdfclown.documents
'Imports org.pdfclown.files
'Imports ExcelToEnumerable
'Imports ExcelToEnumerable.Exceptions
Imports ExcelDataReader
Imports Rstyx.Utilities
Imports Rstyx.Utilities.Collections
Imports Rstyx.Utilities.Domain
Imports Rstyx.Utilities.Domain.IO
Imports Rstyx.Utilities.Math.MathExtensions
Imports Rstyx.Utilities.IO
Imports Rstyx.Utilities.PDF.PdfUtils
Imports Rstyx.Utilities.UI.ViewModel
Imports Rstyx.Utilities.StringUtils
Public Class MainViewModel
Inherits Rstyx.Utilities.UI.ViewModel.ViewModelBase
Private Shared ReadOnly Logger As Rstyx.LoggingConsole.Logger = Rstyx.LoggingConsole.LogBox.getLogger("Rstyx.Utilities.TestWpf.MainViewModel")
#Region "Initializing and Finalizing"
''' <summary> Creates a new instance and sets display names. </summary>
Public Sub New()
Logger.logDebug("New(): Init MainViewModel ...")
End Sub
'' <summary> Disposes WpfPanel. </summary>
'Protected Overrides Sub OnDispose()
' If (_SheetDefinitionLevelList IsNot Nothing) Then _SheetDefinitionLevelList.Dispose()
' BatchPlotViewPanel = Nothing
'End Sub
#End Region
#Region "Properties"
Private _TestTaskAsyncCommand As AsyncDelegateUICommand = Nothing
Public Property FilePath1 As String
Public Property Textbox As String
Public Property ValidatingProperty1 As Double
Private _BackStoreKilometer As Kilometer = New Kilometer(1234.5678)
'Private _ValidatingProperty2 As String
Public Property ValidatingProperty2 As String
Get
Return _BackStoreKilometer.ToString()
End Get
Set(value As String)
_BackStoreKilometer.Parse(value)
Me.NotifyPropertyChanged("ValidatingProperty2")
End Set
End Property
Private _TextField As String
Public ReadOnly Property TextField As String
Get
Return _TextField
End Get
End Property
''' <summary> Determines the current ShellCommand for the Test button. </summary>
Public Property TestTaskAsyncCommand() As AsyncDelegateUICommand
Get
Try
If (_TestTaskAsyncCommand Is Nothing) Then
Dim Decoration As New UICommandDecoration()
Decoration.Caption = "Test"
Decoration.Description = "Start des Testes"
Decoration.IconBrush = UI.Resources.UIResources.IconBrush("Handmade_Start1")
Dim CmdInfo As New DelegateUICommandInfo
CmdInfo.ExecuteAction = AddressOf Me.Test_1
CmdInfo.CanExecutePredicate = AddressOf Me.CanStartTestTask
CmdInfo.Decoration = Decoration
_TestTaskAsyncCommand = New AsyncDelegateUICommand(CmdInfo, CancelCallback:=Nothing, SupportsCancellation:=False, runAsync:=True)
'_TestTaskAsyncCommand = New AsyncDelegateUICommand(CmdInfo, CancelCallback:=Nothing, SupportsCancellation:=False, runAsync:=True, ThreadAptState:=Threading.ApartmentState.STA)
End If
Catch ex As System.Exception
Logger.logError(ex, sprintf(Rstyx.Utilities.Resources.Messages.Global_ErrorCreatingCommandIn, System.Reflection.MethodBase.GetCurrentMethod().Name))
End Try
Return _TestTaskAsyncCommand
End Get
Set(ByVal value As AsyncDelegateUICommand)
_TestTaskAsyncCommand = value
Me.NotifyPropertyChanged("TestTaskAsyncCommand")
End Set
End Property
#End Region
#Region "Methods"
Public Sub test()
'Dim Task1 As Task = Task.Factory.StartNew(AddressOf test_1)
Dim TestEnum2 As ArrayUtils.SortType = 2 'ArrayUtils.SortType.Numeric
Logger.logInfo(sprintf("Enum Value=%s: Display=%s", TestEnum2.ToString(), TestEnum2.ToDisplayString()))
End Sub
Public Sub TestOrder()
Dim Files As New Collection(Of String)
Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot - Sortierung absteigend\Profil N94-118.pdf")
Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot - Sortierung absteigend\Profil N94-127.pdf")
Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot - Sortierung absteigend\Profil N94-129 N94-128.pdf")
Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot - Sortierung absteigend\Profil N95-1s N95-2s.pdf")
Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot_negative_Km\Profil km 0.1 + 75.78.pdf")
Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot_negative_Km\Profil km -0.2 - 22.01.pdf")
Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot_negative_Km\Profil km -0.1 - 12.13.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.4 + 82.30, Gleis 5500-re, Krbw Str 5544, Stütze 1.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 27.93, Gleis 5500-li, Krbw Str 5544, Stütze 4.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.4 + 88.55, Gleis 5500-re, Krbw Str 5544, KUK.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.4 + 96.79, Gleis 5500-re, Krbw Str 5544, Stütze 2.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 14.66, Gleis 5500-li, Krbw Str 5544, Stütze 3.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 14.82, Gleis 5501-re, Krbw Str 5544, Stütze 3.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 16.98, Gleis 5501-re, Krbw Str 5544, KUK.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 27.93, Gleis 5501-re, Krbw Str 5544, Stütze 4.pdf")
For Each FilePath As String In Files.OrderBy(Function(ByVal PathName) PathName, New AlphanumericKmComparer(IgnoreCase:=True))
Logger.logInfo(FilePath)
Next
#If DEBUG Then
Dim th As System.Threading.Thread = System.Threading.Thread.CurrentThread
System.Diagnostics.Debug.Print(sprintf("TestPDF: Current thread ID = %d, ApartmentState = %s, IsThreadPoolThread = %s, IsBackground = %s", th.ManagedThreadId, th.GetApartmentState().ToString(), th.IsThreadPoolThread, th.IsBackground))
#End If
End Sub
Public Sub TestPDF()
Dim Files As New Collection(Of String)
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.4 + 82.30, Gleis 5500-re, Krbw Str 5544, Stütze 1.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.4 + 88.55, Gleis 5500-re, Krbw Str 5544, KUK.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.4 + 96.79, Gleis 5500-re, Krbw Str 5544, Stütze 2.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 14.66, Gleis 5500-li, Krbw Str 5544, Stütze 3.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 14.82, Gleis 5501-re, Krbw Str 5544, Stütze 3.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 16.98, Gleis 5501-re, Krbw Str 5544, KUK.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 27.76, Gleis 5500-li, Krbw Str 5544, Stütze 4.pdf")
'Files.Add("X:\Quellen\DotNet\VisualBasic\Rstyx.Microstation\BatchplotAddin\Test\Batchplot-Bug_6\Lichtraumprofil Km 5.5 + 27.93, Gleis 5501-re, Krbw Str 5544, Stütze 4.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.0 - 27.18.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.0 - 67.10.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.0 + 17.60 b.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.0 + 17.60.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.0 + 68.33.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.1 + 22.03.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.1 + 75.78.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.8 + 84.82.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 0.9 + 29.88.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km 1.4 + 76.54.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km -0.1 - 12.13.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km -0.1 - 67.04.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km -0.2 - 22.01.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km -0.2 - 73.95.pdf")
Files.Add("D:\daten\Batchplot_negative_Km\Einzelplots_Test\Profil km a 0.2 + 20.05.pdf")
#If DEBUG Then
Dim th As System.Threading.Thread = System.Threading.Thread.CurrentThread
System.Diagnostics.Debug.Print(sprintf("TestPDF: Current thread ID = %d, ApartmentState = %s, IsThreadPoolThread = %s, IsBackground = %s", th.ManagedThreadId, th.GetApartmentState().ToString(), th.IsThreadPoolThread, th.IsBackground))
#End If
Const Filename As String = "T:\TestOutput.pdf"
Call JoinPdfFiles(InputPaths:=Files, OutputPath:=Filename, Order:=True, DeleteInput:=False)
' ...and start a viewer.
System.Diagnostics.Process.Start(Filename)
End Sub
Public Sub TestJPEG_1()
Dim SourceImage As Bitmap = New Bitmap("D:\Daten\LRP\Fotos\02070001.JPG")
Const TargetWidth As Integer = 512
Const TargetHeight As Integer = 768
Dim IsRotated As Boolean = False
' EXIF: all properties.
'Dim ImageProperties() As PropertyItem = SourceImage.PropertyItems
' Orientation (see http://sylvana.net/jpegcrop/exif_orientation.html).
Dim PropIDs As Collection(Of Integer) = New Collection(Of Integer)(SourceImage.PropertyIdList)
Dim ExifOrientationID As Integer = &H0112 ' decimal: 37510
If (PropIDs.Contains(ExifOrientationID)) Then
Dim Orientation As Byte = SourceImage.GetPropertyItem(ExifOrientationID).Value(0)
If (Orientation > 1) Then
Dim ImageRotateFlipType As Dictionary(Of Byte, RotateFlipType) = New Dictionary(Of Byte, RotateFlipType)
ImageRotateFlipType.Add(0, RotateFlipType.RotateNoneFlipNone) ' Orientation unknown.
ImageRotateFlipType.Add(1, RotateFlipType.RotateNoneFlipNone) ' Orientation o.k.
ImageRotateFlipType.Add(2, RotateFlipType.RotateNoneFlipX)
ImageRotateFlipType.Add(3, RotateFlipType.Rotate180FlipNone)
ImageRotateFlipType.Add(4, RotateFlipType.RotateNoneFlipY)
ImageRotateFlipType.Add(5, RotateFlipType.Rotate90FlipX)
ImageRotateFlipType.Add(6, RotateFlipType.Rotate90FlipNone)
ImageRotateFlipType.Add(7, RotateFlipType.Rotate270FlipX)
ImageRotateFlipType.Add(8, RotateFlipType.Rotate270FlipNone)
SourceImage.RotateFlip(ImageRotateFlipType(Orientation))
IsRotated = True
End If
End If
' Size.
Dim DoResize As Boolean = (Not ((TargetWidth = SourceImage.Width) AndAlso (TargetHeight = SourceImage.Height)) )
'If (DoResize OrElse IsRotated) Then
Dim TargetImage As New Bitmap(TargetWidth, TargetHeight)
Dim FlagColor As Color = Color.FromArgb(255, 0, 0, 255)
Using TargetGraphics As Graphics = Graphics.FromImage(TargetImage)
TargetGraphics.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
TargetGraphics.DrawImage(SourceImage, 0, 0, TargetImage.Width, TargetImage.Height)
TargetGraphics.FillRectangle(Brushes.LightGray, New Rectangle(100, 700, TargetWidth - 200, 40))
TargetGraphics.FillEllipse(Brushes.Blue, New Rectangle(115, 715, 10, 10)) ' Flag
TargetGraphics.FillEllipse(Brushes.Blue, New Rectangle(TargetWidth - 125, 715, 10, 10)) ' Flag
'TargetGraphics.FillRectangle(Brushes.Blue, New Rectangle(114, 716, 8, 8)) ' Flag
'TargetGraphics.FillRectangle(Brushes.Blue, New Rectangle(TargetWidth - 122, 716, 8, 8)) ' Flag
Dim DirText As String = "Bild in Richtung"
'Dim DirText As String = "Bild in Richtung"
Dim DirFont As Font = New Font(FontFamily.GenericSansSerif, 11, FontStyle.Regular, GraphicsUnit.Point)
Dim DirSize As SizeF = TargetGraphics.MeasureString(DirText, DirFont)
TargetGraphics.DrawString(DirText, DirFont, Brushes.Blue, TargetWidth / 2 - DirSize.Width / 2, 705)
End Using
' http://www.wisotop.de/farbabstand-farben-vergleichen.shtml
Const X1 As Integer = 118
Const Y1 As Integer = 720
Dim PixelColor As Color = TargetImage.GetPixel(X1, Y1)
'Dim ColorDist As Double = Sqrt( Pow(FlagColor.R - PixelColor.R, 2) + Pow(FlagColor.G - PixelColor.G, 2) + Pow(FlagColor.B - PixelColor.B, 2) )
'Dim ColorDist As Double = Sqrt( ((FlagColor.R - PixelColor.R) * (FlagColor.R - PixelColor.R)) +
' ((FlagColor.G - PixelColor.G) * (FlagColor.G - PixelColor.G)) +
' ((FlagColor.B - PixelColor.B) * (FlagColor.B - PixelColor.B))
' )
Dim dR As Double = CInt(FlagColor.R) - CInt(PixelColor.R)
Dim dG As Double = CInt(FlagColor.G) - CInt(PixelColor.G)
Dim dB As Double = CInt(FlagColor.B) - CInt(PixelColor.B)
Dim ColorDist As Double = Sqrt( (dR * dR) + (dG * dG) + (dG * dG) )
Dim IsFlag As Boolean = (Abs(ColorDist) < 20)
TargetImage.MakeTransparent()
TargetImage.SetPixel(X1, Y1, FlagColor)
TargetImage.Save("D:\Daten\LRP\Fotos\Test_Ziel.jpg", ImageFormat.Jpeg)
'End If
Dim dummy As String = "d"
End Sub
' For TestExcelToEnumerator:
'Public Class SiteRecord
' Public Property deactivated As String
' Public Property active As String
' Public Property Standort_ID As String
' Public Property UserDomain As String
' Public Property Name As String
' Public Property PLZ As String
' Public Property Ort As String
' Public Property Strasse As String
' Public Property Tel As String
' Public Property Fax As String
' Public Property Mail As String
' Public Property Hinweise As String
' Public Property Fusszeile_Excel_1 As String
' Public Property SourceExcelRow As Integer
'End Class
'Public Sub TestExcelToEnumerator()
'
' Dim TableName = "Standorte"
' Dim Workbook = "X:\Quellen\DotNet\VisualBasic\Rstyx.Utilities\TestWpf\TestData\Standortdaten.xlsx"
' Dim Exceptions = New List(Of Exception)()
'
' Logger.logInfo("TestExcelToEnumerator:")
'
' Using oFS As FileStream = File.OpenRead(Workbook)
'
' Dim Options As ExcelToEnumerableOptionsBuilder(Of SiteRecord) = (New ExcelToEnumerableOptionsBuilder(Of SiteRecord)) _
' .UsingSheet(TableName) _
' .UsingHeaderNames(True) _
' .OutputExceptionsTo(Exceptions) _
' .Property(Function(oSite As SiteRecord) oSite.Standort_ID).ShouldBeUnique() _
' .Property(Function(oSite As SiteRecord) oSite.Standort_ID).IsRequired() _
' .Property(Function(oSite As SiteRecord) oSite.active).UsesColumnNamed("aktiv") _
' .Property(Function(oSite As SiteRecord) oSite.active).ShouldBeOneOf("1", "") _
' .Property(Function(oSite As SiteRecord) oSite.SourceExcelRow).MapsToRowNumber()
'
' 'Dim Sites As IEnumerable(Of SiteRecord) = oFS.ExcelToEnumerable(Of SiteRecord)(Options)
'
' For Each Site As SiteRecord In oFS.ExcelToEnumerable(Of SiteRecord)(Options)
' Logger.logInfo(sprintf("Zeile=%2d, aktiv=%s, ID=%s, PLZ=%s, Ort=%s", Site.SourceExcelRow, Site.active, Site.Standort_ID, Site.PLZ, Site.Ort))
' Next
'
' End Using
'
' For Each ex As Exception In Exceptions
' If (TypeOf ex Is ExcelToEnumerableCellException) Then
' Dim ex2 As ExcelToEnumerableCellException = DirectCast(ex, ExcelToEnumerableCellException)
' Logger.logInfo(sprintf("Fehler: Zeile %2d, Feld=%s: %s", ex2.RowNumber, ex2.PropertyName, ex2.Message))
' Else
' Logger.logInfo(sprintf("Fehler: %s", ex.Message))
' End If
' Next
'
'End Sub
''' <summary> Gets a whole Table from a given Excel worksheet (via ExcelDataReader). </summary>
''' <param name="XlFilePath"> Full path of Excel worksheet. </param>
''' <param name="TableName"> The name of the table to get. </param>
''' <returns> The DataTable. </returns>
''' <exception cref="System.ArgumentNullException"> <paramref name="TableName"/> is <see langword="null"/> or empty. </exception>
''' <exception cref="System.IO.FileNotFoundException"> <paramref name="XlFilePath"/> hasn't been found (may be empty or invalid). </exception>
''' <exception cref="Rstyx.Utilities.RemarkException"> Wraps any exception with a clear message. </exception>
Public Shared Function GetExcelSheet(TableName As String, XlFilePath As String) As DataTable
If (TableName.IsEmptyOrWhiteSpace()) Then Throw New System.ArgumentNullException("TableName")
If (Not File.Exists(XlFilePath)) Then Throw New System.IO.FileNotFoundException(Rstyx.Utilities.Resources.Messages.DBUtils_ExcelWorkbookNotFound, XlFilePath)
Try
Logger.logDebug(sprintf("getExcelSheet(): Try to get table '%s' from Excel workbook '%s'.", TableName, XlFilePath))
Using oFS As FileStream = File.OpenRead(XlFilePath)
Dim DataSetConfig As New ExcelDataSetConfiguration()
DataSetConfig.UseColumnDataType = False
DataSetConfig.ConfigureDataTable = Function(Reader As IExcelDataReader) (New ExcelDataTableConfiguration() With {.UseHeaderRow = True})
DataSetConfig.FilterSheet = Function(Reader As IExcelDataReader, SheetIndex As Integer) (Reader.Name = TableName)
Dim XlReader As IExcelDataReader = ExcelReaderFactory.CreateOpenXmlReader(oFS)
Dim Sheets As DataSet = XlReader.AsDataSet(DataSetConfig)
If (Not Sheets.Tables.Contains(TableName)) Then
Throw New RemarkException(sprintf(Rstyx.Utilities.Resources.Messages.DBUtils_TableNotFoundInExcelWorkbook, TableName, XlFilePath))
End If
Return Sheets.Tables(TableName)
End Using
Catch ex As System.Exception
Throw New RemarkException(sprintf(Rstyx.Utilities.Resources.Messages.DBUtils_OpenExcelWorksheetFailed, TableName, XlFilePath), ex)
End Try
End Function
Public Sub TestExcelDataReader()
Dim TableName = "Standorte"
Dim Workbook = "X:\Quellen\DotNet\VisualBasic\Rstyx.Utilities\TestWpf\TestData\Standortdaten.xlsx"
Logger.logInfo("TestExcelDataReader:")
Dim Sheet As DataTable = GetExcelSheet(TableName, Workbook)
For Each Site As DataRow In Sheet.Rows
Logger.logInfo(sprintf("aktiv=%s, ID=%s, PLZ=%s, Ort=%s", Site("aktiv"), Site("Standort_ID"), Site("PLZ"), Site("Ort")))
Next
'Using oFS As FileStream = File.OpenRead(Workbook)
'
' Dim Sheet As DataTable
'
' Dim DataSetConfig As New ExcelDataSetConfiguration()
' DataSetConfig.UseColumnDataType = False
' DataSetConfig.ConfigureDataTable = Function(Reader As IExcelDataReader) (New ExcelDataTableConfiguration() With {.UseHeaderRow = True})
' DataSetConfig.FilterSheet = Function(Reader As IExcelDataReader, SheetIndex As Integer) (Reader.Name = TableName)
'
' Dim XlReader As IExcelDataReader = ExcelReaderFactory.CreateOpenXmlReader(oFS)
' Dim Sheets As DataSet = XlReader.AsDataSet(DataSetConfig)
'
' If (Not Sheets.Tables.Contains(TableName)) Then
' Logger.logInfo("Tabelle xxx existiert nicht!")
' Else
' Sheet = Sheets.Tables(TableName)
' For Each Site As DataRow In Sheet.Rows
' Logger.logInfo(sprintf("aktiv=%s, ID=%s, PLZ=%s, Ort=%s", Site("aktiv"), Site("Standort_ID"), Site("PLZ"), Site("Ort")))
' Next
' End If
'End Using
End Sub
Public Shared Sub StartProcessTest()
Logger.logInfo("StartProcessTest startet ..")
'Dim Batch As String = "G:\Bat\Querprf.bat"
Dim Batch As String = "X:\Quellen\Wscripts\Querprf\Querprf.bat"
Dim ipkt As String = "X:\Quellen\Wscripts\Querprf\Bf_Memmingen_QP_5400.ipkt"
' Start process.
Dim StartInfo As New System.Diagnostics.ProcessStartInfo()
StartInfo.FileName = Batch
StartInfo.Arguments = ipkt
StartInfo.UseShellExecute = False
StartInfo.WorkingDirectory = "X:\Quellen\Wscripts\Querprf"
'Logger.logDebug(StringUtils.sprintf("startEditor(): Auszuführende Datei: '%s'.", StartInfo.FileName))
'Logger.logDebug(StringUtils.sprintf("startEditor(): Argumente: '%s'.", StartInfo.Arguments))
'Logger.logDebug(StringUtils.sprintf("startEditor(): %s wird gestartet.", TargetEditor.ToDisplayString()))
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture
Using Proc As System.Diagnostics.Process = System.Diagnostics.Process.Start(StartInfo)
End Using
Logger.logInfo("StartProcessTest Ende.")
End Sub
Public Sub Test_1(CancelToken As System.Threading.CancellationToken)
'Dim TcReader As TcFileReader
'Try
Logger.logInfo("")
'Call StartProcessTest()
'Call TestExcelDataReader()
'Call TestOrder()
'Call TestPDF()
'Call TestJPEG()
Logger.logInfo(sprintf(" GeoPointEditOptions.ParseInfoForActualCant => '%s'", GeoPointEditOptions.ParseInfoForActualCant.ToDisplayString()))
Logger.logInfo(sprintf(" GeoPointEditOptions.ParseInfoForPointKind => '%s'" , GeoPointEditOptions.ParseInfoForPointKind.ToDisplayString()))
Logger.logInfo(sprintf(" GeoPointEditOptions.Parse_iTC => '%s'" , GeoPointEditOptions.Parse_iTC.ToDisplayString()))
Logger.logInfo(sprintf(" GeoPointOutputOptions.CreateInfoWithActualCant => '%s'", GeoPointOutputOptions.CreateInfoWithActualCant.ToDisplayString()))
Logger.logInfo(sprintf(" GeoPointOutputOptions.CreateInfoWithPointKind => '%s'", GeoPointOutputOptions.CreateInfoWithPointKind.ToDisplayString()))
Logger.logInfo(sprintf(" GeoPointOutputOptions.Create_iTC => '%s'", GeoPointOutputOptions.Create_iTC.ToDisplayString()))
Dim TestString As String = "u=5 WA 28"
Dim TestString2 As String
Dim Matches As System.Text.RegularExpressions.MatchCollection = TestString.GetMatches(" ")
If (Matches.Count > 0) Then
TestString2 = TestString.Left(Matches(0).Index) & TestString.Substring(Matches(0).Index + 1)
End If
Logger.logInfo(sprintf(" '%s' => '%s'", TestString, TestString2))
'Dim p As New GeoIPoint ()
'p.ParseTextForKindCodes(Me.Textbox)
'Logger.logInfo(sprintf(" Punktart = %s, VArtAB = %s, VArt = %s, u = %3.0f Info = '%s'", p.Kind.ToDisplayString(), p.MarkTypeAB, p.MarkType, p.ActualCant * 1000, p.Info))
'p.Info = Me.Textbox
'p.Comment = " HB 22.33"
'p.ParseInfoForKindHints(TryComment:=False)
'Logger.logInfo(sprintf(" Info = '%s' => Punktart = %s u = %3.0f Info neu = '%s' ", Me.Textbox, p.Kind.ToDisplayString(), p.ActualCant * 1000, p.Info))
'Dim Km1 As Kilometer = New Kilometer("-0.1 - 212.13")
'Dim Km2 As Kilometer = New Kilometer("-0.1 - 12.13")
'Dim Km3 As Kilometer = New Kilometer("*12.3456")
'Dim Km4 As Kilometer = New Kilometer("123.4567*")
'Dim Km5 As Kilometer = New Kilometer("0.1 + 12.13")
'Logger.logInfo(sprintf("Km %+18s TDB = %9.2f", Km1.ToKilometerNotation(2), Km1.TDBValue))
'Logger.logInfo(sprintf("Km %+18s TDB = %9.2f", Km2.ToKilometerNotation(2), Km2.TDBValue))
'Logger.logInfo(sprintf("Km %+18s TDB = %9.2f", Km3.ToKilometerNotation(2), Km3.TDBValue))
'Logger.logInfo(sprintf("Km %+18s TDB = %9.2f", Km4.ToKilometerNotation(2), Km4.TDBValue))
'Logger.logInfo(sprintf("Km %+18s TDB = %9.2f", Km5.ToKilometerNotation(2), Km5.TDBValue))
Logger.logInfo(sprintf("CurrentCulture = %s", System.Globalization.CultureInfo.CurrentCulture.Name))
Dim d1 As Double = Double.NaN
d1.TryParse("+Unendlich")
Logger.logInfo(sprintf("%+5.3f", d1))
Dim d2 As Double = Double.NegativeInfinity
Dim d3 As Double = Double.PositiveInfinity
Logger.logInfo(d2.ToString())
Logger.logInfo(d3.ToString())
Logger.logInfo(sprintf("%+5.3f", d2))
'Logger.logInfo(sprintf("%+5.3f", d3))
Dim NegInf As String = "" & ChrW(&H221E)
Logger.logInfo("")
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture.Clone()
System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.PositiveInfinitySymbol = ChrW(&H221E)
System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeInfinitySymbol = "-" & ChrW(&H221E)
'System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("de")
Logger.logInfo(sprintf("CurrentCulture = %s", System.Globalization.CultureInfo.CurrentCulture.Name))
d1 = Double.NaN
d1.TryParse("+Unendlich")
Logger.logInfo(sprintf("%+5.3f", d1))
d2 = Double.NegativeInfinity
d3 = Double.PositiveInfinity
Logger.logInfo(d2.ToString())
Logger.logInfo(d3.ToString())
Logger.logInfo(sprintf("%+5.3f", d2))
d1.TryParse(NegInf)
Logger.logInfo(sprintf(" %s => %+5.3f", NegInf, d1))
'Dim int1 As Integer = 1
'Dim int2 As Nullable(Of Integer) = 2
'Dim int3 As Nullable(Of Integer) = Nothing
'Dim TestType1 As Type = int1.GetType()
'Dim TestType2 As Type = GetType(Nullable(Of Integer))
'Dim TestType3 As Type = GetType(Nullable(Of))
'Dim TestType4 As Type = TestType2.GetGenericTypeDefinition()
'Dim test As Boolean = (TestType2.IsGenericType AndAlso (TestType4 Is TestType3))
'Dim test2 As Boolean = (TestType2.IsGenericType AndAlso (TestType2.GetGenericTypeDefinition() Is GetType(Nullable(Of))))
'Dim test3 As Boolean = (TestType2.Name = "Nullable`1")
'Dim test4 As Boolean = (TestType2 Is GetType(Nullable(Of Integer)))
'
'Dim text As String = sprintf("%5.3f%5.3f", "1", int3)
''Dim text As String = CStr(Nothing)
''int2 = int3 '.GetValueOrDefault()
'Dim KV As New KvFile(Me.FilePath1)
'Dim KV As New KvFile("D:\Daten\koo\Test-KV.kv")
''Dim KF As New KfFile(Me.FilePath1)
''Dim iP As New iPktFile(Me.FilePath1)
'Dim TC As New TcFileReader(Me.FilePath1)
''TC.FilePath = "T:\_test\zaun_li_IstGleis.txt"
''TC.FilePath = "X:\Quellen\Awk\Bahn\SOLLIST\2018-06-22_Bf_Ungerhausen_MVk_GL3.A0"
''Dim TC As New TcFileReader("X:\Quellen\DotNet\VisualBasic\Rstyx.Apps\VEedit\Test\Ulm_LiRa_4700_Endzu.A0")
''TC.EditOptions = GeoPointEditOptions.GuessAllKindsFromInfo
''KV.CollectParseErrors = True
''TC.ShowParseErrorsInJedit = False
''iP.Constraints = GeoPointConstraints.UniqueID
''TC.CollectParseErrors = True
''KV.Constraints = GeoPointConstraints.UniqueID
''Dim pts As GeoPointOpenList = iP.Load(Me.FilePath1)
''Dim pts As GeoPointOpenList = KV.Load()
''TC.Load("X:\Quellen\DotNet\VisualBasic\Rstyx.Utilities\TestWpf\source\Test1_AKG----D.A0")
''Dim pts As GeoPointOpenList = TC.Load("X:\Quellen\DotNet\VisualBasic\Rstyx.Utilities\TestWpf\source\IstGleis_2008_GIC.a0")
'Try
' TC.Load()
'Catch ex As Exception
' Logger.logError(ex, "Crash...")
'Finally
' 'Logger.logInfo(TC.ToReport(OnlySummary:=False))
'End Try
' 'Dim pts As New GeoPointOpenList(iP.PointStream, iP)
'Dim pts As New GeoPointOpenList(KV.PointStream, KV)
'
'Dim iP2 As New iPktFile("D:\Daten\koo\Test-KV_out.ipkt")
'iP2.Store(pts)
'Dim KV2 As New KvFile("X:\Quellen\DotNet\VisualBasic\Rstyx.Apps\VEedit\Test\Test_out.kv")
'KV2.Store(pts)
'KV2.Header = KV.Header
' KV2.Store(KV.PointStream, KV)
'iP.Store(pts, "X:\Quellen\DotNet\VisualBasic\Rstyx.Utilities\TestWpf\source\Test_out.ipkt")
'Dim dtUTC As DateTime = DateTime.UtcNow
'Logger.logInfo(dtUTC.ToLongDateString())
'Logger.logInfo(dtUTC.ToShortDateString())
'Logger.logInfo(dtUTC.ToLongTimeString())
'Logger.logInfo(dtUTC.ToShortTimeString())
'Dim dtLocal As DateTime = dtUTC.ToLocalTime()
'Logger.logInfo(dtLocal.ToShortTimeString())
'Logger.logInfo("")
'
''Dim RefTime As DateTime = DateTime.Parse("01.01.1970 0:00")
'Dim RefTime As DateTime = DateTime.SpecifyKind(DateTime.Parse("01.01.1970 0:00"), DateTimeKind.Utc)
'Dim ts As TimeSpan = dtUTC.Subtract(RefTime)
'Dim sec As Integer = CInt(ts.TotalSeconds)
'Dim NewTime As DateTime = RefTime.AddSeconds(sec)
'Logger.logInfo(RefTime.ToString())
'Logger.logInfo(RefTime.ToLocalTime().ToString())
'Logger.logInfo("")
'
'Logger.logInfo(ts.TotalSeconds.ToString())
'
''Logger.logInfo(StringUtils.sprintf("3 Stellen: '%3s'", "123456789".TrimToMaxLength(3)))
''Logger.logInfo(StringUtils.sprintf("Nothing: '%6.3f'", Nothing))
'
' 'Dim TestText1 As String = "25082013"
' Dim TestDate As DateTime
' Dim TestText1 As String = ""
' 'Dim TestDate As Nullable(Of DateTime) = Nothing
' ''Dim success As Boolean = DateTime.TryParse(TestText1, TestDate)
' 'Dim success As Boolean = DateTime.TryParseExact(TestText1, "ddMMyyyy", Nothing, Globalization.DateTimeStyles.None, TestDate)
' Dim success As Boolean = DateTime.TryParseExact(TestText1, "s", Nothing, Globalization.DateTimeStyles.None, TestDate)
' Logger.logInfo(TestDate.ToShortDateString())
' Logger.logInfo(TestDate.ToString("s"))
'
'Dim TestDouble As Double = 33
'Double.TryParse(Nothing , TestDouble)
'Logger.logInfo(StringUtils.sprintf("Double = %.3f", TestDouble))
'
'Dim p1 As New GeoTcPoint()
'p1.Q = -4.000
'p1.HSOK = 5.000
'p1.Ueb = -0.150
'p1.Ra = -1
'Dim p2 As New GeoTcPoint()
'p2.Q = 4.000
'p2.HSOK = 5.000
'p2.Ueb = -0.150
'p2.Ra = -1
'p1.transformHorizontalToCanted()
'p2.transformHorizontalToCanted()
'Logger.logInfo(StringUtils.sprintf("Q=%.3f HSOK=%.3f (u=%.3f) QG=%.3f HG=%.3f", p1.Q, p1.HSOK, p1.Ueb * sign(p1.Ra), p1.QG, p1.HG))
'Logger.logInfo(StringUtils.sprintf("Q=%.3f HSOK=%.3f (u=%.3f) QG=%.3f HG=%.3f", p2.Q, p2.HSOK, p2.Ueb * sign(p2.Ra), p2.QG, p2.HG))
'
'Dim p3 As New GeoTcPoint()
'p3.QG = p1.QG
'p3.HG = p1.HG
'p3.Ueb = -0.150
'p3.Ra = -1
'Dim p4 As New GeoTcPoint()
'p4.QG = p2.QG
'p4.HG = p2.HG
'p4.Ueb = -0.150
'p4.Ra = -1
'p3.transformCantedToHorizontal()
'p4.transformCantedToHorizontal()
'Logger.logInfo(StringUtils.sprintf("Q=%.3f HSOK=%.3f (u=%.3f) QG=%.3f HG=%.3f", p3.Q, p3.HSOK, p3.Ueb * sign(p3.Ra), p3.QG, p3.HG))
'Logger.logInfo(StringUtils.sprintf("Q=%.3f HSOK=%.3f (u=%.3f) QG=%.3f HG=%.3f", p4.Q, p4.HSOK, p4.Ueb * sign(p4.Ra), p4.QG, p4.HG))
'
'Dim dou As Double = 24430.0 'Double.NaN
'Dim i16 As Int16 = 0
'If (Not Double.IsNaN(dou)) Then i16 = CInt(dou)
'Logger.logInfo(i16)
'Dim d1 As Double = 1.2301
'Dim d2 As Double = 1.23
'Dim eps As Double = 0.000099999999999
'Logger.logInfo(StringUtils.sprintf("%.4f = %.4f (eps=%.4f): %s", d1, d2, eps, d1.EqualsAlmost(d2, eps)))
'Dim Km As Kilometer = New Kilometer(Me.Textbox)
'Logger.logInfo(StringUtils.sprintf("Km = %8.3f (Status=%s) => %s", Km.Value, Km.Status.ToDisplayString(), Km.ToKilometerNotation(3)))
'Logger.logInfo(StringUtils.sprintf("gültig = %s", Rstyx.Utilities.IO.FileUtils.isValidFilePath(Me.Textbox)))
'Logger.logInfo(StringUtils.sprintf("korrigiert = %s", Rstyx.Utilities.IO.FileUtils.validateFilePathSpelling(Me.Textbox)))
'Logger.logInfo(StringUtils.sprintf("gültig = %s", Rstyx.Utilities.IO.FileUtils.isValidFileName(Me.Textbox)))
'Logger.logInfo(StringUtils.sprintf("korrigiert = %s", Rstyx.Utilities.IO.FileUtils.validateFileNameSpelling(Me.Textbox)))
'Dim Path As String = "T:\Debug.log"
'Dim fdk As New IO.DataTextFileReader(LineStartCommentToken:="*", LineEndCommentToken:="|", SeparateHeader:=True)
'fdk.Load(Me.FilePath1)
'Logger.logInfo(StringUtils.sprintf("Zeilen gelesen = %d", fdk.TotalLinesCount))
'Dim li As TrackTitle = TrackTitle.GetDBAGTrackTitle(6265)
'TcReader = New TcFileReader()
'TcReader.Load(Me.FilePath1)
'Logger.logInfo(TcReader.ToReport(OnlySummary:=True))
'Logger.logInfo(TcReader.ToString())
'Dim Info As String = Me.Textbox
'Dim Cant As Double = GeoMath.parseCant(Info, strict:=False, absolute:=False, editPointInfo:=True)
'Logger.logInfo(StringUtils.sprintf("Überhöhung = %.0f (Info = '%s')", Cant, Info))
'Dim li As GeoMath.DBAGTrackInfo
'li = GeoMath.getDBAGTrackTitle(6265)
'Logger.logInfo(li.ShortTitle)
'Exit Sub
'Dim Zahl As DataField(Of Double) = Nothing
'Dim Text As DataField(Of String) = Nothing
'Dim PError As ParseError = Nothing
'Dim Errors As New ParseErrorCollection()
'Dim SplitLine As New PreSplittedTextLine(Me.Textbox, Nothing, Nothing)
'
'Dim FieldDefS As New DataFieldDefinition(Of String)("texxxt",
' DataFieldPositionType.WordNumber,
' 2, -1,
' DataFieldOptions.NotRequired
' )
'Dim FieldDefD As New DataFieldDefinition(Of Double)("Zahl",
' DataFieldPositionType.ColumnAndLength,
' 4, 15,
' DataFieldOptions.AllowKilometerNotation Or DataFieldOptions.NotRequired
' )
''
'If (SplitLine.HasData) Then
' If (SplitLine.TryParseField(FieldDefD, Zahl)) Then
' Logger.logInfo(StringUtils.sprintf("Feld '%s' = %.3f", Zahl.Definition.Caption, Zahl.Value))
' Else
' Errors.Add(Zahl.ParseError)
' End If
'
' If (SplitLine.TryParseField(FieldDefS, Text)) Then
' Logger.logInfo(StringUtils.sprintf("Feld '%s' = %s", Text.Definition.Caption, Text.Value))
' Else
' Errors.Add(Text.ParseError)
' End If
'
' Errors.ToLoggingConsole()
'End If
'Apps.AppUtils.startEditor(5, "")
'Logger.logInfo(Rstyx.Utilities.IO.FileUtils.FilePart.Dir.ToDisplayString())
'Logger.logInfo(EnumExtensions.ToDisplayString(Rstyx.Utilities.IO.FileUtils.FilePart.Dir))
'Me.showHelpFile()
'Dim success As Boolean = TrySetProperty("Textbo", "teschtttt", New String() {"hh", "teschtttyy"})
'Throw New InvalidDataException("+++++++++++++++++++++++++++")
'Dim fic As IO.FileInfoCollection = IO.FileUtils.findFile("*.bsh", "G:\Tools\jEdit_51\macros\Aktive_Datei", Nothing, SearchOption.TopDirectoryOnly)
'Dim fi As FileInfo = IO.FileUtils.findFile("*.bsh", ";;G:\Tools\jEdit_51\macros\Aktive_Datei;G:\Tools\jEdit_51\macros\Aktive_Datei", ";", Nothing)
'Logger.logInfo(fi.FullName)
'Logger.logInfo(Me.FilePath1)
'Dim Field = "Symbol_Scale_Width"
'Dim TableName = "Points$"
'Dim Workbook = Me.FilePath1
'
'' Siehe: https://www.microsoft.com/de-DE/download/details.aspx?id=13255
'' Siehe: https://www.microsoft.com/en-us/download/details.aspx?id=54920&751be11f-ede8-5a0c-058c-2ee190a24fa6=True&e6b34bbe-475b-1abd-2c51-b5034bcdd6d2=True&fa43d42b-25b5-4a42-fe9b-1634f450f5ee=True
'' ... Hinweise unter "Anweisungen zur Installation"
'' Siehe: https://www.connectionstrings.com/ace-oledb-12-0/info-and-download/
'' Provider = "Microsoft.ACE.OLEDB.12.0", XLSX => "Excel 12.0 Xml", XLSM = "Excel 12.0 Macro"
''Dim DBconn As OleDbConnection = Nothing
''Dim CSB As OleDbConnectionStringBuilder = New OleDbConnectionStringBuilder()
''CSB.DataSource = Workbook
''CSB.DataSource = Me.FilePath1
''CSB.Provider = "Microsoft.Jet.OLEDB.4.0"
''CSB.Add("Extended Properties", "Excel 8.0;HDR=Yes;IMEX=1;")
''CSB.Provider = "Microsoft.ACE.OLEDB.12.0"
''CSB.Add("Extended Properties", "Excel 12.0 Xml;ReadOnly=True")
''DBconn = New OleDbConnection(CSB.ConnectionString)
''Logger.logInfo(StringUtils.sprintf("ConnectionString = '%s'", CSB.ConnectionString))
''DBconn.Open()
''DBconn.Close()
'
'Dim TableName = "Standorte$"
'Dim Workbook = "C:\ProgramData\intermetric\sync_Ressourcen\MicroStation\Workspace\standards\I_Tabellen\Standortdaten.xlsx"
' Dim Workbook = "R:\Microstation\Workspace\Standards\I_Tabellen\Standortdaten.xlsx"
' 'Using XLconn As System.Data.OleDb.OleDbConnection = DBUtils.connectToExcelWorkbook("R:\Microstation\Workspace\Standards\I_Tabellen\Standortdaten.xlsx")
' 'Using XLconn As System.Data.OleDb.OleDbConnection = DBUtils.connectToExcelWorkbook(Me.FilePath1)
' Using Table As System.Data.DataTable = DBUtils.getExcelSheet(TableName, Workbook)
' 'Using Table As System.Data.DataTable = DBconn.getTable(TableName)
' ''Dim Table As DataTable = DBUtils.getOleDBTable(TableName, XLconn)
' 'Dim Table As DataTable = XLconn.getTable(TableName)
' 'Logger.logInfo(StringUtils.sprintf("Feld '%s' existiert = %s", Field, DBconn.TableContainsField(TableName, Field)))
' 'Logger.logInfo(StringUtils.sprintf("Feld '%s' existiert = %s", Field, Table.containsField(Field)))
'
' 'Dim SQL = "SELECT * FROM " & TableName
' 'Dim Table As DataTable = DBUtils.queryOLEDB(SQL, XLconn)
' 'Dim Query = From site In Table.AsEnumerable() Where site.Field(Of String)("UserDomain") = "dummy"
'
' 'Dim Table As DataTable = DBUtils.getExcelSheet(TableName, Workbook)
' 'Dim yes = Table.containsField(Field)
' 'Logger.logInfo(StringUtils.sprintf("Existiert Feld '%s' in Tabelle '%s' = %s", Field, Table.TableName, Table.containsField(Field)))
' '
' For Each row As System.Data.DataRow In Table.AsEnumerable()
' Logger.logInfo(StringUtils.sprintf("Standort '%s' = UserDomain '%s'", row("Standort_ID"), row("UserDomain")))
' Next
' End Using
'UI.ClassEvents.SelectAllOnTextBoxGotFocus = (Not UI.ClassEvents.SelectAllOnTextBoxGotFocus)
'Logger.logInfo(StringUtils.sprintf("gültig = %s", Rstyx.Utilities.IO.FileUtils.isValidFilePath(Me.Textbox)))
'Logger.logInfo(StringUtils.sprintf("korrigiert = %s", Rstyx.Utilities.IO.FileUtils.validateFilePathSpelling(Me.Textbox)))
'Catch ex As ParseException
' 'Logger.logError(ex, StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.TcFileReader_LoadFailed, TcReader.FilePath))
' 'TcReader.ParseErrors.ShowInJEdit()
' Logger.logError(ex, "==> Fehler...")
'
'Catch ex As System.Exception
' Logger.logError(ex, StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.Global_UnexpectedErrorIn, System.Reflection.MethodBase.GetCurrentMethod().Name))
' 'Throw New RemarkException("test_1(): Unerwarteter Fehler.", ex)
'End Try
End Sub
Protected Overrides Sub showHelpFile()
Throw New InvalidDataException("showHelpFile() +++++++++++++++++++++++++++")
End Sub
''' <summary> Checks if test_1 could be started. </summary>
''' <returns> Boolean </returns>
Private Function CanStartTestTask() As Boolean
Dim RetValue As Boolean = False
Try
'Throw New RemarkException("AAAAAAAAAAA")
RetValue = True
Catch ex As System.Exception
Logger.logError(ex, StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.Global_UnexpectedErrorIn, System.Reflection.MethodBase.GetCurrentMethod().Name))
End Try
Return RetValue
End Function
Public Sub test_0()
'Dim s As String
'Dim sa() As String
'Dim d As Nullable(Of Double)
''Dim bool As Boolean
'
Dim TestEnum As Cinch.CustomDialogIcons = Cinch.CustomDialogIcons.Question
Logger.logInfo(StringUtils.sprintf("Enum Value=%s: Display=%s", TestEnum.ToString(), TestEnum.ToDisplayString()))
Me.StatusText = TestEnum.ToDisplayString()
System.Threading.Thread.Sleep(3000)
Dim TestEnum2 As ArrayUtils.SortType = ArrayUtils.SortType.Numeric
Logger.logInfo(StringUtils.sprintf("Enum Value=%s: Display=%s", TestEnum2.ToString(), TestEnum2.ToDisplayString()))
Me.StatusText = TestEnum2.ToDisplayString()
's = "klop-123.4+8y9u=+987#äö"
'd = 123456789.789
'sa = s.Split("\s+")
'Logger.logInfo(GeoMath.Hex2Dec("2fde"))
'd = GeoMath.getKilometer(a)
'GeoMath.getCantFromPointinfo(s, d, False )
Dim li As TrackTitle = TrackTitle.GetDBAGTrackTitle(6265)
Logger.logInfo(li.ShortTitle)
'Logger.logInfo(Strings.FileSpec2RegExp("X:\Quellen\DotNet\VisualBasic\_Backup\Rstyx.Utilities_2012-??-14.*"))
'Logger.logInfo(s.left("y"c))
'Logger.logInfo("\sc\rf\\\#\\\".removeTrailingBackslashes())
'Logger.logInfo("\sc\rf\\\#\\\".TrimEnd("\"))
'Logger.logInfo(Strings.getFilePart("D:\daten\Test_QP\qp_ueb.dgn", Strings.FilePart.Dir_Proj ))
'Logger.logInfo(System.IO.File.Exists("D:\daten\Test_QP\"))
'dim keyName as string = "HKEY_CURRENT_USER\Software\VB and VBA Program Settings\Microstation\frmBatchPlot\"
''dim valueName as string = "Dialog_Left"
'dim valueName as string = "test"
'dim valueString as string = "1234"
'dim valueObj as Object = "123456"
'Logger.logInfo(RegUtils.ValueExists(key))
'Logger.logInfo(RegUtils.getValue(Of String)(keyName & valueName))
'Logger.logInfo("Pfad = '" & RegUtils.getApplicationPath("HKEY_CLASSES_ROOT\i_M5_file\shell\i_zzHilfe\ShellCommand\") & "'")
'
'Dim Folders As String = Environment.ExpandEnvironmentVariables("%PATH%")
'Dim Folders As String = Environment.GetEnvironmentVariable("PROGRAMFILES")
'Dim Folders As String = "T:\"
'Dim File As String = " *"
'Dim File As String = "cedt.exe"
'Dim File As String = "uedit*.exe;ultaedit*.exe"
''Logger.logInfo(Folders.IndexOfAny(System.IO.Path.GetInvalidPathChars()))
''
'Dim found As System.Collections.ObjectModel.Collection(Of System.IO.fileinfo) = IO.FileUtils.findFiles(File, Folders, ";", IO.SearchOption.AllDirectories)
'
'If (found.IsNotNull) Then
' For Each fi In found
' Logger.logInfo(fi.FullName)
' Next
' Logger.logInfo(found.Count)
'End If
'Logger.logInfo(StringUtils.sprintf(" %d Dateien gefunden", found.Count))
'Logger.logInfo(Environment.GetEnvironmentVariable("jedit_home"))
'Logger.logInfo(AppUtils.AppPathJava)
'AppUtils.startEditor(AppUtils.SupportedEditors.jEdit , """T:\_test\12 3 Ö .tx t"" +line:44,11")
'Logger.logInfo(AppUtils.startFile("T:\_test\12 3 Ö .txt"))
'AppUtils.startEditor(AppUtils.SupportedEditors.UltraEdit , """T:\_test\12 3 Ö .txt"" +line:44,11")
'AppUtils.CurrentEditor = AppUtils.SupportedEditors.CrimsonEditor
'AppUtils.startEditor(AppUtils.CurrentEditor, """T:\_test\12 3 Ö .txt""")
'Dim IconDictionary As ResourceDictionary = UI.Resources.UIResources.Icons
'
'Logger.logInfo("Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory = " & Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory)
'Logger.logInfo("System.Environment.CurrentDirectory = " & System.Environment.CurrentDirectory())
'Logger.logInfo("System.IO.Directory.GetCurrentDirectory() = " & System.IO.Directory.GetCurrentDirectory())
'
'Logger.logInfo("EditorCombo2.ActualHeight = " & EditorCombo2.ActualHeight)
'
'FileChoser1.InputFilePath = "rrrrrrrrrr"
'Dim bytes() As Byte = {111, 112, 113, 00, 00, 00}
' Statt ByteArray2String() - Nullwerte am Ende des Arrays sind egal...
'Dim text As String = System.Text.Encoding.Default.GetString(bytes)
'Dim bytes() As Byte = System.Text.Encoding.Default.GetBytes("str")
'Dim Field = "UserDomain"
'Dim TableName = "Standorte$"
'Dim Workbook = "R:\Microstation\Workspace\Standards\I_Tabellen\Standortdaten.xls"
'Dim Workbook = "C:\ProgramData\intermetric\sync_Ressourcen\MicroStation\Workspace\standards\I_Tabellen\Standortdaten.xlsx"
'
'Dim XLconn As OleDbConnection = DBUtils.connectToExcelWorkbook("R:\Microstation\Workspace\Standards\I_Tabellen\Standortdaten.xls")
''Dim Table As DataTable = DBUtils.getOleDBTable(TableName, XLconn)
'Dim Table As DataTable = XLconn.getTable(TableName)
'Logger.logInfo(StringUtils.sprintf("Feld '%s' existiert = %s", Field, XLconn.TableContainsField(TableName, Field)))
'Logger.logInfo(StringUtils.sprintf("Feld '%s' existiert = %s", Field, Table.containsField(Field)))
'Dim SQL = "SELECT * FROM " & TableName
'Dim Table As DataTable = DBUtils.queryOLEDB(SQL, XLconn)
'Dim Query = From site In Table.AsEnumerable() Where site.Field(Of String)("UserDomain") = "dummy"
'Dim Table As DataTable = DBUtils.getExcelSheet(TableName, Workbook)
'Dim yes = DBExtensions.containsField(Table, Field)
'Dim yes = Table.containsField(Field)
'For Each row As DataRow In Table.AsEnumerable()
' Logger.logInfo(StringUtils.sprintf("Standort '%s' = UserDomain '%s'", row("Standort_ID"), row("UserDomain")))
'Next
'TestPanel.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity))
End Sub
#End Region
End Class
' for jEdit: :collapseFolds=2::tabSize=4::indentSize=4:
|
rschwenn/Rstyx.Utilities
|
TestWpf/source/MainViewModel.vb
|
Visual Basic
|
mit
| 57,120
|
' 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.Collections.ObjectModel
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.VisualStudio.Debugger.Clr
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Imports Roslyn.Test.PdbUtilities
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class LocalsTests
Inherits ExpressionCompilerTestBase
<Fact>
Public Sub NoLocals()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.Equal(0, assembly.Count)
Assert.Equal(0, locals.Count)
locals.Free()
End Sub
<Fact>
Public Sub Locals()
Const source =
"Class C
Sub M(a As Integer())
Dim b As String
a(1) += 1
SyncLock New C()
#ExternalSource(""test"", 999)
Dim c As Integer = 3
b = a(c).ToString()
#End ExternalSource
End SyncLock
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.NotEqual(0, assembly.Count)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0, //b
Integer& V_1,
Object V_2,
Boolean V_3,
Integer V_4) //c
IL_0000: ldarg.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "a", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0, //b
Integer& V_1,
Object V_2,
Boolean V_3,
Integer V_4) //c
IL_0000: ldarg.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "b", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0, //b
Integer& V_1,
Object V_2,
Boolean V_3,
Integer V_4) //c
IL_0000: ldloc.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "c", expectedILOpt:=
"{
// Code size 3 (0x3)
.maxstack 1
.locals init (String V_0, //b
Integer& V_1,
Object V_2,
Boolean V_3,
Integer V_4) //c
IL_0000: ldloc.s V_4
IL_0002: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub LocalsAndPseudoVariables()
Const source =
"Class C
Sub M(o As Object)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
"C.M")
Dim aliases = ImmutableArray.Create(
ExceptionAlias(GetType(System.IO.IOException)),
ReturnValueAlias(2, GetType(String)),
ReturnValueAlias(),
ObjectIdAlias(2, GetType(Boolean)),
VariableAlias("o", "C"))
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim diagnostics = DiagnosticBag.GetInstance()
Dim testData = New CompilationTestData()
context.CompileGetLocals(
locals,
argumentsOnly:=True,
aliases:=aliases,
diagnostics:=diagnostics,
typeName:=typeName,
testData:=testData)
Assert.Equal(1, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "o")
locals.Clear()
testData = New CompilationTestData()
context.CompileGetLocals(
locals,
argumentsOnly:=False,
aliases:=aliases,
diagnostics:=diagnostics,
typeName:=typeName,
testData:=testData)
Assert.Equal(7, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "$exception", "Error", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException() As System.Exception""
IL_0005: castclass ""System.IO.IOException""
IL_000a: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "$ReturnValue2", "Method M2 returned", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldc.i4.2
IL_0001: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(Integer) As Object""
IL_0006: castclass ""String""
IL_000b: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "$ReturnValue", "Method M returned", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(Integer) As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "$2", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""2""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: unbox.any ""Boolean""
IL_000f: ret
}")
VerifyLocal(testData, typeName, locals(4), "<>m4", "o", expectedILOpt:=
"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""o""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: castclass ""C""
IL_000f: ret
}")
VerifyLocal(testData, typeName, locals(5), "<>m5", "Me", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(6), "<>m6", "o", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}")
locals.Free()
End Sub
''' <summary>
''' No local signature (debugging a .dmp with no heap). Local
''' names are known but types are not so the locals are dropped.
''' Expressions that do not involve locals can be evaluated however.
''' </summary>
<Fact>
Public Sub NoLocalSignature()
Const source =
"Class C
Sub M(a As Integer())
Dim b As String
a(1) += 1
SyncLock New C()
#ExternalSource(""test"", 999)
Dim c As Integer = 3
b = a(c).ToString()
#End ExternalSource
End SyncLock
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes), includeLocalSignatures:=False)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "a", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}")
locals.Free()
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("b", errorMessage, testData, VisualBasicDiagnosticFormatter.Instance)
Assert.Equal(errorMessage, "(1) : error BC30451: 'b' is not declared. It may be inaccessible due to its protection level.")
testData = New CompilationTestData()
context.CompileExpression("a(1)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: ldelem.i4
IL_0003: ret
}")
End Sub
<Fact>
Public Sub [Me]()
Const source = "
Class C
Sub M([Me] As Object)
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
")
' Dev11 shows "Me" in the Locals window and "[Me]" in the Autos window.
VerifyLocal(testData, typeName, locals(1), "<>m1", "[Me]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}
")
locals.Free()
End Sub
<Fact>
Public Sub ArgumentsOnly()
Const source = "
Class C
Sub M(Of T)(x As T)
Dim y As Object = x
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=True, typeName:=typeName, testData:=testData)
Assert.Equal(1, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0(Of T)", "x", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Object V_0) //y
IL_0000: ldarg.1
IL_0001: ret
}",
expectedGeneric:=True)
locals.Free()
End Sub
''' <summary>
''' Compiler-generated locals should be ignored.
''' </summary>
<Fact>
Public Sub CompilerGeneratedLocals()
Const source = "
Class C
Shared Function F(args As Object()) As Boolean
If args Is Nothing Then
Return True
End If
For Each o In args
#ExternalSource(""test"", 999)
System.Console.WriteLine() ' Force non-hidden sequence point
#End ExternalSource
Next
DirectCast(Function() args(0), System.Func(Of Object))()
Return False
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.F",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "args", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-0 V_0, //$VB$Closure_0
Boolean V_1, //F
Boolean V_2,
Object() V_3,
Integer V_4,
Object V_5, //o
Boolean V_6)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_args As Object()""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (C._Closure$__1-0 V_0, //$VB$Closure_0
Boolean V_1, //F
Boolean V_2,
Object() V_3,
Integer V_4,
Object V_5, //o
Boolean V_6)
IL_0000: ldloc.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "o", expectedILOpt:=
"{
// Code size 3 (0x3)
.maxstack 1
.locals init (C._Closure$__1-0 V_0, //$VB$Closure_0
Boolean V_1, //F
Boolean V_2,
Object() V_3,
Integer V_4,
Object V_5, //o
Boolean V_6)
IL_0000: ldloc.s V_5
IL_0002: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub Constants()
Const source = "
Class C
Const x As Integer = 2
Shared Function F(w As Integer) As Integer
#ExternalSource(""test"", 888)
System.Console.WriteLine() ' Force non-hidden sequence point
#End ExternalSource
Const y As Integer = 3
Const v As Object = Nothing
If v Is Nothing orelse w < 2 Then
Const z As String = ""str""
#ExternalSource(""test"", 999)
Dim u As String = z
w += z.Length
#End ExternalSource
End If
Return w + x + y
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.F",
atLineNumber:=888)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "w")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //F
Boolean V_1,
String V_2)
IL_0000: ldc.i4.3
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "v", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //F
Boolean V_1,
String V_2)
IL_0000: ldnull
IL_0001: ret
}
")
context = CreateMethodContext(
runtime,
methodName:="C.F",
atLineNumber:=999) ' Changed this (was Nothing)
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(6, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "w")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F")
VerifyLocal(testData, typeName, locals(2), "<>m2", "u")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult)
VerifyLocal(testData, typeName, locals(4), "<>m4", "v", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult)
VerifyLocal(testData, typeName, locals(5), "<>m5", "z", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Integer V_0, //F
Boolean V_1,
String V_2) //u
IL_0000: ldstr ""str""
IL_0005: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub ConstantEnum()
Const source =
"Enum E
A
B
End Enum
Class C
Shared Sub M(x As E)
Const y = E.B
End Sub
Shared Sub Main()
M(E.A)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugExe)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes, exeBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
Dim method = DirectCast(testData.GetMethodData("<>x.<>m0").Method, MethodSymbol)
Assert.Equal(method.Parameters(0).Type, method.ReturnType)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}")
method = DirectCast(testData.GetMethodData("<>x.<>m1").Method, MethodSymbol)
Assert.Equal(method.Parameters(0).Type, method.ReturnType)
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub ConstantEnumAndTypeParameter()
Const source =
"Class C(Of T)
Enum E
A
End Enum
Friend Shared Sub M(Of U As T)()
Const x As C(Of T).E = E.A
Const y As C(Of U).E = Nothing
End Sub
End Class
Class P
Shared Sub Main()
C(Of Object).M(Of String)()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugExe)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes, exeBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, "<>x(Of T)", locals(0), "<>m0(Of U)", "x", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedGeneric:=True, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}")
VerifyLocal(testData, "<>x(Of T)", locals(1), "<>m1(Of U)", "y", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedGeneric:=True, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}")
VerifyLocal(testData, "<>x(Of T)", locals(2), "<>m2(Of U)", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedGeneric:=True, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""Sub <>c__TypeVariables(Of T, U)..ctor()""
IL_0005: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub CapturedLocalsOutsideLambda()
Const source = "
Imports System
Class C
Shared Sub F(f As Func(Of Object))
End Sub
Sub M(x As C)
Dim y As New C()
F(Function() If(x, If(y, Me)))
If x IsNot Nothing
#ExternalSource(""test"", 999)
Dim z = 6
Dim w = 7
F(Function() If(y, DirectCast(w, Object)))
#End ExternalSource
End If
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M",
atLineNumber:=999)
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(5, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Me As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "x", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Local_x As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "z", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.3
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Local_y As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(4), "<>m4", "w", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.2
IL_0001: ldfld ""C._Closure$__2-1.$VB$Local_w As Integer""
IL_0006: ret
}")
End Sub
<Fact>
Public Sub CapturedLocalsInsideLambda()
Const source = "
Imports System
Class C
Shared Sub F(ff As Func(Of Object, Object))
ff(Nothing)
End Sub
Sub M()
Dim x As New Object()
F(Function(_1)
Dim y As New Object()
F(Function(_2) y)
Return If(x, Me)
End Function)
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__2-0._Lambda$__1")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 2)
VerifyLocal(testData, typeName, locals(0), "<>m0", "_2", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Local_y As Object""
IL_0006: ret
}")
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__2-1._Lambda$__0")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 4)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Object V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__2-1.$VB$Me As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "_1", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Object V_1)
IL_0000: ldarg.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Object V_1)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Local_y As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "x", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Object V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__2-1.$VB$Local_x As Object""
IL_0006: ret
}")
End Sub
<Fact>
Public Sub NestedLambdas()
Const source = "
Imports System
Class C
Shared Sub Main()
Dim f As Func(Of Object, Object, Object, Object, Func(Of Object, Object, Object, Func(Of Object, Object, Func(Of Object, Object)))) =
Function(x1, x2, x3, x4)
If x1 Is Nothing Then Return Nothing
Return Function(y1, y2, y3)
If If(y1, x2) Is Nothing Then Return Nothing
Return Function(z1, z2)
If If(z1, If(y2, x3)) Is Nothing Then Return Nothing
Return Function(w1)
If If(z2, If(y3, x4)) Is Nothing Then Return Nothing
Return w1
End Function
End Function
End Function
End Function
f(1, 2, 3, 4)(5, 6, 7)(8, 9)(10)
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__._Lambda$__1-0")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 4)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x2", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-0 V_0, //$VB$Closure_0
System.Func(Of Object, Object, Object, System.Func(Of Object, Object, System.Func(Of Object, Object))) V_1,
Boolean V_2)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_x2 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "x3")
VerifyLocal(testData, typeName, locals(2), "<>m2", "x4")
VerifyLocal(testData, typeName, locals(3), "<>m3", "x1")
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-0._Lambda$__1")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 6)
VerifyLocal(testData, typeName, locals(0), "<>m0", "y2", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-1 V_0, //$VB$Closure_0
System.Func(Of Object, Object, System.Func(Of Object, Object)) V_1,
Boolean V_2)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__1-1.$VB$Local_y2 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y3")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y1")
VerifyLocal(testData, typeName, locals(3), "<>m3", "x2")
VerifyLocal(testData, typeName, locals(4), "<>m4", "x3", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-1 V_0, //$VB$Closure_0
System.Func(Of Object, Object, System.Func(Of Object, Object)) V_1,
Boolean V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_x3 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(5), "<>m5", "x4")
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-1._Lambda$__2")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 7)
VerifyLocal(testData, typeName, locals(0), "<>m0", "z2", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-2 V_0, //$VB$Closure_0
System.Func(Of Object, Object) V_1,
Boolean V_2)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__1-2.$VB$Local_z2 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "z1")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y2")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y3")
VerifyLocal(testData, typeName, locals(4), "<>m4", "x2")
VerifyLocal(testData, typeName, locals(5), "<>m5", "x3", expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 1
.locals init (C._Closure$__1-2 V_0, //$VB$Closure_0
System.Func(Of Object, Object) V_1,
Boolean V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-1.$VB$NonLocal_$VB$Closure_2 As C._Closure$__1-0""
IL_0006: ldfld ""C._Closure$__1-0.$VB$Local_x3 As Object""
IL_000b: ret
}")
VerifyLocal(testData, typeName, locals(6), "<>m6", "x4")
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-2._Lambda$__3")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 7)
VerifyLocal(testData, typeName, locals(0), "<>m0", "w1")
VerifyLocal(testData, typeName, locals(1), "<>m1", "z2", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0,
Boolean V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-2.$VB$Local_z2 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y2")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y3")
VerifyLocal(testData, typeName, locals(4), "<>m4", "x2")
VerifyLocal(testData, typeName, locals(5), "<>m5", "x3")
VerifyLocal(testData, typeName, locals(6), "<>m6", "x4", expectedILOpt:=
"{
// Code size 17 (0x11)
.maxstack 1
.locals init (Object V_0,
Boolean V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-2.$VB$NonLocal_$VB$Closure_3 As C._Closure$__1-1""
IL_0006: ldfld ""C._Closure$__1-1.$VB$NonLocal_$VB$Closure_2 As C._Closure$__1-0""
IL_000b: ldfld ""C._Closure$__1-0.$VB$Local_x4 As Object""
IL_0010: ret
}")
locals.Free()
End Sub
''' <summary>
''' Should not include "Me" inside display class instance method if
''' "Me" is not captured.
''' </summary>
<Fact>
Public Sub NoMeInsideDisplayClassInstanceMethod()
Const source = "
Imports System
Class C
Sub M(Of T As Class)(x As T)
Dim f As Func(Of Object, Func(Of T, Object)) = Function(y) _
Function(z)
return If(x, If(DirectCast(y, Object), z))
End Function
f(2)(x)
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-0._Lambda$__0")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, "<>x(Of $CLS0)", locals(0), "<>m0", "y")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(1), "<>m1", "x")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(2), "<>m2", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult)
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-1._Lambda$__1")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, "<>x(Of $CLS0)", locals(0), "<>m0", "z")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(1), "<>m1", "y")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(2), "<>m2", "x")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(3), "<>m3", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult)
locals.Free()
End Sub
<Fact>
Public Sub GenericMethod()
Const source = "
Class A (Of T)
Structure B(Of U, V)
Sub M(Of W)(o As A(Of U).B(Of V, Object)())
Dim t1 As T = Nothing
Dim u1 As U = Nothing
Dim w1 As W = Nothing
End Sub
End Structure
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="A.B.M")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(6, locals.Count)
VerifyLocal(testData, "<>x(Of T, U, V)", locals(0), "<>m0(Of W)", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldarg.0
IL_0001: ldobj ""A(Of T).B(Of U, V)""
IL_0006: ret
}",
expectedGeneric:=True)
Dim method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m0(Of W)").Method, MethodSymbol)
Dim containingType = method.ContainingType
Dim containingTypeTypeParameters = containingType.TypeParameters
Dim typeParameterT As TypeParameterSymbol = containingTypeTypeParameters(0)
Dim typeParameterU As TypeParameterSymbol = containingTypeTypeParameters(1)
Dim typeParameterV As TypeParameterSymbol = containingTypeTypeParameters(2)
Dim returnType = DirectCast(method.ReturnType, NamedTypeSymbol)
Assert.Equal(typeParameterU, returnType.TypeArguments(0))
Assert.Equal(typeParameterV, returnType.TypeArguments(1))
returnType = returnType.ContainingType
Assert.Equal(typeParameterT, returnType.TypeArguments(0))
VerifyLocal(testData, "<>x(Of T, U, V)", locals(1), "<>m1(Of W)", "o", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldarg.1
IL_0001: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m1(Of W)").Method, MethodSymbol)
' method.ReturnType: A(Of U).B(Of V, object)()
returnType = DirectCast(DirectCast(method.ReturnType, ArrayTypeSymbol).ElementType, NamedTypeSymbol)
Assert.Equal(typeParameterV, returnType.TypeArguments(0))
returnType = returnType.ContainingType
Assert.Equal(typeParameterU, returnType.TypeArguments(0))
VerifyLocal(testData, "<>x(Of T, U, V)", locals(2), "<>m2(Of W)", "t1", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldloc.0
IL_0001: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m2(Of W)").Method, MethodSymbol)
Assert.Equal(typeParameterT, method.ReturnType)
VerifyLocal(testData, "<>x(Of T, U, V)", locals(3), "<>m3(Of W)", "u1", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldloc.1
IL_0001: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m3(Of W)").Method, MethodSymbol)
Assert.Equal(typeParameterU, method.ReturnType)
VerifyLocal(testData, "<>x(Of T, U, V)", locals(4), "<>m4(Of W)", "w1", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldloc.2
IL_0001: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m4(Of W)").Method, MethodSymbol)
Assert.Equal(method.TypeParameters.Single(), method.ReturnType)
VerifyLocal(testData, "<>x(Of T, U, V)", locals(5), "<>m5(Of W)", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: newobj ""Sub <>c__TypeVariables(Of T, U, V, W)..ctor()""
IL_0005: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m5(Of W)").Method, MethodSymbol)
returnType = DirectCast(method.ReturnType, NamedTypeSymbol)
Assert.Equal(typeParameterT, returnType.TypeArguments(0))
Assert.Equal(typeParameterU, returnType.TypeArguments(1))
Assert.Equal(typeParameterV, returnType.TypeArguments(2))
Assert.Equal(method.TypeParameters.Single(), returnType.TypeArguments(3))
' Verify <>c__TypeVariables types was emitted (#976772)
Using metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))
Dim reader = metadata.MetadataReader
Dim typeDef = reader.GetTypeDef("<>c__TypeVariables")
reader.CheckTypeParameters(typeDef.GetGenericParameters(), "T", "U", "V", "W")
End Using
locals.Free()
End Sub
<Fact>
Public Sub GenericLambda()
Const source = "
Imports System
Class C(Of T As Class)
Shared Sub M(Of U)(t1 As T)
Dim u1 As U = Nothing
Dim f As Func(Of Object) = Function() If(t1, DirectCast(u1, Object))
f()
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-0._Lambda$__0")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
' NOTE: $CLS0 does not appear in the UI.
VerifyLocal(testData, "<>x(Of T, $CLS0)", locals(0), "<>m0", "t1")
VerifyLocal(testData, "<>x(Of T, $CLS0)", locals(1), "<>m1", "u1", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C(Of T)._Closure$__1-0(Of $CLS0).$VB$Local_u1 As $CLS0""
IL_0006: ret
}")
VerifyLocal(testData, "<>x(Of T, $CLS0)", locals(2), "<>m2", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0)
IL_0000: newobj ""Sub <>c__TypeVariables(Of T, $CLS0)..ctor()""
IL_0005: ret
}")
Dim method = DirectCast(testData.GetMethodData("<>x(Of T, $CLS0).<>m1").Method, MethodSymbol)
Dim containingType = method.ContainingType
Assert.Equal(containingType.TypeParameters(1), method.ReturnType)
locals.Free()
End Sub
<Fact>
Public Sub Iterator_InstanceMethod()
Const source = "
Imports System.Collections
Class C
Private ReadOnly _c As Object()
Friend Sub New(c As Object())
_c = c
End Sub
Friend Iterator Function F() As IEnumerable
For Each o In _c
#ExternalSource(""test"", 999)
Yield o
#End ExternalSource
Next
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_2_F.MoveNext",
atLineNumber:=999)
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1,
Boolean V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$Me As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "o", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1,
Boolean V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$ResumableLocal_o$2 As Object""
IL_0006: ret
}")
locals.Free()
End Sub
<Fact()>
Public Sub Iterator_StaticMethod_Generic()
Const source = "
Imports System.Collections.Generic
Class C
Friend Shared Iterator Function F(Of T)(o As T()) As IEnumerable(Of T)
For i = 1 To o.Length
#ExternalSource(""test"", 999)
Dim t1 As T = Nothing
Yield t1
Yield o(i)
#End ExternalSource
Next
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_1_F.MoveNext",
atLineNumber:=999)
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, "<>x(Of T)", locals(0), "<>m0", "o", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_F(Of T).$VB$Local_o As T()""
IL_0006: ret
}")
VerifyLocal(testData, "<>x(Of T)", locals(1), "<>m1", "i", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_F(Of T).$VB$ResumableLocal_i$1 As Integer""
IL_0006: ret
}")
VerifyLocal(testData, "<>x(Of T)", locals(2), "<>m2", "t1", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_F(Of T).$VB$ResumableLocal_t1$2 As T""
IL_0006: ret
}
")
VerifyLocal(testData, "<>x(Of T)", locals(3), "<>m3", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: newobj ""Sub <>c__TypeVariables(Of T)..ctor()""
IL_0005: ret
}")
locals.Free()
End Sub
<Fact(Skip:="1002672"), WorkItem(1002672)>
Public Sub Async_InstanceMethod_Generic()
Const source = "
Imports System.Threading.Tasks
Structure S(Of T As Class)
Private x As T
Friend Async Function F(Of U As Class)(y As u) As Task(Of Object)
Dim z As T = Nothing
Return If(Me.x, If(DirectCast(y, Object), z))
End Function
End Structure
"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="S.VB$StateMachine_0_F.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(5, locals.Count)
VerifyLocal(testData, "<>x(Of T, U)", locals(0), "<>m0", "Me", expectedILOpt:="
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0, //VB$returnTemp
Integer V_1, //VB$cachedState
System.Threading.Tasks.Task(Of Object) V_2, //MoveNext
T V_3, //z
T V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""Friend $VB$Me As S(Of T)""
IL_0006: ret
}
")
VerifyLocal(testData, "<>x(Of T, U)", locals(1), "<>m1", "MoveNext") ' We don't actually step into MoveNext, so this does not appear in the UI.
VerifyLocal(testData, "<>x(Of T, U)", locals(2), "<>m2", "z", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Object V_0, //VB$returnTemp
Integer V_1, //VB$cachedState
System.Threading.Tasks.Task(Of Object) V_2, //MoveNext
T V_3, //z
T V_4,
System.Exception V_5)
IL_0000: ldloc.3
IL_0001: ret
}
")
VerifyLocal(testData, "<>x(Of T, U)", locals(3), "<>m3", "y", expectedILOpt:="
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0, //VB$returnTemp
Integer V_1, //VB$cachedState
System.Threading.Tasks.Task(Of Object) V_2, //MoveNext
T V_3, //z
T V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""Friend $VB$Local_y As U""
IL_0006: ret
}
")
' TODO: Don't show does U in the UI (DevDiv #1014763).
VerifyLocal(testData, "<>x(Of T, U)", locals(4), "<>m4", "<>TypeVariables", expectedILOpt:="
{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0, //VB$returnTemp
Integer V_1, //VB$cachedState
System.Threading.Tasks.Task(Of Object) V_2, //MoveNext
T V_3, //z
T V_4,
System.Exception V_5)
IL_0000: newobj ""Sub <>c__TypeVariables(Of T, U)..ctor()""
IL_0005: ret
}
")
locals.Free()
End Sub
<Fact(Skip:="1002672"), WorkItem(1002672)>
Public Sub Async_StaticMethod()
Const source = "
Imports System.Threading.Tasks
Class C
Shared Async Function F(o As Object) As Task(Of Object)
Return o
End Function
Shared Async Function M(x As Object) As task
Dim y = Await F(x)
Await F(y)
End Function
End Class
"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_1_M.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "MoveNext") ' We don't actually step into MoveNext, so this does not appear in the UI.
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //VB$cachedState
System.Threading.Tasks.Task V_1, //MoveNext
Object V_2, //y
System.Runtime.CompilerServices.TaskAwaiter(Of Object) V_3,
Boolean V_4,
Object V_5,
System.Runtime.CompilerServices.TaskAwaiter(Of Object) V_6,
System.Exception V_7)
IL_0000: ldloc.2
IL_0001: ret
}
")
VerifyLocal(testData, typeName, locals(2), "<>m2", "x", expectedILOpt:="
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0, //VB$cachedState
System.Threading.Tasks.Task V_1, //MoveNext
Object V_2, //y
System.Runtime.CompilerServices.TaskAwaiter(Of Object) V_3,
Boolean V_4,
Object V_5,
System.Runtime.CompilerServices.TaskAwaiter(Of Object) V_6,
System.Exception V_7)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_M.$VB$Local_x As Object""
IL_0006: ret
}
")
locals.Free()
End Sub
<WorkItem(995976)>
<WorkItem(997613)>
<WorkItem(1002672)>
<WorkItem(1085911)>
<Fact>
Public Sub AsyncAndLambda()
Const source =
"Imports System
Imports System.Threading.Tasks
Class C
Shared Async Function F() As Task
End Function
Shared Sub G(a As Action)
a()
End Sub
Shared Async Function M(x As Integer) As Task(Of Integer)
Dim y = x + 1
Await F()
G(Sub()
x = x + 2
y = y + 2
End Sub)
x = x + y
Return x
End Function
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_3_M.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Integer) V_2,
System.Runtime.CompilerServices.TaskAwaiter V_3,
C.VB$StateMachine_3_M V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_3_M.$VB$Local_x As Integer""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 1
.locals init (Integer V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Integer) V_2,
System.Runtime.CompilerServices.TaskAwaiter V_3,
C.VB$StateMachine_3_M V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_3_M.$VB$ResumableLocal_$VB$Closure_$0 As C._Closure$__3-0""
IL_0006: ldfld ""C._Closure$__3-0.$VB$Local_y As Integer""
IL_000b: ret
}")
locals.Free()
End Sub
<WorkItem(2240)>
<Fact>
Public Sub AsyncLambda()
Const source =
"Imports System
Imports System.Threading.Tasks
Class C
Shared Sub M()
Dim f As Func(Of Integer, Task) = Async Function (x)
Dim y = 42
End Function
End Sub
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__.VB$StateMachine___Lambda$__1-0.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Threading.Tasks.Task V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__.VB$StateMachine___Lambda$__1-0.$VB$Local_x As Integer""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Threading.Tasks.Task V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__.VB$StateMachine___Lambda$__1-0.$VB$ResumableLocal_y$0 As Integer""
IL_0006: ret
}")
locals.Free()
End Sub
<WorkItem(996571)>
<Fact>
Public Sub MissingReference()
Const source0 =
"Public Class A
End Class
Public Structure B
End Structure"
Const source1 =
"Class C
Shared Sub M(a As A, b As B, c As C)
End Sub
End Class"
Dim comp0 = CreateCompilationWithMscorlib({source0}, options:=TestOptions.DebugDll)
Dim comp1 = CreateCompilationWithMscorlib({source1}, options:=TestOptions.DebugDll, references:={comp0.EmitToImageReference()})
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp1.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef), ' no reference to compilation0
exeBytes,
New SymReader(pdbBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData, expectedDiagnostics:=
{
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "a").WithArguments("A", "Test.dll").WithLocation(1, 1)
})
Assert.Equal(0, locals.Count)
locals.Free()
End Sub
<Fact>
Public Sub AssignmentToLockLocal()
Const source = "
Class C
Sub M(o As Object)
SyncLock(o)
#ExternalSource(""test"", 999)
Dim x As Integer = 1
#End ExternalSource
End SyncLock
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M",
atLineNumber:=999)
Dim errorMessage As String = Nothing
Dim testData As New CompilationTestData()
context.CompileAssignment("o", "Nothing", errorMessage, testData, VisualBasicDiagnosticFormatter.Instance)
Assert.Null(errorMessage) ' In regular code, there would be an error about modifying a lock local.
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 4 (0x4)
.maxstack 1
.locals init (Object V_0,
Boolean V_1,
Integer V_2) //x
IL_0000: ldnull
IL_0001: starg.s V_1
IL_0003: ret
}")
End Sub
<WorkItem(1015887)>
<Fact>
Public Sub LocalDateConstant()
Const source = "
Class C
Shared Sub M()
Const d = #2010/01/02#
Dim dt As New System.DateTime(2010, 1, 2) ' It's easier to figure out the signature to pass if this is here.
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes, exeBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim errorMessage As String = Nothing
context.CompileAssignment("d", "Nothing", errorMessage, formatter:=VisualBasicDiagnosticFormatter.Instance)
Assert.Equal("(1) : error BC30074: Constant cannot be the target of an assignment.", errorMessage)
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim testData As New CompilationTestData()
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "dt", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Date V_0) //dt
IL_0000: ldloc.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "d", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 15 (0xf)
.maxstack 1
.locals init (Date V_0) //dt
IL_0000: ldc.i8 0x8cc5955a94ec000
IL_0009: newobj ""Sub Date..ctor(Long)""
IL_000e: ret
}")
End Sub
<WorkItem(1015887)>
<Fact>
Public Sub LocalDecimalConstant()
Const source = "
Class C
Shared Sub M()
Const d As Decimal = 1.5D
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes, exeBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim errorMessage As String = Nothing
context.CompileAssignment("d", "Nothing", errorMessage, formatter:=VisualBasicDiagnosticFormatter.Instance)
Assert.Equal("(1) : error BC30074: Constant cannot be the target of an assignment.", errorMessage)
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim testData As New CompilationTestData()
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(1, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "d", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 5
IL_0000: ldc.i4.s 15
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: newobj ""Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)""
IL_000b: ret
}")
End Sub
<Fact, WorkItem(1022165), WorkItem(1028883), WorkItem(1034204)>
Public Sub KeywordIdentifiers()
Const source = "
Class C
Sub M([Nothing] As Integer)
Dim [Me] = 1
Dim [True] = ""t""c
Dim [Namespace] = ""NS""
End Sub
End Class"
Dim compilation0 = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation0)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.NotEqual(assembly.Count, 0)
Assert.Equal(locals.Count, 5)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldarg.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "[Nothing]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldarg.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "[Me]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldloc.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "[True]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldloc.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(4), "<>m4", "[Namespace]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldloc.2
IL_0001: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub ExtensionIterator()
Const source = "
Module M
<System.Runtime.CompilerServices.Extension>
Iterator Function F(x As Integer) As System.Collections.IEnumerable
Yield x
End Function
End Module
"
Const expectedIL = "
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""M.VB$StateMachine_0_F.$VB$Local_x As Integer""
IL_0006: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(runtime, "M.VB$StateMachine_0_F.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.NotEqual(0, assembly.Count)
Assert.Equal(1, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=expectedIL)
Assert.Equal(SpecialType.System_Int32, testData.GetMethodData(typeName & ".<>m0").Method.ReturnType.SpecialType)
locals.Free()
testData = New CompilationTestData()
Dim errorMessage As String = Nothing
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
Dim methodData = testData.GetMethodData("<>x.<>m0")
methodData.VerifyIL(expectedIL)
Assert.Equal(SpecialType.System_Int32, methodData.Method.ReturnType.SpecialType)
End Sub
<WorkItem(1014763)>
<Fact>
Public Sub TypeVariablesTypeParameterNames()
Const source = "
Imports System.Collections.Generic
Class C
Iterator Shared Function I(Of T)() As IEnumerable(Of T)
Yield Nothing
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(runtime, "C.VB$StateMachine_1_I.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.NotEqual(0, assembly.Count)
Dim local = locals.Single()
Assert.Equal("<>TypeVariables", local.LocalName)
Assert.Equal("<>m0", local.MethodName)
Dim method = testData.GetMethodData("<>x(Of T).<>m0").Method
Dim typeVariablesType = DirectCast(method.ReturnType, NamedTypeSymbol)
Assert.Equal("T", typeVariablesType.TypeParameters.Single().Name)
Assert.Equal("T", typeVariablesType.TypeArguments.Single().Name)
End Sub
<Fact, WorkItem(1063254)>
Public Sub OverloadedIteratorDifferentParameterTypes_ArgumentsOnly()
Dim source = "
Imports System.Collections.Generic
Class C
Iterator Function M1(x As Integer, y As Integer) As IEnumerable(Of Integer)
Dim local = 0
Yield local
End Function
Iterator Function M1(x As Integer, y As Single) As IEnumerable(Of Single)
Dim local = 0.0F
Yield local
End Function
Shared Iterator Function M2(x As Integer, y As Single) As IEnumerable(Of Single)
Dim local = 0.0F
Yield local
End Function
Shared Iterator Function M2(Of T)(x As Integer, y As T) As IEnumerable(Of T)
Dim local As T = Nothing
Yield local
End Function
Shared Iterator Function M2(x As Integer, y As Integer) As IEnumerable(Of Integer)
Dim local = 0
Yield local
End Function
End Class"
Dim compilation = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim displayClassName As String
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim ilTemplate = "
{{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C.{1}.$VB$Local_{2} As {0}""
IL_0006: ret
}}"
' M1(Integer, Integer)
displayClassName = "VB$StateMachine_1_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "y"))
locals.Clear()
' M1(Integer, Single)
displayClassName = "VB$StateMachine_2_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Single", displayClassName, "y"))
locals.Clear()
' M2(Integer, Single)
displayClassName = "VB$StateMachine_3_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Single", displayClassName, "y"))
locals.Clear()
' M2(Integer, T)
displayClassName = "VB$StateMachine_4_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
typeName += "(Of T)"
displayClassName += "(Of T)"
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "T", displayClassName, "y"))
locals.Clear()
' M2(Integer, Integer)
displayClassName = "VB$StateMachine_5_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "y"))
locals.Clear()
locals.Free()
End Sub
<Fact, WorkItem(1063254)>
Public Sub OverloadedAsyncDifferentParameterTypes_ArgumentsOnly()
Dim source = "
Imports System.Threading.Tasks
Class C
Async Function M1(x As Integer) As Task(Of Integer)
Dim local = 0
Return local
End Function
Async Function M1(x As Integer, y As Single) As Task(Of Single)
Dim local = 0.0F
Return local
End Function
Shared Async Function M2(x As Integer, y As Single) As Task(Of Single)
Dim local = 0.0F
return local
End Function
Shared Async Function M2(Of T)(x As T) As Task(Of T)
Dim local As T = Nothing
Return local
End Function
Shared Async Function M2(x As Integer) As Task(Of Integer)
Dim local = 0
Return local
End Function
End Class"
Dim compilation = CreateCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim displayClassName As String
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim ilTemplate = "
{{
// Code size 7 (0x7)
.maxstack 1
.locals init ({0} V_0,
Integer V_1,
System.Threading.Tasks.Task(Of {0}) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C.{2}.$VB$Local_{3} As {1}""
IL_0006: ret
}}"
' M1(Integer)
displayClassName = "VB$StateMachine_1_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", "Integer", displayClassName, "x"))
locals.Clear()
' M1(Integer, Single)
displayClassName = "VB$StateMachine_2_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Single", "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Single", "Single", displayClassName, "y"))
locals.Clear()
' M2(Integer, Single)
displayClassName = "VB$StateMachine_3_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Single", "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Single", "Single", displayClassName, "y"))
locals.Clear()
' M2(T)
displayClassName = "VB$StateMachine_4_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "T", "T", displayClassName + "(Of T)", "x"))
locals.Clear()
' M2(Integer)
displayClassName = "VB$StateMachine_5_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", "Integer", displayClassName, "x"))
locals.Clear()
locals.Free()
End Sub
<Fact, WorkItem(1063254)>
Public Sub MultipleLambdasDifferentParameterNames_ArgumentsOnly()
Dim source = "
Imports System
Class C
Sub M1(x As Integer)
Dim a As Action(Of Integer) = Sub(y) x.ToString()
Dim f As Func(Of Integer, Integer) = Function(z) x
End Sub
Shared Sub M2(Of T)(x As Integer)
Dim a As Action(Of Integer) = Sub(y) y.ToString()
Dim f As Func(Of Integer, Integer) = Function(z) z
Dim g As Func(Of T, T) = Function(ti) ti
End Sub
End Class"
Dim compilation = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim displayClassName As String
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim voidRetILTemplate = "
{{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.{0}
IL_0001: ret
}}"
Dim funcILTemplate = "
{{
// Code size 2 (0x2)
.maxstack 1
.locals init ({0} V_0)
IL_0000: ldarg.{1}
IL_0001: ret
}}"
' Sub(y) x.ToString()
displayClassName = "_Closure$__1-0"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__0", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "y", expectedILOpt:=String.Format(voidRetILTemplate, 1))
locals.Clear()
' Function(z) x
displayClassName = "_Closure$__1-0"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__1", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "z", expectedILOpt:=String.Format(funcILTemplate, "Integer", 1))
locals.Clear()
' Sub(y) y.ToString()
displayClassName = "_Closure$__2"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__2-0", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of $CLS0)", locals(0), "<>m0", "y", expectedILOpt:=String.Format(voidRetILTemplate, 1))
locals.Clear()
' Function(z) z
displayClassName = "_Closure$__2"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__2-1", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of $CLS0)", locals(0), "<>m0", "z", expectedILOpt:=String.Format(funcILTemplate, "Integer", 1))
locals.Clear()
' Function(ti) ti
displayClassName = "_Closure$__2"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__2-2", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of $CLS0)", locals(0), "<>m0", "ti", expectedILOpt:=String.Format(funcILTemplate, "$CLS0", 1))
locals.Clear()
locals.Free()
End Sub
<Fact, WorkItem(1063254)>
Public Sub OverloadedRegularMethodDifferentParameterTypes_ArgumentsOnly()
Dim source = "
Class C
Sub M1(x As Integer, y As Integer)
Dim local = 0
End Sub
Function M1(x As Integer, y As String) As String
Dim local As String = Nothing
return local
End Function
Shared Sub M2(x As Integer, y As String)
Dim local As String = Nothing
End Sub
Shared Function M2(Of T)(x As Integer, y As T) As T
Dim local As T = Nothing
Return local
End Function
Shared Function M2(x As Integer, ByRef y As Integer) As Integer
Dim local As Integer = 0
Return local
End Function
End Class"
Dim compilation = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim voidRetILTemplate = "
{{
// Code size 2 (0x2)
.maxstack 1
.locals init ({0} V_0) //local
IL_0000: ldarg.{1}
IL_0001: ret
}}"
Dim funcILTemplate = "
{{
// Code size 2 (0x2)
.maxstack 1
.locals init ({0} V_0, {1}
{0} V_1) //local
IL_0000: ldarg.{2}
IL_0001: ret
}}"
Dim refParamILTemplate = "
{{
// Code size 3 (0x3)
.maxstack 1
.locals init ({0} V_0, {1}
{0} V_1) //local
IL_0000: ldarg.{2}
IL_0001: ldind.i4
IL_0002: ret
}}"
' M1(Integer, Integer)
GetLocals(runtime, "C.M1(Int32,Int32)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(voidRetILTemplate, "Integer", 1))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(voidRetILTemplate, "Integer", 2))
locals.Clear()
' M1(Integer, String)
GetLocals(runtime, "C.M1(Int32,String)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(funcILTemplate, "String", "//M1", 1))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(funcILTemplate, "String", "//M1", 2))
locals.Clear()
' M2(Integer, String)
GetLocals(runtime, "C.M2(Int32,String)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(voidRetILTemplate, "String", 0))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(voidRetILTemplate, "String", 1))
locals.Clear()
' M2(Integer, T)
GetLocals(runtime, "C.M2(Int32,T)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0(Of T)", "x", expectedILOpt:=String.Format(funcILTemplate, "T", "//M2", 0), expectedGeneric:=True)
VerifyLocal(testData, typeName, locals(1), "<>m1(Of T)", "y", expectedILOpt:=String.Format(funcILTemplate, "T", "//M2", 1), expectedGeneric:=True)
locals.Clear()
' M2(Integer, Integer)
GetLocals(runtime, "C.M2(Int32,Int32)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(funcILTemplate, "Integer", "//M2", 0))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(refParamILTemplate, "Integer", "//M2", 1))
locals.Clear()
locals.Free()
End Sub
<Fact, WorkItem(1063254)>
Public Sub MultipleMethodsLocalConflictsWithParameterName_ArgumentsOnly()
Dim source = "
Imports System.Collections.Generic
Imports System.Threading.Tasks
Class C(Of T)
Iterator Function M1() As IEnumerable(Of Integer)
Dim x = 0
Yield x
End Function
Iterator Function M1(x As Integer) As IEnumerable(Of Integer)
Yield x
End Function
Iterator Function M2(x As Integer) As IEnumerable(Of Integer)
Yield x
End Function
Iterator Function M2() As IEnumerable(Of Integer)
Dim x = 0
Yield x
End Function
Shared Async Function M3() As Task(Of T)
Dim x As T = Nothing
return x
End Function
Shared Async Function M3(x As T) As Task(Of T)
Return x
End Function
Shared Async Function M4(x As T) As Task(Of T)
Return x
End Function
Shared Async Function M4() As Task(Of T)
Dim x As T = Nothing
Return x
End Function
End Class"
Dim compilation = CreateCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim displayClassName As String
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim iteratorILTemplate = "
{{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
{0} V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C(Of T).{1}.$VB$Local_{2} As {0}""
IL_0006: ret
}}"
Dim asyncILTemplate = "
{{
// Code size 7 (0x7)
.maxstack 1
.locals init ({0} V_0,
Integer V_1,
System.Threading.Tasks.Task(Of {0}) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C(Of T).{1}.$VB$Local_{2} As {0}""
IL_0006: ret
}}"
' M1()
displayClassName = "VB$StateMachine_1_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=0, typeName:=typeName, testData:=testData)
locals.Clear()
' M1(Integer)
displayClassName = "VB$StateMachine_2_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(iteratorILTemplate, "Integer", displayClassName, "x"))
locals.Clear()
' M2(Integer)
displayClassName = "VB$StateMachine_3_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(iteratorILTemplate, "Integer", displayClassName, "x"))
locals.Clear()
' M2()
displayClassName = "VB$StateMachine_4_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=0, typeName:=typeName, testData:=testData)
locals.Clear()
' M3()
displayClassName = "VB$StateMachine_5_M3"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=0, typeName:=typeName, testData:=testData)
locals.Clear()
' M3(Integer)
displayClassName = "VB$StateMachine_6_M3"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(asyncILTemplate, "T", displayClassName, "x"))
locals.Clear()
' M4(Integer)
displayClassName = "VB$StateMachine_7_M4"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(asyncILTemplate, "T", displayClassName, "x"))
locals.Clear()
' M4()
displayClassName = "VB$StateMachine_8_M4"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=0, typeName:=typeName, testData:=testData)
locals.Clear()
locals.Free()
End Sub
<WorkItem(1115044, "DevDiv")>
<Fact>
Public Sub CaseSensitivity()
Const source = "
Class C
Shared Sub M(p As Integer)
Dim s As String
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim errorMessage As String = Nothing
Dim testData As CompilationTestData
testData = New CompilationTestData()
context.CompileExpression("P", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0) //s
IL_0000: ldarg.0
IL_0001: ret
}
")
testData = New CompilationTestData()
context.CompileExpression("S", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0) //s
IL_0000: ldloc.0
IL_0001: ret
}
")
End Sub
<WorkItem(1115030)>
<Fact>
Public Sub CatchInAsyncStateMachine()
Const source =
"Imports System
Imports System.Threading.Tasks
Class C
Shared Function F() As Object
Throw New ArgumentException()
End Function
Shared Async Function M() As Task
Dim o As Object
Try
o = F()
Catch e As Exception
#ExternalSource(""test"", 999)
o = e
#End ExternalSource
End Try
End Function
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_2_M.MoveNext",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "o", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Exception V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_o$0 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "e", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Exception V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_e$1 As System.Exception""
IL_0006: ret
}")
locals.Free()
End Sub
<WorkItem(1115030)>
<Fact>
Public Sub CatchInIteratorStateMachine()
Const source =
"Imports System
Imports System.Collections
Class C
Shared Function F() As Object
Throw New ArgumentException()
End Function
Shared Iterator Function M() As IEnumerable
Dim o As Object
Try
o = F()
Catch e As Exception
#ExternalSource(""test"", 999)
o = e
#End ExternalSource
End Try
Yield o
End Function
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_2_M.MoveNext",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "o", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_o$0 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "e", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_e$1 As System.Exception""
IL_0006: ret
}")
locals.Free()
End Sub
<WorkItem(947)>
<Fact>
Public Sub DuplicateEditorBrowsableAttributes()
Const libSource = "
Namespace System.ComponentModel
Public Enum EditorBrowsableState
Always = 0
Never = 1
Advanced = 2
End Enum
<AttributeUsage(AttributeTargets.All)>
Friend NotInheritable Class EditorBrowsableAttribute
Inherits Attribute
Public Sub New(state As EditorBrowsableState)
End Sub
End Class
End Namespace
"
Const source = "
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)>
Class C
Sub M()
End Sub
End Class
"
Dim libRef = CreateCompilationWithMscorlib({libSource}, options:=TestOptions.DebugDll).EmitToImageReference()
Dim comp = CreateCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef, SystemRef}, TestOptions.DebugDll)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim unusedReferences As ImmutableArray(Of MetadataReference) = Nothing
Dim result = comp.EmitAndGetReferences(exeBytes, pdbBytes, unusedReferences)
Assert.True(result)
' Referencing SystemCoreRef and SystemXmlLinqRef will cause Microsoft.VisualBasic.Embedded to be compiled
' and it depends on EditorBrowsableAttribute.
Dim runtimeReferences = ImmutableArray.Create(MscorlibRef, SystemRef, SystemCoreRef, SystemXmlLinqRef, libRef)
Dim runtime = CreateRuntimeInstance(GetUniqueName(), runtimeReferences, exeBytes, New SymReader(pdbBytes))
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, "C.M", argumentsOnly:=False, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
Assert.Equal("Me", locals.Single().LocalName)
locals.Free()
End Sub
<WorkItem(2089, "https://github.com/dotnet/roslyn/issues/2089")>
<Fact>
Public Sub MultipleMeFields()
Const source =
"Imports System
Imports System.Threading.Tasks
Class C
Async Shared Function F(a As Action) As Task
a()
End Function
Sub G(s As String)
End Sub
Async Sub M()
Dim s As String = Nothing
Await F(Sub() G(s))
End Sub
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(runtime, methodName:="C.VB$StateMachine_3_M.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.VB$StateMachine_3_M V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_3_M.$VB$Me As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "s", expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 1
.locals init (Integer V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.VB$StateMachine_3_M V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_3_M.$VB$ResumableLocal_$VB$Closure_$0 As C._Closure$__3-0""
IL_0006: ldfld ""C._Closure$__3-0.$VB$Local_s As String""
IL_000b: ret
}")
locals.Free()
End Sub
<WorkItem(2336, "https://github.com/dotnet/roslyn/issues/2336")>
<Fact>
Public Sub LocalsOnAsyncEndSub()
Const source = "
Imports System
Imports System.Threading.Tasks
Class C
Async Sub M()
Dim s As String = Nothing
#ExternalSource(""test"", 999)
End Sub
#End ExternalSource
End Class
"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(runtime, methodName:="C.VB$StateMachine_1_M.MoveNext", atLineNumber:=999)
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me")
VerifyLocal(testData, typeName, locals(1), "<>m1", "s")
locals.Free()
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_FromParameter()
Const source = "
Imports System.Linq
Class C
Sub M(args As String())
Dim concat =
From x In args
Let y = x.ToString()
Let z = x.GetHashCode()
Select x & y & z
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-2"
Const zIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$z As Integer""
IL_0006: ret
}
"
Const xIL = "
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$$VB$It As VB$AnonymousType_0(Of String, String)""
IL_0006: ldfld ""VB$AnonymousType_0(Of String, String).$x As String""
IL_000b: ret
}
"
Const yIL = "
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$$VB$It As VB$AnonymousType_0(Of String, String)""
IL_0006: ldfld ""VB$AnonymousType_0(Of String, String).$y As String""
IL_000b: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=3, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "z", expectedILOpt:=zIL)
VerifyLocal(testData, typeName, locals(1), "<>m1", "x", expectedILOpt:=xIL)
VerifyLocal(testData, typeName, locals(2), "<>m2", "y", expectedILOpt:=yIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("z", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(zIL)
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
testData = New CompilationTestData()
context.CompileExpression("y", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(yIL)
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_FromDisplayClassField()
Const source = "
Imports System.Linq
Class C
Sub M(args As String())
Dim concat =
From x In args
Let y = x.ToString()
Let z = x.GetHashCode()
Select x.Select(Function(c) y & z)
End Sub
End Class
"
Const methodName = "C._Closure$__1-0._Lambda$__3"
Const cIL = "
{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0)
IL_0000: ldarg.1
IL_0001: ret
}
"
Const zIL = "
{
// Code size 12 (0xc)
.maxstack 1
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_$VB$It As VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer)""
IL_0006: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$z As Integer""
IL_000b: ret
}
"
Const xIL = "
{
// Code size 17 (0x11)
.maxstack 1
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_$VB$It As VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer)""
IL_0006: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$$VB$It As VB$AnonymousType_0(Of String, String)""
IL_000b: ldfld ""VB$AnonymousType_0(Of String, String).$x As String""
IL_0010: ret
}
"
Const yIL = "
{
// Code size 17 (0x11)
.maxstack 1
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_$VB$It As VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer)""
IL_0006: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$$VB$It As VB$AnonymousType_0(Of String, String)""
IL_000b: ldfld ""VB$AnonymousType_0(Of String, String).$y As String""
IL_0010: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=4, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "c", expectedILOpt:=cIL)
VerifyLocal(testData, typeName, locals(1), "<>m1", "z", expectedILOpt:=zIL)
VerifyLocal(testData, typeName, locals(2), "<>m2", "x", expectedILOpt:=xIL)
VerifyLocal(testData, typeName, locals(3), "<>m3", "y", expectedILOpt:=yIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("c", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(cIL)
testData = New CompilationTestData()
context.CompileExpression("z", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(zIL)
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
testData = New CompilationTestData()
context.CompileExpression("y", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(yIL)
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_It1()
Const source = "
Imports System.Linq
Class C
Sub M(args As String())
Dim concat =
From x In args, y In args
From z In args
Select x & y & z
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-3"
Const zIL = "
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.2
IL_0001: ret
}
"
Const xIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_0(Of String, String).$x As String""
IL_0006: ret
}
"
Const yIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_0(Of String, String).$y As String""
IL_0006: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=3, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "z", expectedILOpt:=zIL)
VerifyLocal(testData, typeName, locals(1), "<>m1", "x", expectedILOpt:=xIL)
VerifyLocal(testData, typeName, locals(2), "<>m2", "y", expectedILOpt:=yIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("z", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(zIL)
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
testData = New CompilationTestData()
context.CompileExpression("y", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(yIL)
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_It2()
Const source = "
Imports System.Linq
Class C
Sub M(nums As Integer())
Dim q = From x In nums
Join y In nums
Join z In nums
On z Equals y
On x Equals y And z Equals x
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-5"
Const xIL = "
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}
"
Const yIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.2
IL_0001: ldfld ""VB$AnonymousType_1(Of Integer, Integer).$y As Integer""
IL_0006: ret
}
"
Const zIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.2
IL_0001: ldfld ""VB$AnonymousType_1(Of Integer, Integer).$z As Integer""
IL_0006: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=3, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=xIL)
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=yIL)
VerifyLocal(testData, typeName, locals(2), "<>m2", "z", expectedILOpt:=zIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
testData = New CompilationTestData()
context.CompileExpression("y", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(yIL)
testData = New CompilationTestData()
context.CompileExpression("z", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(zIL)
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_ItAnonymous()
Const source = "
Imports System.Linq
Class C
Sub M(args As String())
Dim concat =
From x In args
Group y = x.GetHashCode() By x
Into s = Sum(y + 3)
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-2"
Const xIL = "
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=xIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
End Sub
Private Shared Sub GetLocals(runtime As RuntimeInstance, methodName As String, argumentsOnly As Boolean, locals As ArrayBuilder(Of LocalAndMethod), count As Integer, ByRef typeName As String, ByRef testData As CompilationTestData)
Dim context = CreateMethodContext(runtime, methodName)
testData = New CompilationTestData()
Dim assembly = context.CompileGetLocals(locals, argumentsOnly, typeName, testData)
Assert.NotNull(assembly)
If count = 0 Then
Assert.Equal(0, assembly.Count)
Else
Assert.InRange(assembly.Count, 0, Integer.MaxValue)
End If
Assert.Equal(count, locals.Count)
End Sub
End Class
End Namespace
|
furesoft/roslyn
|
src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb
|
Visual Basic
|
apache-2.0
| 117,629
|
Imports System.Text
Public Class Executor
Private _vars As New VarStorage
Private Sub CallFunction(ByRef out As StringBuilder, ByRef errs As StringBuilder, ByVal instr As Instruction)
End Sub
Private Sub CallInternalFunction(ByRef out As StringBuilder, ByRef errs As StringBuilder, ByVal instr As Instruction, funcName As String)
Try
Dim funcFound As Boolean
'WRITE
If funcName = "WRITE" Or funcName = "WRITELINE" Then
'возврат - 0
Dim result = GetVariable(instr.Args(1).Value)
result.Type = DataType.dataInteger
result.Value = 0
'выводим аргументы
For i As Integer = 2 To (instr.Args.Count) - 1
Dim val1 = ResolveToValue(instr.Args(i))
out.Append(val1.Value)
Next i
If funcName = "WRITELINE" Then out.AppendLine()
funcFound = True
End If
'АРИФМЕТИЧЕСКИЕ И ЛОГИЧЕСКИЕ ОПЕРАЦИИ
If (funcName = "ADD") OrElse (funcName = "SB") OrElse (funcName = "MUL") OrElse (funcName = "DIV") OrElse (funcName = "AND") OrElse (funcName = "OR") Then
funcFound = True
Dim arg1 As Integer = ResolveToValue(instr.Args(2)).Value
Dim arg2 As Integer = ResolveToValue(instr.Args(3)).Value
Dim result As Integer
If funcName = "ADD" Then
result = arg1 + arg2
End If
If funcName = "SB" Then
result = arg1 - arg2
End If
If funcName = "MUL" Then
result = arg1 * arg2
End If
If funcName = "DIV" Then
result = arg1 \ arg2
End If
If funcName = "AND" Then
result = ((arg1 > 0) AndAlso (arg2 > 0))
End If
If funcName = "OR" Then
result = ((arg1 > 0) OrElse (arg2 > 0))
End If
Dim resultValue = GetVariable(instr.Args(1).Value)
resultValue.Type = DataType.dataInteger
resultValue.Value = result
End If
If (funcName = "EQUAL") OrElse (funcName = "LOWER") OrElse (funcName = "GREATER") Then
funcFound = True
Dim val1 = ResolveToValue(instr.Args(2))
Dim val2 = ResolveToValue(instr.Args(3))
If val1.Type = val2.Type Then
Dim result As Integer = 0
If val1.Type = DataType.dataInteger Then
If (funcName = "EQUAL") AndAlso CInt(val1.Value) = CInt(val2.Value) Then
result = 1
End If
If (funcName = "LOWER") AndAlso CInt(val1.Value) < CInt(val2.Value) Then
result = 1
End If
If (funcName = "GREATER") AndAlso CInt(val1.Value) > CInt(val2.Value) Then
result = 1
End If
End If
If val1.Type = DataType.dataString Then
If (funcName = "EQUAL") AndAlso val1.Value = val2.Value Then
result = 1
End If
If (funcName = "LOWER") AndAlso val1.Value < val2.Value Then
result = 1
End If
If (funcName = "GREATER") AndAlso val1.Value > val2.Value Then
result = 1
End If
End If
Dim resultValue = GetVariable(instr.Args(1).Value)
resultValue.Type = DataType.dataInteger
resultValue.Value = result
Else
errs.AppendLine("Сравниваются данные разных типов.")
End If
End If
If (funcName = "INC") OrElse (funcName = "DEC") OrElse (funcName = "NO") Then
funcFound = True
Dim result As Integer
Dim arg1 = ResolveToValue(instr.Args(2))
If funcName = "INC" Then
If instr.Args(2).IsPointer Then
arg1.Value = (CInt(arg1.Value) + 1).ToString
End If
result = arg1.Value + 1
End If
If funcName = "DEC" Then
If instr.Args(2).IsPointer Then
arg1.Value = (CInt(arg1.Value) - 1).ToString
End If
result = arg1.Value - 1
End If
If funcName = "NO" Then
Select Case arg1.Value
Case "0"
result = 1
Case Else
result = -CInt(result)
End Select
End If
Dim resultValue = GetVariable(instr.Args(1).Value)
resultValue.Type = DataType.dataInteger
resultValue.Value = result
End If
If funcName = "VAL" Then
funcFound = True
Dim arg1 = ResolveToValue(instr.Args(2))
Dim result As Integer = CInt(Val(arg1.Value))
Dim resultValue = GetVariable(instr.Args(1).Value)
resultValue.Type = DataType.dataInteger
resultValue.Value = result
End If
If Not funcFound Then
RaiseEvent UnknownFunctionCall(funcFound, funcName, instr, out)
'TODO 1
End If
If Not funcFound Then
Dim exc As New RunTimeError
exc.Text = "Не найдена функция: " + funcName
Throw exc
End If
Catch ex As TranslatorError
Dim exc As New RunTimeError
exc.LineNumber = instr.DebugFromLine
exc.Text = ex.Text
Throw exc
Catch ex As Exception
' Throw ex
Dim exc As New RunTimeError
exc.LineNumber = instr.DebugFromLine
exc.Text = ex.Message
Throw exc
End Try
End Sub
Public Event UnknownFunctionCall(ByRef found As Boolean, funcName As String, instruction As Instruction, out As StringBuilder)
Private Function GetVariable(name As String) As Var
Dim var = _vars.Find(name)
If var Is Nothing Then
Throw New Exception("Var not exist")
End If
Return var
End Function
Private Function ResolveToValue(ByRef arg As Argument) As Var
If arg.IsPointer Then
Dim var = GetVariable(arg.Value)
Return var
Else
Dim value As New Var
value.Name = "FromArg"
value.Value = arg.Value
value.Type = arg.Type
Return value
End If
End Function
Private Function GetParamDataType(ByRef param As Argument) As DataType
Return ResolveToValue(param).Type
End Function
'запускаем программу
Public Sub Run(program() As Instruction, out As StringBuilder)
Dim errs As New StringBuilder
'исполняем программу на ПЯ
Dim cs As Integer = 0
Dim working As Boolean = True
'поток для
Do While (cs < program.Length) AndAlso working
Dim instr As Instruction = program(cs)
'инструкция вызова функции
If instr.Action = Instruction.ActionType.callProgram Then
CallFunction(out, errs, instr)
End If
'инструкция вызова функции
If instr.Action = Instruction.ActionType.callByName Then
Dim funcName As String = instr.Args(0).Value
CallInternalFunction(out, errs, instr, funcName)
End If
'инструкция добавления переменной
If instr.Action = Instruction.ActionType.addVariable Then
Dim arg = instr.Args(0)
If _vars.Find(arg.Value) Is Nothing Then
Dim var As New Var
var.Name = arg.Value
var.Type = arg.Type
Select Case var.Type
Case DataType.dataInteger
var.Value = "0"
End Select
_vars.Add(var)
End If
End If
'инструкция присваивания переменной
If instr.Action = Instruction.ActionType.setVariable Then
Dim var = GetVariable(instr.Args(0).Value)
Dim arg = ResolveToValue(instr.Args(1))
var.Value = arg.Value
'TODO типы данных
End If
'инструкция условного перехода
If instr.Action = Instruction.ActionType.jumpIfNot Then
'значение-условие
Dim arg = ResolveToValue(instr.Args(0))
'если значение ложно, переходим
If CInt(arg.Value) <= 0 Then
Dim v = CInt(instr.Args(1).Value)
cs += v
End If
End If
'инструкция безусловного перехода
If instr.Action = Instruction.ActionType.jumpAlways Then
Dim v = CInt(instr.Args(0).Value)
cs = cs + v
End If
'инкрементируем счетчик
cs += 1
'если были ошибки
If errs.Length > 0 Then
working = False
Dim exc = New RunTimeError
exc.Text = errs.ToString
Throw exc
End If
Loop
End Sub
End Class
|
Lifemotion/Bwl.Translator.One
|
Bwl.Translator.One.Execution/Executor.vb
|
Visual Basic
|
apache-2.0
| 10,603
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Desktop.Analyzers
''' <summary>
''' CA1306: Set locale for data types
''' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public NotInheritable Class BasicSetLocaleForDataTypesFixer
Inherits SetLocaleForDataTypesFixer
End Class
End Namespace
|
mattwar/roslyn-analyzers
|
src/Desktop.Analyzers/VisualBasic/BasicSetLocaleForDataTypes.Fixer.vb
|
Visual Basic
|
apache-2.0
| 689
|
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Drawing.Imaging
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports Microsoft.Office.Interop
Imports System.Data.OleDb
Imports System.Data.Sql
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class Ruche
Dim CenterX As Integer
Dim CenterY As Integer
Dim MaxFont As Integer = 1
Dim TailleLabel As Integer
Dim myPort As Array 'myPort est un tableau, il va servir pour la communication.
Dim Compteur As Integer
Private Sub Ruche_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
On Error GoTo Err_Communication 'Si erreur, aller à "Err_Handler"
'Config du Form
IconeAbeille.Icon = New System.Drawing.Icon("E:\Ruche\Ruche\Images\Abeille.ico") 'Icone de l'appli
IconeAbeille.Visible = True
IconeAbeille.Text = "Ruche"
Me.Icon = IconeAbeille.Icon
Me.Text = "Ruche" 'Titre de l'appli
Me.BackgroundImage = System.Drawing.Image.FromFile("E:\Ruche\Ruche\Images\FondEcran.png") 'Image de fond
Me.Size = New Size(730, 490) 'Taille de la page (du Form)
Me.WindowState = FormWindowState.Maximized 'Application en plein écran
Me.BackgroundImageLayout = ImageLayout.Stretch 'Etirement du l'image par rapport au Form
'-------------------------------------------------------------------------------------
'Servira pour plus tard
MaxFont = Me.Size.Width 'On enregistre la taille maximum du Form (Plein écran)
'-------------------------------------------------------------------------------------
'Config des boutons et des labels
btn_Quitter.Text = "Quitter"
btn_Quitter.BackgroundImage = System.Drawing.Image.FromFile("E:\Ruche\Ruche\Images\hyhnd.png") 'Lien vers l'image à afficher
btn_Quitter.Size = New Size(138, 43) 'Taille du bouton
CenterX = (Me.Size.Width / 2) - (btn_Quitter.Size.Width / 2) 'X du bouton par rapport au X du Form
CenterY = (Me.Size.Height - 150) - (btn_Quitter.Size.Height / 2) 'Y du bouton par rapport au Y du Form
btn_Quitter.Location = New Point(CenterX, CenterY) 'Mouvement du bouton avec le Form
btn_Quitter.BackgroundImageLayout = ImageLayout.Stretch 'Etirer l'image à la taille demandée [Btn_Quitter.Size = New Size(138, 43)]
btn_Quitter.BackColor = Color.Transparent 'Eviter un carré blanc derrière l'écran
btn_Quitter.Focus()
btn_Effacer.Text = "Effacer"
btn_Effacer.Size = New Size(138, 43) 'Taille du bouton
CenterX = (Me.Size.Width / 4) - (btn_Quitter.Size.Width / 2) 'X du bouton par rapport au X du Form
CenterY = (Me.Size.Height - 150) - (btn_Quitter.Size.Height / 2) 'Y du bouton par rapport au Y du Form
btn_Effacer.Location = New Point(CenterX, CenterY) 'Mouvement du bouton avec le Form
btn_Effacer.ForeColor = Color.Orange 'Couleur bouton
btn_Effacer.BackColor = Color.BlueViolet
btn_Effacer.FlatStyle = FlatStyle.Popup 'Type de bouton
btn_Effacer.Font = New Font("Comic Sans MS", 11, FontStyle.Bold) 'Ecriture du bouton
btn_BaseDeDonnees.Text = "Base de données"
btn_BaseDeDonnees.Size = New Size(138, 43) 'Taille du bouton
CenterX = (Me.Size.Width / 4 * 3) - (btn_Quitter.Size.Width / 2) 'X du bouton par rapport au X du Form
CenterY = (Me.Size.Height - 150) - (btn_Quitter.Size.Height / 2) 'Y du bouton par rapport au Y du Form
btn_BaseDeDonnees.Location = New Point(CenterX, CenterY) 'Mouvement du bouton avec le Form
btn_BaseDeDonnees.ForeColor = Color.Orange
btn_BaseDeDonnees.BackColor = Color.BlueViolet
btn_BaseDeDonnees.FlatStyle = FlatStyle.Popup
btn_BaseDeDonnees.Font = New Font("Comic Sans MS", 11, FontStyle.Bold)
'Réglage de la zone de texte
rtb_Donnees.Enabled = False 'Empeche l'écriture
rtb_Donnees.Size = New Size((Me.Size.Width - 200), (Me.Size.Height - 300)) 'Taille
rtb_Donnees.Location = New Point(100, 100) 'Emplacement
lbl_Creator.Text = "By Nora"
lbl_Creator.Font = New Font(lbl_Creator.Text, 13.0, FontStyle.Italic)
CenterX = 50 'X du bouton par rapport au X du Form
CenterY = Me.Size.Height - 100 'Y du bouton par rapport au Y du Form
lbl_Creator.Location = New Point(CenterX, CenterY) 'Mouvement du label avec le Form
lbl_Creator.BackColor = Color.Transparent 'Eviter d'avoir un rectangle blanc derrière l'écriture
lbl_Titre.Text = "Nombre d'abeilles à l'intérieur de la ruche :"
TailleLabel = Me.Size.Width / MaxFont * 35 'Réglage de la taille du label en fonction de la taille maxi du Form
lbl_Titre.Font = New Font("Segoe Script", TailleLabel, FontStyle.Bold And FontStyle.Underline)
lbl_Titre.ForeColor = Color.BlueViolet
CenterX = (Me.Size.Width / 2) - (lbl_Titre.Size.Width / 2)
CenterY = 25 'Y du bouton par rapport au Y du Form
lbl_Titre.Location = New Point(CenterX, CenterY) 'Mouvement du label avec le Form
lbl_Titre.BackgroundImageLayout = ImageLayout.Stretch
lbl_Titre.BackColor = Color.Transparent
'-------------------------------------------------------------------------------------
'Communication
myPort = IO.Ports.SerialPort.GetPortNames() 'On entre toute les ports séries connectés dans le tableau "myPort"
Compteur = 0
Dim TestCOM As String
TestCOM = myPort(Compteur)
'On affiche sur quel port sur laquel nous sommes connectés
rtb_Donnees.Text = vbCrLf & "Vous êtes maintenant connecté au port : " & myPort(Compteur) & rtb_Donnees.Text & vbCrLf
PortSerieIN.Close()
PortSerieIN.PortName = myPort(Compteur) 'Sélection du port
PortSerieIN.BaudRate = 9600 'Sélection du baud rate
PortSerieIN.Parity = IO.Ports.Parity.None 'Sélection de la parité
PortSerieIN.StopBits = IO.Ports.StopBits.One 'Sélection des bits de stop
PortSerieIN.DataBits = 8 'Sélection des bits de données
PortSerieIN.Encoding = System.Text.Encoding.Default
PortSerieIN.Open() 'On ouvre le port, la communication peut commencer
Exit Sub
Err_Communication:
Dim Choix As Integer
Choix = MsgBox("Veuillez rebrancher la puce XBee au PC, attendre 5 secondes puis retester" & vbCrLf & "Appuyez sur 'OK' pour retester", 1, "Problème de communication")
'exemple vaut maintenant le chiffre correspondant au bouton appuyé
If Choix = 1 Then 'Si "OK"
myPort = IO.Ports.SerialPort.GetPortNames() 'On entre toute les ports séries connectés dans le tableau "myPort"
Resume 'Sert à revenir au moment où l'erreur est survenue
ElseIf Choix = 2 Then 'Si "Annuler"
End
End If
End Sub
Private Sub PortSerieIN_DataReceived1(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles PortSerieIN.DataReceived
Threading.Thread.Sleep(500) 'Fonction permettant une attente de 500ms
ReceivedText(PortSerieIN.ReadExisting()) 'Reception des données
End Sub
Delegate Sub SetTextCallback(ByVal NbrAbeilles As String)
Private Sub ReceivedText(ByVal NbrAbeilles As String) 'input from ReadExisting
'Cette fonction sert à afficher les donneées recus dans la zone de texte de réception
If Me.rtb_Donnees.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(NbrAbeilles)})
Else
rtb_Donnees.Text = vbCrLf & NbrAbeilles & rtb_Donnees.Text & vbCrLf 'Texte à noter sur la zone de données
ReceptionExcel(NbrAbeilles)
End If
End Sub
Private Sub ReceptionExcel(ByVal NbrAbeillesActuel As String)
On Error GoTo Err_FichierExcel1 'Si erreur, aller à "Err_Handler"
'Assemblage des données dans le fichier excel
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
' On démarre l'application excel sans la rendre visible
appXL = CreateObject("Excel.Application")
wbXl = appXL.Workbooks.Open("E:\Base_de_donnees.xlsx")
shXL = wbXl.ActiveSheet
' Si le fichier excel est encore vierge, mise des titres de colonnes
If shXL.Cells(1, 1).Value = "" Then ' si la case du titre est vide alors
shXL.Columns("A").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter 'Le texte se trouve au milieu de la case
shXL.Columns("A").HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
shXL.Cells(1, 1).Value = "Date" 'On note "Date"
shXL.Columns("A").Font.Bold = False 'On ne met que la premiere case en gras, le reste en normal
shXL.Cells(1, 1).Font.Bold = True
End If
If shXL.Cells(1, 2).Value = "" Then
shXL.Columns("B").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
shXL.Columns("B").HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
shXL.Cells(1, 2).Value = "Heure"
shXL.Columns("B").Font.Bold = False
shXL.Cells(1, 2).Font.Bold = True
End If
If shXL.Cells(1, 3).Value = "" Then
shXL.Columns("C").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
shXL.Columns("C").HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
shXL.Cells(1, 3).Value = "Nombre d'Abeilles"
shXL.Columns("C").Font.Bold = False
shXL.Cells(1, 3).Font.Bold = True
End If
shXL.Rows(2).Insert()
shXL.Cells(2, 1).Value = Date.Today
shXL.Cells(2, 2).Value = TimeOfDay
shXL.Cells(2, 3).Value = NbrAbeillesActuel
'On ferme tout
wbXl.Save()
wbXl.Close()
appXL.Workbooks.Close()
appXL.Quit()
GC.Collect() 'Empeche l'ouverture du plus d'un fichier excel
PortSerieIN.Open() 'On ouvre le port, la communication peut commencer
Exit Sub
Err_FichierExcel1:
Dim Choix As Integer ' "OK" ou "Annuler" selon le choix de l'utilisateur
Choix = MsgBox("Veuillez revérifier ces points-ci :" & vbCrLf &
" - Que la clé USB se nomme 'USB_RUCHE' sous le disque 'F:'" & vbCrLf &
" - Qu'il y ait un fichier excel dans la clé USB" & vbCrLf &
" - Que ce fichier excel se nomme 'Base_de_donnees' sous format '.xlsx'" & vbCrLf &
vbCrLf & "Appuyez sur 'OK' pour retester", 1, "Fichier excel introuvable")
'Choix = MsgBox(Message à dire, Type de MsgBox, Titre de la MsgBox)
If Choix = 1 Then 'Si "OK"
Resume 'Sert à revenir au moment où l'erreur est survenue
ElseIf Choix = 2 Then 'Si "Annuler"
End 'Quitter l'application
End If
End Sub
'Si changement de taille du form :
Private Sub Ruche_ClientSizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.ClientSizeChanged
Me.MinimumSize = New System.Drawing.Size(730, 490) 'On ne peut pas rétrécir plus
CenterX = (Me.Size.Width / 2) - (btn_Quitter.Size.Width / 2) 'X du bouton par rapport au X du Form
CenterY = (Me.Size.Height - 150) - (btn_Quitter.Size.Height / 2) 'Y du bouton par rapport au Y du Form
btn_Quitter.Location = New Point(CenterX, CenterY) 'Mouvement du bouton avec le Form
CenterX = (50) 'X du label par rapport au X du Form
CenterY = Me.Size.Height - 100 'Y du label par rapport au Y du Form
lbl_Creator.Location = New Point(CenterX, CenterY) 'Mouvement du label avec le Form
CenterX = (Me.Size.Width / 4) - (btn_Quitter.Size.Width / 2) 'X du bouton par rapport au X du Form
CenterY = (Me.Size.Height - 150) - (btn_Quitter.Size.Height / 2) 'Y du bouton par rapport au Y du Form
btn_Effacer.Location = New Point(CenterX, CenterY) 'Mouvement du bouton avec le Form
CenterX = (Me.Size.Width / 4 * 3) - (btn_Quitter.Size.Width / 2) 'X du bouton par rapport au X du Form
CenterY = (Me.Size.Height - 150) - (btn_Quitter.Size.Height / 2) 'Y du bouton par rapport au Y du Form
btn_BaseDeDonnees.Location = New Point(CenterX, CenterY) 'Mouvement du bouton avec le Form
rtb_Donnees.Size = New Size((Me.Size.Width - 200), (Me.Size.Height - 300)) 'Réglage zone de texte
TailleLabel = Me.Size.Width / MaxFont * 35 'Réglage de la taille du titre en fonction de la taille de la page
lbl_Titre.Font = New Font("Segoe Script", TailleLabel, FontStyle.Underline And FontStyle.Bold) 'Config police
CenterX = (Me.Size.Width / 2) - (lbl_Titre.Size.Width / 2)
CenterY = 25
lbl_Titre.Location = New Point(CenterX, CenterY) 'Mouvement du label en fonction du Form
End Sub
Private Sub Ruche_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.MouseEnter
Me.Cursor = Cursors.Default
End Sub
Private Sub btn_Quitter_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Quitter.MouseEnter
Me.Cursor = Cursors.Hand
End Sub
Private Sub btn_Quitter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Quitter.Click
IconeAbeille.Visible = False
End 'Fin du programme
End Sub
Private Sub btn_Effacer_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Effacer.MouseEnter
Me.Cursor = Cursors.Hand 'La souris devient une main si on se met sur le bouton
End Sub
Private Sub btn_Effacer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Effacer.Click
rtb_Donnees.Text = ""
End Sub
Private Sub btn_BaseDeDonnees_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_BaseDeDonnees.MouseEnter
Me.Cursor = Cursors.Hand
End Sub
Private Sub btn_BaseDeDonnees_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_BaseDeDonnees.Click
PortSerieIN.Close() 'Coupe la communication pour éviter que le fichier excel soit ouvert par l'utilisateur en même temps que par l'application
On Error GoTo Err_FichierExcel2 'Si erreur, aller à "Err_Handler"
' Add the following code snippet on top of Form1.vb
Dim appXL As Excel.Application 'On ouvre l appli
Dim wbXl As Excel.Workbook
appXL = CreateObject("Excel.Application")
appXL.Visible = True 'On la rend visible
wbXl = appXL.Workbooks.Open("E:\Base_de_donnees.xlsx") 'On ouvre ce fichier dans l'appli
PortSerieIN.Open() 'On relance la communication
Exit Sub
Err_FichierExcel2:
appXL.WindowState = Excel.XlWindowState.xlMinimized 'On réduit la page excel pour ne pas cacher le MsgBox qui vient ensuite
Dim Choix As Integer ' "OK" ou "Annuler" selon le choix de l'utilisateur
Choix = MsgBox("Veuillez revérifier ces points-ci :" & vbCrLf &
" - Que la clé USB se nomme 'USB_RUCHE' sous le disque 'F:'" & vbCrLf &
" - Qu'il y ait un fichier excel dans la clé USB" & vbCrLf &
" - Que ce fichier excel se nomme 'Base_de_donnees' sous format '.xlsx'" & vbCrLf &
vbCrLf & "Appuyez sur 'OK' pour retester", 1, "Fichier excel introuvable")
'Choix = MsgBox(Message à dire, Type de MsgBox, Titre de la MsgBox)
If Choix = 1 Then 'Si "OK"
Resume 'Sert à revenir au moment où l'erreur est survenue
ElseIf Choix = 2 Then 'Si "Annuler"
End 'Quitter l'application
End If
End Sub
End Class
|
Zom13i/Compteur-d-abeilles
|
Nora/Appli_VB/Ruche/Ruche/Ruche/Ruche.vb
|
Visual Basic
|
mit
| 16,012
|
' 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.Reflection.Metadata
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Roslyn.Test.PdbUtilities
Imports Roslyn.Test.Utilities
Imports Xunit
Imports CommonResources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Public Class WinMdTests
Inherits ExpressionCompilerTestBase
''' <summary>
''' Handle runtime assemblies rather than Windows.winmd
''' (compile-time assembly) since those are the assemblies
''' loaded in the debuggee.
''' </summary>
<WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")>
<ConditionalFact(GetType(OSVersionWin8))>
Public Sub Win8RuntimeAssemblies()
Const source =
"Class C
Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, references:=WinRtRefs)
Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")
Assert.True(runtimeAssemblies.Length >= 2)
' no reference to Windows.winmd
WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies),
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(p Is Nothing, f, Nothing)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldnull
IL_0004: ret
IL_0005: ldarg.0
IL_0006: ret
}")
End Sub)
End Sub
<Fact>
Public Sub Win8OnWin8()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(CommonResources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(CommonResources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(CommonResources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(CommonResources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(CommonResources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(CommonResources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(CommonResources.LibraryB).GetReference()),
"Windows.Storage")
End Sub
<Fact>
Public Sub Win8OnWin10()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(CommonResources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(CommonResources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(CommonResources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(CommonResources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(CommonResources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(CommonResources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(CommonResources.LibraryB).GetReference()),
"Windows.Storage")
End Sub
<Fact>
Public Sub Win10OnWin10()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(CommonResources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(CommonResources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(CommonResources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(CommonResources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(CommonResources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(CommonResources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(CommonResources.LibraryB).GetReference()),
"Windows")
End Sub
Private Sub CompileTimeAndRuntimeAssemblies(
compileReferences As ImmutableArray(Of MetadataReference),
runtimeReferences As ImmutableArray(Of MetadataReference),
storageAssemblyName As String)
Const source =
"Class C
Shared Sub M(a As LibraryA.A, b As LibraryB.B, t As Windows.Data.Text.TextSegment, f As Windows.Storage.StorageFolder)
End Sub
End Class"
Dim c0 = CreateCompilationWithMscorlib40({source}, compileReferences, TestOptions.DebugDll)
WithRuntimeInstance(c0, runtimeReferences,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(a, If(b, If(t, f)))", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldarg.1
IL_0006: dup
IL_0007: brtrue.s IL_0010
IL_0009: pop
IL_000a: ldarg.2
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldarg.3
IL_0010: ret
}")
testData = New CompilationTestData()
Dim result = context.CompileExpression("f", errorMessage, testData)
Assert.Null(errorMessage)
Dim methodData = testData.GetMethodData("<>x.<>m0")
methodData.VerifyIL(
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.3
IL_0001: ret
}")
' Check return type is from runtime assembly.
Dim assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference()
Dim comp = VisualBasicCompilation.Create(
assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName(),
references:=runtimeReferences.Concat(ImmutableArray.Create(Of MetadataReference)(assemblyReference)))
Using metadata = ModuleMetadata.CreateFromImage(result.Assembly)
Dim reader = metadata.MetadataReader
Dim typeDef = reader.GetTypeDef("<>x")
Dim methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0")
Dim [module] = DirectCast(comp.GetMember("<>x").ContainingModule, PEModuleSymbol)
Dim metadataDecoder = New MetadataDecoder([module])
Dim signatureHeader As SignatureHeader = Nothing
Dim metadataException As BadImageFormatException = Nothing
Dim parameters = metadataDecoder.GetSignatureForMethod(methodHandle, signatureHeader, metadataException)
Assert.Equal(parameters.Length, 5)
Dim actualReturnType = parameters(0).Type
Assert.Equal(actualReturnType.TypeKind, TypeKind.Class) ' not error
Dim expectedReturnType = comp.GetMember("Windows.Storage.StorageFolder")
Assert.Equal(expectedReturnType, actualReturnType)
Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name)
End Using
End Sub)
End Sub
''' <summary>
''' Assembly-qualified name containing "ContentType=WindowsRuntime",
''' and referencing runtime assembly.
''' </summary>
<WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")>
<ConditionalFact(GetType(OSVersionWin8))>
Public Sub AssemblyQualifiedName()
Const source =
"Class C
Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, WinRtRefs, TestOptions.DebugDll)
Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")
WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies),
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim aliases = ImmutableArray.Create(
VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"))
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"If(DirectCast(s.Attributes, Object), d.UniversalTime)",
DkmEvaluationFlags.TreatAsExpression,
aliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Function Windows.Storage.StorageFolder.get_Attributes() As Windows.Storage.FileAttributes""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""Windows.Foundation.DateTime.UniversalTime As Long""
IL_0031: box ""Long""
IL_0036: ret
}")
End Sub)
End Sub
Private Shared Function ToVersion1_3(bytes As Byte()) As Byte()
Return ExpressionCompilerTestHelpers.ToVersion1_3(bytes)
End Function
Private Shared Function ToVersion1_4(bytes As Byte()) As Byte()
Return ExpressionCompilerTestHelpers.ToVersion1_4(bytes)
End Function
End Class
End Namespace
|
Giftednewt/roslyn
|
src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/WinMdTests.vb
|
Visual Basic
|
apache-2.0
| 12,137
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateMethod
<ExportLanguageService(GetType(IGenerateConversionService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicGenerateConversionService
Inherits AbstractGenerateConversionService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax)
Protected Overrides Function AreSpecialOptionsActive(semanticModel As SemanticModel) As Boolean
Return VisualBasicCommonGenerationServiceMethods.AreSpecialOptionsActive(semanticModel)
End Function
Protected Overrides Function CreateInvocationMethodInfo(document As SemanticDocument, abstractState As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As AbstractInvocationInfo
Return New VisualBasicGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService).InvocationExpressionInfo(document, abstractState)
End Function
Protected Overrides Function IsExplicitConversionGeneration(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(AddressOf IsCastExpression).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Protected Overrides Function IsImplicitConversionGeneration(node As SyntaxNode) As Boolean
Return TypeOf node Is ExpressionSyntax AndAlso
Not IsExplicitConversionGeneration(node) AndAlso
Not IsInMemberAccessExpression(node) AndAlso
Not IsInImplementsClause(node)
End Function
Private Function IsInImplementsClause(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(Function(n) n.IsKind(SyntaxKind.ImplementsClause)).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Private Function IsInMemberAccessExpression(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(Function(n) n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Protected Overrides Function IsValidSymbol(symbol As ISymbol, semanticModel As SemanticModel) As Boolean
Return VisualBasicCommonGenerationServiceMethods.IsValidSymbol(symbol, semanticModel)
End Function
Protected Overrides Function TryInitializeExplicitConversionState(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
If TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, methodSymbol, typeToGenerateIn) Then
identifierToken = SyntaxFactory.Token(
SyntaxKind.NarrowingKeyword,
WellKnownMemberNames.ExplicitConversionName)
Return True
End If
identifierToken = Nothing
methodSymbol = Nothing
typeToGenerateIn = Nothing
Return False
End Function
Protected Overrides Function TryInitializeImplicitConversionState(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
If TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, methodSymbol, typeToGenerateIn) Then
identifierToken = SyntaxFactory.Token(
SyntaxKind.WideningKeyword,
WellKnownMemberNames.ImplicitConversionName)
Return True
End If
identifierToken = Nothing
methodSymbol = Nothing
typeToGenerateIn = Nothing
Return False
End Function
Private Function TryGetConversionMethodAndTypeToGenerateIn(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
Dim castExpression = TryCast(expression.AncestorsAndSelf.Where(AddressOf IsCastExpression).Where(Function(n) n.Span.Contains(expression.Span)).FirstOrDefault, CastExpressionSyntax)
If castExpression IsNot Nothing Then
Return TryGetExplicitConversionMethodAndTypeToGenerateIn(
document,
castExpression,
classInterfaceModuleStructTypes,
cancellationToken,
methodSymbol,
typeToGenerateIn)
End If
expression = TryCast(expression.AncestorsAndSelf.Where(Function(n) TypeOf n Is ExpressionSyntax And n.Span.Contains(expression.Span)).FirstOrDefault, ExpressionSyntax)
If expression IsNot Nothing Then
Return TryGetImplicitConversionMethodAndTypeToGenerateIn(
document,
expression,
classInterfaceModuleStructTypes,
cancellationToken,
methodSymbol,
typeToGenerateIn)
End If
Return False
End Function
Private Shared Function IsCastExpression(node As SyntaxNode) As Boolean
Return TypeOf node Is DirectCastExpressionSyntax OrElse TypeOf node Is CTypeExpressionSyntax OrElse TypeOf node Is TryCastExpressionSyntax
End Function
Private Function TryGetExplicitConversionMethodAndTypeToGenerateIn(document As SemanticDocument, castExpression As CastExpressionSyntax, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
methodSymbol = Nothing
typeToGenerateIn = TryCast(document.SemanticModel.GetTypeInfo(castExpression.Type, cancellationToken).Type, INamedTypeSymbol)
Dim parameterSymbol = TryCast(document.SemanticModel.GetTypeInfo(castExpression.Expression, cancellationToken).Type, INamedTypeSymbol)
If typeToGenerateIn Is Nothing OrElse parameterSymbol Is Nothing OrElse typeToGenerateIn.IsErrorType OrElse parameterSymbol.IsErrorType Then
Return False
End If
methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol)
If Not ValidateTypeToGenerateIn(document.Project.Solution, typeToGenerateIn, True, classInterfaceModuleStructTypes, cancellationToken) Then
typeToGenerateIn = parameterSymbol
End If
Return True
End Function
Private Function TryGetImplicitConversionMethodAndTypeToGenerateIn(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
methodSymbol = Nothing
typeToGenerateIn = TryCast(document.SemanticModel.GetTypeInfo(expression, cancellationToken).ConvertedType, INamedTypeSymbol)
Dim parameterSymbol = TryCast(document.SemanticModel.GetTypeInfo(expression, cancellationToken).Type, INamedTypeSymbol)
If typeToGenerateIn Is Nothing OrElse parameterSymbol Is Nothing OrElse typeToGenerateIn.IsErrorType OrElse parameterSymbol.IsErrorType Then
Return False
End If
methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol)
If Not ValidateTypeToGenerateIn(document.Project.Solution, typeToGenerateIn, True, classInterfaceModuleStructTypes, cancellationToken) Then
typeToGenerateIn = parameterSymbol
End If
Return True
End Function
Private Function GenerateMethodSymbol(typeToGenerateIn As INamedTypeSymbol, parameterSymbol As INamedTypeSymbol) As IMethodSymbol
If typeToGenerateIn.IsGenericType Then
typeToGenerateIn = typeToGenerateIn.ConstructUnboundGenericType.ConstructedFrom
End If
Return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes:=ImmutableArray(Of AttributeData).Empty,
accessibility:=Nothing,
modifiers:=Nothing,
returnType:=typeToGenerateIn,
returnsByRef:=False,
explicitInterfaceSymbol:=Nothing,
name:=Nothing,
typeParameters:=ImmutableArray(Of ITypeParameterSymbol).Empty,
parameters:=ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(parameterSymbol, "v")),
statements:=Nothing,
handlesExpressions:=Nothing,
returnTypeAttributes:=Nothing,
methodKind:=MethodKind.Conversion)
End Function
Protected Overrides Function GetExplicitConversionDisplayText(state As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As String
Return String.Format(VBFeaturesResources.Generate_narrowing_conversion_in_0, state.TypeToGenerateIn.Name)
End Function
Protected Overrides Function GetImplicitConversionDisplayText(state As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As String
Return String.Format(VBFeaturesResources.Generate_widening_conversion_in_0, state.TypeToGenerateIn.Name)
End Function
End Class
End Namespace
|
amcasey/roslyn
|
src/Features/VisualBasic/Portable/GenerateMember/GenerateParameterizedMember/VisualBasicGenerateConversionService.vb
|
Visual Basic
|
apache-2.0
| 10,703
|
' 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 Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class InKeywordRecommenderTests
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InInForEach1()
VerifyRecommendationsContain(<MethodBody>For Each x |</MethodBody>, "In")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InInForEach2()
VerifyRecommendationsContain(<MethodBody>For Each x As Foo |</MethodBody>, "In")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InInFromQuery1()
VerifyRecommendationsContain(<MethodBody>Dim x = From x |</MethodBody>, "In")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InInFromQuery2()
VerifyRecommendationsContain(<MethodBody>Dim x = From x As Foo |</MethodBody>, "In")
End Sub
<WorkItem(543231)>
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InInFromQuery3()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = From x As Integer |</MethodBody>, "In")
End Sub
<WorkItem(530953)>
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotAfterEol()
VerifyRecommendationsMissing(
<MethodBody>For Each x
|</MethodBody>, "In")
End Sub
<WorkItem(530953)>
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterExplicitLineContinuation()
VerifyRecommendationsContain(
<MethodBody>For Each x _
|</MethodBody>, "In")
End Sub
End Class
End Namespace
|
VPashkov/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/InKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 2,042
|
' 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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Editor.Implementation.Outlining
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Outlining
Friend Class DocumentationCommentOutliner
Inherits AbstractSyntaxNodeOutliner(Of DocumentationCommentTriviaSyntax)
Private Shared Function GetBannerText(documentationComment As DocumentationCommentTriviaSyntax, cancellationToken As CancellationToken) As String
' TODO: Consider unifying code to extract text from an Xml Documentation Comment (https://github.com/dotnet/roslyn/issues/2290)
Dim summaryElement = documentationComment.Content.OfType(Of XmlElementSyntax)() _
.FirstOrDefault(Function(e) e.StartTag.Name.ToString = "summary")
Dim text As String
If summaryElement IsNot Nothing Then
Dim sb As New StringBuilder(summaryElement.Span.Length)
sb.Append("''' <summary>")
For Each node In summaryElement.ChildNodes()
If node.Kind() = SyntaxKind.XmlText Then
Dim textNode = DirectCast(node, XmlTextSyntax)
Dim textTokens As SyntaxTokenList = textNode.TextTokens
AppendTextTokens(sb, textTokens)
ElseIf node.Kind() = SyntaxKind.XmlEmptyElement Then
Dim elementNode = DirectCast(node, XmlEmptyElementSyntax)
For Each attribute In elementNode.Attributes
If TypeOf attribute Is XmlCrefAttributeSyntax Then
sb.Append(" ")
sb.Append(DirectCast(attribute, XmlCrefAttributeSyntax).Reference.ToString())
ElseIf TypeOf attribute Is XmlNameAttributeSyntax Then
sb.Append(" ")
sb.Append(DirectCast(attribute, XmlNameAttributeSyntax).Reference.ToString())
ElseIf TypeOf attribute Is XmlAttributeSyntax Then
AppendTextTokens(sb, DirectCast(DirectCast(attribute, XmlAttributeSyntax).Value, XmlStringSyntax).TextTokens)
Else
Debug.Fail($"Unexpected XML syntax kind {attribute.Kind()}")
End If
Next
End If
Next
text = sb.ToString()
Else
' If a summary element isn't found, use the first line of the XML doc comment.
Dim span = documentationComment.Span
Dim syntaxTree = documentationComment.SyntaxTree
Dim line = syntaxTree.GetText(cancellationToken).Lines.GetLineFromPosition(span.Start)
text = "''' " & line.ToString().Substring(span.Start - line.Start).Trim() & " " + Ellipsis
End If
If text.Length > MaxXmlDocCommentBannerLength Then
text = text.Substring(0, MaxXmlDocCommentBannerLength) & " " & Ellipsis
End If
Return text
End Function
Private Shared Sub AppendTextTokens(sb As StringBuilder, textTokens As SyntaxTokenList)
For Each token In textTokens.Where(Function(t) t.Kind = SyntaxKind.XmlTextLiteralToken)
Dim s = token.ToString().Trim()
If s.Length <> 0 Then
sb.Append(" ")
sb.Append(s)
End If
Next
End Sub
Protected Overrides Sub CollectOutliningSpans(documentationComment As DocumentationCommentTriviaSyntax, spans As List(Of OutliningSpan), cancellationToken As CancellationToken)
Dim firstCommentToken = documentationComment.ChildNodesAndTokens().FirstOrNullable()
Dim lastCommentToken = documentationComment.ChildNodesAndTokens().LastOrNullable()
If firstCommentToken Is Nothing Then
Return
End If
' TODO: Need to redo this when DocumentationCommentTrivia.SpanStart points to the start of the exterior trivia.
Dim startPos = firstCommentToken.Value.FullSpan.Start
' The trailing newline is included in DocumentationCommentTrivia, so we need to strip it.
Dim endPos = lastCommentToken.Value.SpanStart + lastCommentToken.Value.ToString().TrimEnd().Length
Dim fullSpan = TextSpan.FromBounds(startPos, endPos)
spans.Add(VisualBasicOutliningHelpers.CreateRegion(
fullSpan,
GetBannerText(documentationComment, cancellationToken),
autoCollapse:=True))
End Sub
End Class
End Namespace
|
jbhensley/roslyn
|
src/EditorFeatures/VisualBasic/Outlining/Outliners/DocumentationCommentOutliner.vb
|
Visual Basic
|
apache-2.0
| 5,062
|
' 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 Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class CodeAttributeTests
Inherits AbstractCodeAttributeTests
#Region "GetStartPoint() tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint1()
Dim code =
<Code>Imports System
<$$Serializable()>
Class C
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=16)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint2()
Dim code =
<Code>Imports System
<$$CLSCompliant(True)>
Class C
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=2, absoluteOffset:=18, lineLength:=20)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint3()
Dim code =
<Code>
<$$Assembly: CLSCompliant(True)>
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=2, absoluteOffset:=2, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=1, lineOffset:=2, absoluteOffset:=2, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=2, absoluteOffset:=2, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=1, lineOffset:=2, absoluteOffset:=2, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=2, absoluteOffset:=2, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=1, lineOffset:=2, absoluteOffset:=2, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=2, absoluteOffset:=2, lineLength:=30)))
End Sub
#End Region
#Region "GetEndPoint() tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint1()
Dim code =
<Code>Imports System
<$$Serializable()>
Class C
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=14, absoluteOffset:=30, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=16)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint2()
Dim code =
<Code>Imports System
<$$CLSCompliant(True)>
Class C
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=20, absoluteOffset:=36, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=20, absoluteOffset:=36, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=20, absoluteOffset:=36, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=20, absoluteOffset:=36, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=14, absoluteOffset:=30, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=20, absoluteOffset:=36, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=20, absoluteOffset:=36, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=20, absoluteOffset:=36, lineLength:=20)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint3()
Dim code =
<Code>
<$$Assembly: CLSCompliant(True)>
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=30, absoluteOffset:=30, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=1, lineOffset:=30, absoluteOffset:=30, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=30, absoluteOffset:=30, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=1, lineOffset:=30, absoluteOffset:=30, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=1, lineOffset:=24, absoluteOffset:=24, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=30, absoluteOffset:=30, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=1, lineOffset:=30, absoluteOffset:=30, lineLength:=30)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=30, absoluteOffset:=30, lineLength:=30)))
End Sub
#End Region
#Region "AttributeArgument GetStartPoint() tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetAttributeArgumentStartPoint1()
Dim code =
<Code>
Imports System
<$$Assembly: Goo(0,,Z:=42)>
Class GooAttribute
Inherits Attribute
Sub New(x As Integer, Optional y As Integer = 0)
End Sub
Property Z As integer
End Class
</Code>
TestAttributeArgumentStartPoint(code, 1,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=25)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetAttributeArgumentStartPoint2()
Dim code =
<Code>
Imports System
<$$Assembly: Goo(0,,Z:=42)>
Class GooAttribute
Inherits Attribute
Sub New(x As Integer, Optional y As Integer = 0)
End Sub
Property Z As integer
End Class
</Code>
TestAttributeArgumentStartPoint(code, 2,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetAttributeArgumentStartPoint3()
Dim code =
<Code>
Imports System
<$$Assembly: Goo(,Z:=42)>
Class GooAttribute
Inherits Attribute
Sub New(Optional y As Integer = 0)
End Sub
Property Z As integer
End Class
</Code>
TestAttributeArgumentStartPoint(code, 1,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=15, absoluteOffset:=31, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=15, absoluteOffset:=31, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=15, absoluteOffset:=31, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=15, absoluteOffset:=31, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=15, absoluteOffset:=31, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=15, absoluteOffset:=31, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=15, absoluteOffset:=31, lineLength:=23)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetAttributeArgumentStartPoint4()
Dim code =
<Code>
Imports System
<$$Assembly: Goo(,Z:=42)>
Class GooAttribute
Inherits Attribute
Sub New(Optional y As Integer = 0)
End Sub
Property Z As integer
End Class
</Code>
TestAttributeArgumentStartPoint(code, 2,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=23)))
End Sub
#End Region
#Region "AttributeArgument GetEndPoint() tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetAttributeArgumentEndPoint1()
Dim code =
<Code>
Imports System
<$$Assembly: Goo(0,,Z:=42)>
Class GooAttribute
Inherits Attribute
Sub New(x As Integer, Optional y As Integer = 0)
End Sub
Property Z As integer
End Class
</Code>
TestAttributeArgumentEndPoint(code, 1,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=17, absoluteOffset:=33, lineLength:=25)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetAttributeArgumentEndPoint2()
Dim code =
<Code>
Imports System
<$$Assembly: Goo(0,,Z:=42)>
Class GooAttribute
Inherits Attribute
Sub New(x As Integer, Optional y As Integer = 0)
End Sub
Property Z As integer
End Class
</Code>
TestAttributeArgumentEndPoint(code, 2,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=18, absoluteOffset:=34, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=18, absoluteOffset:=34, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=18, absoluteOffset:=34, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=18, absoluteOffset:=34, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=18, absoluteOffset:=34, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=18, absoluteOffset:=34, lineLength:=25)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=18, absoluteOffset:=34, lineLength:=25)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetAttributeArgumentEndPoint3()
Dim code =
<Code>
Imports System
<$$Assembly: Goo(,Z:=42)>
Class GooAttribute
Inherits Attribute
Sub New(Optional y As Integer = 0)
End Sub
Property Z As integer
End Class
</Code>
TestAttributeArgumentEndPoint(code, 1,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=16, absoluteOffset:=32, lineLength:=23)))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetAttributeArgumentEndPoint4()
Dim code =
<Code>
Imports System
<$$Assembly: Goo(,Z:=42)>
Class GooAttribute
Inherits Attribute
Sub New(Optional y As Integer = 0)
End Sub
Property Z As integer
End Class
</Code>
TestAttributeArgumentEndPoint(code, 2,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=38, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=38, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=38, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=38, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=18, absoluteOffset:=34, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=38, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=38, lineLength:=23)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=38, lineLength:=23)))
End Sub
#End Region
#Region "FullName tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetFullName1()
Dim code =
<Code>
Imports System
<$$Serializable>
Class C
End Class
</Code>
TestFullName(code, "System.SerializableAttribute")
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetFullName2()
Dim code =
<Code>
<$$System.Serializable>
Class C
End Class
</Code>
TestFullName(code, "System.SerializableAttribute")
End Sub
#End Region
#Region "Parent tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetParent1()
Dim code =
<Code>
Imports System
<$$Serializable>
Class C
End Class
</Code>
TestParent(code, IsElement("C", kind:=EnvDTE.vsCMElement.vsCMElementClass))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetParent2()
Dim code =
<Code>
Imports System
<Serializable, $$CLSCompliant(False)>
Class C
End Class
</Code>
TestParent(code, IsElement("C", kind:=EnvDTE.vsCMElement.vsCMElementClass))
End Sub
#End Region
#Region "Attribute argument tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetArguments1()
Dim code =
<Code>
Imports System
<$$Serializable>
Class C
End Class
</Code>
TestAttributeArguments(code, NoElements)
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetArguments2()
Dim code =
<Code>
Imports System
<$$Serializable()>
Class C
End Class
</Code>
TestAttributeArguments(code, NoElements)
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetArguments3()
Dim code =
<Code>
Imports System
<$$CLSCompliant(True)>
Class C
End Class
</Code>
TestAttributeArguments(code, IsAttributeArgument(value:="True"))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetArguments4()
Dim code =
<Code>
Imports System
<$$AttributeUsage(AttributeTargets.All, AllowMultiple := False)>
Class CAttribute
Inherits Attribute
End Class
</Code>
TestAttributeArguments(code, IsAttributeArgument(value:="AttributeTargets.All"), IsAttributeArgument(name:="AllowMultiple", value:="False"))
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetArguments5_Omitted()
Dim code =
<Code>
<$$Goo(, Baz:=True)>
Class GooAttribute
Inherits Attribute
Sub New(Optional bar As String = Nothing)
End Sub
Public Property Baz As Boolean
Get
End Get
Set(value As Boolean)
End Set
End Property
End Class
</Code>
TestAttributeArguments(code, IsAttributeArgument(name:=""), IsAttributeArgument(name:="Baz", value:="True"))
End Sub
#End Region
#Region "Target tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetTarget1()
Dim code =
<Code>
Imports System
<Assembly: CLSCompliant$$(False)>
</Code>
TestTarget(code, "Assembly")
End Sub
#End Region
#Region "Value tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetValue1()
Dim code =
<Code>
Imports System
<$$Serializable>
Class C
End Class
</Code>
TestValue(code, "")
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetValue2()
Dim code =
<Code>
Imports System
<$$Serializable()>
Class C
End Class
</Code>
TestValue(code, "")
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetValue3()
Dim code =
<Code>
Imports System
<$$CLSCompliant(False)>
Class C
End Class
</Code>
TestValue(code, "False")
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetValue4()
Dim code =
<Code>
Imports System
<$$AttributeUsage(AttributeTargets.All, AllowMultiple = False)>
Class CAttribute
Inherits Attribute
End Class
</Code>
TestValue(code, "AttributeTargets.All, AllowMultiple = False")
End Sub
#End Region
#Region "AddAttributeArgument tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttributeArgument1() As Task
Dim code =
<Code>
Imports System
<$$CLSCompliant>
Class C
End Class
</Code>
Dim expectedCode =
<Code>
Imports System
<CLSCompliant(True)>
Class C
End Class
</Code>
Await TestAddAttributeArgument(code, expectedCode, New AttributeArgumentData With {.Value = "True"})
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttributeArgument2() As Task
Dim code =
<Code>
Imports System
<$$CLSCompliant()>
Class C
End Class
</Code>
Dim expectedCode =
<Code>
Imports System
<CLSCompliant(True)>
Class C
End Class
</Code>
Await TestAddAttributeArgument(code, expectedCode, New AttributeArgumentData With {.Value = "True"})
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddArgument3() As Task
Dim code =
<Code>
Imports System
<$$AttributeUsage(AttributeTargets.All)>
Class CAttribute
Inherits Attribute
End Class
</Code>
Dim expectedCode =
<Code>
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class CAttribute
Inherits Attribute
End Class
</Code>
Await TestAddAttributeArgument(code, expectedCode, New AttributeArgumentData With {.Name = "AllowMultiple", .Value = "False", .Position = 1})
End Function
#End Region
#Region "Delete tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDelete1() As Task
Dim code =
<Code><![CDATA[
<$$Goo>
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Class C
End Class
]]></Code>
Await TestDelete(code, expected)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDelete2() As Task
Dim code =
<Code><![CDATA[
<$$Goo, Bar>
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
<Bar>
Class C
End Class
]]></Code>
Await TestDelete(code, expected)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDelete3() As Task
Dim code =
<Code><![CDATA[
<Goo>
<$$Bar>
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
<Goo>
Class C
End Class
]]></Code>
Await TestDelete(code, expected)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDelete4() As Task
Dim code =
<Code><![CDATA[
<Assembly: $$Goo>
]]></Code>
Dim expected =
<Code><![CDATA[
]]></Code>
Await TestDelete(code, expected)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDelete5() As Task
Dim code =
<Code><![CDATA[
<Assembly: $$Goo, Assembly: Bar>
]]></Code>
Dim expected =
<Code><![CDATA[
<Assembly: Bar>
]]></Code>
Await TestDelete(code, expected)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDelete6() As Task
Dim code =
<Code><![CDATA[
<Assembly: Goo>
<Assembly: $$Bar>
]]></Code>
Dim expected =
<Code><![CDATA[
<Assembly: Goo>
]]></Code>
Await TestDelete(code, expected)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDelete7() As Task
Dim code =
<Code><![CDATA[
''' <summary>
''' Doc comment
''' </summary>
<$$Goo>
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
''' <summary>
''' Doc comment
''' </summary>
Class C
End Class
]]></Code>
Await TestDelete(code, expected)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDelete8() As Task
Dim code =
<Code><![CDATA[
<$$Goo> ' Comment comment comment
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Class C
End Class
]]></Code>
Await TestDelete(code, expected)
End Function
#End Region
#Region "Delete attribute argument tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDeleteAttributeArgument1() As Task
Dim code =
<Code><![CDATA[
<$$System.CLSCompliant(True)>
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
<System.CLSCompliant()>
Class C
End Class
]]></Code>
Await TestDeleteAttributeArgument(code, expected, 1)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDeleteAttributeArgument2() As Task
Dim code =
<Code><![CDATA[
<$$AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class CAttribute
Inherits Attribute
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
<AttributeUsage(AllowMultiple:=False)>
Class CAttribute
Inherits Attribute
End Class
]]></Code>
Await TestDeleteAttributeArgument(code, expected, 1)
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestDeleteAttributeArgument3() As Task
Dim code =
<Code><![CDATA[
<$$AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class CAttribute
Inherits Attribute
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
<AttributeUsage(AttributeTargets.All)>
Class CAttribute
Inherits Attribute
End Class
]]></Code>
Await TestDeleteAttributeArgument(code, expected, 2)
End Function
#End Region
#Region "Set Name tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetName_NewName() As Task
Dim code =
<Code><![CDATA[
<$$Goo()>
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
<Bar()>
Class C
End Class
]]></Code>
Await TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetName_SimpleNameToDottedName() As Task
Dim code =
<Code><![CDATA[
<$$Goo()>
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
<Bar.Baz()>
Class C
End Class
]]></Code>
Await TestSetName(code, expected, "Bar.Baz", NoThrow(Of String)())
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetName_DottedNameToSimpleName() As Task
Dim code =
<Code><![CDATA[
<$$Goo()>
Class C
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
<Bar.Baz()>
Class C
End Class
]]></Code>
Await TestSetName(code, expected, "Bar.Baz", NoThrow(Of String)())
End Function
#End Region
#Region "Set Target tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetTarget1() As Task
Dim code =
<Code>
Imports System
<Assembly: CLSCompliant$$(False)>
</Code>
Dim expected =
<Code>
Imports System
<Module: CLSCompliant(False)>
</Code>
Await TestSetTarget(code, expected, "Module")
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetTarget2() As Task
Dim code =
<Code>
Imports System
<CLSCompliant$$(False)>
Class C
End Class
</Code>
Dim expected =
<Code>
Imports System
<Assembly: CLSCompliant(False)>
Class C
End Class
</Code>
Await TestSetTarget(code, expected, "Assembly")
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetTarget3() As Task
Dim code =
<Code>
Imports System
<Assembly: CLSCompliant$$(False)>
</Code>
Dim expected =
<Code>
Imports System
<CLSCompliant(False)>
</Code>
Await TestSetTarget(code, expected, "")
End Function
#End Region
#Region "Set Value tests"
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetValue1() As Task
Dim code =
<Code>
Imports System
<Assembly: CLSCompliant$$(False)>
</Code>
Dim expected =
<Code>
Imports System
<Assembly: CLSCompliant(True)>
</Code>
Await TestSetValue(code, expected, "True")
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetValue2() As Task
Dim code =
<Code>
Imports System
<Assembly: CLSCompliant$$()>
</Code>
Dim expected =
<Code>
Imports System
<Assembly: CLSCompliant(True)>
</Code>
Await TestSetValue(code, expected, "True")
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetValue3() As Task
Dim code =
<Code>
Imports System
<Assembly: CLSCompliant$$>
</Code>
Dim expected =
<Code>
Imports System
<Assembly: CLSCompliant(True)>
</Code>
Await TestSetValue(code, expected, "True")
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetValue4() As Task
Dim code =
<Code>
Imports System
<Assembly: CLSCompliant$$(False)>
</Code>
Dim expected =
<Code>
Imports System
<Assembly: CLSCompliant()>
</Code>
Await TestSetValue(code, expected, "")
End Function
#End Region
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
|
brettfo/roslyn
|
src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeAttributeTests.vb
|
Visual Basic
|
apache-2.0
| 41,205
|
' 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.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class Binder_Statements_Tests
Inherits SemanticModelTestBase
#Region "GetDeclaredSymbol Function"
<Fact()>
Public Sub LocalSymbolsAreEquivalentAcrossSemanticModelsFromTheSameCompilation()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Public Class C
Public Sub M()
Dim x As Integer = 0
End Sub
End Public
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim model2 = comp.GetSemanticModel(tree)
Assert.NotEqual(model1, model2)
Dim vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of ModifiedIdentifierSyntax)().First()
Dim symbol1 = model1.GetDeclaredSymbol(vardecl)
Dim symbol2 = model2.GetDeclaredSymbol(vardecl)
Assert.Equal(False, symbol1 Is symbol2)
Assert.Equal(symbol1, symbol2)
End Sub
<WorkItem(749753, "DevDiv2/DevDiv")>
<Fact()>
Public Sub TopLevelSub()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Namespace MyNS2
End Namespace
Sub foo()
End Sub
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim memberSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodStatementSyntax)().First()
Dim symbol1 = model1.GetDeclaredSymbol(memberSyntax)
Assert.NotNull(symbol1)
Assert.Equal("foo", symbol1.Name)
End Sub
<Fact()>
Public Sub SubInNamespace()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Namespace MyNS2
Sub foo()
End Sub
End Namespace
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim memberSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodStatementSyntax)().First()
Dim symbol1 = model1.GetDeclaredSymbol(memberSyntax)
Assert.Equal("foo", symbol1.Name)
End Sub
<Fact()>
Public Sub SubInNamespaceWithRootNamespace()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Namespace MyNS2
Sub foo()
End Sub
End Namespace
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml, TestOptions.ReleaseDll.WithRootNamespace("Pavement"))
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim memberSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodStatementSyntax)().First()
Dim symbol1 = model1.GetDeclaredSymbol(memberSyntax)
Assert.Equal("foo", symbol1.Name)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub LocalSymbolsAreEquivalentAcrossSemanticModelsFromTheSameCompilationStaticLocal()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Public Class C
Public Sub M()
Static x As Integer = 0
End Sub
End Public
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim model2 = comp.GetSemanticModel(tree)
Assert.NotEqual(model1, model2)
Dim vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of ModifiedIdentifierSyntax)().First()
Dim symbol1 = model1.GetDeclaredSymbol(vardecl)
Dim symbol2 = model2.GetDeclaredSymbol(vardecl)
Assert.Equal(False, symbol1 Is symbol2)
Assert.Equal(symbol1, symbol2)
End Sub
<Fact()>
Public Sub LocalSymbolsAreDifferentAcrossSemanticModelsFromDifferentCompilations()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Public Class C
Public Sub M()
Dim x As Integer = 0
End Sub
End Public
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree1 = comp1.SyntaxTrees(0)
Dim tree2 = comp2.SyntaxTrees(0)
Dim model1 = comp1.GetSemanticModel(tree1)
Dim model2 = comp2.GetSemanticModel(tree2)
Assert.NotEqual(model1, model2)
Dim vardecl1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ModifiedIdentifierSyntax)().First()
Dim symbol1 = model1.GetDeclaredSymbol(vardecl1)
Dim vardecl2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ModifiedIdentifierSyntax)().First()
Dim symbol2 = model2.GetDeclaredSymbol(vardecl2)
Assert.Equal(False, symbol1 Is symbol2)
Assert.NotEqual(symbol1, symbol2)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub LocalSymbolsAreDifferentAcrossSemanticModelsFromDifferentCompilationsStaticLocal()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Public Class C
Public Sub M()
Static x As Integer = 0
End Sub
End Public
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree1 = comp1.SyntaxTrees(0)
Dim tree2 = comp2.SyntaxTrees(0)
Dim model1 = comp1.GetSemanticModel(tree1)
Dim model2 = comp2.GetSemanticModel(tree2)
Assert.NotEqual(model1, model2)
Dim vardecl1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ModifiedIdentifierSyntax)().First()
Dim symbol1 = model1.GetDeclaredSymbol(vardecl1)
Dim vardecl2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ModifiedIdentifierSyntax)().First()
Dim symbol2 = model2.GetDeclaredSymbol(vardecl2)
Assert.Equal(False, symbol1 Is symbol2)
Assert.NotEqual(symbol1, symbol2)
End Sub
<Fact()>
Public Sub LambdaParameterSymbolsAreEquivalentAcrossSemanticModelsFromTheSameCompilation()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Public Class C
Public Sub M()
Dim f As Func(Of Integer, Integer) = Function(p) p
End Sub
End Public
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim model2 = comp.GetSemanticModel(tree)
Assert.NotEqual(model1, model2)
Dim paramRef = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().First(Function(ins) ins.ToString() = "p")
Dim symbol1 = model1.GetSemanticInfoSummary(paramRef).Symbol
Dim symbol2 = model2.GetSemanticInfoSummary(paramRef).Symbol
Assert.Equal(False, symbol1 Is symbol2)
Assert.Equal(symbol1, symbol2)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub LambdaParameterSymbolsAreEquivalentAcrossSemanticModelsFromTheSameCompilationStaticLocal()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Public Class C
Public Sub M()
Static f As Func(Of Integer, Integer) = Function(p) p
End Sub
End Public
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim model2 = comp.GetSemanticModel(tree)
Assert.NotEqual(model1, model2)
Dim paramRef = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().First(Function(ins) ins.ToString() = "p")
Dim symbol1 = model1.GetSemanticInfoSummary(paramRef).Symbol
Dim symbol2 = model2.GetSemanticInfoSummary(paramRef).Symbol
Assert.Equal(False, symbol1 Is symbol2)
Assert.Equal(symbol1, symbol2)
End Sub
<Fact()>
Public Sub LambdaParameterSymbolsAreDifferentAcrossSemanticModelsFromDifferentCompilations()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Public Class C
Public Sub M()
Dim f As Func(Of Integer, Integer) = Function(p) p
End Sub
End Public
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree1 = comp1.SyntaxTrees(0)
Dim tree2 = comp2.SyntaxTrees(0)
Dim model1 = comp1.GetSemanticModel(tree1)
Dim model2 = comp2.GetSemanticModel(tree2)
Assert.NotEqual(model1, model2)
Dim paramRef1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().First(Function(ins) ins.ToString() = "p")
Dim symbol1 = model1.GetSemanticInfoSummary(paramRef1).Symbol
Dim paramRef2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().First(Function(ins) ins.ToString() = "p")
Dim symbol2 = model2.GetSemanticInfoSummary(paramRef2).Symbol
Assert.Equal(False, symbol1 Is symbol2)
Assert.NotEqual(symbol1, symbol2)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub LambdaParameterSymbolsAreDifferentAcrossSemanticModelsFromDifferentCompilationsStaticLocal()
Dim xml =
<compilation name="TST">
<file name="C.vb">
Public Class C
Public Sub M()
Static f As Func(Of Integer, Integer) = Function(p) p
End Sub
End Public
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree1 = comp1.SyntaxTrees(0)
Dim tree2 = comp2.SyntaxTrees(0)
Dim model1 = comp1.GetSemanticModel(tree1)
Dim model2 = comp2.GetSemanticModel(tree2)
Assert.NotEqual(model1, model2)
Dim paramRef1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().First(Function(ins) ins.ToString() = "p")
Dim symbol1 = model1.GetSemanticInfoSummary(paramRef1).Symbol
Dim paramRef2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().First(Function(ins) ins.ToString() = "p")
Dim symbol2 = model2.GetSemanticInfoSummary(paramRef2).Symbol
Assert.Equal(False, symbol1 Is symbol2)
Assert.NotEqual(symbol1, symbol2)
End Sub
<WorkItem(539707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539707")>
<Fact()>
Public Sub GetDeclaredSymbolSameForStatementOrBlock()
Dim xml =
<compilation>
<file name="a.vb">
Namespace N1
Interface I1
Sub M1()
End Interface
Enum E1
m1
m2
End Enum
Structure S1
Public i as integer
End Structure
Class C1
Public Function F() as integer
return 0
End Function
Public Sub S()
End Sub
Public ReadOnly Property P as string
Get
return nothing
End Get
End Property
Public Sub New()
End Sub
End Class
Module Program
Sub main()
End Sub
End Module
End Namespace
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(xml)
Dim diag = comp.GetDiagnostics()
Debug.Assert(diag.Length = 0)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
' Test NamespaceBlockSyntax and NamespaceStatementSyntax
Dim n1Syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of NamespaceBlockSyntax)().First()
Dim sym1 = model1.GetDeclaredSymbol(DirectCast(n1Syntax, VisualBasicSyntaxNode))
Assert.Equal("N1", sym1.ToDisplayString(SymbolDisplayFormat.TestFormat))
Dim sym2 = model1.GetDeclaredSymbol(DirectCast(n1Syntax.NamespaceStatement, VisualBasicSyntaxNode))
Assert.Equal(sym1, sym2)
' Test TypeBlocks in the Namespace (Interface, Class, Structure, Module)
Dim typeBlocks = n1Syntax.DescendantNodes().OfType(Of TypeBlockSyntax)()
For Each tb In typeBlocks
sym1 = model1.GetDeclaredSymbol(DirectCast(tb, VisualBasicSyntaxNode))
sym2 = model1.GetDeclaredSymbol(DirectCast(tb.BlockStatement, VisualBasicSyntaxNode))
Assert.Equal(sym1.ToDisplayString(SymbolDisplayFormat.TestFormat), sym2.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(sym1, sym2)
Next
' Test EnumBlockSyntax and EnumStatementSyntax
Dim e1Syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of EnumBlockSyntax)().First()
sym1 = model1.GetDeclaredSymbol(DirectCast(e1Syntax, VisualBasicSyntaxNode))
Assert.Equal("N1.E1", sym1.ToDisplayString(SymbolDisplayFormat.TestFormat))
sym2 = model1.GetDeclaredSymbol(DirectCast(e1Syntax.EnumStatement, VisualBasicSyntaxNode))
Assert.Equal(sym1, sym2)
' Test ClassBlockSyntax and ClassStatementSyntax
Dim c1Syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
sym1 = model1.GetDeclaredSymbol(DirectCast(c1Syntax, VisualBasicSyntaxNode))
Assert.Equal("N1.C1", sym1.ToDisplayString(SymbolDisplayFormat.TestFormat))
sym2 = model1.GetDeclaredSymbol(DirectCast(c1Syntax.BlockStatement, VisualBasicSyntaxNode))
Assert.Equal(sym1, sym2)
' Test MethodBlock Members of C1
Dim methodBlocks = c1Syntax.DescendantNodes().OfType(Of MethodBlockSyntax)()
For Each mb In methodBlocks
sym1 = model1.GetDeclaredSymbol(DirectCast(mb, VisualBasicSyntaxNode))
sym2 = model1.GetDeclaredSymbol(DirectCast(mb.BlockStatement, VisualBasicSyntaxNode))
Assert.Equal(sym1.ToDisplayString(SymbolDisplayFormat.TestFormat), sym2.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(sym1, sym2)
Next
' Test PropertyBlock Members of C1
Dim propertyBlocks = c1Syntax.DescendantNodes().OfType(Of PropertyBlockSyntax)()
For Each pb In propertyBlocks
sym1 = model1.GetDeclaredSymbol(DirectCast(pb, VisualBasicSyntaxNode))
sym2 = model1.GetDeclaredSymbol(DirectCast(pb.PropertyStatement, VisualBasicSyntaxNode))
Assert.Equal(sym1.ToDisplayString(SymbolDisplayFormat.TestFormat), sym2.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(sym1, sym2)
Next
End Sub
' Ensure local symbols gotten from same Binding instance are same object.
<Fact()>
Public Sub GetSemanticInfoLocalVariableTwice()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="GetSemanticInfo">
<file name="a.vb">
Imports System
Class B
Public f1 as Integer
End Class
Class M
Public Sub Main()
Dim bInstance As B
bInstance = New B()
Console.WriteLine(bInstance.f1) 'BIND:"bInstance"
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.GlobalNamespace
Dim classB = DirectCast(globalNS.GetMembers("B").Single(), NamedTypeSymbol)
Dim fieldF1 = DirectCast(classB.GetMembers("f1").Single(), FieldSymbol)
Dim node As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim bindInfo1 As SemanticInfoSummary = semanticModel.GetSemanticInfoSummary(DirectCast(node, ExpressionSyntax))
Dim bindInfo2 As SemanticInfoSummary = semanticModel.GetSemanticInfoSummary(DirectCast(node, ExpressionSyntax))
Assert.Equal(SymbolKind.Local, bindInfo1.Symbol.Kind)
Assert.Equal("bInstance", bindInfo1.Symbol.Name)
Assert.Equal("B", bindInfo1.Type.ToTestDisplayString())
Assert.Same(bindInfo1.Symbol, bindInfo2.Symbol)
Assert.Same(bindInfo1.Type, bindInfo2.Type)
Dim Syntax As ModifiedIdentifierSyntax = Nothing
Dim varSymbol = GetVariableSymbol(compilation, semanticModel, "a.vb", "bInstance", Syntax)
Assert.Same(bindInfo1.Symbol, varSymbol)
CompilationUtils.AssertNoErrors(compilation)
End Sub
' Ensure local symbols gotten from same Binding instance are same object.
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub GetSemanticInfoLocalVariableTwiceStaticLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="GetSemanticInfo">
<file name="a.vb">
Imports System
Class B
Public f1 as Integer
End Class
Class M
Public Sub Main()
Static bInstance As B
bInstance = New B()
Console.WriteLine(bInstance.f1) 'BIND:"bInstance"
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.GlobalNamespace
Dim classB = DirectCast(globalNS.GetMembers("B").Single(), NamedTypeSymbol)
Dim fieldF1 = DirectCast(classB.GetMembers("f1").Single(), FieldSymbol)
Dim node As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim bindInfo1 As SemanticInfoSummary = semanticModel.GetSemanticInfoSummary(DirectCast(node, ExpressionSyntax))
Dim bindInfo2 As SemanticInfoSummary = semanticModel.GetSemanticInfoSummary(DirectCast(node, ExpressionSyntax))
Assert.Equal(SymbolKind.Local, bindInfo1.Symbol.Kind)
Assert.Equal("bInstance", bindInfo1.Symbol.Name)
Assert.Equal("B", bindInfo1.Type.ToTestDisplayString())
Assert.Same(bindInfo1.Symbol, bindInfo2.Symbol)
Assert.Same(bindInfo1.Type, bindInfo2.Type)
Dim Syntax As ModifiedIdentifierSyntax = Nothing
Dim varSymbol = GetVariableSymbol(compilation, semanticModel, "a.vb", "bInstance", Syntax)
Assert.Same(bindInfo1.Symbol, varSymbol)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(540580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540580")>
<Fact()>
Public Sub GetSemanticInfoInsideType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="GetSemanticInfo">
<file name="a.vb">
Imports System
Class C
Public Property P As Func(Of Func(Of A.B.String))
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim genericName = tree.FindNodeOrTokenByKind(SyntaxKind.GenericName)
Dim info = model.GetSemanticInfoSummary(CType(genericName.AsNode(), ExpressionSyntax))
genericName = tree.FindNodeOrTokenByKind(SyntaxKind.GenericName, 2)
info = model.GetSemanticInfoSummary(CType(genericName.AsNode(), ExpressionSyntax))
Dim qualifiedIdent = tree.FindNodeOrTokenByKind(SyntaxKind.QualifiedName)
info = model.GetSemanticInfoSummary(CType(qualifiedIdent.AsNode(), ExpressionSyntax))
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolFromTypeDeclaration()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
' top of file
Option Strict On
Imports System.Collections
Namespace N1
Class C1
End Class
Namespace N2
Partial Class C2
End Class
public partial class Q'first
end class
public class Q'second
end class
public structure Q'third
end structure
public class Q(Of T)
end class
End Namespace
End Namespace
</file>
<file name="b.vb">
Option Strict Off
Namespace N1.N2
Partial Class C2
End Class
Public Interface Q
end interface
End Namespace
Namespace Global.System
Class C3
End Class
End Namespace
Class N1'class
Namespace N2
Class Wack
End Class
Enum Wack2
End Enum
Delegate Function Wack3(p as Integer) as Byte
End Namespace
End Class
</file>
</compilation>, options)
Dim expectedErrors = <errors>
BC30179: class 'Q' and structure 'Q' conflict in namespace 'Foo.Bar.N1.N2'.
public partial class Q'first
~
BC30179: class 'Q' and structure 'Q' conflict in namespace 'Foo.Bar.N1.N2'.
public class Q'second
~
BC30179: structure 'Q' and class 'Q' conflict in namespace 'Foo.Bar.N1.N2'.
public structure Q'third
~
BC30179: interface 'Q' and class 'Q' conflict in namespace 'Foo.Bar.N1.N2'.
Public Interface Q
~
BC30481: 'Class' statement must end with a matching 'End Class'.
Class N1'class
~~~~~~~~
BC30179: class 'N1' and namespace 'N1' conflict in namespace 'Foo.Bar'.
Class N1'class
~~
BC30618: 'Namespace' statements can occur only at file or namespace level.
Namespace N2
~~~~~~~~~~~~
BC30280: Enum 'Wack2' must contain at least one member.
Enum Wack2
~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
End Class
~~~~~~~~~
</errors>
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim treeB = CompilationUtils.GetTree(compilation, "b.vb")
Dim bindingsB = compilation.GetSemanticModel(treeB)
Dim typeSymbol, typeSymbol2, typeSymbol3, typeSymbol4, typeSymbol5, typeSymbol6 As INamedTypeSymbol
typeSymbol = CompilationUtils.GetTypeSymbol(compilation, bindingsA, "a.vb", "C1")
Assert.NotNull(typeSymbol)
Assert.Equal("Foo.Bar.N1.C1", typeSymbol.ToTestDisplayString())
typeSymbol = CompilationUtils.GetTypeSymbol(compilation, bindingsA, "a.vb", "C2")
Assert.NotNull(typeSymbol)
Assert.Equal("Foo.Bar.N1.N2.C2", typeSymbol.ToTestDisplayString())
typeSymbol2 = CompilationUtils.GetTypeSymbol(compilation, bindingsB, "b.vb", "C2")
Assert.NotNull(typeSymbol2)
Assert.Equal("Foo.Bar.N1.N2.C2", typeSymbol2.ToTestDisplayString())
Assert.Equal(typeSymbol, typeSymbol2)
typeSymbol = CompilationUtils.GetTypeSymbol(compilation, bindingsA, "a.vb", "Q'first")
Assert.NotNull(typeSymbol)
Assert.Equal("Foo.Bar.N1.N2.Q", typeSymbol.ToTestDisplayString())
Assert.Equal(0, typeSymbol.Arity)
Assert.Equal(TypeKind.Class, typeSymbol.TypeKind)
typeSymbol2 = CompilationUtils.GetTypeSymbol(compilation, bindingsA, "a.vb", "Q'second")
Assert.NotNull(typeSymbol2)
Assert.Equal("Foo.Bar.N1.N2.Q", typeSymbol2.ToTestDisplayString())
Assert.Equal(TypeKind.Class, typeSymbol2.TypeKind)
Assert.Equal(0, typeSymbol2.Arity)
Assert.Equal(typeSymbol, typeSymbol2)
typeSymbol3 = CompilationUtils.GetTypeSymbol(compilation, bindingsA, "a.vb", "Q'third")
Assert.NotNull(typeSymbol3)
Assert.Equal("Foo.Bar.N1.N2.Q", typeSymbol3.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, typeSymbol3.TypeKind)
Assert.Equal(0, typeSymbol3.Arity)
Assert.NotEqual(typeSymbol, typeSymbol3)
Assert.NotEqual(typeSymbol2, typeSymbol3)
typeSymbol4 = CompilationUtils.GetTypeSymbol(compilation, bindingsB, "b.vb", "Q")
Assert.NotNull(typeSymbol4)
Assert.Equal("Foo.Bar.N1.N2.Q", typeSymbol4.ToTestDisplayString())
Assert.Equal(TypeKind.Interface, typeSymbol4.TypeKind)
Assert.Equal(0, typeSymbol4.Arity)
Assert.NotEqual(typeSymbol4, typeSymbol3)
Assert.NotEqual(typeSymbol4, typeSymbol2)
Assert.NotEqual(typeSymbol4, typeSymbol)
typeSymbol5 = CompilationUtils.GetTypeSymbol(compilation, bindingsA, "a.vb", "Q(Of T)")
Assert.NotNull(typeSymbol5)
Assert.Equal("Foo.Bar.N1.N2.Q(Of T)", typeSymbol5.ToTestDisplayString())
Assert.Equal(TypeKind.Class, typeSymbol5.TypeKind)
Assert.Equal(1, typeSymbol5.Arity)
Assert.NotEqual(typeSymbol5, typeSymbol4)
Assert.NotEqual(typeSymbol5, typeSymbol3)
Assert.NotEqual(typeSymbol5, typeSymbol2)
Assert.NotEqual(typeSymbol5, typeSymbol)
typeSymbol6 = CompilationUtils.GetTypeSymbol(compilation, bindingsB, "b.vb", "C3")
Assert.NotNull(typeSymbol6)
Assert.Equal("System.C3", typeSymbol6.ToTestDisplayString())
Assert.Equal(TypeKind.Class, typeSymbol6.TypeKind)
Assert.Equal(0, typeSymbol6.Arity)
Dim typeSymbol7 = CompilationUtils.GetTypeSymbol(compilation, bindingsB, "b.vb", "N1'class")
Assert.NotNull(typeSymbol7)
Assert.Equal("Foo.Bar.N1", typeSymbol7.ToTestDisplayString())
Assert.Equal(TypeKind.Class, typeSymbol7.TypeKind)
Dim typeSymbol8 = CompilationUtils.GetTypeSymbol(compilation, bindingsB, "b.vb", "Wack")
Assert.NotNull(typeSymbol8)
Assert.Equal("Foo.Bar.N2.Wack", typeSymbol8.ToTestDisplayString())
Assert.Equal(TypeKind.Class, typeSymbol8.TypeKind)
Dim typeSymbol9 = CompilationUtils.GetEnumSymbol(compilation, bindingsB, "b.vb", "Wack2")
Assert.NotNull(typeSymbol9)
Assert.Equal("Foo.Bar.N2.Wack2", typeSymbol9.ToTestDisplayString())
Assert.Equal(TypeKind.Enum, typeSymbol9.TypeKind)
Dim typeSymbol10 = CompilationUtils.GetDelegateSymbol(compilation, bindingsB, "b.vb", "Wack3")
Assert.NotNull(typeSymbol10)
Assert.Equal("Foo.Bar.N2.Wack3", typeSymbol10.ToTestDisplayString())
Assert.Equal(TypeKind.Delegate, typeSymbol10.TypeKind)
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
Private Function GetNamespaceSymbol(compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
treeName As String,
stringInDecl As String) As INamespaceSymbol
Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName)
Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent
While Not (TypeOf node Is NamespaceStatementSyntax)
node = node.Parent
Assert.NotNull(node)
End While
Return semanticModel.GetDeclaredSymbol(DirectCast(node, NamespaceStatementSyntax))
End Function
<Fact()>
Public Sub TestGetDeclaredSymbolFromNamespaceDeclaration()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
' top of file
Option Strict On
Imports System.Collections
Namespace N1
Namespace N2.N3
End Namespace
End Namespace
Class N4
End Class
Namespace N4'first
End Namespace
Namespace N4'second
End Namespace
</file>
<file name="b.vb">
Option Strict Off
Namespace N1.N2
Namespace N3
End Namespace
End Namespace
Namespace N4
End Namespace
Namespace Global.N1
End Namespace
Namespace Global'lone global
Namespace N7
End Namespace
End Namespace
Class Outer
Namespace N1'bad
End Namespace
End Class
</file>
</compilation>, options)
Dim expectedErrors = <errors>
BC30179: class 'N4' and namespace 'N4' conflict in namespace 'Foo.Bar'.
Class N4
~~
BC30481: 'Class' statement must end with a matching 'End Class'.
Class Outer
~~~~~~~~~~~
BC30618: 'Namespace' statements can occur only at file or namespace level.
Namespace N1'bad
~~~~~~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
End Class
~~~~~~~~~
</errors>
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim treeB = CompilationUtils.GetTree(compilation, "b.vb")
Dim bindingsB = compilation.GetSemanticModel(treeB)
Dim nsSymbol0 = GetNamespaceSymbol(compilation, bindingsA, "a.vb", "N1")
Assert.NotNull(nsSymbol0)
Assert.Equal("Foo.Bar.N1", nsSymbol0.ToTestDisplayString())
Dim nsSymbol1 = GetNamespaceSymbol(compilation, bindingsA, "a.vb", "N2.N3")
Assert.NotNull(nsSymbol1)
Assert.Equal("Foo.Bar.N1.N2.N3", nsSymbol1.ToTestDisplayString())
Dim nsSymbol2 = GetNamespaceSymbol(compilation, bindingsA, "a.vb", "N4'first")
Assert.NotNull(nsSymbol2)
Assert.Equal("Foo.Bar.N4", nsSymbol2.ToTestDisplayString())
Dim nsSymbol3 = GetNamespaceSymbol(compilation, bindingsA, "a.vb", "N4'second")
Assert.NotNull(nsSymbol3)
Assert.Equal("Foo.Bar.N4", nsSymbol3.ToTestDisplayString())
Assert.Equal(nsSymbol2, nsSymbol3)
Dim nsSymbol4 = GetNamespaceSymbol(compilation, bindingsB, "b.vb", "N1.N2")
Assert.NotNull(nsSymbol4)
Assert.Equal("Foo.Bar.N1.N2", nsSymbol4.ToTestDisplayString())
Dim nsSymbol5 = GetNamespaceSymbol(compilation, bindingsB, "b.vb", "N3")
Assert.NotNull(nsSymbol5)
Assert.Equal("Foo.Bar.N1.N2.N3", nsSymbol5.ToTestDisplayString())
Assert.Equal(nsSymbol1, nsSymbol5)
Dim nsSymbol6 = GetNamespaceSymbol(compilation, bindingsB, "b.vb", "N4")
Assert.NotNull(nsSymbol6)
Assert.Equal("Foo.Bar.N4", nsSymbol6.ToTestDisplayString())
Assert.Equal(nsSymbol2, nsSymbol6)
Dim nsSymbol7 = GetNamespaceSymbol(compilation, bindingsB, "b.vb", "N1'bad")
Assert.NotNull(nsSymbol7)
Assert.Equal("Foo.Bar.N1", nsSymbol7.ToTestDisplayString())
Dim nsSymbol8 = GetNamespaceSymbol(compilation, bindingsB, "b.vb", "Global.N1")
Assert.NotNull(nsSymbol8)
Assert.Equal("N1", nsSymbol8.ToTestDisplayString())
Dim nsSymbol9 = GetNamespaceSymbol(compilation, bindingsB, "b.vb", "N7")
Assert.NotNull(nsSymbol9)
Assert.Equal("N7", nsSymbol9.ToTestDisplayString())
Dim nsSymbol10 = GetNamespaceSymbol(compilation, bindingsB, "b.vb", "Global'lone global")
Assert.NotNull(nsSymbol10)
Assert.Equal("Global", nsSymbol10.ToTestDisplayString())
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
Private Function GetMethodSymbol(compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
treeName As String,
stringInDecl As String,
ByRef syntax As MethodBaseSyntax) As MethodSymbol
Return DirectCast(GetMethodBaseSymbol(compilation, semanticModel, treeName, stringInDecl, syntax), MethodSymbol)
End Function
Private Function GetPropertySymbol(compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
treeName As String,
stringInDecl As String,
ByRef syntax As MethodBaseSyntax) As PropertySymbol
Return DirectCast(GetMethodBaseSymbol(compilation, semanticModel, treeName, stringInDecl, syntax), PropertySymbol)
End Function
Private Function GetMethodBaseSymbol(compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
treeName As String,
stringInDecl As String,
ByRef syntax As MethodBaseSyntax) As ISymbol
Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName)
Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent
While Not (TypeOf node Is MethodBaseSyntax)
node = node.Parent
Assert.NotNull(node)
End While
syntax = DirectCast(node, MethodBaseSyntax)
Return semanticModel.GetDeclaredSymbol(syntax)
End Function
<Fact()>
Public Sub TestGetDeclaredSymbolFromMethodDeclaration()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
' top of file
Option Strict On
Imports System.Collections
Namespace N1
Namespace N2.N3
Partial Class C1
Public Sub Foo(x as Integer)
End Sub
Public MustOverride Function Foo() As String
Private Function Foo(a as Integer, y As String) As Long
End Function
Public Sub New()
End Sub
End Class
End Namespace
End Namespace
</file>
<file name="b.vb">
Option Strict Off
Namespace N1.N2.N3
Partial Class C1
Shared Sub New()
End Sub
Private Function Foo(b as Integer, y As String) As Long
End Function
End Class
Public Sub Bar()
End Sub
End Namespace
Class Outer
Namespace N1'bad
Class Wack
Public Sub Wackadoodle()
End Sub
End Class
End Namespace
End Class
</file>
</compilation>, options)
Dim expectedDeclErrors =
<errors>
BC31411: 'C1' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Partial Class C1
~~
BC30269: 'Private Function Foo(a As Integer, y As String) As Long' has multiple definitions with identical signatures.
Private Function Foo(a as Integer, y As String) As Long
~~~
BC30001: Statement is not valid in a namespace.
Public Sub Bar()
~~~~~~~~~~~~~~~~
</errors>
Dim expectedParseErrors =
<errors>
BC30481: 'Class' statement must end with a matching 'End Class'.
Class Outer
~~~~~~~~~~~
BC30618: 'Namespace' statements can occur only at file or namespace level.
Namespace N1'bad
~~~~~~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
End Class
~~~~~~~~~
</errors>
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim treeB = CompilationUtils.GetTree(compilation, "b.vb")
Dim bindingsB = compilation.GetSemanticModel(treeB)
Dim syntax As MethodBaseSyntax = Nothing
Dim methSymbol1 = GetMethodSymbol(compilation, bindingsA, "a.vb", "Sub Foo(x as Integer)", syntax)
Assert.NotNull(methSymbol1)
Assert.Equal("Sub Foo.Bar.N1.N2.N3.C1.Foo(x As System.Int32)", methSymbol1.ToTestDisplayString())
Assert.Equal(treeA.GetLineSpan(syntax.Span).StartLinePosition.Line,
methSymbol1.Locations.Single().GetLineSpan().StartLinePosition.Line)
Dim methSymbol2 = GetMethodSymbol(compilation, bindingsA, "a.vb", "Function Foo() As String", syntax)
Assert.NotNull(methSymbol2)
Assert.Equal("Function Foo.Bar.N1.N2.N3.C1.Foo() As System.String", methSymbol2.ToTestDisplayString())
Assert.Equal(treeA.GetLineSpan(syntax.Span).StartLinePosition.Line,
methSymbol2.Locations.Single().GetLineSpan().StartLinePosition.Line)
Dim methSymbol3 = GetMethodSymbol(compilation, bindingsA, "a.vb", "Foo(a as Integer, y As String)", syntax)
Assert.NotNull(methSymbol3)
Assert.Equal("Function Foo.Bar.N1.N2.N3.C1.Foo(a As System.Int32, y As System.String) As System.Int64", methSymbol3.ToTestDisplayString())
Assert.Equal(treeA.GetLineSpan(syntax.Span).StartLinePosition.Line,
methSymbol3.Locations.Single().GetLineSpan().StartLinePosition.Line)
Dim methSymbol4 = GetMethodSymbol(compilation, bindingsA, "a.vb", "Sub New", syntax)
Assert.NotNull(methSymbol4)
Assert.Equal("Sub Foo.Bar.N1.N2.N3.C1..ctor()", methSymbol4.ToTestDisplayString())
Assert.Equal(treeA.GetLineSpan(syntax.Span).StartLinePosition.Line,
methSymbol4.Locations.Single().GetLineSpan().StartLinePosition.Line)
Dim methSymbol5 = GetMethodSymbol(compilation, bindingsB, "b.vb", "Sub New", syntax)
Assert.NotNull(methSymbol5)
Assert.Equal("Sub Foo.Bar.N1.N2.N3.C1..cctor()", methSymbol5.ToTestDisplayString())
Assert.Equal(treeB.GetLineSpan(syntax.Span).StartLinePosition.Line,
methSymbol5.Locations.Single().GetLineSpan().StartLinePosition.Line)
Dim methSymbol6 = GetMethodSymbol(compilation, bindingsB, "b.vb", "Foo(b as Integer, y As String)", syntax)
Assert.NotNull(methSymbol6)
Assert.Equal("Function Foo.Bar.N1.N2.N3.C1.Foo(b As System.Int32, y As System.String) As System.Int64", methSymbol6.ToTestDisplayString())
Assert.Equal(treeB.GetLineSpan(syntax.Span).StartLinePosition.Line,
methSymbol6.Locations.Single().GetLineSpan().StartLinePosition.Line)
Dim methSymbol7 = GetMethodSymbol(compilation, bindingsB, "b.vb", "Bar()", syntax)
Assert.NotNull(methSymbol7)
Dim methSymbol8 = GetMethodSymbol(compilation, bindingsB, "b.vb", "Wackadoodle()", syntax)
Assert.NotNull(methSymbol8)
Assert.Equal("Sub Foo.Bar.N1.Wack.Wackadoodle()", methSymbol8.ToTestDisplayString())
Assert.Equal(treeB.GetLineSpan(syntax.Span).StartLinePosition.Line,
methSymbol8.Locations.Single().GetLineSpan().StartLinePosition.Line)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedDeclErrors)
CompilationUtils.AssertTheseParseDiagnostics(compilation, expectedParseErrors)
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolFromPropertyDeclaration()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="c.vb">
Class C
Property P As Integer
Get
Return 0
End Get
Set
End Set
End Property
Property Q As Object
Property R(index As Integer)
Get
Return Nothing
End Get
Set(value As Object)
End Set
End Property
End Class
</file>
</compilation>, options)
Dim tree = CompilationUtils.GetTree(compilation, "c.vb")
Dim bindings = compilation.GetSemanticModel(tree)
Dim propertySyntax As MethodBaseSyntax = Nothing
Dim propertySymbol As IPropertySymbol
Dim parameterSyntax As ParameterSyntax = Nothing
Dim parameterSymbol As IParameterSymbol
propertySymbol = GetPropertySymbol(compilation, bindings, "c.vb", "Property P As Integer", propertySyntax)
Assert.NotNull(propertySymbol)
propertySymbol = GetPropertySymbol(compilation, bindings, "c.vb", "Property Q As Object", propertySyntax)
Assert.NotNull(propertySymbol)
propertySymbol = GetPropertySymbol(compilation, bindings, "c.vb", "Property R(index As Integer)", propertySyntax)
Assert.NotNull(propertySymbol)
parameterSymbol = GetParameterSymbol(compilation, bindings, "c.vb", "index As Integer", parameterSyntax)
Assert.NotNull(parameterSymbol)
Assert.Equal(parameterSymbol.ContainingSymbol, propertySymbol)
parameterSymbol = GetParameterSymbol(compilation, bindings, "c.vb", "value As Object", parameterSyntax)
Assert.NotNull(parameterSymbol)
Assert.Equal(parameterSymbol.ContainingSymbol, propertySymbol.SetMethod)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolFromOperatorDeclaration()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("NS")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
' top of file
Option Strict Off
Imports System
Enum E
Zero
One
Two
End Enum
Class A
Structure S
Shared Narrowing Operator CType(x As S) As E?
System.Console.WriteLine("Operator Conv")
Return Nothing
End Operator
Shared Operator Mod(x As S?, y As E) As E
System.Console.WriteLine("Operator Mod")
Return y
End Operator
End Structure
End Class
</file>
</compilation>, options)
Dim tree = CompilationUtils.GetTree(compilation, "a.vb")
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of OperatorStatementSyntax)()
Assert.Equal(2, nodes.Count)
Dim sym1 = model.GetDeclaredSymbol(nodes.First())
Dim sym2 = model.GetDeclaredSymbol(nodes.Last())
Assert.Equal(MethodKind.Conversion, sym1.MethodKind)
Assert.Equal(MethodKind.UserDefinedOperator, sym2.MethodKind)
Assert.Equal("Public Shared Narrowing Operator CType(x As NS.A.S) As NS.E?", sym1.ToDisplayString())
Assert.Equal("Public Shared Operator Mod(x As NS.A.S?, y As NS.E) As NS.E", sym2.ToDisplayString())
End Sub
Private Function GetParameterSymbol(compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
treeName As String,
stringInDecl As String,
ByRef syntax As ParameterSyntax) As IParameterSymbol
Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName)
Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent
While Not (TypeOf node Is ParameterSyntax)
node = node.Parent
Assert.NotNull(node)
End While
syntax = DirectCast(node, ParameterSyntax)
Return semanticModel.GetDeclaredSymbol(syntax)
End Function
Private Function GetLabelSymbol(compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
treeName As String,
stringInDecl As String,
ByRef syntax As LabelStatementSyntax) As ILabelSymbol
Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName)
Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent
While Not (TypeOf node Is LabelStatementSyntax)
node = node.Parent
Assert.NotNull(node)
End While
syntax = DirectCast(node, LabelStatementSyntax)
Return semanticModel.GetDeclaredSymbol(syntax, Nothing)
End Function
<Fact()>
Public Sub TestGetDeclaredSymbolFromParameter()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
' top of file
Option Strict On
Imports System.Collections
Namespace N1
Partial Class C1
Public Sub Foo(x as Integer, Optional yopt as String = "hi")
End Sub
Public MustOverride Function Foo(a as Long, a as integer) As String
Public Sub New(c as string, d as string)
End Sub
End Class
End Namespace
</file>
<file name="b.vb">
Option Strict Off
Namespace N1
Partial Class C1
Shared Sub New()
End Sub
End Class
Public Sub Bar(aaa as integer)
End Sub
End Namespace
</file>
</compilation>, options)
Dim expectedErrors =
<errors>
BC31411: 'C1' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Partial Class C1
~~
BC30237: Parameter already declared with name 'a'.
Public MustOverride Function Foo(a as Long, a as integer) As String
~
BC30001: Statement is not valid in a namespace.
Public Sub Bar(aaa as integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim treeB = CompilationUtils.GetTree(compilation, "b.vb")
Dim bindingsB = compilation.GetSemanticModel(treeB)
Dim syntax As ParameterSyntax = Nothing
Dim paramSymbol1 = GetParameterSymbol(compilation, bindingsA, "a.vb", "x as Integer", syntax)
Assert.NotNull(paramSymbol1)
Assert.Equal("x", paramSymbol1.Name)
Assert.Equal("System.Int32", paramSymbol1.Type.ToTestDisplayString())
Assert.Equal("Sub Foo.Bar.N1.C1.Foo(x As System.Int32, [yopt As System.String = ""hi""])", paramSymbol1.ContainingSymbol.ToTestDisplayString())
Assert.Equal(syntax.SpanStart,
paramSymbol1.Locations.Single().SourceSpan.Start)
Dim paramSymbol2 = GetParameterSymbol(compilation, bindingsA, "a.vb", "yopt as String", syntax)
Assert.NotNull(paramSymbol2)
Assert.Equal("yopt", paramSymbol2.Name)
Assert.Equal("System.String", paramSymbol2.Type.ToTestDisplayString())
Assert.Equal("Sub Foo.Bar.N1.C1.Foo(x As System.Int32, [yopt As System.String = ""hi""])", paramSymbol2.ContainingSymbol.ToTestDisplayString())
Assert.Equal(syntax.SpanStart,
paramSymbol2.Locations.Single().SourceSpan.Start - "Optional ".Length)
Dim paramSymbol3 = GetParameterSymbol(compilation, bindingsA, "a.vb", "a as Long", syntax)
Assert.NotNull(paramSymbol3)
Assert.Equal("a", paramSymbol3.Name)
Assert.Equal("System.Int64", paramSymbol3.Type.ToTestDisplayString())
Assert.Equal("Function Foo.Bar.N1.C1.Foo(a As System.Int64, a As System.Int32) As System.String", paramSymbol3.ContainingSymbol.ToTestDisplayString())
Assert.Equal(syntax.SpanStart,
paramSymbol3.Locations.Single().SourceSpan.Start)
Dim paramSymbol4 = GetParameterSymbol(compilation, bindingsA, "a.vb", "a as integer", syntax)
Assert.NotNull(paramSymbol4)
Assert.Equal("a", paramSymbol4.Name)
Assert.Equal("System.Int32", paramSymbol4.Type.ToTestDisplayString())
Assert.Equal("Function Foo.Bar.N1.C1.Foo(a As System.Int64, a As System.Int32) As System.String", paramSymbol4.ContainingSymbol.ToTestDisplayString())
Assert.Equal(syntax.SpanStart,
paramSymbol4.Locations.Single().SourceSpan.Start)
Dim paramSymbol5 = GetParameterSymbol(compilation, bindingsA, "a.vb", "d as string", syntax)
Assert.NotNull(paramSymbol5)
Assert.Equal("d", paramSymbol5.Name)
Assert.Equal("System.String", paramSymbol5.Type.ToTestDisplayString())
Assert.Equal("Sub Foo.Bar.N1.C1..ctor(c As System.String, d As System.String)", paramSymbol5.ContainingSymbol.ToTestDisplayString())
Assert.Equal(syntax.SpanStart,
paramSymbol5.Locations.Single().SourceSpan.Start)
Dim paramSymbol6 = GetParameterSymbol(compilation, bindingsB, "b.vb", "aaa as integer", syntax)
Assert.NotNull(paramSymbol6)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolFromEventParameter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="TestGetDeclaredSymbolFromEventParameter">
<file name="a.vb">
Namespace N1
Class Test
Public Event Percent(ByVal Percent As Single)
Public Shared Sub Main()
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim tree = CompilationUtils.GetTree(compilation, "a.vb")
Dim model = compilation.GetSemanticModel(tree)
Dim syntax As ParameterSyntax = Nothing
Dim paramSymbol1 = GetParameterSymbol(compilation, model, "a.vb", "Percent As Single", syntax)
Assert.NotNull(paramSymbol1)
Assert.Equal("Percent", paramSymbol1.Name)
Assert.Equal("System.Single", paramSymbol1.Type.ToTestDisplayString())
Assert.Equal("Event N1.Test.Percent(Percent As System.Single)", paramSymbol1.ContainingType.AssociatedSymbol.ToTestDisplayString())
Assert.Equal("Sub N1.Test.PercentEventHandler.Invoke(Percent As System.Single)", paramSymbol1.ContainingSymbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolFromParameterWithTypeChar()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="TypeChar.vb">
Imports System
Imports Microsoft.VisualBasic
Namespace VBN
Module Program
Function osGetWindowLong&(ByVal h&, ByVal ndx&)
Return h
End Function
Function F1!(ByRef p1!, p2%)
Return p1 + p2
End Function
Function F2$(ByRef px$, ByVal py$, ByVal pz#, ByRef pw@)
Return p2
End Function
Sub Main()
End Sub
End Module
End Namespace
</file>
</compilation>)
Const file = "TypeChar.vb"
Dim treeA = CompilationUtils.GetTree(compilation, file)
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim syntax As ParameterSyntax = Nothing
Dim paramSymbol1 = GetParameterSymbol(compilation, bindingsA, file, "ByVal ndx&", syntax)
Assert.Equal("ndx", paramSymbol1.Name)
Assert.Equal("System.Int64", paramSymbol1.Type.ToTestDisplayString())
Assert.Equal(syntax.SpanStart + 6, paramSymbol1.Locations.Single().SourceSpan.Start)
Dim paramSymbol2 = GetParameterSymbol(compilation, bindingsA, file, "ByRef p1!", syntax)
Assert.Equal("p1", paramSymbol2.Name)
Assert.Equal("System.Single", paramSymbol2.Type.ToTestDisplayString())
Assert.Equal(syntax.SpanStart + 6, paramSymbol2.Locations.Single().SourceSpan.Start)
Dim paramSymbol3 = GetParameterSymbol(compilation, bindingsA, file, "p2%", syntax)
Assert.Equal("p2", paramSymbol3.Name)
Assert.Equal("System.Int32", paramSymbol3.Type.ToTestDisplayString())
Assert.Equal(syntax.SpanStart, paramSymbol3.Locations.Single().SourceSpan.Start)
Dim paramSymbol4 = GetParameterSymbol(compilation, bindingsA, file, "ByRef px$", syntax)
Assert.Equal("px", paramSymbol4.Name)
Assert.Equal("System.String", paramSymbol4.Type.ToTestDisplayString())
Assert.Equal(syntax.SpanStart + 6, paramSymbol4.Locations.Single().SourceSpan.Start)
Dim paramSymbol5 = GetParameterSymbol(compilation, bindingsA, file, "ByVal py$", syntax)
Assert.Equal("py", paramSymbol5.Name)
Assert.Equal("System.String", paramSymbol5.Type.ToTestDisplayString())
Dim paramSymbol6 = GetParameterSymbol(compilation, bindingsA, file, "ByVal pz#", syntax)
Assert.Equal("pz", paramSymbol6.Name)
Assert.Equal("System.Double", paramSymbol6.Type.ToTestDisplayString())
Dim paramSymbol7 = GetParameterSymbol(compilation, bindingsA, file, "ByRef pw@", syntax)
Assert.Equal("pw", paramSymbol7.Name)
Assert.Equal("System.Decimal", paramSymbol7.Type.ToTestDisplayString())
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolLambdaParam()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam As Integer)
Return lambdaParam + 1
End Function
End Sub
End Module
</file>
</compilation>, options)
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim node = treeA.GetCompilationUnitRoot().FindToken(treeA.GetCompilationUnitRoot().ToFullString().IndexOf("lambdaParam", StringComparison.Ordinal)).Parent
Dim symbol = bindingsA.GetDeclaredSymbolFromSyntaxNode(node)
Assert.NotNull(symbol)
Assert.Equal(SymbolKind.Parameter, symbol.Kind)
Assert.Equal("lambdaParam As Integer", symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolFromPropertyStatementSyntax()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="TypeChar.vb">
Class Program
Default Overridable Property DefProp(p As Integer) As String
Get
Return Nothing
End Get
Set(value As String)
End Set
End Property
Property AutoProp As String = "error"
WriteOnly Property RegularProp As String
Set(value As String)
End Set
End Property
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim defPropSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.PropertyStatement, 1).AsNode(), PropertyStatementSyntax)
Dim autoPropSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.PropertyStatement, 2).AsNode(), PropertyStatementSyntax)
Dim regularPropSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.PropertyStatement, 3).AsNode(), PropertyStatementSyntax)
Dim defPropSymbol = model.GetDeclaredSymbol(defPropSyntax)
Assert.NotNull(defPropSymbol)
Assert.Equal("Property Program.DefProp(p As System.Int32) As System.String", defPropSymbol.ToTestDisplayString())
Dim autoPropSymbol = model.GetDeclaredSymbol(autoPropSyntax)
Assert.NotNull(autoPropSymbol)
Assert.Equal("Property Program.AutoProp As System.String", autoPropSymbol.ToTestDisplayString())
Dim regularPropSymbol = model.GetDeclaredSymbol(regularPropSyntax)
Assert.NotNull(regularPropSymbol)
Assert.Equal("WriteOnly Property Program.RegularProp As System.String", regularPropSymbol.ToTestDisplayString())
Dim defPropBlockSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.PropertyBlock, 1).AsNode(), PropertyBlockSyntax)
Assert.Equal(defPropSymbol, model.GetDeclaredSymbol(defPropBlockSyntax))
Dim regularPropBlockSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.PropertyBlock, 2).AsNode(), PropertyBlockSyntax)
Assert.Equal(regularPropSymbol, model.GetDeclaredSymbol(regularPropBlockSyntax))
Dim defPropGetBlockSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.GetAccessorBlock, 1).AsNode(), AccessorBlockSyntax)
Assert.Equal("Public Overridable Property Get DefProp(p As Integer) As String", model.GetDeclaredSymbol(defPropGetBlockSyntax).ToString())
Assert.True(TypeOf (model.GetDeclaredSymbol(defPropGetBlockSyntax)) Is MethodSymbol, "API should return a MethodSymbol")
Dim defPropSetBlockSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SetAccessorBlock, 1).AsNode(), AccessorBlockSyntax)
Assert.Equal("Public Overridable Property Set DefProp(p As Integer, value As String)", model.GetDeclaredSymbol(defPropSetBlockSyntax).ToString())
Dim regularPropSetBlockSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SetAccessorBlock, 2).AsNode(), AccessorBlockSyntax)
Assert.Equal("Public Property Set RegularProp(value As String)", model.GetDeclaredSymbol(regularPropSetBlockSyntax).ToString())
Dim defPropGetSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.GetAccessorStatement, 1).AsNode(), MethodBaseSyntax)
Assert.Equal("Public Overridable Property Get DefProp(p As Integer) As String", model.GetDeclaredSymbol(defPropGetSyntax).ToString())
Dim defPropSetSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SetAccessorStatement, 1).AsNode(), MethodBaseSyntax)
Assert.Equal("Public Overridable Property Set DefProp(p As Integer, value As String)", model.GetDeclaredSymbol(defPropSetSyntax).ToString())
Dim regularPropSetSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SetAccessorStatement, 2).AsNode(), MethodBaseSyntax)
Assert.Equal("Public Property Set RegularProp(value As String)", model.GetDeclaredSymbol(regularPropSetSyntax).ToString())
End Sub
<WorkItem(540877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540877")>
<Fact()>
Public Sub TestGetDeclaredSymbolFromAlias()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="TypeChar.vb">
Imports M=
Imports MS_ = Microsoft
Imports Sys = System.Collections,
Sys_Collections = System,
Sys_Collections_BitArray = System.Collections.BitArray
Imports MS_ = System.Collections
Imports M = System.Collections
Class Program
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim importsClause = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SimpleImportsClause, 1).AsNode(), SimpleImportsClauseSyntax)
Dim aliasSymbol = DirectCast(model.GetDeclaredSymbol(importsClause), AliasSymbol)
Assert.NotNull(aliasSymbol)
Assert.Equal("M", aliasSymbol.Name)
Assert.Equal(SymbolKind.ErrorType, aliasSymbol.Target.Kind)
Assert.Equal("", aliasSymbol.Target.Name)
Assert.False(aliasSymbol.IsNotOverridable)
Assert.False(aliasSymbol.IsMustOverride)
Assert.False(aliasSymbol.IsOverrides)
Assert.False(aliasSymbol.IsOverridable)
Assert.False(aliasSymbol.IsShared)
Assert.Equal(1, aliasSymbol.DeclaringSyntaxReferences.Length)
Assert.Equal(SyntaxKind.SimpleImportsClause, aliasSymbol.DeclaringSyntaxReferences.First.GetSyntax().Kind)
Assert.Equal(Accessibility.NotApplicable, aliasSymbol.DeclaredAccessibility)
Dim x8 As Symbol = aliasSymbol.ContainingSymbol
Assert.Equal(aliasSymbol.Locations.Item(0).GetHashCode, aliasSymbol.GetHashCode)
Assert.Equal(aliasSymbol, aliasSymbol)
Assert.NotNull(aliasSymbol)
importsClause = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SimpleImportsClause, 2).AsNode(), SimpleImportsClauseSyntax)
Assert.Equal("MS_=Microsoft", model.GetDeclaredSymbol(importsClause).ToTestDisplayString())
importsClause = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SimpleImportsClause, 3).AsNode(), SimpleImportsClauseSyntax)
Assert.Equal("Sys=System.Collections", model.GetDeclaredSymbol(importsClause).ToTestDisplayString())
importsClause = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SimpleImportsClause, 4).AsNode(), SimpleImportsClauseSyntax)
Assert.Equal("Sys_Collections=System", model.GetDeclaredSymbol(importsClause).ToTestDisplayString())
importsClause = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SimpleImportsClause, 5).AsNode(), SimpleImportsClauseSyntax)
Assert.Equal("Sys_Collections_BitArray=System.Collections.BitArray", model.GetDeclaredSymbol(importsClause).ToTestDisplayString())
importsClause = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SimpleImportsClause, 6).AsNode(), SimpleImportsClauseSyntax)
Assert.Equal("MS_=System.Collections", model.GetDeclaredSymbol(importsClause).ToTestDisplayString())
importsClause = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SimpleImportsClause, 7).AsNode(), SimpleImportsClauseSyntax)
Assert.Equal("M=System.Collections", model.GetDeclaredSymbol(importsClause).ToTestDisplayString())
Dim genericSyntax = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleImportsClause, 7).AsNode()
Assert.Equal("M=System.Collections", model.GetDeclaredSymbolFromSyntaxNode(genericSyntax).ToTestDisplayString())
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolForOnErrorGotoLabels()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="TypeChar.vb">
Import System
Class Program
Shared Sub Main()
On Error Goto Foo
Exit Sub
Foo:
Resume next
End Sub
Shared Sub ResumeNext()
On Error Resume Next
Exit Sub
Foo:
Resume next
End Sub
Shared Sub Goto0()
On Error Goto 0
End Sub
Shared Sub Goto1()
On Error Goto -1
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim Labels = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.LabelStatement, 1).AsNode(), LabelStatementSyntax)
Assert.Equal(2, Labels.SlotCount)
Dim LabelSymbol = DirectCast(model.GetDeclaredSymbol(Labels), LabelSymbol)
Assert.NotNull(LabelSymbol)
Assert.Equal("Foo", LabelSymbol.Name)
Dim OnErrorGoto = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.OnErrorGoToLabelStatement, 1).AsNode(), OnErrorGoToStatementSyntax)
Assert.NotNull(OnErrorGoto)
Dim OnErrorResumeNext = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.OnErrorResumeNextStatement, 1).AsNode(), OnErrorResumeNextStatementSyntax)
Assert.NotNull(OnErrorResumeNext)
Dim OnErrorGoto0 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.OnErrorGoToZeroStatement, 1).AsNode(), OnErrorGoToStatementSyntax)
Assert.NotNull(OnErrorGoto0)
Dim OnErrorGoto1 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.OnErrorGoToMinusOneStatement, 1).AsNode(), OnErrorGoToStatementSyntax)
Assert.NotNull(OnErrorGoto1)
End Sub
<WorkItem(541238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541238")>
<Fact()>
Public Sub TestGetDeclaredSymbolFromAliasDecl()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
Imports VB6 = Microsoft.VisualBasic
</file>
</compilation>, options)
compilation.AssertTheseDiagnostics(<expected>
BC40056: Namespace or type specified in the Imports 'Microsoft.VisualBasic' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports VB6 = Microsoft.VisualBasic
~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim node = treeA.GetCompilationUnitRoot().FindToken(treeA.GetCompilationUnitRoot().ToFullString().IndexOf("VB6", StringComparison.Ordinal)).Parent.Parent
Dim symbol = bindingsA.GetDeclaredSymbol(node)
Assert.Equal(SyntaxKind.SimpleImportsClause, node.Kind)
Assert.Equal("VB6=Microsoft.VisualBasic", symbol.ToTestDisplayString())
End Sub
<Fact(), WorkItem(544076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544076")>
Public Sub TestGetDeclaredSymbolFromSubFunctionConstructor()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="TypeChar.vb">
Interface I1
Function F() As String
End Interface
Class C1
Implements I1
Public Sub New()
End Sub
Public Sub S()
End Sub
Public Function F() As String Implements I1.F
Return Nothing
End Function
Declare Sub PInvokeSub Lib "Bar" ()
Declare Function PInvokeFun Lib "Baz" () As Integer
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim fSyntax1 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.FunctionStatement, 1).AsNode(), MethodStatementSyntax)
Dim nSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SubNewStatement, 1).AsNode(), SubNewStatementSyntax)
Dim sSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SubStatement, 1).AsNode(), MethodStatementSyntax)
Dim fSyntax2 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.FunctionStatement, 2).AsNode(), MethodStatementSyntax)
Dim declareSubSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.DeclareSubStatement, 1).AsNode(), DeclareStatementSyntax)
Dim declareFunSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.DeclareFunctionStatement, 1).AsNode(), DeclareStatementSyntax)
Dim fSymbol1 = model.GetDeclaredSymbol(fSyntax1)
Assert.NotNull(fSymbol1)
Assert.Equal("Function I1.F() As System.String", fSymbol1.ToTestDisplayString())
Dim nSymbol = model.GetDeclaredSymbol(nSyntax)
Assert.NotNull(nSymbol)
Assert.Equal("Sub C1..ctor()", nSymbol.ToTestDisplayString())
Dim sSymbol = model.GetDeclaredSymbol(sSyntax)
Assert.NotNull(sSymbol)
Assert.Equal("Sub C1.S()", sSymbol.ToTestDisplayString())
Dim fSymbol2 = model.GetDeclaredSymbol(fSyntax2)
Assert.NotNull(fSymbol2)
Assert.Equal("Function C1.F() As System.String", fSymbol2.ToTestDisplayString())
Dim declareSubSymbol = model.GetDeclaredSymbol(declareSubSyntax)
Assert.NotNull(declareSubSymbol)
Assert.Equal("Declare Ansi Sub C1.PInvokeSub Lib ""Bar"" ()", declareSubSymbol.ToTestDisplayString())
Dim declareFunSymbol = model.GetDeclaredSymbol(declareFunSyntax)
Assert.NotNull(declareFunSymbol)
Assert.Equal("Declare Ansi Function C1.PInvokeFun Lib ""Baz"" () As System.Int32", declareFunSymbol.ToTestDisplayString())
Assert.Same(fSymbol2, model.GetDeclaredSymbol(DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.FunctionBlock, 1).AsNode(), MethodBlockSyntax)))
Assert.Same(nSymbol, model.GetDeclaredSymbol(DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.ConstructorBlock, 1).AsNode(), ConstructorBlockSyntax)))
Assert.Same(sSymbol, model.GetDeclaredSymbol(DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.SubBlock, 1).AsNode(), MethodBlockSyntax)))
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolFromTypes()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="TypeChar.vb">
Interface I1
End Interface
Namespace NS
Class C1
Enum E2
None
End Enum
Class C2
End Class
Interface I2
End Interface
End Class
End Namespace
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim nsSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.NamespaceStatement, 1).AsNode(), NamespaceStatementSyntax)
Dim i1Syntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.InterfaceStatement, 1).AsNode(), TypeStatementSyntax)
Dim c1Syntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.ClassStatement, 1).AsNode(), TypeStatementSyntax)
Dim e2Syntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.EnumStatement, 1).AsNode(), EnumStatementSyntax)
Dim c2Syntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.ClassStatement, 2).AsNode(), TypeStatementSyntax)
Dim i2Syntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.InterfaceStatement, 2).AsNode(), TypeStatementSyntax)
Dim e2NoneSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.EnumMemberDeclaration, 1).AsNode(), EnumMemberDeclarationSyntax)
Dim i1Symbol = model.GetDeclaredSymbol(i1Syntax)
Assert.NotNull(i1Symbol)
Assert.Equal("I1", i1Symbol.ToTestDisplayString())
Dim nsSymbol = model.GetDeclaredSymbol(nsSyntax)
Assert.NotNull(nsSymbol)
Assert.Equal("NS", nsSymbol.ToTestDisplayString())
Dim c1Symbol = model.GetDeclaredSymbol(c1Syntax)
Assert.NotNull(c1Symbol)
Assert.Equal("NS.C1", c1Symbol.ToTestDisplayString())
Dim i2Symbol = model.GetDeclaredSymbol(i2Syntax)
Assert.NotNull(i2Symbol)
Assert.Equal("NS.C1.I2", i2Symbol.ToTestDisplayString())
Dim c2Symbol = model.GetDeclaredSymbol(c2Syntax)
Assert.NotNull(c2Symbol)
Assert.Equal("NS.C1.C2", c2Symbol.ToTestDisplayString())
Dim e2Symbol = model.GetDeclaredSymbol(e2Syntax)
Assert.NotNull(e2Symbol)
Assert.Equal("NS.C1.E2", e2Symbol.ToTestDisplayString())
Dim e2NoneSymbol = model.GetDeclaredSymbol(e2NoneSyntax)
Assert.NotNull(e2NoneSymbol)
Assert.Equal("NS.C1.E2.None", e2NoneSymbol.ToTestDisplayString())
Assert.Equal(i1Symbol, model.GetDeclaredSymbol(DirectCast(i1Syntax.Parent, TypeBlockSyntax)))
Assert.Equal(i2Symbol, model.GetDeclaredSymbol(DirectCast(i2Syntax.Parent, TypeBlockSyntax)))
Assert.Equal(c1Symbol, model.GetDeclaredSymbol(DirectCast(c1Syntax.Parent, TypeBlockSyntax)))
Assert.Equal(c2Symbol, model.GetDeclaredSymbol(DirectCast(c2Syntax.Parent, TypeBlockSyntax)))
Assert.Equal(e2Symbol, model.GetDeclaredSymbol(DirectCast(e2Syntax.Parent, EnumBlockSyntax)))
Assert.Equal(nsSymbol, model.GetDeclaredSymbol(DirectCast(nsSyntax.Parent, NamespaceBlockSyntax)))
End Sub
Private Function GetTypeParameterSymbol(compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
treeName As String,
stringInDecl As String,
ByRef syntax As TypeParameterSyntax) As ITypeParameterSymbol
Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName)
Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent
While Not (TypeOf node Is TypeParameterSyntax)
node = node.Parent
Assert.NotNull(node)
End While
syntax = DirectCast(node, TypeParameterSyntax)
Return semanticModel.GetDeclaredSymbol(syntax)
End Function
<Fact()>
Public Sub TestGetDeclaredSymbolFromTypeParameter()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
' top of file
Option Strict On
Imports System.Collections
Namespace N1
Partial Class C1(Of TTT, UUU)
Sub K(Of VVV)(a as VVV)
End Sub
End Class
End Namespace
</file>
<file name="b.vb">
Option Strict Off
Namespace N1
Partial Class C1(Of TTT, UUU)
End Class
Sub Goofy(Of ZZZ)()
End Sub
End Namespace
</file>
</compilation>, options)
Dim expectedErrors =
<errors>
BC30001: Statement is not valid in a namespace.
Sub Goofy(Of ZZZ)()
~~~~~~~~~~~~~~~~~~~
</errors>
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim treeB = CompilationUtils.GetTree(compilation, "b.vb")
Dim bindingsB = compilation.GetSemanticModel(treeB)
Dim syntax As TypeParameterSyntax = Nothing
Dim tpSymbol1 = GetTypeParameterSymbol(compilation, bindingsA, "a.vb", "TTT", syntax)
Assert.NotNull(tpSymbol1)
Assert.Equal("TTT", tpSymbol1.Name)
Assert.Equal("Foo.Bar.N1.C1(Of TTT, UUU)", tpSymbol1.ContainingSymbol.ToTestDisplayString())
Assert.Equal(2, tpSymbol1.Locations.Length())
Assert.True(syntax.SpanStart = tpSymbol1.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = tpSymbol1.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, tpSymbol1))
Dim tpSymbol2 = GetTypeParameterSymbol(compilation, bindingsA, "a.vb", "UUU", syntax)
Assert.NotNull(tpSymbol2)
Assert.Equal("UUU", tpSymbol2.Name)
Assert.Equal("Foo.Bar.N1.C1(Of TTT, UUU)", tpSymbol2.ContainingSymbol.ToTestDisplayString())
Assert.Equal(2, tpSymbol2.Locations.Length())
Assert.True(syntax.SpanStart = tpSymbol2.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = tpSymbol2.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, tpSymbol2))
Dim tpSymbol3 = GetTypeParameterSymbol(compilation, bindingsB, "b.vb", "TTT", syntax)
Assert.NotNull(tpSymbol3)
Assert.Equal("TTT", tpSymbol3.Name)
Assert.Equal("Foo.Bar.N1.C1(Of TTT, UUU)", tpSymbol3.ContainingSymbol.ToTestDisplayString())
Assert.Equal(2, tpSymbol3.Locations.Length())
Assert.True(syntax.SpanStart = tpSymbol3.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = tpSymbol3.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, tpSymbol3))
Dim tpSymbol4 = GetTypeParameterSymbol(compilation, bindingsB, "b.vb", "UUU", syntax)
Assert.NotNull(tpSymbol4)
Assert.Equal("UUU", tpSymbol4.Name)
Assert.Equal("Foo.Bar.N1.C1(Of TTT, UUU)", tpSymbol4.ContainingSymbol.ToTestDisplayString())
Assert.Equal(2, tpSymbol4.Locations.Length())
Assert.True(syntax.SpanStart = tpSymbol4.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = tpSymbol4.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, tpSymbol4))
Dim tpSymbol5 = GetTypeParameterSymbol(compilation, bindingsA, "a.vb", "VVV", syntax)
Assert.NotNull(tpSymbol5)
Assert.Equal("VVV", tpSymbol5.Name)
Assert.Equal("Sub Foo.Bar.N1.C1(Of TTT, UUU).K(Of VVV)(a As VVV)", tpSymbol5.ContainingSymbol.ToTestDisplayString())
Assert.Equal(1, tpSymbol5.Locations.Length())
Assert.Equal(syntax.SpanStart, tpSymbol5.Locations.Single().SourceSpan.Start)
Dim tpSymbol6 = GetTypeParameterSymbol(compilation, bindingsB, "b.vb", "ZZZ", syntax)
Assert.NotNull(tpSymbol6)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
Private Function GetVariableSymbol(compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
treeName As String,
stringInDecl As String,
ByRef syntax As ModifiedIdentifierSyntax) As ISymbol
Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName)
Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent
While Not (TypeOf node Is ModifiedIdentifierSyntax)
node = node.Parent
Assert.NotNull(node)
End While
syntax = DirectCast(node, ModifiedIdentifierSyntax)
Return semanticModel.GetDeclaredSymbol(syntax)
End Function
<Fact()>
Public Sub TestGetDeclaredFromLabel()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
Module Module1
Sub Main()
Label1:
Label2:
End Sub
End Module
</file>
</compilation>, options)
Dim tree = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindings = compilation.GetSemanticModel(tree)
Dim root As Object = tree.GetRoot(Nothing)
Dim label1 = GetLabelSymbol(compilation, bindings, "a.vb", "Label1", Nothing)
Assert.NotNull(label1)
Assert.Equal("Label1", label1.Name)
Dim label2 = GetLabelSymbol(compilation, bindings, "a.vb", "Label2", Nothing)
Assert.NotNull(label2)
Assert.Equal("Label2", label2.Name)
Dim symLabel = DirectCast(label1, LabelSymbol)
Assert.False(SymbolExtensions.IsOverloadable(symLabel))
Assert.False(symLabel.IsMustOverride)
Assert.False(symLabel.IsOverrides)
Assert.False(symLabel.IsOverridable)
Assert.False(symLabel.IsShared)
Assert.Equal(Of Accessibility)(Accessibility.NotApplicable, symLabel.DeclaredAccessibility)
Assert.Equal(1, symLabel.Locations.Length)
Assert.Equal("Public Sub Main()", symLabel.ContainingSymbol.ToString)
Assert.Equal("Public Sub Main()", symLabel.ContainingMethod.ToString)
Assert.Equal(1, symLabel.Locations.Length)
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolFromVariableName()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
' top of file
Option Strict Off
Imports System.Collections
Namespace N1
Partial Class C1
Private aa, b$, aa$, b()
End Class
End Namespace
</file>
<file name="b.vb">
Option Strict Off
Namespace N1
Partial Class C1
public aa As String
Function f(xxx as integer, yyy as string) As integer
dim aaa, bbb, ccc as Integer, ccc$
return ccc
End Function
End Class
End Namespace
</file>
</compilation>, options)
Dim expectedErrors =
<errors>
BC30260: 'aa' is already declared as 'Private aa As Object' in this class.
Private aa, b$, aa$, b()
~~~
BC30260: 'b' is already declared as 'Private b As String' in this class.
Private aa, b$, aa$, b()
~
BC30260: 'aa' is already declared as 'Private aa As Object' in this class.
public aa As String
~~
BC42024: Unused local variable: 'aaa'.
dim aaa, bbb, ccc as Integer, ccc$
~~~
BC42024: Unused local variable: 'bbb'.
dim aaa, bbb, ccc as Integer, ccc$
~~~
BC30288: Local variable 'ccc' is already declared in the current block.
dim aaa, bbb, ccc as Integer, ccc$
~~~~
BC42024: Unused local variable: 'ccc'.
dim aaa, bbb, ccc as Integer, ccc$
~~~~
</errors>
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim treeB = CompilationUtils.GetTree(compilation, "b.vb")
Dim bindingsB = compilation.GetSemanticModel(treeB)
Dim syntax As ModifiedIdentifierSyntax = Nothing
Dim varSymbol1 = GetVariableSymbol(compilation, bindingsA, "a.vb", "aa", syntax)
Assert.NotNull(varSymbol1)
Assert.Equal("aa", varSymbol1.Name)
Assert.Equal(SymbolKind.Field, varSymbol1.Kind)
Assert.Equal("System.Object", DirectCast(varSymbol1, FieldSymbol).Type.ToTestDisplayString())
Assert.Equal(1, varSymbol1.Locations.Length())
Assert.True(syntax.SpanStart = varSymbol1.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = varSymbol1.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, varSymbol1))
Dim varSymbol2 = GetVariableSymbol(compilation, bindingsA, "a.vb", "aa$", syntax)
Assert.NotNull(varSymbol2)
Assert.Equal("aa", varSymbol2.Name)
Assert.Equal(SymbolKind.Field, varSymbol2.Kind)
Assert.Equal("System.String", DirectCast(varSymbol2, FieldSymbol).Type.ToTestDisplayString())
Assert.Equal(1, varSymbol2.Locations.Length())
Assert.True(syntax.SpanStart = varSymbol2.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = varSymbol2.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, varSymbol2))
Dim varSymbol3 = GetVariableSymbol(compilation, bindingsA, "a.vb", "b$", syntax)
Assert.NotNull(varSymbol3)
Assert.Equal("b", varSymbol3.Name)
Assert.Equal(SymbolKind.Field, varSymbol3.Kind)
Assert.Equal("System.String", DirectCast(varSymbol3, FieldSymbol).Type.ToTestDisplayString())
Assert.Equal(1, varSymbol3.Locations.Length())
Assert.True(syntax.SpanStart = varSymbol3.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = varSymbol3.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, varSymbol3))
Dim varSymbol4 = GetVariableSymbol(compilation, bindingsA, "a.vb", "b(", syntax)
Assert.NotNull(varSymbol4)
Assert.Equal("b", varSymbol4.Name)
Assert.Equal(SymbolKind.Field, varSymbol4.Kind)
Assert.Equal("System.Object()", DirectCast(varSymbol4, FieldSymbol).Type.ToTestDisplayString())
Assert.Equal(1, varSymbol4.Locations.Length())
Assert.True(syntax.SpanStart = varSymbol4.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = varSymbol4.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, varSymbol4))
Dim varSymbol5 = GetVariableSymbol(compilation, bindingsB, "b.vb", "aa", syntax)
Assert.NotNull(varSymbol5)
Assert.Equal("aa", varSymbol5.Name)
Assert.Equal(SymbolKind.Field, varSymbol5.Kind)
Assert.Equal("System.String", DirectCast(varSymbol5, FieldSymbol).Type.ToTestDisplayString())
Assert.Equal(1, varSymbol5.Locations.Length())
Assert.True(syntax.SpanStart = varSymbol5.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = varSymbol5.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, varSymbol5))
Dim varSymbol6 = GetVariableSymbol(compilation, bindingsB, "b.vb", "yyy", syntax)
Assert.NotNull(varSymbol6)
Assert.Equal("yyy", varSymbol6.Name)
Assert.Equal(SymbolKind.Parameter, varSymbol6.Kind)
Assert.Equal("System.String", DirectCast(varSymbol6, ParameterSymbol).Type.ToTestDisplayString())
Assert.Equal(1, varSymbol6.Locations.Length())
Assert.True(syntax.SpanStart = varSymbol6.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = varSymbol6.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, varSymbol6))
Dim varSymbol7 = GetVariableSymbol(compilation, bindingsB, "b.vb", "ccc$", syntax)
Assert.NotNull(varSymbol7)
Assert.Equal("ccc", varSymbol7.Name)
Assert.Equal(SymbolKind.Local, varSymbol7.Kind)
Assert.Equal("System.String", DirectCast(varSymbol7, LocalSymbol).Type.ToTestDisplayString())
Assert.Equal(1, varSymbol7.Locations.Length())
Assert.True(syntax.SpanStart = varSymbol7.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = varSymbol7.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, varSymbol7))
Dim varSymbol8 = GetVariableSymbol(compilation, bindingsB, "b.vb", "ccc as Integer", syntax)
Assert.NotNull(varSymbol8)
Assert.Equal("ccc", varSymbol8.Name)
Assert.Equal(SymbolKind.Local, varSymbol8.Kind)
Assert.Equal("System.Int32", DirectCast(varSymbol8, LocalSymbol).Type.ToTestDisplayString())
Assert.Equal(1, varSymbol8.Locations.Length())
Assert.True(syntax.SpanStart = varSymbol8.Locations.Item(0).SourceSpan.Start OrElse
syntax.SpanStart = varSymbol8.Locations.Item(1).SourceSpan.Start,
GetStartSpanErrorMessage(syntax, varSymbol8))
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub Locals()
Dim c = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
Module Program
Sub Main(args As String())
Dim $32 = 45
Dim $45 = 55
End Sub
End Module
</file>
</compilation>)
c.VerifyDiagnostics(
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_IllegalChar, "$"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_IllegalChar, "$"))
End Sub
<Fact()>
Public Sub TestGetDeclaredSymbolArrayField()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Class C
Public F(2) As Integer
End Class
</file>
</compilation>)
Dim tree = CompilationUtils.GetTree(compilation, "a.vb")
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToFullString().IndexOf("F(2)", StringComparison.Ordinal)).Parent
Dim symbol = DirectCast(semanticModel.GetDeclaredSymbol(node), FieldSymbol)
Assert.Equal("F", symbol.Name)
Assert.Equal("System.Int32()", symbol.Type.ToTestDisplayString())
End Sub
<WorkItem(543476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543476")>
<Fact()>
Public Sub BindingLocalConstantValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="BindingLocalConstantValue">
<file name="a.vb">
Imports System
Module M1
Sub Main()
const c1 as integer = 100 'BIND:"100"
const c2 as string = "Hi There" 'BIND1:""Hi There""
const c3 As AttributeTargets = AttributeTargets.Property 'BIND2:"AttributeTargets.Property"
const c5 As DateTime = #2/24/2012# 'BIND3:"#2/24/2012#"
const c6 As Decimal = 99.99D 'BIND4:"99.99D"
const c7 = nothing 'BIND5:"nothing"
const c8 as string = nothing 'BIND6:"nothing"
dim s = sub()
const c1 as integer = 100 'BIND7:"100"
const c2 as string = "Hi There" 'BIND8:""Hi There""
const c3 As AttributeTargets = AttributeTargets.Property 'BIND9:"AttributeTargets.Property"
const c5 As DateTime = #2/24/2012# 'BIND10:"#2/24/2012#"
const c6 As Decimal = 99.99D 'BIND11:"99.99D"
const c7 = nothing 'BIND12:"nothing"
const c8 as string = nothing 'BIND13:"nothing"
end sub
End Sub
End Module
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 0)
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(100, semanticInfo.ConstantValue.Value)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 1)
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal("Hi There", semanticInfo.ConstantValue.Value)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 2)
Assert.Equal("System.AttributeTargets", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(AttributeTargets.Property, CType(semanticInfo.ConstantValue.Value, AttributeTargets))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 3)
Assert.Equal("System.DateTime", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(#2/24/2012#, CType(semanticInfo.ConstantValue.Value, DateTime))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 4)
Assert.Equal("System.Decimal", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(99.99D, CType(semanticInfo.ConstantValue.Value, Decimal))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 5)
Assert.Equal(Nothing, semanticInfo.Type)
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(Nothing, semanticInfo.ConstantValue.Value)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 6)
Assert.Equal(Nothing, semanticInfo.Type)
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(Nothing, semanticInfo.ConstantValue.Value)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 7)
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(100, semanticInfo.ConstantValue.Value)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 8)
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal("Hi There", semanticInfo.ConstantValue.Value)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 9)
Assert.Equal("System.AttributeTargets", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(AttributeTargets.Property, CType(semanticInfo.ConstantValue.Value, AttributeTargets))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 10)
Assert.Equal("System.DateTime", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(#2/24/2012#, CType(semanticInfo.ConstantValue.Value, DateTime))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 11)
Assert.Equal("System.Decimal", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(99.99D, CType(semanticInfo.ConstantValue.Value, Decimal))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 12)
Assert.Equal(Nothing, semanticInfo.Type)
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(Nothing, semanticInfo.ConstantValue.Value)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb", 13)
Assert.Equal(Nothing, semanticInfo.Type)
Assert.Equal(True, semanticInfo.ConstantValue.HasValue)
Assert.Equal(Nothing, semanticInfo.ConstantValue.Value)
End Sub
<WorkItem(543476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543476")>
<Fact()>
Public Sub BindingLocalConstantVariable()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="BindingLocalConstantVariable">
<file name="a.vb">
Imports System
Module M1
Sub Main()
const c1 as integer = 100 'BIND:"c1"
const c2 as string = "Hi There" 'BIND1:"c2"
const c3 As AttributeTargets = AttributeTargets.Property 'BIND2:"c3"
const c4 As DateTime = #2/24/2012# 'BIND3:"c4"
const c5 As Decimal = 99.99D 'BIND4:"c5"
const c6 = nothing 'BIND5:"c6"
const c7 as string = nothing 'BIND6:"c7"
dim s = sub()
const c1 as integer = 100 'BIND7:"c1"
const c2 as string = "Hi There" 'BIND8:"c2"
const c3 As AttributeTargets = AttributeTargets.Property 'BIND9:"c3"
const c4 As DateTime = #2/24/2012# 'BIND10:"c4"
const c5 As Decimal = 99.99D 'BIND11:"c5"
end sub
End Sub
End Module
</file>
</compilation>)
Dim model = GetSemanticModel(compilation, "a.vb")
Dim expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 0)
Dim local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(100, CType(local.ConstantValue, Integer))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal("Hi There", CType(local.ConstantValue, String))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(AttributeTargets.Property, CType(local.ConstantValue, AttributeTargets))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(#2/24/2012#, CType(local.ConstantValue, DateTime))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(99.99D, CType(local.ConstantValue, Decimal))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(Nothing, local.ConstantValue)
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(Nothing, local.ConstantValue)
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(100, CType(local.ConstantValue, Integer))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal("Hi There", CType(local.ConstantValue, String))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 9)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(AttributeTargets.Property, CType(local.ConstantValue, AttributeTargets))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 10)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(#2/24/2012#, CType(local.ConstantValue, DateTime))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 11)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.True(local.HasConstantValue)
Assert.Equal(99.99D, CType(local.ConstantValue, Decimal))
End Sub
#End Region
#Region "Regression"
<WorkItem(540374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540374")>
<Fact()>
Public Sub Bug6617()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="GetSemanticInfo">
<file name="a.vb">
Imports System
Class C
Sub M()
Dim i As Integer = New String(" "c, 10).Length
Console.Write(i)
Console.Write(New String(" "c, 10).Length)
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression)
Dim semanticInfo = model.GetSemanticInfoSummary(CType(node.AsNode(), ExpressionSyntax))
Assert.NotNull(semanticInfo.Type)
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.NotNull(semanticInfo.Symbol)
Assert.Equal("ReadOnly Property System.String.Length As System.Int32", semanticInfo.Symbol.ToTestDisplayString())
node = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 4)
semanticInfo = model.GetSemanticInfoSummary(CType(node.AsNode(), ExpressionSyntax))
Assert.NotNull(semanticInfo.Type)
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.NotNull(semanticInfo.Symbol)
Assert.Equal("ReadOnly Property System.String.Length As System.Int32", semanticInfo.Symbol.ToTestDisplayString())
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(540665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540665")>
<Fact()>
Public Sub GetSemanticInfoForPartiallyTypedMemberAccessNodes()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="GetSemanticInfoForPartiallyTypedMemberAccessNodes">
<file name="a.vb">
Imports System
Namespace NS
Class Dummy
End Class
Class Test
Function F() As String
Return Nothing
End Function
Property P() As Integer
Public Sub Main()
Call NS.
Call Dummy.
Call F.
Call P.
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As SyntaxNode = Nothing
Dim info As SemanticInfoSummary = Nothing
' CHECK: NS.
node = tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName, 3).AsNode()
Assert.Equal("NS.", node.Parent.ToString().Trim())
info = model.GetSemanticInfoSummary(CType(node, ExpressionSyntax))
Assert.Null(info.Type)
Assert.NotNull(info.Symbol)
Assert.Equal("NS", info.Symbol.ToString())
' CHECK: Dummy.
node = tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName, 5).AsNode()
Assert.Equal("Dummy.", node.Parent.ToString().Trim())
info = model.GetSemanticInfoSummary(CType(node, ExpressionSyntax))
Assert.Equal("NS.Dummy", info.Type.ToString())
' CHECK: F.
node = tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName, 7).AsNode()
Assert.Equal("F.", node.Parent.ToString().Trim())
info = model.GetSemanticInfoSummary(CType(node, ExpressionSyntax))
Assert.Equal("String", info.Type.ToString())
' CHECK: P.
node = tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName, 9).AsNode()
Assert.Equal("P.", node.Parent.ToString().Trim())
info = model.GetSemanticInfoSummary(CType(node, ExpressionSyntax))
Assert.Equal("Integer", info.Type.ToString())
End Sub
<WorkItem(541134, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541134")>
<Fact()>
Public Sub Bug7732()
Dim xml =
<compilation>
<file name="a.vb">
Module Program
Delegate Sub D(x As D)
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim delegateDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of DelegateStatementSyntax)().First()
Dim delegateSymbol = model1.GetDeclaredSymbol(delegateDecl)
Assert.Equal("Program.D", delegateSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))
End Sub
<WorkItem(541244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541244")>
<Fact()>
Public Sub GetDeclaredSymbolDelegateStatementSyntax()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
Namespace Server
Delegate Function FD(ByVal vStr As String) As String
Delegate Sub FD2(ByVal vStr As String)
Class C1
Delegate Function FD3(ByVal vStr As String) As String
Delegate Sub FD4(ByVal vStr As String)
End Class
End Namespace
</file>
</compilation>, options)
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim node = treeA.GetCompilationUnitRoot().FindToken(treeA.GetCompilationUnitRoot().ToFullString().IndexOf("Delegate", StringComparison.Ordinal)).Parent
Assert.Equal(SyntaxKind.DelegateFunctionStatement, node.Kind)
Dim symbol = bindingsA.GetDeclaredSymbol(node)
Assert.Equal("Foo.Bar.Server.FD", symbol.ToString())
node = treeA.GetCompilationUnitRoot().FindToken(treeA.GetCompilationUnitRoot().ToFullString().IndexOf("Delegate", 30, StringComparison.Ordinal)).Parent
Assert.Equal(SyntaxKind.DelegateSubStatement, node.Kind)
symbol = bindingsA.GetDeclaredSymbol(node)
Assert.Equal("Foo.Bar.Server.FD2", symbol.ToString())
node = treeA.GetCompilationUnitRoot().FindToken(treeA.GetCompilationUnitRoot().ToFullString().IndexOf("Delegate", 140, StringComparison.Ordinal)).Parent
Assert.Equal(SyntaxKind.DelegateFunctionStatement, node.Kind)
symbol = bindingsA.GetDeclaredSymbol(node)
Assert.Equal("Foo.Bar.Server.C1.FD3", symbol.ToString())
node = treeA.GetCompilationUnitRoot().FindToken(treeA.GetCompilationUnitRoot().ToFullString().IndexOf("Delegate", 160, StringComparison.Ordinal)).Parent
Assert.Equal(SyntaxKind.DelegateSubStatement, node.Kind)
symbol = bindingsA.GetDeclaredSymbol(node)
Assert.Equal("Foo.Bar.Server.C1.FD4", symbol.ToString())
End Sub
<WorkItem(541379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541379")>
<Fact()>
Public Sub GetDeclaredSymbolLambdaParamError()
Dim options = TestOptions.ReleaseDll.WithRootNamespace("Foo.Bar")
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
' Imports System ' Func won't bind without this!
Module Module1
Sub Main()
Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam As Integer)
Return lambdaParam + 1
End Function
End Sub
End Module
</file>
</compilation>, options)
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim node = treeA.GetCompilationUnitRoot().FindToken(treeA.GetCompilationUnitRoot().ToFullString().IndexOf("lambdaParam", StringComparison.Ordinal)).Parent
Dim symbol = bindingsA.GetDeclaredSymbolFromSyntaxNode(node)
Assert.NotNull(symbol)
Assert.Equal(SymbolKind.Parameter, symbol.Kind)
Assert.Equal("lambdaParam As Integer", symbol.ToDisplayString())
End Sub
<WorkItem(541425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541425")>
<Fact()>
Public Sub NoParenthesisSub()
Dim xml =
<compilation>
<file name="a.vb">
Class Class
Sub Bob
End Sub
Sub New
End Sub
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model1 = comp.GetSemanticModel(tree)
Dim memberSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodStatementSyntax)().First()
Dim memberSymbol = model1.GetDeclaredSymbol(memberSyntax)
Assert.Equal("Sub [Class].Bob()", memberSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))
End Sub
<WorkItem(542342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542342")>
<Fact()>
Public Sub SourceNamespaceSymbolMergeWithMetadata()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
Namespace System
Partial Public Class PartialClass
Public Property Prop As Integer
End Class
End Namespace
</file>
<file name="b.vb">
Namespace System
Partial Public Class PartialClass
Default Public Property Item(i As Integer) As Integer
Get
Return i
End Get
Set(value As Integer)
End Set
End Property
End Class
End Namespace
</file>
</compilation>)
Dim treeA = CompilationUtils.GetTree(compilation, "a.vb")
Dim rootA = treeA.GetCompilationUnitRoot()
Dim bindingsA = compilation.GetSemanticModel(treeA)
Dim treeB = CompilationUtils.GetTree(compilation, "b.vb")
Dim rootB = treeB.GetCompilationUnitRoot()
Dim bindingsB = compilation.GetSemanticModel(treeB)
Dim nsA = DirectCast(rootA.Members(0), NamespaceBlockSyntax)
Dim nsB = DirectCast(rootB.Members(0), NamespaceBlockSyntax)
Dim nsSymbolA = bindingsA.GetDeclaredSymbol(nsA)
Assert.NotNull(nsSymbolA)
Assert.Equal("System", nsSymbolA.ToTestDisplayString())
Assert.Equal(3, nsSymbolA.Locations.Length)
Assert.Equal(GetType(MergedNamespaceSymbol).FullName & "+CompilationMergedNamespaceSymbol", nsSymbolA.GetType().ToString())
Assert.Equal(NamespaceKind.Compilation, nsSymbolA.NamespaceKind)
Assert.Equal(2, nsSymbolA.ConstituentNamespaces.Length)
Assert.True(nsSymbolA.ConstituentNamespaces.Contains(DirectCast(compilation.SourceAssembly.GlobalNamespace.GetMembers("System").First(), NamespaceSymbol)))
Assert.True(nsSymbolA.ConstituentNamespaces.Contains(DirectCast(compilation.GetReferencedAssemblySymbol(compilation.References(0)).GlobalNamespace.GetMembers("System").First(), NamespaceSymbol)))
Dim nsSymbolB = bindingsB.GetDeclaredSymbol(nsB)
Assert.NotNull(nsSymbolB)
Assert.Equal(nsSymbolA, nsSymbolB)
Dim memSymbol = compilation.GlobalNamespace.GetMembers("System").Single()
Assert.Equal(nsSymbolA.Locations.Length, memSymbol.Locations.Length)
Assert.Equal(Of ISymbol)(nsSymbolA, memSymbol)
End Sub
<WorkItem(542595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542595")>
<Fact()>
Public Sub Bug9881Test()
Dim xml =
<compilation name="Bug9881Test">
<file name="C.vb">
Module Program
Sub Main(args As String())
Dim a = Function(x) x + 1
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(xml)
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree)
Dim binaryOp = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of BinaryExpressionSyntax)().First()
Assert.NotNull(binaryOp)
Dim info1 = model.GetSemanticInfoSummary(binaryOp)
End Sub
<WorkItem(542702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542702")>
<Fact>
Public Sub Bug10037()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M
Sub M()
Try
Catch ex As Exception When (Function(function(Function(functio
End Try
End Sub
End Module
]]></file>
</compilation>, {SystemCoreRef})
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim text = "Function(function(Function(func"
Dim position = FindPositionFromText(tree, text) + text.Length - 1
Dim node = tree.GetCompilationUnitRoot().FindToken(position).Parent
Dim identifier = DirectCast(node, ModifiedIdentifierSyntax)
Dim symbol = model.GetDeclaredSymbol(identifier)
CheckSymbol(symbol, "functio As Object")
End Sub
<WorkItem(543605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543605")>
<Fact()>
Public Sub TestGetDeclaredSymbolFromParameterInLambdaExprOfAddHandlerStatement()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="TestGetDeclaredSymbolFromEventParameter">
<file name="a.vb">
Module Program
Sub Main(args As String())
AddHandler Function(ByVal x) x
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler Function(ByVal x) x
~~~~~~~~~~~~~~~~~~~
BC30196: Comma expected.
AddHandler Function(ByVal x) x
~
BC30201: Expression expected.
AddHandler Function(ByVal x) x
~
]]></expected>)
Dim tree = CompilationUtils.GetTree(compilation, "a.vb")
Dim model = compilation.GetSemanticModel(tree)
Dim syntax As ParameterSyntax = Nothing
Dim paramSymbol1 = GetParameterSymbol(compilation, model, "a.vb", "ByVal x", syntax)
Assert.NotNull(paramSymbol1)
Assert.Equal("x As System.Object", paramSymbol1.ToTestDisplayString())
End Sub
<WorkItem(543666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543666")>
<Fact()>
Public Sub BindingLocalConstantObjectVariable()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="BindingLocalConstantObjectVariable">
<file name="a.vb">
Option Strict On
Imports System
Module M1
Class C
Function F() As Object
Const c1 As Integer = 100 'BIND:"c1"
Const c2 As Object = "Hi" & " There" 'BIND1:"c2"
Const c3 As Object = AttributeTargets.Property 'BIND2:"c3"
Const c4 As Object = #12/12/2012 1:23:45AM # 'BIND3:"c4"
Const c5 As Object = 99.99D 'BIND4:"c5"
Const c6 As Object = Nothing 'BIND5:"c6"
Dim an = New With {.p1 = c1, Key .p2 = c2, .p3 = c3, .p4 = c4, Key .p5 = c5, .p6 = c6}
Return an
End Function
End Class
Sub Main()
Dim s = Function() As Object
Const c1 As Object = -100 'BIND6:"c1"
Const c2 As Object = "q"c 'BIND7:"c2"
Const c3 As Object = True 'BIND8:"c3"
Const c4 As Object = 12345! 'BIND9:"c4"
Const c5 As Object = CByte(255) 'BIND10:"c5"
Const c6 As Object = Nothing + Nothing 'BIND11:"c6"
Dim an = New With {.p1 = c1, Key .p2 = c2, .p3 = c3, .p4 = c4, Key .p5 = c5, .p6 = c6}
Return an
End Function
End Sub
End Module
</file>
</compilation>)
Dim model = GetSemanticModel(compilation, "a.vb")
Dim expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 0)
Dim local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Int32), local.Type)
Assert.Equal(100, CType(local.ConstantValue, Integer))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_String), local.Type)
Assert.Equal("Hi There", CType(local.ConstantValue, String))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(TypeKind.Enum, local.Type.TypeKind)
Assert.Equal(AttributeTargets.Property, CType(local.ConstantValue, AttributeTargets))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_DateTime), local.Type)
Assert.Equal(#12/12/2012 1:23:45 AM#, CType(local.ConstantValue, DateTime))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Decimal), local.Type)
Assert.Equal(99.99D, CType(local.ConstantValue, Decimal))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Object), local.Type)
Assert.Equal(Nothing, local.ConstantValue)
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Int32), local.Type)
Assert.Equal(-100, CType(local.ConstantValue, Integer))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Char), local.Type)
Assert.Equal("q"c, CType(local.ConstantValue, Char))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Boolean), local.Type)
Assert.Equal(True, CType(local.ConstantValue, Boolean))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 9)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Single), local.Type)
Assert.Equal(12345.0!, CType(local.ConstantValue, Single))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 10)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Byte), local.Type)
Assert.Equal(255, CType(local.ConstantValue, Byte))
expressionSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 11)
local = DirectCast(model.GetDeclaredSymbol(expressionSyntax), LocalSymbol)
Assert.True(local.IsConst)
Assert.Equal(compilation.GetSpecialType(System_Int32), local.Type)
Assert.Equal(0, CType(local.ConstantValue, Integer))
End Sub
<Fact(), WorkItem(545106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545106")>
Public Sub GetDeclaredSymbolForDeclaredControlVariable()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Friend Module M
Sub Main(args As String())
For x? As SByte = Nothing To Nothing
Console.Write("Hi")
Next
For Each y As String In args
Next
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of ModifiedIdentifierSyntax)()
Assert.Equal(3, nodes.Count)
' x?
Dim node = nodes(1)
Assert.Equal("x?", node.ToString())
Dim sym = semanticModel.GetDeclaredSymbol(node)
Assert.NotNull(sym)
Assert.Equal(SymbolKind.Local, sym.Kind)
' y
node = nodes.Last()
Assert.Equal("y", node.ToString())
sym = semanticModel.GetDeclaredSymbol(node)
Assert.NotNull(sym)
Assert.Equal(SymbolKind.Local, sym.Kind)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(611537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611537")>
<Fact()>
Public Sub Bug611537()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Class
Namespace
Property 'BIND1:"Property"
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of PropertyStatementSyntax)()
Assert.Null(semanticModel.GetDeclaredSymbol(nodes(0)))
End Sub
<Fact(), WorkItem(747446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747446")>
Public Sub TestGetDeclaredSymbolWithChangedRootNamespace()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
Interface I1
Function F() As String
End Interface
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim fSyntax1 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.FunctionStatement, 1).AsNode(), MethodStatementSyntax)
Dim fSymbol1 = model.GetDeclaredSymbol(fSyntax1)
Assert.NotNull(fSymbol1)
Assert.Equal("Function I1.F() As System.String", fSymbol1.ToTestDisplayString())
' Create a cloned compilation with a different root namespace and perform the same semantic queries.
compilation = compilation.WithOptions(compilation.Options.WithRootNamespace("NewNs"))
Dim newTree = compilation.SyntaxTrees(0)
Dim newModel = compilation.GetSemanticModel(newTree)
Dim fSyntax2 = DirectCast(newTree.FindNodeOrTokenByKind(SyntaxKind.FunctionStatement, 1).AsNode(), MethodStatementSyntax)
Dim fSymbol2 = newModel.GetDeclaredSymbol(fSyntax2)
Assert.NotNull(fSymbol2)
Assert.Equal("Function NewNs.I1.F() As System.String", fSymbol2.ToTestDisplayString())
' Create a cloned compilation without a root namespace and perform the same semantic queries.
compilation = compilation.WithOptions(compilation.Options.WithRootNamespace(Nothing))
newTree = compilation.SyntaxTrees(0)
newModel = compilation.GetSemanticModel(newTree)
fSyntax2 = DirectCast(newTree.FindNodeOrTokenByKind(SyntaxKind.FunctionStatement, 1).AsNode(), MethodStatementSyntax)
fSymbol2 = newModel.GetDeclaredSymbol(fSyntax2)
Assert.NotNull(fSymbol2)
Assert.Equal("Function I1.F() As System.String", fSymbol2.ToTestDisplayString())
End Sub
<Fact(), WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")>
Public Sub TestGetDeclaredSymbolWithIncompleteDeclaration()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compilation">
<file name="a.vb">
Class C0
End Class
Class
Class C1
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim syntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.ClassStatement, 2).AsNode(), ClassStatementSyntax)
Dim symbol = model.GetDeclaredSymbol(syntax)
Assert.NotNull(symbol)
Assert.Equal("?", symbol.ToTestDisplayString())
Assert.Equal(TypeKind.Class, symbol.TypeKind)
End Sub
#End Region
End Class
End Namespace
|
bbarry/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelGetDeclaredSymbolAPITests.vb
|
Visual Basic
|
apache-2.0
| 134,100
|
' 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 Microsoft.CodeAnalysis.Text
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class VisualBasicSyntaxTreeTests
<Fact>
Public Sub WithRootAndOptions_ParsedTree()
Dim oldTree = SyntaxFactory.ParseSyntaxTree("Class B : End Class")
Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class")
Dim newOptions = New VisualBasicParseOptions()
Dim newTree = oldTree.WithRootAndOptions(newRoot, newOptions)
Dim newText = newTree.GetText()
Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString())
Assert.Same(newOptions, newTree.Options)
Assert.Null(newText.Encoding)
Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm)
End Sub
<Fact>
Public Sub WithRootAndOptions_ParsedTreeWithText()
Dim oldText = SourceText.From("Class B : End Class", Encoding.UTF7, SourceHashAlgorithm.Sha256)
Dim oldTree = SyntaxFactory.ParseSyntaxTree(oldText)
Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class")
Dim newOptions = New VisualBasicParseOptions()
Dim newTree = oldTree.WithRootAndOptions(newRoot, newOptions)
Dim newText = newTree.GetText()
Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString())
Assert.Same(newOptions, newTree.Options)
Assert.Same(Encoding.UTF7, newText.Encoding)
Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm)
End Sub
<Fact>
Public Sub WithRootAndOptions_DummyTree()
Dim dummy = New VisualBasicSyntaxTree.DummySyntaxTree()
Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class")
Dim newOptions = New VisualBasicParseOptions()
Dim newTree = dummy.WithRootAndOptions(newRoot, newOptions)
Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString())
Assert.Same(newOptions, newTree.Options)
End Sub
<Fact>
Public Sub WithFilePath_ParsedTree()
Dim oldTree = SyntaxFactory.ParseSyntaxTree("Class B : End Class", path:="old.vb")
Dim newTree = oldTree.WithFilePath("new.vb")
Dim newText = newTree.GetText()
Assert.Equal(newTree.FilePath, "new.vb")
Assert.Equal(oldTree.ToString(), newTree.ToString())
Assert.Null(newText.Encoding)
Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm)
End Sub
<Fact>
Public Sub WithFilePath_ParsedTreeWithText()
Dim oldText = SourceText.From("Class B : End Class", Encoding.UTF7, SourceHashAlgorithm.Sha256)
Dim oldTree = SyntaxFactory.ParseSyntaxTree(oldText, path:="old.vb")
Dim newTree = oldTree.WithFilePath("new.vb")
Dim newText = newTree.GetText()
Assert.Equal(newTree.FilePath, "new.vb")
Assert.Equal(oldTree.ToString(), newTree.ToString())
Assert.Same(Encoding.UTF7, newText.Encoding)
Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm)
End Sub
<Fact>
Public Sub WithFilePath_DummyTree()
Dim oldTree = New VisualBasicSyntaxTree.DummySyntaxTree()
Dim newTree = oldTree.WithFilePath("new.vb")
Assert.Equal(newTree.FilePath, "new.vb")
Assert.Equal(oldTree.ToString(), newTree.ToString())
End Sub
<Fact, WorkItem(12638, "https://github.com/dotnet/roslyn/issues/12638")>
Public Sub WithFilePath_Nothing()
Dim oldTree As SyntaxTree = New VisualBasicSyntaxTree.DummySyntaxTree()
Assert.Equal(String.Empty, oldTree.WithFilePath(Nothing).FilePath)
oldTree = SyntaxFactory.ParseSyntaxTree("", path:="old.vb")
Assert.Equal(String.Empty, oldTree.WithFilePath(Nothing).FilePath)
Assert.Equal(String.Empty, SyntaxFactory.ParseSyntaxTree("", path:=Nothing).FilePath)
Assert.Equal(String.Empty, VisualBasicSyntaxTree.Create(CType(oldTree.GetRoot, VisualBasicSyntaxNode), path:=Nothing).FilePath)
End Sub
End Class
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTreeTests.vb
|
Visual Basic
|
apache-2.0
| 4,495
|
Partial Public Module ClientControls
Public Class ClientMasteryTree
Public Const Width As Double = ClientSize.Small.Width / 270
Public Const Height As Double = ClientSize.Small.Height / 160
Public Structure ChampionSelect
Public Const X As Double = ClientSize.Small.Width / 270
Public Const Y As Double = ClientSize.Small.Height / 160
End Structure
Public Structure Menu
Public Const X As Double = ClientSize.Small.Width / 275
Public Const Y As Double = ClientSize.Small.Height / 195
End Structure
End Class
End Module
|
dewster/lol-mastery-manager-new-client
|
LoLMasteryManager/ClientControls/ClientMasteryTree.vb
|
Visual Basic
|
mit
| 636
|
#Region "Microsoft.VisualBasic::aac64ac5731b624d86d8aa24375f6e9c, src\metadb\SMILES\Graph\ChemicalKey.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Class ChemicalKey
'
' Properties: bond
'
' Function: ToString
'
' /********************************************************************************/
#End Region
Imports Microsoft.VisualBasic.Data.GraphTheory.Network
Public Class ChemicalKey : Inherits Edge(Of ChemicalElement)
Public Property bond As Bonds
Public Overrides Function ToString() As String
Return $"{U.elementName}{bond.Description}{V.elementName} (+{CInt(bond)})"
End Function
End Class
|
xieguigang/MassSpectrum-toolkits
|
src/metadb/SMILES/Graph/ChemicalKey.vb
|
Visual Basic
|
mit
| 2,081
|
Imports LNF
Imports LNF.Web.Models
Imports LNF.Web.Scheduler
Public Class SessionLog
Inherits Page
<Inject> Public Property Provider As IProvider
Public Property ContextBase As HttpContextBase
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ContextBase = New HttpContextWrapper(Context)
Dim helper As New SchedulerContextHelper(ContextBase, Provider)
Dim log As List(Of SessionLogMessage) = helper.GetLog().ToList()
rptSessionLog.DataSource = log
rptSessionLog.DataBind()
End Sub
End Class
|
lurienanofab/labscheduler
|
LabScheduler/SessionLog.aspx.vb
|
Visual Basic
|
mit
| 603
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.269
'
' 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("CollectionBenchmark.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
|
jakubjenis/lecture.net
|
Vb.Net/Skolenie/CollectionBenchmark/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,726
|
''' <summary>
''' Provides methods to convert from a color space to an other.
''' </summary>
Public NotInheritable Class ColorHelper
Private Sub New()
'
End Sub
#Region "Color processing"
''' <summary>
''' Gets the given color based on a color and an alpha.
''' </summary>
''' <param name="c">Color applying the alpha channel.</param>
''' <param name="alpha">Alpha channel value.</param>
Public Shared Function GetAlphaColor(ByVal c As Color, ByVal alpha As Integer) As Color
If (c <> Color.Transparent And (alpha > -1 And alpha < 256)) Then
Return Color.FromArgb(alpha, c)
End If
Return Color.Empty
End Function
''' <summary>
''' Blends two colors.
''' </summary>
''' <param name="c1">First color to blend</param>
''' <param name="c2">Second color to blend</param>
''' <param name="ratio">Blend ratio. 0.5 will give even blend, 1.0 will return color1, 0.0 will return color2 and so on.</param>
Public Shared Function GetBlendColor(ByVal c1 As Color, ByVal c2 As Color, ByVal ratio As Double) As Color
Dim r As Single = CSng(ratio)
Dim ir As Single = 1.0F - r
Dim rgb1() As Single = {CSng(c1.R) / 255.0F, _
CSng(c1.G) / 255.0F, _
CSng(c1.B) / 255.0F}
Dim rgb2() As Single = {CSng(c2.R) / 255.0F, _
CSng(c2.G) / 255.0F, _
CSng(c2.B) / 255.0F}
Return Color.FromArgb(CInt(rgb1(0) * r + rgb2(0) * ir), _
CInt(rgb1(1) * r + rgb2(1) * ir), _
CInt(rgb1(2) * r + rgb2(2) * ir))
End Function
''' <summary>
''' Makes an even blend between two colors.
''' </summary>
''' <param name="c1">First color to blend</param>
''' <param name="c2">Second color to blend</param>
Public Shared Function GetBlendColor(ByVal c1 As Color, ByVal c2 As Color) As Color
Return GetBlendColor(c1, c2, 0.5)
End Function
''' <summary>
''' Gets the "distance" between two colors.
''' RGB colors must be normalized (eg. values in [0.0, 1.0]).
''' </summary>
''' <param name="r1">First color red component.</param>
''' <param name="g1">First color green component.</param>
''' <param name="b1">First color blue component.</param>
''' <param name="r2">Second color red component.</param>
''' <param name="g2">Second color green component.</param>
''' <param name="b2">Second color blue component.</param>
Public Shared Function GetColorDistance(ByVal r1 As Double, ByVal g1 As Double, ByVal b1 As Double, ByVal r2 As Double, ByVal g2 As Double, ByVal b2 As Double) As Double
Dim a As Double = r2 - r1
Dim b As Double = g2 - g1
Dim c As Double = b2 - b1
Return Math.Sqrt(a * a + b * b + c * c)
End Function
''' <summary>
''' Gets the "distance" between two colors.
''' RGB colors must be normalized (eg. values in [0.0, 1.0]).
''' </summary>
''' <param name="color1">First color [r,g,b]</param>
''' <param name="color2">Second color [r,g,b]</param>
Public Shared Function GetColorDistance(ByVal color1() As Double, ByVal color2() As Double) As Double
Return GetColorDistance(color1(0), color1(1), color1(2), color2(0), color2(1), color2(2))
End Function
''' <summary>
''' Gets the "distance" between two colors.
''' </summary>
''' <param name="color1">First color.</param>
''' <param name="color2">Second color.</param>
Public Shared Function GetColorDistance(ByVal color1 As Color, ByVal color2 As Color) As Double
Dim rgb1() As Double = {CDbl(color1.R) / 255.0F, _
CDbl(color1.G) / 255.0F, _
CDbl(color1.B) / 255.0F}
Dim rgb2() As Double = {CDbl(color2.R) / 255.0F, _
CDbl(color2.G) / 255.0F, _
CDbl(color2.B) / 255.0F}
Return GetColorDistance(rgb1, rgb2)
End Function
#End Region
#Region "Light Spectrum processing"
''' <summary>
''' Gets visible colors (color wheel).
''' </summary>
''' <param name="alpha">
''' The alpha value used for each colors.
''' </param>
Public Shared Function GetWheelColors(ByVal alpha As Integer) As Color()
Dim temp As Color
Dim colorCount As Integer = 6 * 256
Dim Colors(colorCount) As Color
For i As Integer = 0 To colorCount - 1
temp = HSBtoColor((CDbl(i) * 255.0) / CDbl(colorCount), 255.0, 255.0)
Colors(i) = Color.FromArgb(alpha, temp.R, temp.G, temp.B)
Next
Return Colors
End Function
''' <summary>
''' Gets visible spectrum colors.
''' </summary>
''' <param name="alpha">The alpha value used for each colors.</param>
Public Shared Function GetSpectrumColors(ByVal alpha As Integer) As Color()
Dim Colors(256 * 6) As Color
For i As Integer = 0 To 255
Colors(i) = Color.FromArgb(alpha, 255, i, 0)
Colors(i + 256) = Color.FromArgb(alpha, 255 - i, 255, 0)
Colors(i + 256 * 2) = Color.FromArgb(alpha, 0, 255, i)
Colors(i + 256 * 3) = Color.FromArgb(alpha, 0, 255 - i, 255)
Colors(i + 256 * 4) = Color.FromArgb(alpha, i, 0, 255)
Colors(i + 256 * 5) = Color.FromArgb(alpha, 255, 0, 255 - i)
Next
Return Colors
End Function
''' <summary>
''' Gets visible spectrum colors.
''' </summary>
Public Shared Function GetSpectrumColors() As Color()
Return GetSpectrumColors(255)
End Function
#End Region
#Region "Hex Color Conversion"
''' <summary>
''' Converts a Hex color to a .net Color.
''' </summary>
''' <param name="hexColor">The desired hexadecimal color to convert.</param>
Public Shared Function HEXtoColor(ByVal hexColor As String) As Color
If hexColor Is String.Empty Then Return Color.Empty
hexColor = hexColor.Trim
If hexColor.Chars(0) = "#" Then hexColor = hexColor.Substring(1)
If hexColor.Length < 6 Then hexColor = "000000".Substring(0, 6 - hexColor.Length) + hexColor
Return Color.FromArgb(CInt("&h" + hexColor.Substring(0, 2)), _
CInt("&h" + hexColor.Substring(2, 2)), _
CInt("&h" + hexColor.Substring(4, 2)))
End Function
''' <summary>
''' Converts a RGB color format to an hexadecimal color.
''' </summary>
''' <param name="r">The Red value.</param>
''' <param name="g">The Green value.</param>
''' <param name="b">The Blue value.</param>
Public Shared Function RGBtoHEX(ByVal r As Integer, ByVal g As Integer, ByVal b As Integer) As String
Return String.Format("#{0:x2}{1:x2}{2:x2}", r, g, b).ToUpper
End Function
''' <summary>
''' Converts a .Net Color format to an hexadecimal color.
''' </summary>
''' <param name="c">The .net color to convert.</param>
Public Shared Function ColorToHEX(ByVal c As Color) As String
Return RGBtoHEX(c.R, c.G, c.B)
End Function
#End Region
#Region "HSB Convert"
#Region "HSBtoRGB"
''' <summary>
''' Converts HSB to RGB.
''' </summary>
''' <param name="hsb">The HSB structure to convert.</param>
Public Shared Function HSBtoRGB(ByVal HSB As HSB) As RGB
Return HSBtoRGB(HSB.Hue, HSB.Saturation, HSB.Brightness)
End Function
''' <summary>
''' Converts HSB to RGB.
''' </summary>
''' <param name="H">Hue value. (must be between 0 and 360)</param>
''' <param name="S">Saturation value (must be between 0 and 100).</param>
''' <param name="b">Brigthness value (must be between 0 and 100).</param>
Public Shared Function HSBtoRGB(ByVal h As Integer, ByVal s As Integer, ByVal b As Integer) As RGB
Return HSBtoRGB(CDbl(h), CDbl(s / 100.0), CDbl(b / 100.0))
End Function
''' <summary>
''' Converts HSB to a RGB.
''' </summary>
''' <param name="h">Hue value (must be between 0 and 360).</param>
''' <param name="s">Saturation value (must be between 0 and 1).</param>
''' <param name="b">Brightness value (must be between 0 and 1).</param>
Public Shared Function HSBtoRGB(ByVal h As Double, ByVal s As Double, ByVal b As Double) As RGB
Dim red As Double = 0.0
Dim green As Double = 0.0
Dim blue As Double = 0.0
If (s = 0) Then
red = b
green = b
blue = b
Else
' the color wheel consists of 6 sectors. Figure out which sector you're in.
Dim sectorPos As Double = h / 60.0
Dim sectorNumber As Integer = CInt(Math.Floor(sectorPos))
' get the fractional part of the sector
Dim fractionalSector As Double = sectorPos - sectorNumber
' calculate values for the three axes of the color.
Dim p As Double = b * (1.0 - s)
Dim q As Double = b * (1.0 - (s * fractionalSector))
Dim t As Double = b * (1.0 - (s * (1 - fractionalSector)))
' assign the fractional colors to r, g, and b based on the sector the angle is in.
Select Case sectorNumber
Case 0
red = b
green = t
blue = p
Case 1
red = q
green = b
blue = p
Case 2
red = p
green = b
blue = t
Case 3
red = p
green = q
blue = b
Case 4
red = t
green = p
blue = b
Case 5
red = b
green = p
blue = q
End Select
End If
'Return New RGB(cint((Math.Ceiling(T(0) * 255.0)), _
' cint((Math.Ceiling(T(1) * 255.0)), _
' cint((Math.Ceiling(T(2) * 255.0)))
Return New RGB(CInt(Double.Parse(String.Format("{0:0.00}", red * 255.0))), _
CInt(Double.Parse(String.Format("{0:0.00}", green * 255.0))), _
CInt(Double.Parse(String.Format("{0:0.00}", blue * 255.0))))
End Function
#End Region
#Region "HSBtoColor"
''' <summary>
''' Converts HSB to .Net Color.
''' </summary>
''' <param name="hsb">the HSB structure to convert.</param>
Public Shared Function HSBtoColor(ByVal HSB As HSB) As Color
Return HSBtoColor(HSB.Hue, HSB.Saturation, HSB.Brightness)
End Function
''' <summary>
''' Converts HSB to a .Net Color.
''' </summary>
''' <param name="h">Hue value (must be between 0 and 360).</param>
''' <param name="s">Saturation value (must be between 0 and 1).</param>
''' <param name="b">Brightness value (must be between 0 and 1).</param>
Public Shared Function HSBtoColor(ByVal h As Double, ByVal s As Double, ByVal b As Double) As Color
Dim rgb As RGB = HSBtoRGB(h, s, b)
Return Color.FromArgb(rgb.Red, rgb.Green, rgb.Blue)
End Function
#End Region
#End Region
#Region "RGB Convert"
#Region "RGBtoHSB"
''' <summary>
''' Converts .Net Color to HSB.
''' </summary>
Public Shared Function RGBtoHSB(ByVal c As Color) As HSB
Return RGBtoHSB(c.R, c.G, c.B)
End Function
''' <summary>
''' Converts RGB to HSB.
''' </summary>
Public Shared Function RGBtoHSB(ByVal rgb As RGB) As HSB
Return RGBtoHSB(rgb.Red, rgb.Green, rgb.Blue)
End Function
''' <summary>
''' Converts RGB to HSB.
''' </summary>
Public Shared Function RGBtoHSB(ByVal red As Integer, ByVal green As Integer, ByVal blue As Integer) As HSB
Dim h As Double = 0.0
Dim s As Double = 0.0
' normalizes red-green-blue values
Dim nRed As Double = CDbl(red) / 255.0
Dim nGreen As Double = CDbl(green) / 255.0
Dim nBlue As Double = CDbl(blue) / 255.0
Dim max As Double = Math.Max(nRed, Math.Max(nGreen, nBlue))
Dim min As Double = Math.Min(nRed, Math.Min(nGreen, nBlue))
' Hue
If (max = nRed) And (nGreen >= nBlue) Then
If (max - min = 0) Then
h = 0.0
Else
h = 60 * (nGreen - nBlue) / (max - min)
End If
ElseIf (max = nRed) And (nGreen < nBlue) Then
h = 60 * (nGreen - nBlue) / (max - min) + 360
ElseIf (max = nGreen) Then
h = 60 * (nBlue - nRed) / (max - min) + 120
ElseIf (max = nBlue) Then
h = 60 * (nRed - nGreen) / (max - min) + 240
End If
' Saturation
If (max = 0) Then
s = 0.0
Else
s = 1.0 - (min / max)
End If
Return New HSB(h, s, max)
End Function
#End Region
#End Region
End Class
|
willowslaboratory/WLABV3
|
library.willowslab.net/Library_v3/References/ColorHelper.vb
|
Visual Basic
|
mit
| 13,149
|
Imports System
Class PkgCmdIDList
Private Sub New()
'
End Sub
End Class
|
chrisdias/VSKeyBindings
|
PkgCmdID.vb
|
Visual Basic
|
mit
| 106
|
Imports System.Data.SQLite
Imports System.IO
Public Class SQLiteStorage
Inherits Storage
Private _conn As SQLiteConnection
Private InitDBSQL As String = My.Resources.ddl
Private _InitDBCommand As SQLiteCommand
Const EnqueueSendSQL As String = "INSERT INTO [ReadySend] ([Time], [RemoteAddress], [RemoteAddressType], [Message]) VALUES (@Time, @RemoteAddress, @RemoteAddressType, @Message)"
Private _EnqueueSendCommand As SQLiteCommand
Const DequeueSendSQL As String = "SELECT [ID], [Time], [RemoteAddress], [RemoteAddressType], [Message] FROM [ReadySend] LIMIT 1"
Private _DequeueSendCommand As SQLiteCommand
Const GetReadySendByIDSQL As String = "SELECT [ID], [Time], [RemoteAddress], [RemoteAddressType], [Message] FROM [ReadySend] WHERE [ID]=@id"
Private _GetReadySendByIDCommand As SQLiteCommand
Const DeleteReadySendByIDSQL As String = "DELETE FROM [ReadySend] WHERE [ID]=@id"
Private _DeleteReadySendByIDCommand As SQLiteCommand
Const ReadySendCountSQL As String = "SELECT COUNT(*) FROM [ReadySend]"
Private _ReadySendCountCommand As SQLiteCommand
Const InsertSentSQL As String = "INSERT INTO [Sent] ([Time], [RemoteAddress], [RemoteAddressType], [Message], [Succeeded]) VALUES (@Time, @RemoteAddress, @RemoteAddressType, @Message, @Succeeded)"
Private _InsertSentCommand As SQLiteCommand
Const InsertReceivedSQL As String = "INSERT INTO [Received] ([Time], [RemoteAddress], [RemoteAddressType], [Message]) VALUES (@Time, @RemoteAddress, @RemoteAddressType, @Message)"
Private _InsertReceivedCommand As SQLiteCommand
Const GetReceivedByIDSQL As String = "SELECT [ID], [Time], [RemoteAddress], [RemoteAddressType], [Message] FROM [Received] WHERE [ID]=@id"
Private _GetReceivedByIDCommand As SQLiteCommand
Const DeleteReceivedByIDSQL As String = "DELETE FROM [Received] WHERE [ID]=@id"
Private _DeleteReceivedByIDCommand As SQLiteCommand
Const ListReceivedSQL As String = "SELECT [ID], [Time], [RemoteAddress], [RemoteAddressType], [Message] FROM [Received]"
Private _ListReceivedCommand As SQLiteCommand
Const ListContactsSQL As String = "SELECT [ID], [Name], [Number], [Remark] FROM [Contacts]"
Private _ListContactsCommand As SQLiteCommand
Const GetContactsByNameSQL As String = "SELECT [ID], [Name], [Number], [Remark] FROM [Contacts] WHERE [Name]=@Name"
Private _GetContactsByNameCommand As SQLiteCommand
Const SetContactsByNameSQL As String = "UPDATE [Contacts] SET [Number]=@Number, [Remark]=@Remark WHERE [Name]=@Name"
Private _SetContactsByNameCommand As SQLiteCommand
Const InsertContactsSQL As String = "INSERT INTO [Contacts] ([Name], [Number], [Remark]) VALUES (@Name, @Number, @Remark)"
Private _InsertContactsCommand As SQLiteCommand
Const DeleteContactsByNameSQL As String = "DELETE FROM [Contacts] WHERE [Name]=@Name"
Private _DeleteContactsByNameCommand As SQLiteCommand
Const ListSettingsSQL As String = "SELECT [Key], [Value] FROM [Settings]"
Private _ListSettingsCommand As SQLiteCommand
Const GetSettingsByKeySQL As String = "SELECT [Key], [Value] FROM [Settings] WHERE [Key]=@Key"
Private _GetSettingsByKeyCommand As SQLiteCommand
Const SetSettingsByKeySQL As String = "UPDATE [Settings] SET [Value]=@Value WHERE [Key]=@Key"
Private _SetSettingsByKeyCommand As SQLiteCommand
Const InsertSettingsSQL As String = "INSERT INTO [Settings] ([Key], [Value]) VALUES (@Key, @Value)"
Private _InsertSettingsCommand As SQLiteCommand
Private Sub initCommands()
_InitDBCommand = New SQLiteCommand(InitDBSQL, _conn)
_EnqueueSendCommand = New SQLiteCommand(EnqueueSendSQL, _conn)
_DequeueSendCommand = New SQLiteCommand(DequeueSendSQL, _conn)
_GetReadySendByIDCommand = New SQLiteCommand(GetReadySendByIDSQL, _conn)
_DeleteReadySendByIDCommand = New SQLiteCommand(DeleteReadySendByIDSQL, _conn)
_ReadySendCountCommand = New SQLiteCommand(ReadySendCountSQL, _conn)
_InsertSentCommand = New SQLiteCommand(InsertSentSQL, _conn)
_InsertReceivedCommand = New SQLiteCommand(InsertReceivedSQL, _conn)
_GetReceivedByIDCommand = New SQLiteCommand(GetReceivedByIDSQL, _conn)
_DeleteReceivedByIDCommand = New SQLiteCommand(DeleteReceivedByIDSQL, _conn)
_ListReceivedCommand = New SQLiteCommand(ListReceivedSQL, _conn)
_ListContactsCommand = New SQLiteCommand(ListContactsSQL, _conn)
_GetContactsByNameCommand = New SQLiteCommand(GetContactsByNameSQL, _conn)
_SetContactsByNameCommand = New SQLiteCommand(SetContactsByNameSQL, _conn)
_InsertContactsCommand = New SQLiteCommand(InsertContactsSQL, _conn)
_DeleteContactsByNameCommand = New SQLiteCommand(DeleteContactsByNameSQL, _conn)
_ListSettingsCommand = New SQLiteCommand(ListSettingsSQL, _conn)
_GetSettingsByKeyCommand = New SQLiteCommand(GetSettingsByKeySQL, _conn)
_SetSettingsByKeyCommand = New SQLiteCommand(SetSettingsByKeySQL, _conn)
_InsertSettingsCommand = New SQLiteCommand(InsertSettingsSQL, _conn)
End Sub
Public Sub New(dbfilename As String, Optional ByVal pwd As String = Nothing)
Dim sb As New SQLiteConnectionStringBuilder
sb.DataSource = dbfilename
If pwd IsNot Nothing Then
sb.Password = pwd
End If
_conn = New SQLiteConnection(sb.ToString)
_conn.Open()
initCommands()
Using cmd As SQLiteCommand = _InitDBCommand.Clone()
cmd.ExecuteNonQuery()
'Utils.dbg("Built Database Structure")
End Using
End Sub
Public Overrides Sub AckSent(smsid As String, Succeeded As Boolean)
Dim sms = GetReadySend(smsid)
DeleteReadySend(smsid)
Using cmd As SQLiteCommand = _InsertSentCommand.Clone()
AddParametersWithShortMessage(cmd, sms)
cmd.Parameters.AddWithValue("Succeeded", Succeeded)
cmd.ExecuteReader()
End Using
End Sub
Public Sub DeleteReadySend(smsid As String)
Using cmd As SQLiteCommand = _DeleteReadySendByIDCommand.Clone()
cmd.Parameters.AddWithValue("ID", Int32.Parse(smsid))
cmd.ExecuteNonQuery()
End Using
End Sub
Public Overrides Sub DeleteReceived(smsid As String)
Using cmd As SQLiteCommand = _DeleteReceivedByIDCommand.Clone()
cmd.Parameters.AddWithValue("ID", Int32.Parse(smsid))
cmd.ExecuteNonQuery()
End Using
End Sub
Private Function ReaderToSMS(rd As SQLiteDataReader) As ShortMessage
If rd.Read() Then
Dim sms As New ShortMessage
sms.IDForModule = rd.GetInt32(0)
sms.UUID = rd.GetInt32(0)
sms.Time = rd.GetDateTime(1)
sms.RemoteAddress = rd.GetString(2)
sms.RemoteAddressType = Convert.ToInt32(rd.GetString(3))
sms.Message = rd.GetString(4)
Return sms
Else
Return Nothing
End If
End Function
Private Sub AddParametersWithShortMessage(cmd As SQLiteCommand, sms As ShortMessage)
cmd.Parameters.AddWithValue("Time", Now)
cmd.Parameters.AddWithValue("RemoteAddress", sms.RemoteAddress)
cmd.Parameters.AddWithValue("RemoteAddressType", sms.RemoteAddressType)
cmd.Parameters.AddWithValue("Message", sms.Message)
End Sub
Public Overrides Function DequeueSend() As ShortMessage
Using cmd As SQLiteCommand = _DequeueSendCommand.Clone()
Dim rd = cmd.ExecuteReader()
Return ReaderToSMS(rd)
End Using
End Function
Public Overloads Overrides Sub EnqueueSend(sms As ShortMessage)
Using cmd As SQLiteCommand = _EnqueueSendCommand.Clone()
AddParametersWithShortMessage(cmd, sms)
cmd.ExecuteNonQuery()
End Using
End Sub
Public Overrides Sub ExportReceived(smsid As String, copyto As String)
Dim sms = GetReceived(smsid)
Using sw As New StreamWriter(copyto)
sw.WriteLine(sms.IDForModule.ToString)
sw.WriteLine(sms.Time.ToString)
sw.WriteLine(sms.RemoteAddress)
sw.WriteLine(DirectCast(sms.RemoteAddressType, Integer))
sw.WriteLine(sms.Message)
sw.Flush()
End Using
End Sub
Public Overrides Function GetReadySend(smsid As String) As ShortMessage
Using cmd As SQLiteCommand = _GetReadySendByIDCommand.Clone()
cmd.Parameters.AddWithValue("ID", Int32.Parse(smsid))
Dim rd = cmd.ExecuteReader()
Return ReaderToSMS(rd)
End Using
End Function
Public Overrides Function ReadySendCount() As Integer
Using cmd As SQLiteCommand = _ReadySendCountCommand.Clone()
Dim rd = cmd.ExecuteReader()
rd.Read()
Return rd.GetInt32(0)
End Using
End Function
Public Overrides Function GetReceived(smsid As String) As ShortMessage
Using cmd As SQLiteCommand = _GetReceivedByIDCommand.Clone()
cmd.Parameters.AddWithValue("ID", Int32.Parse(smsid))
Dim rd = cmd.ExecuteReader()
Return ReaderToSMS(rd)
End Using
End Function
Public Overrides Sub InsertReceived(sms As ShortMessage)
Using cmd As SQLiteCommand = _InsertReceivedCommand.Clone()
AddParametersWithShortMessage(cmd, sms)
cmd.ExecuteNonQuery()
End Using
End Sub
Public Overrides Function ListReceived() As List(Of ShortMessage)
Using cmd As SQLiteCommand = _ListReceivedCommand.Clone()
Dim rd = cmd.ExecuteReader()
Dim lastsms = ReaderToSMS(rd)
Dim lstsms As New List(Of ShortMessage)
Do While lastsms IsNot Nothing
lstsms.Add(lastsms)
lastsms = ReaderToSMS(rd)
Loop
Return lstsms
End Using
End Function
Public Overrides Sub InitContacts()
Using cmd As SQLiteCommand = _ListContactsCommand.Clone()
Dim rd = cmd.ExecuteReader()
_ContactsCache = New List(Of ContactPerson)
Do While rd.Read()
Dim cp As New ContactPerson
cp.ID = rd.GetInt32(0)
cp.Name = rd.GetString(1)
cp.Number = rd.GetString(2)
cp.Remark = rd.GetString(3)
_ContactsCache.Add(cp)
Loop
End Using
End Sub
Protected Overrides Sub InternalDeleteContactsRecord(Name As String)
Using cmd As SQLiteCommand = _DeleteContactsByNameCommand.Clone()
cmd.Parameters.AddWithValue("Name", Name)
cmd.ExecuteNonQuery()
End Using
End Sub
Protected Overrides Sub InternalInsertContactsRecord(cp As ContactPerson)
Using cmd As SQLiteCommand = _InsertContactsCommand.Clone()
cmd.Parameters.AddWithValue("Name", cp.Name)
cmd.Parameters.AddWithValue("Number", cp.Number)
cmd.Parameters.AddWithValue("Remark", cp.Remark)
cmd.ExecuteNonQuery()
End Using
End Sub
Public Overrides Sub InitSettings()
Dim ak(_SettingsCache.Keys.Count - 1) As String
_SettingsCache.Keys.CopyTo(ak, 0)
For Each k In ak
Dim v = InternalGetSetting(k)
If v IsNot Nothing Then
_SettingsCache(k) = v
Else
'数据库中没有则插入默认值
InternalInsertSetting(k, _SettingsCache(k))
End If
Next
Using cmd As SQLiteCommand = _ListSettingsCommand.Clone()
Dim rd = cmd.ExecuteReader()
Do While rd.Read()
Dim k = rd.GetString(0),
v = rd.GetString(1)
If Not _SettingsCache.ContainsKey(k) Then
'数据库有额外的信息则加入
_SettingsCache.Add(k, v)
End If
Loop
End Using
End Sub
Protected Overrides Function InternalGetSetting(key As String) As String
Using cmd As SQLiteCommand = _GetSettingsByKeyCommand.Clone()
cmd.Parameters.AddWithValue("Key", key)
Dim rd = cmd.ExecuteReader()
If rd.Read() Then
Return rd.GetString(1)
Else
Return Nothing
End If
End Using
End Function
Protected Overrides Sub InternalInsertSetting(key As String, value As String)
Using cmd As SQLiteCommand = _InsertSettingsCommand.Clone()
cmd.Parameters.AddWithValue("Key", key)
cmd.Parameters.AddWithValue("Value", value)
cmd.ExecuteNonQuery()
End Using
End Sub
Protected Overrides Sub InternalSetSetting(key As String, value As String)
Using cmd As SQLiteCommand = _SetSettingsByKeyCommand.Clone()
cmd.Parameters.AddWithValue("Key", key)
cmd.Parameters.AddWithValue("Value", value)
cmd.ExecuteNonQuery()
End Using
End Sub
Public Overrides Function Type() As Storage.StorageType
Return StorageType.SQLite
End Function
Protected Overrides Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' DO: 释放托管状态(托管对象)。
_InitDBCommand.Dispose()
_EnqueueSendCommand.Dispose()
_DequeueSendCommand.Dispose()
_GetReadySendByIDCommand.Dispose()
_DeleteReadySendByIDCommand.Dispose()
_ReadySendCountCommand.Dispose()
_InsertSentCommand.Dispose()
_InsertReceivedCommand.Dispose()
_GetReceivedByIDCommand.Dispose()
_DeleteReceivedByIDCommand.Dispose()
_ListReceivedCommand.Dispose()
_ListContactsCommand.Dispose()
_GetContactsByNameCommand.Dispose()
_SetContactsByNameCommand.Dispose()
_InsertContactsCommand.Dispose()
_DeleteContactsByNameCommand.Dispose()
_ListSettingsCommand.Dispose()
_GetSettingsByKeyCommand.Dispose()
_SetSettingsByKeyCommand.Dispose()
_InsertSettingsCommand.Dispose()
_conn.Close()
End If
' DO: 释放非托管资源(非托管对象)并重写下面的 Finalize()。
' DO: 将大型字段设置为 null。
End If
Me.disposedValue = True
End Sub
End Class
|
twd2/MyGSM
|
MyGSM/Storage/SQLiteStorage.vb
|
Visual Basic
|
mit
| 14,674
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.42
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.VBHelloWord.My.MySettings
Get
Return Global.VBHelloWord.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
AndreKuzubov/Easy_Report
|
packages/Independentsoft.Office.Word.2.0.400/Tutorial/VBHelloWord/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,967
|
Namespace Global.Moq
Partial Friend Class Mock
Shared Sub New()
Sdk.MockFactory.[Default] = New Sdk.DynamicMockFactory
OnInitialized()
End Sub
''' <summary>
''' Invoked after the default <see cref="MockFactory.Default"/>
''' is initialized.
''' </summary>
Partial Private Shared Sub OnInitialized()
End Sub
End Class
End Namespace
|
Moq/moq
|
src/Moq.DynamicProxy/Mock.DynamicFactory.vb
|
Visual Basic
|
apache-2.0
| 432
|
' 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.Globalization
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.CSharp
Imports Microsoft.CodeAnalysis.Editor.CSharp.Formatting
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Text.Projection
Imports Microsoft.VisualStudio.Utilities
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
<[UseExportProvider]>
Public Class CSharpCompletionCommandHandlerTests
<WorkItem(541201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541201")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TabCommitsWithoutAUniqueMatch() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
$$
</Document>)
state.SendTypeChars("using System.Ne")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Net", isHardSelected:=True)
state.SendTypeChars("x")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Net", isSoftSelected:=True)
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("using System.Net", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAtEndOfFile() As Task
Using state = TestState.CreateCSharpTestState(
<Document>$$</Document>)
state.SendTypeChars("us")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotAtStartOfExistingWord() As Task
Using state = TestState.CreateCSharpTestState(
<Document>$$using</Document>)
state.SendTypeChars("u")
Await state.AssertNoCompletionSession()
Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMSCorLibTypes() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
using System;
class c : $$
</Document>)
state.SendTypeChars("A")
Await state.AssertCompletionSession()
Assert.True(state.CompletionItemsContainsAll(displayText:={"Attribute", "Exception", "IDisposable"}))
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFiltering1() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
using System;
class c { $$
</Document>)
state.SendTypeChars("Sy")
Await state.AssertCompletionSession()
Assert.True(state.CompletionItemsContainsAll(displayText:={"OperatingSystem", "System", "SystemException"}))
Assert.False(state.CompletionItemsContainsAny(displayText:={"Exception", "Activator"}))
End Using
End Function
' NOTE(cyrusn): This should just be a unit test for SymbolCompletionProvider. However, I'm
' just porting the integration tests to here for now.
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMultipleTypes() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class C { $$ } struct S { } enum E { } interface I { } delegate void D();
</Document>)
state.SendTypeChars("C")
Await state.AssertCompletionSession()
Assert.True(state.CompletionItemsContainsAll(displayText:={"C", "S", "E", "I", "D"}))
End Using
End Function
' NOTE(cyrusn): This should just be a unit test for KeywordCompletionProvider. However, I'm
' just porting the integration tests to here for now.
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInEmptyFile() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
$$
</Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Assert.True(state.CompletionItemsContainsAll(displayText:={"abstract", "class", "namespace"}))
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotAfterTypingDotAfterIntegerLiteral() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class c { void M() { 3$$ } }
</Document>)
state.SendTypeChars(".")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAfterExplicitInvokeAfterDotAfterIntegerLiteral() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class c { void M() { 3.$$ } }
</Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Assert.True(state.CompletionItemsContainsAll({"ToString"}))
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEnterIsConsumed() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class Class1
{
void Main(string[] args)
{
$$
}
}</Document>)
state.SendTypeChars("System.TimeSpan.FromMin")
state.SendReturn()
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal(<text>
class Class1
{
void Main(string[] args)
{
System.TimeSpan.FromMinutes
}
}</text>.NormalizedValue, state.GetDocumentText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDescription1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
/// <summary>
/// TestDocComment
/// </summary>
class TestException : Exception { }
class MyException : $$]]></Document>)
state.SendTypeChars("Test")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(description:="class TestException" & vbCrLf & "TestDocComment")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestObjectCreationPreselection1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.Collections.Generic;
class C
{
public void Goo()
{
List<int> list = new$$
}
}]]></Document>)
state.SendTypeChars(" ")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True)
Assert.True(state.CompletionItemsContainsAll(displayText:={"LinkedList<>", "List<>", "System"}))
state.SendTypeChars("Li")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True)
Assert.True(state.CompletionItemsContainsAll(displayText:={"LinkedList<>", "List<>"}))
Assert.False(state.CompletionItemsContainsAny(displayText:={"System"}))
state.SendTypeChars("n")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="LinkedList<>", isHardSelected:=True)
state.SendBackspace()
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True)
state.SendTab()
Assert.Contains("new List<int>", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDeconstructionDeclaration() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Goo()
{
var ($$
}
}]]></Document>)
state.SendTypeChars("i")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDeconstructionDeclaration2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Goo()
{
var (a, $$
}
}]]></Document>)
state.SendTypeChars("i")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDeconstructionDeclaration3() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Goo()
{
var ($$) = (1, 2);
}
}]]></Document>)
state.SendTypeChars("i")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParenthesizedDeconstructionDeclarationWithVar() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
(var a$$) = (1, 2);
}
}]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=False)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParenthesizedDeconstructionDeclarationWithVarAfterComma() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
(var a, var a$$) = (1, 2);
}
}]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=False)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParenthesizedVarDeconstructionDeclarationWithVar() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
(var a, var ($$)) = (1, 2);
}
}]]></Document>)
state.SendTypeChars("a")
Await state.AssertNoCompletionSession()
state.SendTypeChars(", a")
Await state.AssertNoCompletionSession()
Assert.Contains("(var a, var (a, a)) = ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestVarDeconstructionDeclarationWithVar() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
$$
}
}]]></Document>)
state.SendTypeChars("va")
Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True)
state.SendTypeChars(" (a")
Await state.AssertNoCompletionSession()
state.SendTypeChars(", a")
Await state.AssertNoCompletionSession()
Assert.Contains("var (a, a", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParenthesizedDeconstructionDeclarationWithSymbol() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
($$) = (1, 2);
}
}]]></Document>)
state.SendTypeChars("vari")
Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=True)
state.SendTypeChars(" ")
Assert.Contains("(Variable ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
Await state.AssertNoCompletionSession()
state.SendTypeChars("x, vari")
Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=True)
state.SendTypeChars(" ")
Assert.Contains("(Variable x, Variable ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=False)
Assert.True(state.CompletionItemsContainsAll({"variable"}))
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParenthesizedDeconstructionDeclarationWithInt() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Integer
{
public void Goo()
{
($$) = (1, 2);
}
}]]></Document>)
state.SendTypeChars("int")
Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True)
state.SendTypeChars(" ")
Assert.Contains("(int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
Await state.AssertNoCompletionSession()
state.SendTypeChars("x, int")
Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True)
state.SendTypeChars(" ")
Assert.Contains("(int x, int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestIncompleteParenthesizedDeconstructionDeclaration() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
($$
}
}]]></Document>)
state.SendTypeChars("va")
Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
state.SendTypeChars("a")
Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True)
state.SendTypeChars(", va")
Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
state.SendTypeChars("a")
Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True)
state.SendTypeChars(")")
Assert.Contains("(var a, var a)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestIncompleteParenthesizedDeconstructionDeclaration2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
($$)
}
}]]></Document>)
state.SendTypeChars("va")
Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
state.SendTypeChars("a")
Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True)
state.SendTypeChars(", va")
Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
state.SendTypeChars("a")
Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True)
state.SendReturn()
Assert.Contains("(var a, var a", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBackspaceInIncompleteParenthesizedDeconstructionDeclaration() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
(var as$$
}
}]]></Document>)
state.Workspace.Options = state.Workspace.Options.WithChangedOption(
CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True)
state.SendBackspace()
' This completion is hard-selected because the suggestion mode never triggers on backspace
' See issue https://github.com/dotnet/roslyn/issues/15302
Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=True)
state.SendTypeChars(", var as")
state.SendBackspace()
Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True)
state.SendTypeChars(")")
Await state.AssertNoCompletionSession()
Assert.Contains("(var as, var a)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBackspaceInParenthesizedDeconstructionDeclaration() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Variable
{
public void Goo()
{
(var as$$)
}
}]]></Document>)
state.Workspace.Options = state.Workspace.Options.WithChangedOption(
CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True)
state.SendBackspace()
' This completion is hard-selected because the suggestion mode never triggers on backspace
' See issue https://github.com/dotnet/roslyn/issues/15302
Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=True)
state.SendTypeChars(", var as")
state.SendBackspace()
Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True)
state.SendReturn()
Await state.AssertNoCompletionSession()
Assert.Contains("(var as, var a", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(17256, "https://github.com/dotnet/roslyn/issues/17256")>
Public Async Function TestThrowExpression() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
public object Goo()
{
return null ?? throw new$$
}
}]]></Document>)
state.SendTypeChars(" ")
Await state.AssertSelectedCompletionItem(displayText:="Exception", isHardSelected:=True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(17256, "https://github.com/dotnet/roslyn/issues/17256")>
Public Async Function TestThrowStatement() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
public object Goo()
{
throw new$$
}
}]]></Document>)
state.SendTypeChars(" ")
Await state.AssertSelectedCompletionItem(displayText:="Exception", isHardSelected:=True)
End Using
End Function
<WpfFact>
Public Async Function TestNonTrailingNamedArgumentInCSharp7_1() As Task
Using state = TestState.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="C#" LanguageVersion="CSharp7_1" CommonReferences="true" AssemblyName="CSProj">
<Document FilePath="C.cs">
class C
{
public void M()
{
int better = 2;
M(a: 1, $$)
}
public void M(int a, int bar, int c) { }
}
</Document>
</Project>
</Workspace>)
state.SendTypeChars("b")
Await state.AssertSelectedCompletionItem(displayText:="bar:", isHardSelected:=True)
state.SendTypeChars("e")
Await state.AssertSelectedCompletionItem(displayText:="bar:", isSoftSelected:=True)
End Using
End Function
<WpfFact>
Public Async Function TestNonTrailingNamedArgumentInCSharp7_2() As Task
Using state = TestState.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="C#" LanguageVersion="CSharp7_2" CommonReferences="true" AssemblyName="CSProj">
<Document FilePath="C.cs">
class C
{
public void M()
{
int better = 2;
M(a: 1, $$)
}
public void M(int a, int bar, int c) { }
}
</Document>
</Project>
</Workspace>)
state.SendTypeChars("b")
Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True)
state.SendTypeChars("a")
Await state.AssertSelectedCompletionItem(displayText:="bar:", isHardSelected:=True)
state.SendBackspace()
Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True)
state.SendTypeChars(", ")
Assert.Contains("M(a: 1, better,", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")>
Public Async Function TestDefaultSwitchLabel() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M(object o)
{
switch (o)
{
default:
goto $$
}
}
}]]></Document>)
state.SendTypeChars("d")
Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True)
state.SendTypeChars(";")
Assert.Contains("goto default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")>
Public Async Function TestGotoOrdinaryLabel() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M(object o)
{
label1:
goto $$
}
}]]></Document>)
state.SendTypeChars("l")
Await state.AssertSelectedCompletionItem(displayText:="label1", isHardSelected:=True)
state.SendTypeChars(";")
Assert.Contains("goto label1;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")>
Public Async Function TestEscapedDefaultLabel() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M(object o)
{
@default:
goto $$
}
}]]></Document>)
state.SendTypeChars("d")
Await state.AssertSelectedCompletionItem(displayText:="@default", isHardSelected:=True)
state.SendTypeChars(";")
Assert.Contains("goto @default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")>
Public Async Function TestEscapedDefaultLabel2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M(object o)
{
switch (o)
{
default:
@default:
goto $$
}
}
}]]></Document>)
state.SendTypeChars("d")
Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True)
state.SendTypeChars(";")
Assert.Contains("goto default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")>
Public Async Function TestEscapedDefaultLabelWithoutSwitch() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M(object o)
{
@default:
goto $$
}
}]]></Document>)
state.SendTypeChars("d")
Await state.AssertSelectedCompletionItem(displayText:="@default", isHardSelected:=True)
state.SendTypeChars(";")
Assert.Contains("goto @default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestArrayInitialization() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
Class[] x = $$
}
}]]></Document>)
state.SendTypeChars("new ")
Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True)
state.SendTypeChars("C")
Await state.AssertSelectedCompletionItem(displayText:="Class", isHardSelected:=True)
state.SendTypeChars("[")
Assert.Contains("Class[] x = new Class[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
state.SendTypeChars("] {")
Assert.Contains("Class[] x = new Class[] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestImplicitArrayInitialization() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
Class[] x = $$
}
}]]></Document>)
state.SendTypeChars("n")
Await state.AssertSelectedCompletionItem(displayText:="nameof", isHardSelected:=True)
state.SendTypeChars("e")
Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True)
state.SendTypeChars("[")
Assert.Contains("Class[] x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
state.SendTypeChars("] {")
Assert.Contains("Class[] x = new [] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestImplicitArrayInitialization2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
Class[] x = $$
}
}]]></Document>)
state.SendTypeChars("ne")
Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True)
state.SendTypeChars("[")
Assert.Contains("Class[] x = new[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestImplicitArrayInitialization3() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
Class[] x = $$
}
}]]></Document>)
state.SendTypeChars("ne")
Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True)
Assert.Contains("Class[] x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
state.SendTypeChars("[")
Assert.Contains("Class[] x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestImplicitArrayInitialization4() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
Class[] x =$$
}
}]]></Document>)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
state.SendTypeChars("{")
Assert.Contains("Class[] x = {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestImplicitArrayInitialization_WithTab() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
Class[] x = $$
}
}]]></Document>)
state.SendTypeChars("ne")
Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True)
Assert.Contains("Class[] x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
state.SendTab()
Assert.Contains("Class[] x = new Class", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestTypelessImplicitArrayInitialization() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
var x = $$
}
}]]></Document>)
state.SendTypeChars("ne")
Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
state.SendTypeChars("[")
Assert.Contains("var x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
state.SendTypeChars("] {")
Assert.Contains("var x = new [] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestTypelessImplicitArrayInitialization2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
var x = $$
}
}]]></Document>)
state.SendTypeChars("ne")
Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True)
state.SendTypeChars("[")
Assert.Contains("var x = new[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")>
Public Async Function TestTypelessImplicitArrayInitialization3() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Class
{
public void M()
{
var x = $$
}
}]]></Document>)
state.SendTypeChars("ne")
Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True)
state.SendTypeChars(" ")
Assert.Contains("var x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
state.SendTypeChars("[")
Assert.Contains("var x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestSymbolInTupleLiteral() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Fo()
{
($$)
}
}]]></Document>)
state.SendTypeChars("F")
Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(F:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestSymbolInTupleLiteralAfterComma() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Fo()
{
(x, $$)
}
}]]></Document>)
state.SendTypeChars("F")
Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(x, F:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")>
Public Async Function ColonInTupleNameInTupleLiteral() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M()
{
(int first, int second) t = ($$
}
}]]></Document>)
state.SendTypeChars("fi")
Await state.AssertSelectedCompletionItem(displayText:="first:", isHardSelected:=True)
Assert.Equal("first", state.CurrentCompletionPresenterSession.SelectedItem.FilterText)
state.SendTypeChars(":")
Assert.Contains("(first:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")>
Public Async Function ColonInExactTupleNameInTupleLiteral() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M()
{
(int first, int second) t = ($$
}
}]]></Document>)
state.SendTypeChars("first")
Await state.AssertSelectedCompletionItem(displayText:="first:", isHardSelected:=True)
Assert.Equal("first", state.CurrentCompletionPresenterSession.SelectedItem.FilterText)
state.SendTypeChars(":")
Assert.Contains("(first:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")>
Public Async Function ColonInTupleNameInTupleLiteralAfterComma() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M()
{
(int first, int second) t = (0, $$
}
}]]></Document>)
state.SendTypeChars("se")
Await state.AssertSelectedCompletionItem(displayText:="second:", isHardSelected:=True)
Assert.Equal("second", state.CurrentCompletionPresenterSession.SelectedItem.FilterText)
state.SendTypeChars(":")
Assert.Contains("(0, second:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")>
Public Async Function TabInTupleNameInTupleLiteral() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M()
{
(int first, int second) t = ($$
}
}]]></Document>)
state.SendTypeChars("fi")
Await state.AssertSelectedCompletionItem(displayText:="first:", isHardSelected:=True)
Assert.Equal("first", state.CurrentCompletionPresenterSession.SelectedItem.FilterText)
state.SendTab()
state.SendTypeChars(":")
state.SendTypeChars("0")
Assert.Contains("(first:0", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")>
Public Async Function TabInExactTupleNameInTupleLiteral() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M()
{
(int first, int second) t = ($$
}
}]]></Document>)
state.SendTypeChars("first")
Await state.AssertSelectedCompletionItem(displayText:="first:", isHardSelected:=True)
Assert.Equal("first", state.CurrentCompletionPresenterSession.SelectedItem.FilterText)
state.SendTab()
state.SendTypeChars(":")
state.SendTypeChars("0")
Assert.Contains("(first:0", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")>
Public Async Function TabInTupleNameInTupleLiteralAfterComma() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void M()
{
(int first, int second) t = (0, $$
}
}]]></Document>)
state.SendTypeChars("se")
Await state.AssertSelectedCompletionItem(displayText:="second:", isHardSelected:=True)
Assert.Equal("second", state.CurrentCompletionPresenterSession.SelectedItem.FilterText)
state.SendTab()
state.SendTypeChars(":")
state.SendTypeChars("1")
Assert.Contains("(0, second:1", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestKeywordInTupleLiteral() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Goo()
{
($$)
}
}]]></Document>)
state.SendTypeChars("d")
Await state.AssertSelectedCompletionItem(displayText:="decimal", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(d:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestTupleType() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Goo()
{
($$)
}
}]]></Document>)
state.SendTypeChars("d")
Await state.AssertSelectedCompletionItem(displayText:="decimal", isHardSelected:=True)
state.SendTypeChars(" ")
Assert.Contains("(decimal ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestDefaultKeyword() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Goo()
{
switch(true)
{
$$
}
}
}]]></Document>)
state.SendTypeChars("def")
Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("default:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestParenthesizedExpression() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Fo()
{
($$)
}
}]]></Document>)
state.SendTypeChars("F")
Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True)
state.SendTypeChars(".")
Assert.Contains("(Fo.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestInvocationExpression() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Goo(int Alice)
{
Goo($$)
}
}]]></Document>)
state.SendTypeChars("A")
Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("Goo(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestInvocationExpressionAfterComma() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Goo(int Alice, int Bob)
{
Goo(1, $$)
}
}]]></Document>)
state.SendTypeChars("B")
Await state.AssertSelectedCompletionItem(displayText:="Bob", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("Goo(1, Bob:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")>
Public Async Function TestCaseLabel() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Fo()
{
switch (1)
{
case $$
}
}
}]]></Document>)
state.SendTypeChars("F")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("case Fo:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(543268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543268")>
Public Async Function TestTypePreselection1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
partial class C
{
}
partial class C
{
$$
}]]></Document>)
state.SendTypeChars("C")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertCompletionSession()
End Using
End Function
<WorkItem(543519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543519")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNewPreselectionAfterVar() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void M()
{
var c = $$
}
}]]></Document>)
state.SendTypeChars("new ")
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(543559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543559")>
<WorkItem(543561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543561")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEscapedIdentifiers() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class @return
{
void goo()
{
$$
}
}
]]></Document>)
state.SendTypeChars("@")
Await state.AssertNoCompletionSession()
state.SendTypeChars("r")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="@return", isHardSelected:=True)
state.SendTab()
Assert.Contains("@return", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitUniqueItem1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteL$$();
}
}]]></Document>)
state.SendCommitUniqueCompletionListItem()
Await state.AssertNoCompletionSession()
Assert.Contains("WriteLine()", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitUniqueItem2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteL$$ine();
}
}]]></Document>)
state.SendCommitUniqueCompletionListItem()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitForUsingDirective1() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
$$
</Document>)
state.SendTypeChars("using Sys")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True)
state.SendTypeChars("(")
Await state.AssertNoCompletionSession()
Assert.Contains("using Sys(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitForUsingDirective2() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
$$
</Document>)
state.SendTypeChars("using Sys")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True)
state.SendTypeChars(".")
Await state.AssertCompletionSession()
Assert.Contains("using System.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitForUsingDirective3() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
$$
</Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("using Sys")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True)
state.SendTypeChars(";")
Await state.AssertNoCompletionSession()
state.AssertMatchesTextStartingAtLine(1, "using System;")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitForUsingDirective4() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
$$
</Document>)
state.SendTypeChars("using Sys")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
Assert.Contains("using Sys ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function KeywordsIncludedInObjectCreationCompletion() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class C
{
void Goo()
{
string s = new$$
}
}
</Document>)
state.SendTypeChars(" ")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="string", isHardSelected:=True)
Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(c) c.DisplayText = "int"))
End Using
End Function
<WorkItem(544293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544293")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NoKeywordsOrSymbolsAfterNamedParameter() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class Goo
{
void Test()
{
object m = null;
Method(obj:m, $$
}
void Method(object obj, int num = 23, string str = "")
{
}
}
</Document>)
state.SendTypeChars("a")
Await state.AssertCompletionSession()
Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "num:"))
Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "System"))
Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(c) c.DisplayText = "int"))
End Using
End Function
<WorkItem(544017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544017")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumCompletionTriggeredOnSpace() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
enum Numeros { Uno, Dos }
class Goo
{
void Bar(int a, Numeros n) { }
void Baz()
{
Bar(0$$
}
}
</Document>)
state.SendTypeChars(", ")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True)
Assert.Equal(1, state.CurrentCompletionPresenterSession.CompletionItems.Where(Function(c) c.DisplayText = "Numeros").Count())
End Using
End Function
<WorkItem(479078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/479078")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumCompletionTriggeredOnSpaceForNullables() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
enum Numeros { Uno, Dos }
class Goo
{
void Bar(int a, Numeros? n) { }
void Baz()
{
Bar(0$$
}
}
</Document>)
state.SendTypeChars(", ")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True)
Assert.Equal(1, state.CurrentCompletionPresenterSession.CompletionItems.Where(Function(c) c.DisplayText = "Numeros").Count())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumCompletionTriggeredOnDot() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
enum Numeros { Uno, Dos }
class Goo
{
void Bar()
{
Numeros num = $$
}
}
</Document>)
state.SendTypeChars("Nu.")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Contains("Numeros num = Numeros.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumCompletionNotTriggeredOnPlusCommitCharacter() As Task
Await EnumCompletionNotTriggeredOn("+"c)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumCompletionNotTriggeredOnLeftBraceCommitCharacter() As Task
Await EnumCompletionNotTriggeredOn("{"c)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumCompletionNotTriggeredOnSpaceCommitCharacter() As Task
Await EnumCompletionNotTriggeredOn(" "c)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumCompletionNotTriggeredOnSemicolonCommitCharacter() As Task
Await EnumCompletionNotTriggeredOn(";"c)
End Function
Private Async Function EnumCompletionNotTriggeredOn(c As Char) As Task
Using state = TestState.CreateCSharpTestState(
<Document>
enum Numeros { Uno, Dos }
class Goo
{
void Bar()
{
Numeros num = $$
}
}
</Document>)
state.SendTypeChars("Nu")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True)
state.SendTypeChars(c.ToString())
Await state.WaitForAsynchronousOperationsAsync()
Assert.NotEqual("Numberos", state.CurrentCompletionPresenterSession?.SelectedItem?.DisplayText)
Assert.Contains(String.Format("Numeros num = Nu{0}", c), state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(544296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544296")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestVerbatimNamedIdentifierFiltering() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class Program
{
void Goo(int @int)
{
Goo($$
}
}
</Document>)
state.SendTypeChars("i")
Await state.AssertCompletionSession()
Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:"))
state.SendTypeChars("n")
Await state.WaitForAsynchronousOperationsAsync()
Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:"))
state.SendTypeChars("t")
Await state.WaitForAsynchronousOperationsAsync()
Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:"))
End Using
End Function
<WorkItem(543687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543687")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoPreselectInInvalidObjectCreationLocation() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class Program
{
void Test()
{
$$
}
}
class Bar { }
class Goo<T> : IGoo<T>
{
}
interface IGoo<T>
{
}]]>
</Document>)
state.SendTypeChars("IGoo<Bar> a = new ")
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(544925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544925")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestQualifiedEnumSelection() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
using System;
class Program
{
void Main()
{
Environment.GetFolderPath$$
}
}
</Document>)
state.SendTypeChars("(")
state.SendTab()
Await state.WaitForAsynchronousOperationsAsync()
Assert.Contains("Environment.SpecialFolder", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(545070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545070")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTextChangeSpanWithAtCharacter() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
public class @event
{
$$@event()
{
}
}
</Document>)
state.SendTypeChars("public ")
Await state.AssertNoCompletionSession()
Assert.Contains("public @event", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotInsertColonSoThatUserCanCompleteOutAVariableNameThatDoesNotCurrentlyExist_IE_TheCyrusCase() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
using System.Threading;
class Program
{
static void Main(string[] args)
{
Goo($$)
}
void Goo(CancellationToken cancellationToken)
{
}
}
</Document>)
state.SendTypeChars("can")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("Goo(cancellationToken)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
#If False Then
<Scenario Name="Verify correct intellisense selection on ENTER">
<SetEditorText>
<![CDATA[class Class1
{
void Main(string[] args)
{
//
}
}]]>
</SetEditorText>
<PlaceCursor Marker="//" />
<SendKeys>var a = System.TimeSpan.FromMin{ENTER}{(}</SendKeys>
<VerifyEditorContainsText>
<![CDATA[class Class1
{
void Main(string[] args)
{
var a = System.TimeSpan.FromMinutes(
}
}]]>
</VerifyEditorContainsText>
</Scenario>
#End If
<WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AttributeNamedPropertyCompletionCommitWithTab() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class MyAttribute : System.Attribute
{
public string Name { get; set; }
}
[MyAttribute($$
public class Goo
{
}
</Document>)
state.SendTypeChars("Nam")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AttributeNamedPropertyCompletionCommitWithEquals() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class MyAttribute : System.Attribute
{
public string Name { get; set; }
}
[MyAttribute($$
public class Goo
{
}
</Document>)
state.SendTypeChars("Nam=")
Await state.AssertNoCompletionSession()
Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AttributeNamedPropertyCompletionCommitWithSpace() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class MyAttribute : System.Attribute
{
public string Name { get; set; }
}
[MyAttribute($$
public class Goo
{
}
</Document>)
state.SendTypeChars("Nam ")
Await state.AssertNoCompletionSession()
Assert.Equal("[MyAttribute(Name ", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(545590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545590")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOverrideDefaultParameter() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public virtual void Goo<S>(S x = default(S))
{
}
}
class D : C
{
override $$
}
]]></Document>)
state.SendTypeChars(" Goo")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("public override void Goo<S>(S x = default(S))", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(545664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545664")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestArrayAfterOptionalParameter() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class A
{
public virtual void Goo(int x = 0, int[] y = null) { }
}
class B : A
{
public override void Goo(int x = 0, params int[] y) { }
}
class C : B
{
override$$
}
]]></Document>)
state.SendTypeChars(" Goo")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains(" public override void Goo(int x = 0, int[] y = null)", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(545967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545967")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestVirtualSpaces() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public string P { get; set; }
void M()
{
var v = new C
{$$
};
}
}
]]></Document>)
state.SendReturn()
Assert.True(state.TextView.Caret.InVirtualSpace)
Assert.Equal(12, state.TextView.Caret.Position.VirtualSpaces)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("P", isSoftSelected:=True)
state.SendDownKey()
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("P", isHardSelected:=True)
state.SendTab()
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal(" P", state.GetLineFromCurrentCaretPosition().GetText())
Dim bufferPosition = state.TextView.Caret.Position.BufferPosition
Assert.Equal(13, bufferPosition.Position - bufferPosition.GetContainingLine().Start.Position)
Assert.False(state.TextView.Caret.InVirtualSpace)
End Using
End Function
<WorkItem(546561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546561")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNamedParameterAgainstMRU() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
void Goo(string s) { }
static void Main()
{
$$
}
}
]]></Document>)
' prime the MRU
state.SendTypeChars("string")
state.SendTab()
Await state.AssertNoCompletionSession()
' Delete what we just wrote.
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendEscape()
Await state.AssertNoCompletionSession()
' ensure we still select the named param even though 'string' is in the MRU.
state.SendTypeChars("Goo(s")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("s:")
End Using
End Function
<WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMissingOnObjectCreationAfterVar1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class A
{
void Goo()
{
var v = new$$
}
}
]]></Document>)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMissingOnObjectCreationAfterVar2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class A
{
void Goo()
{
var v = new $$
}
}
]]></Document>)
state.SendTypeChars("X")
Await state.AssertCompletionSession()
Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "X"))
End Using
End Function
<WorkItem(546917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546917")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEnumInSwitch() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
enum Numeros
{
}
class C
{
void M()
{
Numeros n;
switch (n)
{
case$$
}
}
}
]]></Document>)
state.SendTypeChars(" ")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Numeros")
End Using
End Function
<WorkItem(547016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547016")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAmbiguityInLocalDeclaration() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public int W;
public C()
{
$$
W = 0;
}
}
]]></Document>)
state.SendTypeChars("w")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="W")
End Using
End Function
<WorkItem(530835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530835")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCompletionFilterSpanCaretBoundary() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Method()
{
$$
}
}
]]></Document>)
state.SendTypeChars("Met")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Method")
state.SendLeftKey()
state.SendLeftKey()
state.SendLeftKey()
state.SendTypeChars("new")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Method", isSoftSelected:=True)
End Using
End Function
<WorkItem(5487, "https://github.com/dotnet/roslyn/issues/5487")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitCharTypedAtTheBeginingOfTheFilterSpan() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public bool Method()
{
if ($$
}
}
]]></Document>)
state.SendTypeChars("Met")
Await state.AssertCompletionSession()
state.SendLeftKey()
state.SendLeftKey()
state.SendLeftKey()
Await state.AssertSelectedCompletionItem(isSoftSelected:=True)
state.SendTypeChars("!")
Await state.AssertNoCompletionSession()
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("if (!Met", state.GetLineTextFromCaretPosition().Trim())
Assert.Equal("M", state.GetCaretPoint().BufferPosition.GetChar())
End Using
End Function
<WorkItem(622957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622957")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBangFiltersInDocComment() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
/// $$
/// TestDocComment
/// </summary>
class TestException : Exception { }
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("!")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("!--")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeCompletionDoesNotFilter() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
public void Method()
{
string$$
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("string")
state.CompletionItemsContainsAll({"integer", "Method"})
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeBeforeWordDoesNotSelect() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
public void Method()
{
$$string
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("AccessViolationException")
state.CompletionItemsContainsAll({"integer", "Method"})
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeCompletionSelectsWithoutRegardToCaretPosition() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
public void Method()
{
s$$tring
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("string")
state.CompletionItemsContainsAll({"integer", "Method"})
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TabAfterQuestionMark() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
public void Method()
{
?$$
}
}
]]></Document>)
state.SendTab()
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal(state.GetLineTextFromCaretPosition(), " ?" + vbTab)
End Using
End Function
<WorkItem(657658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657658")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function PreselectionIgnoresBrackets() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
$$
static void Main(string[] args)
{
}
}]]></Document>)
state.SendTypeChars("static void F<T>(int a, Func<T, int> b) { }")
state.SendEscape()
state.TextView.Caret.MoveTo(New VisualStudio.Text.SnapshotPoint(state.SubjectBuffer.CurrentSnapshot, 220))
state.SendTypeChars("F")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("F<>")
End Using
End Function
<WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInvokeSnippetCommandDismissesCompletion() As Task
Using state = TestState.CreateCSharpTestState(
<Document>$$</Document>)
state.SendTypeChars("us")
Await state.AssertCompletionSession()
state.SendInsertSnippetCommand()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSurroundWithCommandDismissesCompletion() As Task
Using state = TestState.CreateCSharpTestState(
<Document>$$</Document>)
state.SendTypeChars("us")
Await state.AssertCompletionSession()
state.SendSurroundWithCommand()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(737239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737239")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function LetEditorHandleOpenParen() As Task
Dim expected = <Document><![CDATA[
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
List<int> x = new List<int>(
}
}]]></Document>.Value.Replace(vbLf, vbCrLf)
Using state = TestState.CreateCSharpTestState(<Document><![CDATA[
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
List<int> x = new$$
}
}]]></Document>)
state.SendTypeChars(" ")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("List<int>")
state.SendTypeChars("(")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal(expected, state.GetDocumentText())
End Using
End Function
<WorkItem(785637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/785637")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitMovesCaretToWordEnd() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
public void Main()
{
M$$ain
}
}
]]></Document>)
state.SendCommitUniqueCompletionListItem()
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition)
End Using
End Function
<WorkItem(775370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775370")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function MatchingConsidersAtSign() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
public void Main()
{
$$
}
}
]]></Document>)
state.SendTypeChars("var @this = ""goo""")
state.SendReturn()
state.SendTypeChars("string str = this.ToString();")
state.SendReturn()
state.SendTypeChars("str = @th")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("@this")
End Using
End Function
<WorkItem(865089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865089")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AttributeFilterTextRemovesAttributeSuffix() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
[$$]
class AtAttribute : System.Attribute { }]]></Document>)
state.SendTypeChars("At")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("At")
Assert.Equal("At", state.CurrentCompletionPresenterSession.SelectedItem.FilterText)
End Using
End Function
<WorkItem(852578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/852578")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function PreselectExceptionOverSnippet() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
Exception goo() {
return new $$
}
}]]></Document>)
state.SendTypeChars(" ")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("Exception")
End Using
End Function
<WorkItem(868286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868286")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitNameAfterAlias() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using goo = System$$]]></Document>)
state.SendTypeChars(".act<")
Await state.WaitForAsynchronousOperationsAsync()
state.AssertMatchesTextStartingAtLine(1, "using goo = System.Action<")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCompletionInLinkedFiles() As Task
Using state = TestState.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Thing2">
<Document FilePath="C.cs">
class C
{
void M()
{
$$
}
#if Thing1
void Thing1() { }
#elif Thing2
void Thing2() { }
#endif
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Thing1">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>)
Dim documents = state.Workspace.Documents
Dim linkDocument = documents.Single(Function(d) d.IsLinkFile)
state.SendTypeChars("Thing1")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("Thing1")
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendEscape()
state.Workspace.SetDocumentContext(linkDocument.Id)
state.SendTypeChars("Thing1")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("Thing1")
Assert.True(state.CurrentCompletionPresenterSession.SelectedItem.Tags.Contains(CompletionTags.Warning))
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.SendTypeChars("M")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("M")
Assert.False(state.CurrentCompletionPresenterSession.SelectedItem.Tags.Contains(CompletionTags.Warning))
End Using
End Function
<WorkItem(951726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951726")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DismissUponSave() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
$$
}]]></Document>)
state.SendTypeChars("voi")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("void")
state.SendSave()
Await state.AssertNoCompletionSession()
state.AssertMatchesTextStartingAtLine(3, " voi")
End Using
End Function
<WorkItem(930254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930254")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NoCompletionWithBoxSelection() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
{|Selection:$$int x;|}
{|Selection:int y;|}
}]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertNoCompletionSession()
state.SendTypeChars("goo")
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(839555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839555")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TriggeredOnHash() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
$$]]></Document>)
state.SendTypeChars("#")
Await state.AssertCompletionSession()
End Using
End Function
<WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function RegionCompletionCommitTriggersFormatting_1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
$$
}]]></Document>)
state.SendTypeChars("#reg")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("region")
state.SendReturn()
Await state.WaitForAsynchronousOperationsAsync()
state.AssertMatchesTextStartingAtLine(3, " #region")
End Using
End Function
<WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function RegionCompletionCommitTriggersFormatting_2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
$$
}]]></Document>)
state.SendTypeChars("#reg")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("region")
state.SendTypeChars(" ")
Await state.WaitForAsynchronousOperationsAsync()
state.AssertMatchesTextStartingAtLine(3, " #region ")
End Using
End Function
<WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EndRegionCompletionCommitTriggersFormatting_2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
#region NameIt
$$
}]]></Document>)
state.SendTypeChars("#endreg")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("endregion")
state.SendReturn()
Await state.WaitForAsynchronousOperationsAsync()
state.AssertMatchesTextStartingAtLine(4, " #endregion ")
End Using
End Function
Private Class SlowProvider
Inherits CommonCompletionProvider
Public checkpoint As Checkpoint = New Checkpoint()
Public Overrides Async Function ProvideCompletionsAsync(context As CompletionContext) As Task
Await checkpoint.Task.ConfigureAwait(False)
End Function
Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Return True
End Function
End Class
<WorkItem(1015893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015893")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspaceDismissesIfComputationIsIncomplete() As Task
Dim slowProvider = New SlowProvider()
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void goo()
{
goo($$
}
}]]></Document>, {slowProvider})
state.SendTypeChars("f")
state.SendBackspace()
' Send a backspace that goes beyond the session's applicable span
' before the model computation has finished. Then, allow the
' computation to complete. There should still be no session.
state.SendBackspace()
slowProvider.checkpoint.Release()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(1065600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065600")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitUniqueItemWithBoxSelection() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void goo(int x)
{
[|$$ |]
}
}]]></Document>)
state.SendReturn()
state.TextView.Selection.Mode = VisualStudio.Text.Editor.TextSelectionMode.Box
state.SendCommitUniqueCompletionListItem()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NoPreselectionOnSpaceWhenAbuttingWord() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
void Main()
{
Program p = new $$Program();
}
}]]></Document>)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SpacePreselectionAtEndOfFile() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
void Main()
{
Program p = new $$]]></Document>)
state.SendTypeChars(" ")
Await state.AssertCompletionSession()
End Using
End Function
<WorkItem(1659, "https://github.com/dotnet/roslyn/issues/1659")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DismissOnSelectAllCommand() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void goo(int x)
{
$$]]></Document>)
' Note: the caret is at the file, so the Select All command's movement
' of the caret to the end of the selection isn't responsible for
' dismissing the session.
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendSelectAll()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionCommitAndFormatAreSeparateUndoTransactions() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void goo(int x)
{
int doodle;
$$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("doo;")
Await state.WaitForAsynchronousOperationsAsync()
state.AssertMatchesTextStartingAtLine(6, " doodle;")
state.SendUndo()
Await state.WaitForAsynchronousOperationsAsync()
state.AssertMatchesTextStartingAtLine(6, "doo;")
End Using
End Function
<WorkItem(4978, "https://github.com/dotnet/roslyn/issues/4978")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SessionNotStartedWhenCaretNotMappableIntoSubjectBuffer() As Task
' In inline diff view, typing delete next to a "deletion",
' can cause our CommandChain to be called with a subjectbuffer
' and TextView such that the textView's caret can't be mapped
' into our subject buffer.
'
' To test this, we create a projection buffer with 2 source
' spans: one of "text" content type and one based on a C#
' buffer. We create a TextView with that projection as
' its buffer, setting the caret such that it maps only
' into the "text" buffer. We then call the completion
' command handlers with commandargs based on that TextView
' but with the C# buffer as the SubjectBuffer.
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void goo(int x)
{$$
/********/
int doodle;
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
Dim textBufferFactoryService = state.GetExportedValue(Of ITextBufferFactoryService)()
Dim contentTypeService = state.GetExportedValue(Of IContentTypeRegistryService)()
Dim contentType = contentTypeService.GetContentType(ContentTypeNames.CSharpContentType)
Dim textViewFactory = state.GetExportedValue(Of ITextEditorFactoryService)()
Dim editorOperationsFactory = state.GetExportedValue(Of IEditorOperationsFactoryService)()
Dim otherBuffer = textBufferFactoryService.CreateTextBuffer("text", contentType)
Dim otherExposedSpan = otherBuffer.CurrentSnapshot.CreateTrackingSpan(0, 4, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward)
Dim subjectBufferExposedSpan = state.SubjectBuffer.CurrentSnapshot.CreateTrackingSpan(0, state.SubjectBuffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward)
Dim projectionBufferFactory = state.GetExportedValue(Of IProjectionBufferFactoryService)()
Dim projection = projectionBufferFactory.CreateProjectionBuffer(Nothing, New Object() {otherExposedSpan, subjectBufferExposedSpan}.ToList(), ProjectionBufferOptions.None)
Using disposableView As DisposableTextView = textViewFactory.CreateDisposableTextView(projection)
disposableView.TextView.Caret.MoveTo(New SnapshotPoint(disposableView.TextView.TextBuffer.CurrentSnapshot, 0))
Dim editorOperations = editorOperationsFactory.GetEditorOperations(disposableView.TextView)
state.CompletionCommandHandler.ExecuteCommand(New DeleteKeyCommandArgs(disposableView.TextView, state.SubjectBuffer), Sub() editorOperations.Delete(), TestCommandExecutionContext.Create())
Await state.AssertNoCompletionSession()
End Using
End Using
End Function
<WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround1() As Task
Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void goo(int x)
{
string.$$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("is")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("IsInterned")
End Using
End Using
End Function
<WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround2() As Task
Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void goo(int x)
{
string.$$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("ı")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem()
End Using
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselection1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.Threading;
class Program
{
void Cancel(int x, CancellationToken cancellationToken)
{
Cancel(x + 1, cancellationToken: $$)
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("cancellationToken", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselection2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
static void Main(string[] args)
{
int aaz = 0;
args = $$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("a")
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("args", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselection_DoesNotOverrideEnumPreselection() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
enum E
{
}
class Program
{
static void Main(string[] args)
{
E e;
e = $$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("E", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselection_DoesNotOverrideEnumPreselection2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
enum E
{
A
}
class Program
{
static void Main(string[] args)
{
E e = E.A;
if (e == $$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("E", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselection3() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class D {}
class Program
{
static void Main(string[] args)
{
int cw = 7;
D cx = new D();
D cx2 = $$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("c")
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionLocalsOverType() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class A {}
class Program
{
static void Main(string[] args)
{
A cx = new A();
A cx2 = $$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("c")
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionParameterOverMethod() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
bool f;
void goo(bool x) { }
void Main(string[] args)
{
goo($$) // Not "Equals"
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("f", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/6942"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionConvertibility1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
abstract class C {}
class D : C {}
class Program
{
static void Main(string[] args)
{
D cx = new D();
C cx2 = $$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("c")
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionLocalOverProperty() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
public int aaa { get; }
void Main(string[] args)
{
int aaq;
int y = a$$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("aaq", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(12254, "https://github.com/dotnet/roslyn/issues/12254")>
Public Async Function TestGenericCallOnTypeContainingAnonymousType() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.Linq;
class Program
{
static void Main(string[] args)
{
new[] { new { x = 1 } }.ToArr$$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
state.SendTypeChars("(")
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
state.AssertMatchesTextStartingAtLine(7, "new[] { new { x = 1 } }.ToArray(")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionSetterValuey() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
int _x;
int X
{
set
{
_x = $$
}
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
Await state.AssertSelectedCompletionItem("value", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(12530, "https://github.com/dotnet/roslyn/issues/12530")>
Public Async Function TestAnonymousTypeDescription() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.Linq;
class Program
{
static void Main(string[] args)
{
new[] { new { x = 1 } }.ToArr$$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(description:=
$"({ CSharpFeaturesResources.extension }) 'a[] System.Collections.Generic.IEnumerable<'a>.ToArray<'a>()
{ FeaturesResources.Anonymous_Types_colon }
'a { FeaturesResources.is_ } new {{ int x }}")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestRecursiveGenericSymbolKey() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.Collections.Generic;
class Program
{
static void ReplaceInList<T>(List<T> list, T oldItem, T newItem)
{
$$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendTypeChars("list")
state.SendTypeChars(".")
Await state.AssertCompletionSession()
state.SendTypeChars("Add")
Await state.AssertSelectedCompletionItem("Add", description:="void List<T>.Add(T item)")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitNamedParameterWithColon() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.Collections.Generic;
class Program
{
static void Main(int args)
{
Main(args$$
}
}]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList())
state.SendInvokeCompletionList()
state.SendTypeChars(":")
Await state.AssertNoCompletionSession()
Assert.Contains("args:", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(13481, "https://github.com/dotnet/roslyn/issues/13481")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBackspaceSelection1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
DateTimeOffset$$
}
}
]]></Document>)
state.Workspace.Options = state.Workspace.Options.WithChangedOption(
CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True)
For Each c In "Offset"
state.SendBackspace()
Await state.WaitForAsynchronousOperationsAsync()
Next
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("DateTime")
End Using
End Function
<WorkItem(13481, "https://github.com/dotnet/roslyn/issues/13481")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBackspaceSelection2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
DateTimeOffset.$$
}
}
]]></Document>)
state.Workspace.Options = state.Workspace.Options.WithChangedOption(
CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True)
For Each c In "Offset."
state.SendBackspace()
Await state.WaitForAsynchronousOperationsAsync()
Next
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("DateTime")
End Using
End Function
<WorkItem(14465, "https://github.com/dotnet/roslyn/issues/14465")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TypingNumberShouldNotDismiss1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void Moo1()
{
new C()$$
}
}
]]></Document>)
state.SendTypeChars(".")
Await state.AssertCompletionSession()
state.SendTypeChars("1")
Await state.AssertSelectedCompletionItem("Moo1")
End Using
End Function
<WorkItem(14085, "https://github.com/dotnet/roslyn/issues/14085")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypingDoesNotOverrideExactMatch() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.IO;
class C
{
void Moo1()
{
string path = $$
}
}
]]></Document>)
state.SendTypeChars("Path")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("Path")
End Using
End Function
<WorkItem(14085, "https://github.com/dotnet/roslyn/issues/14085")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function MRUOverTargetTyping() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.IO;
using System.Threading.Tasks;
class C
{
async Task Moo()
{
await Moo().$$
}
}
]]></Document>)
state.SendTypeChars("Configure")
state.SendTab()
For i = 1 To "ConfigureAwait".Length
state.SendBackspace()
Next
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("ConfigureAwait")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function MovingCaretToStartSoftSelects() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
using System;
class C
{
void M()
{
$$
}
}
</Document>)
state.SendTypeChars("Conso")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=True)
For Each ch In "Conso"
state.SendLeftKey()
Next
Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=False)
state.SendRightKey()
Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoBlockOnCompletionItems1() As Task
Dim tcs = New TaskCompletionSource(Of Boolean)
Using state = TestState.CreateCSharpTestState(
<Document>
using $$
</Document>, {New TaskControlledCompletionProvider(tcs.Task)})
state.Workspace.Options = state.Workspace.Options.WithChangedOption(
CompletionOptions.BlockForCompletionItems, LanguageNames.CSharp, False)
state.SendTypeChars("Sys.")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertNoCompletionSession()
Assert.Contains("Sys.", state.GetLineTextFromCaretPosition())
tcs.SetResult(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoBlockOnCompletionItems2() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
using $$
</Document>, {New TaskControlledCompletionProvider(Task.FromResult(True))})
state.Workspace.Options = state.Workspace.Options.WithChangedOption(
CompletionOptions.BlockForCompletionItems, LanguageNames.CSharp, False)
state.SendTypeChars("Sys")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
state.SendTypeChars(".")
Assert.Contains("System.", state.GetLineTextFromCaretPosition())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoBlockOnCompletionItems4() As Task
Dim tcs = New TaskCompletionSource(Of Boolean)
Using state = TestState.CreateCSharpTestState(
<Document>
using $$
</Document>, {New TaskControlledCompletionProvider(tcs.Task)})
state.Workspace.Options = state.Workspace.Options.WithChangedOption(
CompletionOptions.BlockForCompletionItems, LanguageNames.CSharp, False)
state.SendTypeChars("Sys")
state.SendCommitUniqueCompletionListItem()
Await Task.Delay(250)
Await state.AssertNoCompletionSession(block:=False)
Assert.Contains("Sys", state.GetLineTextFromCaretPosition())
Assert.DoesNotContain("System", state.GetLineTextFromCaretPosition())
tcs.SetResult(True)
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertNoCompletionSession()
Assert.Contains("System", state.GetLineTextFromCaretPosition())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoBlockOnCompletionItems3() As Task
Dim tcs = New TaskCompletionSource(Of Boolean)
Using state = TestState.CreateCSharpTestState(
<Document>
using $$
</Document>, {New TaskControlledCompletionProvider(tcs.Task)})
state.Workspace.Options = state.Workspace.Options.WithChangedOption(
CompletionOptions.BlockForCompletionItems, LanguageNames.CSharp, False)
state.SendTypeChars("Sys")
state.SendCommitUniqueCompletionListItem()
Await Task.Delay(250)
Await state.AssertNoCompletionSession(block:=False)
Assert.Contains("Sys", state.GetLineTextFromCaretPosition())
Assert.DoesNotContain("System", state.GetLineTextFromCaretPosition())
state.SendTypeChars("a")
tcs.SetResult(True)
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
Assert.Contains("Sysa", state.GetLineTextFromCaretPosition())
End Using
End Function
Private Class TaskControlledCompletionProvider
Inherits CompletionProvider
Private ReadOnly _task As Task
Public Sub New(task As Task)
_task = task
End Sub
Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task
Return _task
End Function
End Class
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function Filters_EmptyList1() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.IO;
using System.Threading.Tasks;
class C
{
async Task Moo()
{
var x = asd$$
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync()
Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters
Dim dict = New Dictionary(Of CompletionItemFilter, Boolean)
For Each f In filters
dict(f) = False
Next
dict(CompletionItemFilter.InterfaceFilter) = True
Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary())
state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args)
Await state.WaitForAsynchronousOperationsAsync()
Assert.Null(state.CurrentCompletionPresenterSession.SelectedItem)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function Filters_EmptyList2() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.IO;
using System.Threading.Tasks;
class C
{
async Task Moo()
{
var x = asd$$
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync()
Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters
Dim dict = New Dictionary(Of CompletionItemFilter, Boolean)
For Each f In filters
dict(f) = False
Next
dict(CompletionItemFilter.InterfaceFilter) = True
Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary())
state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args)
Await state.WaitForAsynchronousOperationsAsync()
Assert.Null(state.CurrentCompletionPresenterSession.SelectedItem)
state.SendTab()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function Filters_EmptyList3() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.IO;
using System.Threading.Tasks;
class C
{
async Task Moo()
{
var x = asd$$
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync()
Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters
Dim dict = New Dictionary(Of CompletionItemFilter, Boolean)
For Each f In filters
dict(f) = False
Next
dict(CompletionItemFilter.InterfaceFilter) = True
Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary())
state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args)
Await state.WaitForAsynchronousOperationsAsync()
Assert.Null(state.CurrentCompletionPresenterSession.SelectedItem)
state.SendReturn()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function Filters_EmptyList4() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.IO;
using System.Threading.Tasks;
class C
{
async Task Moo()
{
var x = asd$$
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.WaitForAsynchronousOperationsAsync()
Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters
Dim dict = New Dictionary(Of CompletionItemFilter, Boolean)
For Each f In filters
dict(f) = False
Next
dict(CompletionItemFilter.InterfaceFilter) = True
Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary())
state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args)
Await state.WaitForAsynchronousOperationsAsync()
Assert.Null(state.CurrentCompletionPresenterSession.SelectedItem)
state.SendTypeChars(".")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(15881, "https://github.com/dotnet/roslyn/issues/15881")>
Public Async Function CompletionAfterDotBeforeAwaitTask() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System.Threading.Tasks;
class C
{
async Task Moo()
{
Task.$$
await Task.Delay(50);
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
End Using
End Function
<WorkItem(14704, "https://github.com/dotnet/roslyn/issues/14704")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspaceTriggerSubstringMatching() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
using System;
class Program
{
static void Main(string[] args)
{
if (Environment$$
}
}
</Document>)
Dim key = New OptionKey(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp)
state.Workspace.Options = state.Workspace.Options.WithChangedOption(key, True)
state.SendBackspace()
Await state.AssertSelectedCompletionItem(displayText:="Environment", isHardSelected:=True)
End Using
End Function
<WorkItem(16236, "https://github.com/dotnet/roslyn/issues/16236")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AttributeNamedParameterEqualsItemCommittedOnSpace() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
[A($$)]
class AAttribute: Attribute
{
public string Skip { get; set; }
} </Document>)
state.SendTypeChars("Skip")
Await state.AssertCompletionSession()
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
Assert.Equal("[A(Skip )]", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(362890, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=362890")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFilteringAfterSimpleInvokeShowsAllItemsMatchingFilter() As Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
enum Color
{
Red,
Green,
Blue
}
class C
{
void M()
{
Color.Re$$d
}
}
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("Red")
state.CompletionItemsContainsAll(displayText:={"Red", "Green", "Blue", "Equals"})
Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters
Dim dict = New Dictionary(Of CompletionItemFilter, Boolean)
For Each f In filters
dict(f) = False
Next
dict(CompletionItemFilter.EnumFilter) = True
Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary())
state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args)
Await state.AssertSelectedCompletionItem("Red")
state.CompletionItemsContainsAll(displayText:={"Red", "Green", "Blue"})
Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "Equals"))
For Each f In filters
dict(f) = False
Next
args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary())
state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args)
Await state.AssertSelectedCompletionItem("Red")
state.CompletionItemsContainsAll(displayText:={"Red", "Green", "Blue", "Equals"})
End Using
End Function
<WorkItem(16236, "https://github.com/dotnet/roslyn/issues/16236")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NameCompletionSorting() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
interface ISyntaxFactsService {}
class C
{
void M()
{
ISyntaxFactsService $$
}
} </Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Dim expectedOrder =
{
"syntaxFactsService",
"syntaxFacts",
"factsService",
"syntax",
"service"
}
state.AssertItemsInOrder(expectedOrder)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub TestLargeChangeBrokenUpIntoSmallTextChanges()
Dim provider = New MultipleChangeCompletionProvider()
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
void goo() {
return $$
}
}]]></Document>, {provider})
Dim testDocument = state.Workspace.Documents(0)
Dim textBuffer = testDocument.TextBuffer
Dim snapshotBeforeCommit = textBuffer.CurrentSnapshot
provider.SetInfo(snapshotBeforeCommit.GetText(), testDocument.CursorPosition.Value)
' First send a space to trigger out special completion provider.
state.SendInvokeCompletionList()
state.SendTab()
' Verify that we see the entire change
Dim finalText = textBuffer.CurrentSnapshot.GetText()
Assert.Equal(
"using NewUsing;
using System;
class C
{
void goo() {
return InsertedItem
}
}", finalText)
' This should have happened as two text changes to the buffer.
Dim changes = snapshotBeforeCommit.Version.Changes
Assert.Equal(2, changes.Count)
Dim actualChanges = changes.ToArray()
Dim firstChange = actualChanges(0)
Assert.Equal(New Span(0, 0), firstChange.OldSpan)
Assert.Equal("using NewUsing;", firstChange.NewText)
Dim secondChange = actualChanges(1)
Assert.Equal(New Span(testDocument.CursorPosition.Value, 0), secondChange.OldSpan)
Assert.Equal("InsertedItem", secondChange.NewText)
' Make sure new edits happen after the text that was inserted.
state.SendTypeChars("1")
finalText = textBuffer.CurrentSnapshot.GetText()
Assert.Equal(
"using NewUsing;
using System;
class C
{
void goo() {
return InsertedItem1
}
}", finalText)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub TestLargeChangeBrokenUpIntoSmallTextChanges2()
Dim provider = New MultipleChangeCompletionProvider()
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
class C
{
void goo() {
return Custom$$
}
}]]></Document>, {provider})
Dim testDocument = state.Workspace.Documents(0)
Dim textBuffer = testDocument.TextBuffer
Dim snapshotBeforeCommit = textBuffer.CurrentSnapshot
provider.SetInfo(snapshotBeforeCommit.GetText(), testDocument.CursorPosition.Value)
' First send a space to trigger out special completion provider.
state.SendInvokeCompletionList()
state.SendTab()
' Verify that we see the entire change
Dim finalText = textBuffer.CurrentSnapshot.GetText()
Assert.Equal(
"using NewUsing;
using System;
class C
{
void goo() {
return InsertedItem
}
}", finalText)
' This should have happened as two text changes to the buffer.
Dim changes = snapshotBeforeCommit.Version.Changes
Assert.Equal(2, changes.Count)
Dim actualChanges = changes.ToArray()
Dim firstChange = actualChanges(0)
Assert.Equal(New Span(0, 0), firstChange.OldSpan)
Assert.Equal("using NewUsing;", firstChange.NewText)
Dim secondChange = actualChanges(1)
Assert.Equal(New Span(testDocument.CursorPosition.Value - "Custom".Length, "Custom".Length), secondChange.OldSpan)
Assert.Equal("InsertedItem", secondChange.NewText)
' Make sure new edits happen after the text that was inserted.
state.SendTypeChars("1")
finalText = textBuffer.CurrentSnapshot.GetText()
Assert.Equal(
"using NewUsing;
using System;
class C
{
void goo() {
return InsertedItem1
}
}", finalText)
End Using
End Sub
<WorkItem(296512, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296512")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestRegionDirectiveIndentation() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class C
{
$$
}
</Document>, includeFormatCommandHandler:=True)
state.SendTypeChars("#")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("#", state.GetLineFromCurrentCaretPosition().GetText())
Await state.AssertNoCompletionSession()
state.SendTypeChars("reg")
Await state.AssertSelectedCompletionItem(displayText:="region")
state.SendReturn()
Await state.AssertNoCompletionSession()
Assert.Equal(" #region", state.GetLineFromCurrentCaretPosition().GetText())
Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition)
state.SendReturn()
Assert.Equal("", state.GetLineFromCurrentCaretPosition().GetText())
state.SendTypeChars("#")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("#", state.GetLineFromCurrentCaretPosition().GetText())
Await state.AssertNoCompletionSession()
state.SendTypeChars("endr")
Await state.AssertSelectedCompletionItem(displayText:="endregion")
state.SendReturn()
Await state.AssertNoCompletionSession()
Assert.Equal(" #endregion", state.GetLineFromCurrentCaretPosition().GetText())
Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AfterIdentifierInCaseLabel() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class C
{
void M()
{
switch (true)
{
case identifier $$
}
}
}
</Document>)
state.SendTypeChars("w")
Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=False)
state.SendBackspace()
state.SendTypeChars("i")
Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AfterIdentifierInCaseLabel_ColorColor() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class identifier { }
class C
{
const identifier identifier = null;
void M()
{
switch (true)
{
case identifier $$
}
}
}
</Document>)
state.SendTypeChars("w")
Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=False)
state.SendBackspace()
state.SendTypeChars("i")
Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AfterIdentifierInCaseLabel_ClassNameOnly() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class identifier { }
class C
{
void M()
{
switch (true)
{
case identifier $$
}
}
}
</Document>)
state.SendTypeChars("w")
Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False)
state.SendBackspace()
state.SendTypeChars("i")
Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AfterDoubleIdentifierInCaseLabel() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class C
{
void M()
{
switch (true)
{
case identifier identifier $$
}
}
}
</Document>)
state.SendTypeChars("w")
Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=True)
End Using
End Function
Private Class MultipleChangeCompletionProvider
Inherits CompletionProvider
Private _text As String
Private _caretPosition As Integer
Public Sub SetInfo(text As String, caretPosition As Integer)
_text = text
_caretPosition = caretPosition
End Sub
Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task
context.AddItem(CompletionItem.Create(
"CustomItem",
rules:=CompletionItemRules.Default.WithMatchPriority(1000)))
Return Task.CompletedTask
End Function
Public Overrides Function ShouldTriggerCompletion(text As SourceText, caretPosition As Integer, trigger As CompletionTrigger, options As OptionSet) As Boolean
Return True
End Function
Public Overrides Function GetChangeAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task(Of CompletionChange)
Dim newText =
"using NewUsing;
using System;
class C
{
void goo() {
return InsertedItem"
Dim change = CompletionChange.Create(
New TextChange(New TextSpan(0, _caretPosition), newText))
Return Task.FromResult(change)
End Function
<WorkItem(15348, "https://github.com/dotnet/roslyn/issues/15348")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAfterCasePatternSwitchLabel() As Task
Using state = TestState.CreateCSharpTestState(
<Document>
class C
{
void M()
{
object o = 1;
switch(o)
{
case int i:
$$
break;
}
}
}
</Document>)
state.SendTypeChars("this")
Await state.AssertSelectedCompletionItem(displayText:="this", isHardSelected:=True)
End Using
End Function
End Class
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb
|
Visual Basic
|
apache-2.0
| 146,474
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundUserDefinedBinaryOperator
Public ReadOnly Property Left As BoundExpression
Get
Return [Call].Arguments(0)
End Get
End Property
Public ReadOnly Property Right As BoundExpression
Get
Return [Call].Arguments(1)
End Get
End Property
Public ReadOnly Property [Call] As BoundCall
Get
Return DirectCast(UnderlyingExpression, BoundCall)
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(Type.Equals(UnderlyingExpression.Type))
Debug.Assert((OperatorKind And BinaryOperatorKind.UserDefined) <> 0)
Debug.Assert(UnderlyingExpression.Kind = BoundKind.BadExpression OrElse UnderlyingExpression.Kind = BoundKind.Call)
If UnderlyingExpression.Kind = BoundKind.Call Then
Dim underlyingCall = DirectCast(UnderlyingExpression, BoundCall)
Debug.Assert(underlyingCall.Method.MethodKind = MethodKind.UserDefinedOperator AndAlso underlyingCall.Method.ParameterCount = 2)
If (OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then
For i As Integer = 0 To underlyingCall.Arguments.Length - 1
Dim argument As BoundExpression = underlyingCall.Arguments(i)
Dim parameter As ParameterSymbol = underlyingCall.Method.Parameters(i)
Debug.Assert(OverloadResolution.CanLiftType(parameter.Type))
Debug.Assert(argument.Type.IsNullableType() AndAlso
argument.Type.GetNullableUnderlyingType().IsSameTypeIgnoringAll(parameter.Type))
Next
Debug.Assert(underlyingCall.Type.IsNullableType())
Debug.Assert(underlyingCall.Type.IsSameTypeIgnoringAll(underlyingCall.Method.ReturnType) OrElse
(OverloadResolution.CanLiftType(underlyingCall.Method.ReturnType) AndAlso
underlyingCall.Type.GetNullableUnderlyingType().IsSameTypeIgnoringAll(underlyingCall.Method.ReturnType)))
Else
For i As Integer = 0 To underlyingCall.Arguments.Length - 1
Dim argument As BoundExpression = underlyingCall.Arguments(i)
Dim parameter As ParameterSymbol = underlyingCall.Method.Parameters(i)
Debug.Assert(argument.Type.IsSameTypeIgnoringAll(parameter.Type))
Next
Debug.Assert(underlyingCall.Type.IsSameTypeIgnoringAll(underlyingCall.Method.ReturnType))
End If
End If
End Sub
#End If
End Class
End Namespace
|
physhi/roslyn
|
src/Compilers/VisualBasic/Portable/BoundTree/BoundUserDefinedBinaryOperator.vb
|
Visual Basic
|
apache-2.0
| 3,231
|
' 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.Immutable
Imports System.Reflection.PortableExecutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Partial Friend MustInherit Class PEModuleBuilder
Inherits PEModuleBuilder(Of VisualBasicCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState)
' Not many methods should end up here.
Private ReadOnly _disableJITOptimization As ConcurrentDictionary(Of MethodSymbol, Boolean) = New ConcurrentDictionary(Of MethodSymbol, Boolean)(ReferenceEqualityComparer.Instance)
' Gives the name of this module (may not reflect the name of the underlying symbol).
' See Assembly.MetadataName.
Private ReadOnly _metadataName As String
Private _lazyExportedTypes As ImmutableArray(Of Cci.ExportedType)
Private _lazyNumberOfTypesFromOtherModules As Integer
Private _lazyTranslatedImports As ImmutableArray(Of Cci.UsedNamespaceOrType)
Private _lazyDefaultNamespace As String
Friend Sub New(sourceModule As SourceModuleSymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As Cci.ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription))
MyBase.New(sourceModule.ContainingSourceAssembly.DeclaringCompilation,
sourceModule,
serializationProperties,
manifestResources,
outputKind,
emitOptions,
New ModuleCompilationState())
Dim specifiedName = sourceModule.MetadataName
_metadataName = If(specifiedName <> CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName,
specifiedName,
If(emitOptions.OutputNameOverride, specifiedName))
m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, Me)
If sourceModule.AnyReferencedAssembliesAreLinked Then
_embeddedTypesManagerOpt = New NoPia.EmbeddedTypesManager(Me)
End If
End Sub
''' <summary>
''' True if conditional calls may be omitted when the required preprocessor symbols are not defined.
''' </summary>
''' <remarks>
''' Only false in debugger scenarios (where calls should never be omitted).
''' </remarks>
Friend MustOverride ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Public Overrides ReadOnly Property Name As String
Get
Return _metadataName
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ModuleName As String
Get
Return _metadataName
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property CorLibrary As AssemblySymbol
Get
Return SourceModule.ContainingSourceAssembly.CorLibrary
End Get
End Property
Public NotOverridable Overrides ReadOnly Property GenerateVisualBasicStylePdb As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String)
Get
' NOTE: Dev12 does not seem to emit anything but the name (i.e. no version, token, etc).
' See Builder::WriteNoPiaPdbList
Return SourceModule.ReferencedAssemblySymbols.Where(Function(a) a.IsLinked).Select(Function(a) a.Name)
End Get
End Property
Public NotOverridable Overrides Function GetImports() As ImmutableArray(Of Cci.UsedNamespaceOrType)
' Imports should have been translated in code gen phase.
Debug.Assert(Not _lazyTranslatedImports.IsDefault)
Return _lazyTranslatedImports
End Function
Public Sub TranslateImports(diagnostics As DiagnosticBag)
If _lazyTranslatedImports.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(
_lazyTranslatedImports,
NamespaceScopeBuilder.BuildNamespaceScope(Me, SourceModule.XmlNamespaces, SourceModule.AliasImports, SourceModule.MemberImports, diagnostics))
End If
End Sub
Public NotOverridable Overrides ReadOnly Property DefaultNamespace As String
Get
If _lazyDefaultNamespace IsNot Nothing Then
Return _lazyDefaultNamespace
End If
Dim rootNamespace = SourceModule.RootNamespace
If rootNamespace.IsGlobalNamespace Then
Return String.Empty
End If
_lazyDefaultNamespace = rootNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)
Return _lazyDefaultNamespace
End Get
End Property
Protected NotOverridable Overrides Iterator Function GetAssemblyReferencesFromAddedModules(diagnostics As DiagnosticBag) As IEnumerable(Of Cci.IAssemblyReference)
Dim modules As ImmutableArray(Of ModuleSymbol) = SourceModule.ContainingAssembly.Modules
For i As Integer = 1 To modules.Length - 1
For Each aRef As AssemblySymbol In modules(i).GetReferencedAssemblySymbols()
Yield Translate(aRef, diagnostics)
Next
Next
End Function
Private Sub ValidateReferencedAssembly(assembly As AssemblySymbol, asmRef As AssemblyReference, diagnostics As DiagnosticBag)
Dim asmIdentity As AssemblyIdentity = SourceModule.ContainingAssembly.Identity
Dim refIdentity As AssemblyIdentity = asmRef.Identity
If asmIdentity.IsStrongName AndAlso Not refIdentity.IsStrongName AndAlso
asmRef.Identity.ContentType <> Reflection.AssemblyContentType.WindowsRuntime Then
' Dev12 reported error, we have changed it to a warning to allow referencing libraries
' built for platforms that don't support strong names.
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton)
End If
If OutputKind <> OutputKind.NetModule AndAlso
Not String.IsNullOrEmpty(refIdentity.CultureName) AndAlso
Not String.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase) Then
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton)
End If
Dim refMachine = assembly.Machine
' If other assembly is agnostic, this is always safe
' Also, if no mscorlib was specified for back compat we add a reference to mscorlib
' that resolves to the current framework directory. If the compiler Is 64-bit
' this Is a 64-bit mscorlib, which will produce a warning if /platform:x86 Is
' specified.A reference to the default mscorlib should always succeed without
' warning so we ignore it here.
If assembly IsNot assembly.CorLibrary AndAlso
Not (refMachine = Machine.I386 AndAlso Not assembly.Bit32Required) Then
Dim machine = SourceModule.Machine
If Not (machine = Machine.I386 AndAlso Not SourceModule.Bit32Required) AndAlso
machine <> refMachine Then
' Different machine types, and neither is agnostic
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton)
End If
End If
If _embeddedTypesManagerOpt IsNot Nothing AndAlso _embeddedTypesManagerOpt.IsFrozen Then
_embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics)
End If
End Sub
Friend NotOverridable Overrides Function SynthesizeAttribute(attributeConstructor As WellKnownMember) As Cci.ICustomAttribute
Return Me.Compilation.TrySynthesizeAttribute(attributeConstructor)
End Function
Public NotOverridable Overrides Function GetSourceAssemblyAttributes(isRefAssembly As Boolean) As IEnumerable(Of Cci.ICustomAttribute)
Return SourceModule.ContainingSourceAssembly.GetAssemblyCustomAttributesToEmit(Me.CompilationState,
isRefAssembly,
emittingAssemblyAttributesInNetModule:=OutputKind.IsNetModule())
End Function
Public NotOverridable Overrides Function GetSourceAssemblySecurityAttributes() As IEnumerable(Of Cci.SecurityAttribute)
Return SourceModule.ContainingSourceAssembly.GetSecurityAttributes()
End Function
Public NotOverridable Overrides Function GetSourceModuleAttributes() As IEnumerable(Of Cci.ICustomAttribute)
Return SourceModule.GetCustomAttributesToEmit(Me.CompilationState)
End Function
Public NotOverridable Overrides Function GetSymbolToLocationMap() As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)
Dim result As New MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)()
Dim namespacesAndTypesToProcess As New Stack(Of NamespaceOrTypeSymbol)()
namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace)
Dim location As Location = Nothing
While namespacesAndTypesToProcess.Count > 0
Dim symbol As NamespaceOrTypeSymbol = namespacesAndTypesToProcess.Pop()
Select Case symbol.Kind
Case SymbolKind.Namespace
location = GetSmallestSourceLocationOrNull(symbol)
' filtering out synthesized symbols not having real source
' locations such as anonymous types, my types, etc...
If location IsNot Nothing Then
For Each member In symbol.GetMembers()
Select Case member.Kind
Case SymbolKind.Namespace, SymbolKind.NamedType
namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
Next
End If
Case SymbolKind.NamedType
location = GetSmallestSourceLocationOrNull(symbol)
If location IsNot Nothing Then
' add this named type location
AddSymbolLocation(result, location, DirectCast(symbol, Cci.IDefinition))
For Each member In symbol.GetMembers()
Select Case member.Kind
Case SymbolKind.NamedType
namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol))
Case SymbolKind.Method
Dim method = DirectCast(member, MethodSymbol)
If method.IsDefaultValueTypeConstructor() OrElse
method.IsPartialWithoutImplementation Then
Exit Select
End If
AddSymbolLocation(result, member)
Case SymbolKind.Property,
SymbolKind.Field
AddSymbolLocation(result, member)
Case SymbolKind.Event
AddSymbolLocation(result, member)
Dim AssociatedField = (DirectCast(member, EventSymbol)).AssociatedField
If AssociatedField IsNot Nothing Then
' event backing fields do not show up in GetMembers
AddSymbolLocation(result, AssociatedField)
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
Next
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.Kind)
End Select
End While
Return result
End Function
Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), symbol As Symbol)
Dim location As Location = GetSmallestSourceLocationOrNull(symbol)
If location IsNot Nothing Then
AddSymbolLocation(result, location, DirectCast(symbol, Cci.IDefinition))
End If
End Sub
Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), location As Location, definition As Cci.IDefinition)
Dim span As FileLinePositionSpan = location.GetLineSpan()
Dim doc As Cci.DebugSourceDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath:=location.SourceTree.FilePath)
If (doc IsNot Nothing) Then
result.Add(doc,
New Cci.DefinitionWithLocation(
definition,
span.StartLinePosition.Line,
span.StartLinePosition.Character,
span.EndLinePosition.Line,
span.EndLinePosition.Character))
End If
End Sub
Private Function GetSmallestSourceLocationOrNull(symbol As Symbol) As Location
Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation
Debug.Assert(Me.Compilation Is compilation, "How did we get symbol from different compilation?")
Dim result As Location = Nothing
For Each loc In symbol.Locations
If loc.IsInSource AndAlso (result Is Nothing OrElse compilation.CompareSourceLocations(result, loc) > 0) Then
result = loc
End If
Next
Return result
End Function
''' <summary>
''' Ignore accessibility when resolving well-known type
''' members, in particular for generic type arguments
''' (e.g.: binding to internal types in the EE).
''' </summary>
Friend Overridable ReadOnly Property IgnoreAccessibility As Boolean
Get
Return False
End Get
End Property
Friend Overridable Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol, diagnostics As DiagnosticBag) As VariableSlotAllocator
Return Nothing
End Function
Friend Overridable Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey)
Return ImmutableArray(Of AnonymousTypeKey).Empty
End Function
Friend Overridable Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer
Return 0
End Function
Friend Overridable Function TryGetAnonymousTypeName(template As NamedTypeSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean
Debug.Assert(Compilation Is template.DeclaringCompilation)
name = Nothing
index = -1
Return False
End Function
Friend NotOverridable Overrides Function GetAnonymousTypes(context As EmitContext) As ImmutableArray(Of Cci.INamespaceTypeDefinition)
If context.MetadataOnly Then
Return ImmutableArray(Of Cci.INamespaceTypeDefinition).Empty
End If
Return StaticCast(Of Cci.INamespaceTypeDefinition).
From(SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates)
End Function
Friend Overrides Iterator Function GetTopLevelTypesCore(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition)
For Each topLevel In GetAdditionalTopLevelTypes()
Yield topLevel
Next
Dim embeddedSymbolManager As EmbeddedSymbolManager = SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager
Dim stack As New Stack(Of NamespaceOrTypeSymbol)()
stack.Push(SourceModule.GlobalNamespace)
Do
Dim sym As NamespaceOrTypeSymbol = stack.Pop()
If sym.Kind = SymbolKind.NamedType Then
Debug.Assert(sym Is sym.OriginalDefinition)
Debug.Assert(sym.ContainingType Is Nothing)
' Skip unreferenced embedded types.
If Not sym.IsEmbedded OrElse embeddedSymbolManager.IsSymbolReferenced(sym) Then
Dim type = DirectCast(sym, NamedTypeSymbol)
Yield type
End If
Else
Debug.Assert(sym.Kind = SymbolKind.Namespace)
Dim members As ImmutableArray(Of Symbol) = sym.GetMembers()
For i As Integer = members.Length - 1 To 0 Step -1
Dim nortsym As NamespaceOrTypeSymbol = TryCast(members(i), NamespaceOrTypeSymbol)
If nortsym IsNot Nothing Then
stack.Push(nortsym)
End If
Next
End If
Loop While stack.Count > 0
End Function
Friend Overridable Function GetAdditionalTopLevelTypes() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public NotOverridable Overrides Function GetExportedTypes(diagnostics As DiagnosticBag) As ImmutableArray(Of Cci.ExportedType)
Debug.Assert(HaveDeterminedTopLevelTypes)
If _lazyExportedTypes.IsDefault Then
_lazyExportedTypes = CalculateExportedTypes()
If _lazyExportedTypes.Length > 0 Then
ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics)
End If
End If
Return _lazyExportedTypes
End Function
''' <summary>
''' Builds an array of public type symbols defined in netmodules included in the compilation
''' And type forwarders defined in this compilation Or any included netmodule (in this order).
''' </summary>
Private Function CalculateExportedTypes() As ImmutableArray(Of Cci.ExportedType)
Dim builder = ArrayBuilder(Of Cci.ExportedType).GetInstance()
Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly
If Not OutputKind.IsNetModule() Then
Dim modules = sourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1 'NOTE: skipping modules(0)
GetExportedTypes(modules(i).GlobalNamespace, -1, builder)
Next
End If
Dim seenTopLevelForwardedTypes = New HashSet(Of NamedTypeSymbol)()
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder)
If Not OutputKind.IsNetModule() Then
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder)
End If
Return builder.ToImmutableAndFree()
End Function
Private Sub ReportExportedTypeNameCollisions(exportedTypes As ImmutableArray(Of Cci.ExportedType), diagnostics As DiagnosticBag)
Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly
Dim exportedNamesMap = New Dictionary(Of String, NamedTypeSymbol)()
For Each exportedType In _lazyExportedTypes
Dim type = DirectCast(exportedType.Type, NamedTypeSymbol)
Debug.Assert(type.IsDefinition)
If type.ContainingType IsNot Nothing Then
Continue For
End If
Dim fullEmittedName As String = MetadataHelpers.BuildQualifiedName(
DirectCast(type, Cci.INamespaceTypeReference).NamespaceName,
Cci.MetadataWriter.GetMangledName(type))
' First check against types declared in the primary module
If ContainsTopLevelType(fullEmittedName) Then
If type.ContainingAssembly Is sourceAssembly Then
diagnostics.Add(ERRID.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule)
Else
diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type))
End If
Continue For
End If
Dim contender As NamedTypeSymbol = Nothing
' Now check against other exported types
If exportedNamesMap.TryGetValue(fullEmittedName, contender) Then
If type.ContainingAssembly Is sourceAssembly Then
' all exported types precede forwarded types, therefore contender cannot be a forwarded type.
Debug.Assert(contender.ContainingAssembly Is sourceAssembly)
diagnostics.Add(ERRID.ERR_ExportedTypesConflict, NoLocation.Singleton,
CustomSymbolDisplayFormatter.DefaultErrorFormat(type),
CustomSymbolDisplayFormatter.DefaultErrorFormat(type.ContainingModule),
CustomSymbolDisplayFormatter.DefaultErrorFormat(contender),
CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule))
ElseIf contender.ContainingAssembly Is sourceAssembly Then
' Forwarded type conflicts with exported type
diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton,
CustomSymbolDisplayFormatter.DefaultErrorFormat(type),
type.ContainingAssembly,
CustomSymbolDisplayFormatter.DefaultErrorFormat(contender),
CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule))
Else
' Forwarded type conflicts with another forwarded type
diagnostics.Add(ERRID.ERR_ForwardedTypesConflict, NoLocation.Singleton,
CustomSymbolDisplayFormatter.DefaultErrorFormat(type),
type.ContainingAssembly,
CustomSymbolDisplayFormatter.DefaultErrorFormat(contender),
contender.ContainingAssembly)
End If
Continue For
End If
exportedNamesMap.Add(fullEmittedName, type)
Next
End Sub
Private Overloads Sub GetExportedTypes(symbol As NamespaceOrTypeSymbol, parentIndex As Integer, builder As ArrayBuilder(Of Cci.ExportedType))
Dim index As Integer
If symbol.Kind = SymbolKind.NamedType Then
If symbol.DeclaredAccessibility <> Accessibility.Public Then
Return
End If
Debug.Assert(symbol.IsDefinition)
index = builder.Count
builder.Add(New Cci.ExportedType(DirectCast(symbol, Cci.ITypeReference), parentIndex, isForwarder:=False))
Else
index = -1
End If
For Each member In symbol.GetMembers()
Dim namespaceOrType = TryCast(member, NamespaceOrTypeSymbol)
If namespaceOrType IsNot Nothing Then
GetExportedTypes(namespaceOrType, index, builder)
End If
Next
End Sub
Private Shared Sub GetForwardedTypes(
seenTopLevelTypes As HashSet(Of NamedTypeSymbol),
wellKnownAttributeData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol),
builder As ArrayBuilder(Of Cci.ExportedType))
If wellKnownAttributeData?.ForwardedTypes?.Count > 0 Then
' (type, index of the parent exported type in builder, or -1 if the type is a top-level type)
Dim stack = ArrayBuilder(Of (type As NamedTypeSymbol, parentIndex As Integer)).GetInstance()
' Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names.
Dim orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes.OrderBy(Function(t) t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat))
For Each forwardedType As NamedTypeSymbol In orderedForwardedTypes
Dim originalDefinition As NamedTypeSymbol = forwardedType.OriginalDefinition
Debug.Assert(originalDefinition.ContainingType Is Nothing, "How did a nested type get forwarded?")
' De-dup the original definitions before emitting.
If Not seenTopLevelTypes.Add(originalDefinition) Then
Continue For
End If
' Return all nested types.
' Note the order: depth first, children in reverse order (to match dev10, not a requirement).
Debug.Assert(stack.Count = 0)
stack.Push((originalDefinition, -1))
While stack.Count > 0
Dim entry = stack.Pop()
' In general, we don't want private types to appear in the ExportedTypes table.
If entry.type.DeclaredAccessibility = Accessibility.Private Then
' NOTE: this will also exclude nested types of curr.
Continue While
End If
' NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection.
Dim index = builder.Count
builder.Add(New Cci.ExportedType(entry.type, entry.parentIndex, isForwarder:=True))
' Iterate backwards so they get popped in forward order.
Dim nested As ImmutableArray(Of NamedTypeSymbol) = entry.type.GetTypeMembers() ' Ordered.
For i As Integer = nested.Length - 1 To 0 Step -1
stack.Push((nested(i), index))
Next
End While
Next
stack.Free()
End If
End Sub
Friend Iterator Function GetReferencedAssembliesUsedSoFar() As IEnumerable(Of AssemblySymbol)
For Each assembly In SourceModule.GetReferencedAssemblySymbols()
If Not assembly.IsLinked AndAlso
Not assembly.IsMissing AndAlso
m_AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(assembly) Then
Yield assembly
End If
Next
End Function
Friend NotOverridable Overrides Function GetSystemType(syntaxOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference
Dim systemTypeSymbol As NamedTypeSymbol = SourceModule.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type)
Dim useSiteError = Binder.GetUseSiteErrorForWellKnownType(systemTypeSymbol)
If useSiteError IsNot Nothing Then
Binder.ReportDiagnostic(diagnostics,
If(syntaxOpt IsNot Nothing, syntaxOpt.GetLocation(), NoLocation.Singleton),
useSiteError)
End If
Return Translate(systemTypeSymbol, syntaxOpt, diagnostics, needDeclaration:=True)
End Function
Friend NotOverridable Overrides Function GetSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference
Return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics),
needDeclaration:=True,
syntaxNodeOpt:=syntaxNodeOpt,
diagnostics:=diagnostics)
End Function
Private Function GetUntranslatedSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As NamedTypeSymbol
Dim typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType)
Dim info = Binder.GetUseSiteErrorForSpecialType(typeSymbol)
If info IsNot Nothing Then
Binder.ReportDiagnostic(diagnostics, If(syntaxNodeOpt IsNot Nothing, syntaxNodeOpt.GetLocation(), NoLocation.Singleton), info)
End If
Return typeSymbol
End Function
Public NotOverridable Overrides Function GetInitArrayHelper() As Cci.IMethodReference
Return DirectCast(Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle), MethodSymbol)
End Function
Public NotOverridable Overrides Function IsPlatformType(typeRef As Cci.ITypeReference, platformType As Cci.PlatformType) As Boolean
Dim namedType = TryCast(typeRef, NamedTypeSymbol)
If namedType IsNot Nothing Then
If platformType = Cci.PlatformType.SystemType Then
Return namedType Is Compilation.GetWellKnownType(WellKnownType.System_Type)
End If
Return namedType.SpecialType = CType(platformType, SpecialType)
End If
Return False
End Function
Protected NotOverridable Overrides Function GetCorLibraryReferenceToEmit(context As EmitContext) As Cci.IAssemblyReference
Dim corLib = CorLibrary
If Not corLib.IsMissing AndAlso
Not corLib.IsLinked AndAlso
corLib IsNot SourceModule.ContainingAssembly Then
Return Translate(corLib, context.Diagnostics)
End If
Return Nothing
End Function
Friend NotOverridable Overrides Function GetSynthesizedNestedTypes(container As NamedTypeSymbol) As IEnumerable(Of Cci.INestedTypeDefinition)
Return container.GetSynthesizedNestedTypes()
End Function
Public Sub SetDisableJITOptimization(methodSymbol As MethodSymbol)
Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition)
_disableJITOptimization.TryAdd(methodSymbol, True)
End Sub
Public Function JITOptimizationIsDisabled(methodSymbol As MethodSymbol) As Boolean
Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition)
Return _disableJITOptimization.ContainsKey(methodSymbol)
End Function
Protected NotOverridable Overrides Function CreatePrivateImplementationDetailsStaticConstructor(details As PrivateImplementationDetails, syntaxOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.IMethodDefinition
Return New SynthesizedPrivateImplementationDetailsSharedConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics))
End Function
End Class
End Namespace
|
jkotas/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.vb
|
Visual Basic
|
apache-2.0
| 33,393
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rCasos_EjecutorFechas_Detallado"
'-------------------------------------------------------------------------------------------'
Partial Class rCasos_EjecutorFechas_Detallado
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.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loConsulta As New StringBuilder()
loConsulta.AppendLine("")
loConsulta.AppendLine("SELECT COALESCE(Renglones_Casos.Cod_Eje, Casos.Cod_Eje) AS Cod_Eje,")
loConsulta.AppendLine(" Ejecutores.Nom_Ven AS Nom_Eje,")
loConsulta.AppendLine(" ROW_NUMBER() ")
loConsulta.AppendLine(" OVER(PARTITION BY COALESCE(Renglones_Casos.Cod_Eje, Casos.Cod_Eje)")
loConsulta.AppendLine(" ORDER BY COALESCE(Renglones_Casos.Cod_Eje, Casos.Cod_Eje),")
loConsulta.AppendLine(" CAST(COALESCE(Renglones_Casos.Fec_Ini, Casos.Fec_Ini) AS DATE)) AS Numero,")
loConsulta.AppendLine(" CAST(COALESCE(Renglones_Casos.Fec_Ini, Casos.Fec_Ini) AS DATE) AS Fecha,")
loConsulta.AppendLine(" (CASE dbo.udf_GetISOWeekDay(CAST(COALESCE(Renglones_Casos.Fec_Ini, Casos.Fec_Ini) AS DATE))")
loConsulta.AppendLine(" WHEN 1 THEN 'Lunes'")
loConsulta.AppendLine(" WHEN 2 THEN 'Martes'")
loConsulta.AppendLine(" WHEN 3 THEN 'Miércoles'")
loConsulta.AppendLine(" WHEN 4 THEN 'Jueves'")
loConsulta.AppendLine(" WHEN 5 THEN 'Viernes'")
loConsulta.AppendLine(" WHEN 6 THEN 'Sábado'")
loConsulta.AppendLine(" WHEN 7 THEN 'Domingo'")
loConsulta.AppendLine(" ELSE '[N/A]'")
loConsulta.AppendLine(" END) AS Dia,")
loConsulta.AppendLine(" Casos.Documento AS Documento, ")
loConsulta.AppendLine(" COALESCE(Renglones_Casos.Renglon, 0) AS Renglon,")
loConsulta.AppendLine(" Renglones_Casos.Hor_Ini AS Hor_Ini,")
loConsulta.AppendLine(" Renglones_Casos.Hor_Fin AS Hor_Fin,")
loConsulta.AppendLine(" (CASE WHEN Renglones_Casos.facturable = 1 ")
loConsulta.AppendLine(" THEN Renglones_Casos.duracion")
loConsulta.AppendLine(" ELSE 0 END) AS Horas_Fact,")
loConsulta.AppendLine(" (CASE WHEN Renglones_Casos.facturable = 0")
loConsulta.AppendLine(" THEN Renglones_Casos.duracion")
loConsulta.AppendLine(" ELSE 0 END) AS Horas_No_Fact,")
loConsulta.AppendLine(" COALESCE(Renglones_Casos.duracion, 0) AS Horas_Totales,")
loConsulta.AppendLine(" COALESCE(Renglones_Casos.actividad, Casos.asunto) AS Detalle")
loConsulta.AppendLine("FROM Casos")
loConsulta.AppendLine(" LEFT JOIN Renglones_Casos ON Renglones_Casos.Documento = Casos.Documento")
loConsulta.AppendLine(" JOIN Vendedores AS Ejecutores")
loConsulta.AppendLine(" ON Ejecutores.Cod_Ven = COALESCE(Renglones_Casos.Cod_Eje, Casos.Cod_Eje)")
loConsulta.AppendLine("WHERE Casos.Documento BETWEEN " & lcParametro0Desde)
loConsulta.AppendLine(" AND " & lcParametro0Hasta)
loConsulta.AppendLine(" AND COALESCE(Renglones_Casos.Fec_Ini, Casos.Fec_Ini) BETWEEN " & lcParametro1Desde)
loConsulta.AppendLine(" AND " & lcParametro1Hasta)
loConsulta.AppendLine(" AND Casos.Status IN (" & lcParametro2Desde & ")")
loConsulta.AppendLine(" AND Casos.Cod_Reg BETWEEN " & lcParametro3Desde)
loConsulta.AppendLine(" AND " & lcParametro3Hasta)
loConsulta.AppendLine(" AND Casos.Cod_Coo BETWEEN " & lcParametro4Desde)
loConsulta.AppendLine(" AND " & lcParametro4Hasta)
loConsulta.AppendLine(" AND COALESCE(Renglones_Casos.Cod_Eje, Casos.Cod_Eje) BETWEEN " & lcParametro5Desde)
loConsulta.AppendLine(" AND " & lcParametro5Hasta)
loConsulta.AppendLine(" AND Casos.Cod_Suc BETWEEN " & lcParametro6Desde)
loConsulta.AppendLine(" AND " & lcParametro6Hasta)
loConsulta.AppendLine("ORDER BY " & lcOrdenamiento & ",")
loConsulta.AppendLine(" CAST(COALESCE(Renglones_Casos.Fec_Ini, Casos.Fec_Ini) AS DATE) ASC,")
loConsulta.AppendLine(" Renglones_Casos.Hor_Ini ASC")
loConsulta.AppendLine("")
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString(), "curReportes")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rCasos_EjecutorFechas_Detallado", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrCasos_EjecutorFechas_Detallado.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo. '
'-------------------------------------------------------------------------------------------'
' RJG: 07/07/14: Codigo inicial. '
'-------------------------------------------------------------------------------------------'
' RJG: 24/09/14: Se agregó un total general al RPT. '
'-------------------------------------------------------------------------------------------'
' RJG: 17/03/15: Se ´cambió la clase base para permitir envío por correo desde Alertas. '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rCasos_EjecutorFechas_Detallado.aspx.vb
|
Visual Basic
|
mit
| 9,767
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18444
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.LED_Cube.Form1
End Sub
End Class
End Namespace
|
Trommik/Microcontroller_Codes
|
3x3x3 LED Cube/LED Cube AnimationCreator VB/LED Cube/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,512
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fPedidos_Clientes_NDI"
'-------------------------------------------------------------------------------------------'
Partial Class fPedidos_Clientes_NDI
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 Pedidos.Cod_Cli, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Clientes.Generico = 0) THEN Clientes.Nom_Cli ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Pedidos.Nom_Cli = '') THEN Clientes.Nom_Cli ELSE Pedidos.Nom_Cli END) END) AS Nom_Cli, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Clientes.Generico = 0) THEN Clientes.Rif ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Pedidos.Rif = '') THEN Clientes.Rif ELSE Pedidos.Rif END) END) AS Rif, ")
loComandoSeleccionar.AppendLine(" Clientes.Nit, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Clientes.Generico = 0) THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (SUBSTRING(Pedidos.Dir_Fis,1, 200) = '') THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE SUBSTRING(Pedidos.Dir_Fis,1, 200) END) END) AS Dir_Fis, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Clientes.Generico = 0) THEN Clientes.Telefonos ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Pedidos.Telefonos = '') THEN Clientes.Telefonos ELSE Pedidos.Telefonos END) END) AS Telefonos, ")
loComandoSeleccionar.AppendLine(" Clientes.Fax, ")
loComandoSeleccionar.AppendLine(" Pedidos.Nom_Cli As Nom_Gen, ")
loComandoSeleccionar.AppendLine(" Pedidos.Rif As Rif_Gen, ")
loComandoSeleccionar.AppendLine(" Pedidos.Nit As Nit_Gen, ")
loComandoSeleccionar.AppendLine(" Pedidos.Dir_Fis As Dir_Gen, ")
loComandoSeleccionar.AppendLine(" Pedidos.Telefonos As Tel_Gen, ")
loComandoSeleccionar.AppendLine(" Pedidos.Documento, ")
loComandoSeleccionar.AppendLine(" Pedidos.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Pedidos.Fec_Fin, ")
loComandoSeleccionar.AppendLine(" Pedidos.Mon_Bru, ")
loComandoSeleccionar.AppendLine(" Pedidos.Por_Des1, ")
loComandoSeleccionar.AppendLine(" Pedidos.Por_Rec1, ")
loComandoSeleccionar.AppendLine(" Pedidos.Mon_Des1, ")
loComandoSeleccionar.AppendLine(" Pedidos.Mon_Rec1, ")
loComandoSeleccionar.AppendLine(" Pedidos.Mon_Imp1, ")
loComandoSeleccionar.AppendLine(" Pedidos.Por_Imp1, ")
loComandoSeleccionar.AppendLine(" Pedidos.Mon_Net, ")
loComandoSeleccionar.AppendLine(" Pedidos.Cod_For, ")
loComandoSeleccionar.AppendLine(" SUBSTRING(Formas_Pagos.Nom_For,1,25) AS Nom_For, ")
loComandoSeleccionar.AppendLine(" Pedidos.Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Pedidos.Comentario, ")
loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Cod_Art, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Renglon, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Can_Art1, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Cod_Uni, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Precio1, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Mon_Net As Neto, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Por_Imp1 As Por_Imp, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Cod_Imp, ")
loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Mon_Imp1 As Impuesto ")
loComandoSeleccionar.AppendLine(" FROM Pedidos ")
loComandoSeleccionar.AppendLine(" JOIN Renglones_Pedidos ON (Pedidos.Documento = Renglones_Pedidos.Documento)")
loComandoSeleccionar.AppendLine(" JOIN Clientes ON (Pedidos.Cod_Cli = Clientes.Cod_Cli) ")
loComandoSeleccionar.AppendLine(" JOIN Formas_Pagos ON (Pedidos.Cod_For = Formas_Pagos.Cod_For) ")
loComandoSeleccionar.AppendLine(" JOIN Vendedores ON (Pedidos.Cod_Ven = Vendedores.Cod_Ven) ")
loComandoSeleccionar.AppendLine(" JOIN Articulos ON (Articulos.Cod_Art = Renglones_Pedidos.Cod_Art)")
loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(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("fPedidos_Clientes_NDI", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfPedidos_Clientes_NDI.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' MAT: 03/06/11: Codigo inicial
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
fPedidos_Clientes_NDI.aspx.vb
|
Visual Basic
|
mit
| 8,297
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class Home
Inherits MaterialSkin.Controls.MaterialForm
'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.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Home))
Me.Home_Main_Layout = New System.Windows.Forms.TableLayoutPanel()
Me.TabContainerPanel = New System.Windows.Forms.Panel()
Me.MaterialTabControl = New MaterialSkin.Controls.MaterialTabControl()
Me.HomePage = New System.Windows.Forms.TabPage()
Me.Home_MngScriptGrp = New System.Windows.Forms.Panel()
Me.Home_MngScriptLlb = New System.Windows.Forms.Label()
Me.Home_MngScriptTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.Home_ScriptCopyBtn = New System.Windows.Forms.PictureBox()
Me.Home_ScriptNewBtn = New System.Windows.Forms.PictureBox()
Me.Home_ScriptBrkBtn = New System.Windows.Forms.PictureBox()
Me.Home_ScriptUndoBtn = New System.Windows.Forms.PictureBox()
Me.Home_ScriptIncTxtBtn = New System.Windows.Forms.PictureBox()
Me.Home_ScriptDecTxtBtn = New System.Windows.Forms.PictureBox()
Me.Home_ScriptExprtBtn = New System.Windows.Forms.PictureBox()
Me.Home_InfoTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.Home_FeedbackBtn = New System.Windows.Forms.PictureBox()
Me.Home_InfoBtn = New System.Windows.Forms.PictureBox()
Me.DatabasePage = New System.Windows.Forms.TabPage()
Me.DatabaseTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.Database_NameGrp = New System.Windows.Forms.Panel()
Me.Database_NameLbl = New System.Windows.Forms.Label()
Me.Database_NameFld = New MaterialSkin.Controls.MaterialSingleLineTextField()
Me.Database_ButtonTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.Database_SelectBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.Database_CreateBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.Database_DeleteBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.CreateTablePage = New System.Windows.Forms.TabPage()
Me.CreateActionLayout = New System.Windows.Forms.TableLayoutPanel()
Me.CreateTable_NameGrp = New System.Windows.Forms.Panel()
Me.CreateTable_NameLbl = New System.Windows.Forms.Label()
Me.CreateTable_CreateBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.CreateTable_NameFld = New MaterialSkin.Controls.MaterialSingleLineTextField()
Me.FieldDetails = New System.Windows.Forms.Panel()
Me.CreateTable_ActionDetailContainerPnl = New System.Windows.Forms.Panel()
Me.FieldGroup = New System.Windows.Forms.Panel()
Me.FieldDetails_ColumnLbl = New System.Windows.Forms.Label()
Me.FieldDetails_FormulaChkbx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_ColumnTYpeCmbo = New System.Windows.Forms.ComboBox()
Me.FieldDetails_DefFld = New System.Windows.Forms.TextBox()
Me.FieldDetails_ColumnNameLbl = New System.Windows.Forms.Label()
Me.FieldDetails_DefValChkbx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_ColumnNameFld = New MaterialSkin.Controls.MaterialSingleLineTextField()
Me.FieldDetails_Precision = New System.Windows.Forms.NumericUpDown()
Me.FieldDetails_PreScleLbl = New System.Windows.Forms.Label()
Me.FieldDetails_SizeLbl = New System.Windows.Forms.Label()
Me.FieldDetails_TypeLbl = New System.Windows.Forms.Label()
Me.FieldDetails_Size = New System.Windows.Forms.NumericUpDown()
Me.FieldDetails_Scale = New System.Windows.Forms.NumericUpDown()
Me.FieldDetails_ForeignKeyGrp = New System.Windows.Forms.Panel()
Me.FieldDetails_ForeignKeyLbl = New System.Windows.Forms.Label()
Me.FieldDetails_ForeignKeyFld = New System.Windows.Forms.TextBox()
Me.FieldDetails_PrimyGrp = New System.Windows.Forms.Panel()
Me.FieldDetails_PrimLbl = New System.Windows.Forms.Label()
Me.FieldDetails_PrimFld = New System.Windows.Forms.TextBox()
Me.CreateTable_ActionDetailContainerPnl2 = New System.Windows.Forms.Panel()
Me.FieldDetails_CheckGrp = New System.Windows.Forms.Panel()
Me.FieldDetails_CheckLbl = New System.Windows.Forms.Label()
Me.FieldDetails_CheckChkbx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_CheckTypeLbl = New System.Windows.Forms.Label()
Me.FieldDetails_CheckTypeCmbo = New System.Windows.Forms.ComboBox()
Me.FieldDetails_StringPstnLbl = New System.Windows.Forms.Label()
Me.FieldDetails_CheckPstnCmbo = New System.Windows.Forms.ComboBox()
Me.FieldDetails_CheckFld = New System.Windows.Forms.TextBox()
Me.FieldDetails_RefConsTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.FieldDetails_ReferenceGrp = New System.Windows.Forms.Panel()
Me.FieldDetails_ReferentialLbl = New System.Windows.Forms.Label()
Me.FieldDetails_OnDeleteCmbo = New System.Windows.Forms.ComboBox()
Me.FieldDetails_ReferenceChkBx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_OnUpdateCmbo = New System.Windows.Forms.ComboBox()
Me.FieldDetails_ReferenceFld = New System.Windows.Forms.TextBox()
Me.FieldDetails_OnDeleteChkbx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_OnUpdateChkBx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_ConstraintGrp = New System.Windows.Forms.Panel()
Me.FieldDetails_ConstraintsLbl = New System.Windows.Forms.Label()
Me.FieldDetails_ForeignChkbx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_NotNullChkbx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_UniqueChkbx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_PrimChkbx = New System.Windows.Forms.CheckBox()
Me.FieldDetails_CreateFieldBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.CreateTable_BtbTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.CreateTable_AddPrimKeyBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.CreateTable_CompleteTableBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.CreateTable_AddColumnBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.CreateTable_AddForeignKeyBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.AlterTablePage = New System.Windows.Forms.TabPage()
Me.AlterTableLayoutPanel = New System.Windows.Forms.TableLayoutPanel()
Me.AlterTable_TableNamePnl = New System.Windows.Forms.Panel()
Me.AlterTable_TableNamaLbl = New System.Windows.Forms.Label()
Me.AlterTable_TableNameFld = New MaterialSkin.Controls.MaterialSingleLineTextField()
Me.AlterTable_ActionContainerPnl = New System.Windows.Forms.Panel()
Me.AlterTable_RenamePnl = New System.Windows.Forms.Panel()
Me.AlterTable_RenameLbl = New System.Windows.Forms.Label()
Me.AlterTable_RenameConfirmBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.AlterTable_RenameFld = New MaterialSkin.Controls.MaterialSingleLineTextField()
Me.AlterTable_DeleteColumnPnl = New System.Windows.Forms.Panel()
Me.AlterTable_DeleteColumnLbl = New System.Windows.Forms.Label()
Me.AlterTable_DeleteColumnFld = New MaterialSkin.Controls.MaterialSingleLineTextField()
Me.AlterTable_DeleteColumnConfirmBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.AlterTable_BtnTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.AlterTable_ModifyColumnBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.AlterTable_RenameBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.AlterTable_DeleteColumnBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.AlterTable_AddColumnBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.InsertPage = New System.Windows.Forms.TabPage()
Me.InsertTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.Insert_TableNamePnl = New System.Windows.Forms.Panel()
Me.Insert_TableNameLbl = New System.Windows.Forms.Label()
Me.Insert_TableNameFld = New MaterialSkin.Controls.MaterialSingleLineTextField()
Me.Insert_ConfirmPnl = New System.Windows.Forms.Panel()
Me.Insert_DataItemsConfirmBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.Insert_SpecifyColumnPnl = New System.Windows.Forms.Panel()
Me.Insert_SpecifyColumnLbl = New System.Windows.Forms.Label()
Me.Insert_SpecifyColumnChkbx = New System.Windows.Forms.CheckBox()
Me.Insert_SpecifyColumnFld = New System.Windows.Forms.TextBox()
Me.Insert_DataItemsPnl = New System.Windows.Forms.Panel()
Me.Insert_DataItemsLbl = New System.Windows.Forms.Label()
Me.Insert_DataItemsFld = New System.Windows.Forms.TextBox()
Me.DeleteTablePage = New System.Windows.Forms.TabPage()
Me.DropTableLayout = New System.Windows.Forms.TableLayoutPanel()
Me.Delete_TableNamePnl = New System.Windows.Forms.Panel()
Me.Delete_TableNamePnlLbl = New System.Windows.Forms.Label()
Me.Delete_TableNameFld = New MaterialSkin.Controls.MaterialSingleLineTextField()
Me.Delete_ConfirmPnl = New System.Windows.Forms.Panel()
Me.Delete_ConfirmBtn = New MaterialSkin.Controls.MaterialFlatButton()
Me.MainTableLayoutPanel = New System.Windows.Forms.TableLayoutPanel()
Me.ScriptGrp = New System.Windows.Forms.GroupBox()
Me.Sequence = New System.Windows.Forms.ListBox()
Me.ToolStrip = New System.Windows.Forms.ToolStrip()
Me.ToolStrip_Line = New System.Windows.Forms.ToolStripLabel()
Me.ToolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator()
Me.ToolStrip_FontSize = New System.Windows.Forms.ToolStripLabel()
Me.Tip = New System.Windows.Forms.ToolTip(Me.components)
Me.SaveFileDialog = New System.Windows.Forms.SaveFileDialog()
Me.MaterialTabSelector = New MaterialSkin.Controls.MaterialTabSelector()
Me.Insert_Help = New System.Windows.Forms.PictureBox()
Me.FieldDetails_CheckHelp = New System.Windows.Forms.PictureBox()
Me.Home_Main_Layout.SuspendLayout()
Me.TabContainerPanel.SuspendLayout()
Me.MaterialTabControl.SuspendLayout()
Me.HomePage.SuspendLayout()
Me.Home_MngScriptGrp.SuspendLayout()
Me.Home_MngScriptTableLayout.SuspendLayout()
CType(Me.Home_ScriptCopyBtn, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Home_ScriptNewBtn, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Home_ScriptBrkBtn, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Home_ScriptUndoBtn, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Home_ScriptIncTxtBtn, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Home_ScriptDecTxtBtn, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Home_ScriptExprtBtn, System.ComponentModel.ISupportInitialize).BeginInit()
Me.Home_InfoTableLayout.SuspendLayout()
CType(Me.Home_FeedbackBtn, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Home_InfoBtn, System.ComponentModel.ISupportInitialize).BeginInit()
Me.DatabasePage.SuspendLayout()
Me.DatabaseTableLayout.SuspendLayout()
Me.Database_NameGrp.SuspendLayout()
Me.Database_ButtonTableLayout.SuspendLayout()
Me.CreateTablePage.SuspendLayout()
Me.CreateActionLayout.SuspendLayout()
Me.CreateTable_NameGrp.SuspendLayout()
Me.FieldDetails.SuspendLayout()
Me.CreateTable_ActionDetailContainerPnl.SuspendLayout()
Me.FieldGroup.SuspendLayout()
CType(Me.FieldDetails_Precision, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.FieldDetails_Size, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.FieldDetails_Scale, System.ComponentModel.ISupportInitialize).BeginInit()
Me.FieldDetails_ForeignKeyGrp.SuspendLayout()
Me.FieldDetails_PrimyGrp.SuspendLayout()
Me.CreateTable_ActionDetailContainerPnl2.SuspendLayout()
Me.FieldDetails_CheckGrp.SuspendLayout()
Me.FieldDetails_RefConsTableLayout.SuspendLayout()
Me.FieldDetails_ReferenceGrp.SuspendLayout()
Me.FieldDetails_ConstraintGrp.SuspendLayout()
Me.CreateTable_BtbTableLayout.SuspendLayout()
Me.AlterTablePage.SuspendLayout()
Me.AlterTableLayoutPanel.SuspendLayout()
Me.AlterTable_TableNamePnl.SuspendLayout()
Me.AlterTable_ActionContainerPnl.SuspendLayout()
Me.AlterTable_RenamePnl.SuspendLayout()
Me.AlterTable_DeleteColumnPnl.SuspendLayout()
Me.AlterTable_BtnTableLayout.SuspendLayout()
Me.InsertPage.SuspendLayout()
Me.InsertTableLayout.SuspendLayout()
Me.Insert_TableNamePnl.SuspendLayout()
Me.Insert_ConfirmPnl.SuspendLayout()
Me.Insert_SpecifyColumnPnl.SuspendLayout()
Me.Insert_DataItemsPnl.SuspendLayout()
Me.DeleteTablePage.SuspendLayout()
Me.DropTableLayout.SuspendLayout()
Me.Delete_TableNamePnl.SuspendLayout()
Me.Delete_ConfirmPnl.SuspendLayout()
Me.MainTableLayoutPanel.SuspendLayout()
Me.ScriptGrp.SuspendLayout()
Me.ToolStrip.SuspendLayout()
CType(Me.Insert_Help, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.FieldDetails_CheckHelp, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Home_Main_Layout
'
Me.Home_Main_Layout.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.Home_Main_Layout.AutoSize = True
Me.Home_Main_Layout.ColumnCount = 10
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 9.999999!))
Me.Home_Main_Layout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.Controls.Add(Me.TabContainerPanel, 0, 0)
Me.Home_Main_Layout.Controls.Add(Me.MainTableLayoutPanel, 4, 0)
Me.Home_Main_Layout.Location = New System.Drawing.Point(0, 65)
Me.Home_Main_Layout.Name = "Home_Main_Layout"
Me.Home_Main_Layout.RowCount = 10
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.67416!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.269663!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_Main_Layout.Size = New System.Drawing.Size(1164, 712)
Me.Home_Main_Layout.TabIndex = 1
'
'TabContainerPanel
'
Me.Home_Main_Layout.SetColumnSpan(Me.TabContainerPanel, 4)
Me.TabContainerPanel.Controls.Add(Me.MaterialTabControl)
Me.TabContainerPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.TabContainerPanel.Location = New System.Drawing.Point(0, 0)
Me.TabContainerPanel.Margin = New System.Windows.Forms.Padding(0)
Me.TabContainerPanel.Name = "TabContainerPanel"
Me.Home_Main_Layout.SetRowSpan(Me.TabContainerPanel, 10)
Me.TabContainerPanel.Size = New System.Drawing.Size(464, 712)
Me.TabContainerPanel.TabIndex = 0
'
'MaterialTabControl
'
Me.MaterialTabControl.Controls.Add(Me.HomePage)
Me.MaterialTabControl.Controls.Add(Me.DatabasePage)
Me.MaterialTabControl.Controls.Add(Me.CreateTablePage)
Me.MaterialTabControl.Controls.Add(Me.AlterTablePage)
Me.MaterialTabControl.Controls.Add(Me.InsertPage)
Me.MaterialTabControl.Controls.Add(Me.DeleteTablePage)
Me.MaterialTabControl.Depth = 0
Me.MaterialTabControl.Dock = System.Windows.Forms.DockStyle.Fill
Me.MaterialTabControl.Location = New System.Drawing.Point(0, 0)
Me.MaterialTabControl.Margin = New System.Windows.Forms.Padding(0)
Me.MaterialTabControl.MouseState = MaterialSkin.MouseState.HOVER
Me.MaterialTabControl.Name = "MaterialTabControl"
Me.MaterialTabControl.SelectedIndex = 0
Me.MaterialTabControl.Size = New System.Drawing.Size(464, 712)
Me.MaterialTabControl.TabIndex = 2
'
'HomePage
'
Me.HomePage.BackgroundImage = CType(resources.GetObject("HomePage.BackgroundImage"), System.Drawing.Image)
Me.HomePage.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center
Me.HomePage.Controls.Add(Me.Home_MngScriptGrp)
Me.HomePage.Controls.Add(Me.Home_InfoTableLayout)
Me.HomePage.Location = New System.Drawing.Point(4, 22)
Me.HomePage.Margin = New System.Windows.Forms.Padding(0)
Me.HomePage.Name = "HomePage"
Me.HomePage.Padding = New System.Windows.Forms.Padding(3)
Me.HomePage.Size = New System.Drawing.Size(456, 686)
Me.HomePage.TabIndex = 0
Me.HomePage.Text = "Home"
Me.HomePage.UseVisualStyleBackColor = True
'
'Home_MngScriptGrp
'
Me.Home_MngScriptGrp.Controls.Add(Me.Home_MngScriptLlb)
Me.Home_MngScriptGrp.Controls.Add(Me.Home_MngScriptTableLayout)
Me.Home_MngScriptGrp.Dock = System.Windows.Forms.DockStyle.Top
Me.Home_MngScriptGrp.Location = New System.Drawing.Point(3, 3)
Me.Home_MngScriptGrp.Name = "Home_MngScriptGrp"
Me.Home_MngScriptGrp.Size = New System.Drawing.Size(450, 154)
Me.Home_MngScriptGrp.TabIndex = 4
'
'Home_MngScriptLlb
'
Me.Home_MngScriptLlb.AutoSize = True
Me.Home_MngScriptLlb.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Home_MngScriptLlb.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.Home_MngScriptLlb.Location = New System.Drawing.Point(3, 0)
Me.Home_MngScriptLlb.Name = "Home_MngScriptLlb"
Me.Home_MngScriptLlb.Size = New System.Drawing.Size(100, 15)
Me.Home_MngScriptLlb.TabIndex = 3
Me.Home_MngScriptLlb.Text = "Manage Script"
'
'Home_MngScriptTableLayout
'
Me.Home_MngScriptTableLayout.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.Home_MngScriptTableLayout.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None
Me.Home_MngScriptTableLayout.ColumnCount = 5
Me.Home_MngScriptTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_MngScriptTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_MngScriptTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_MngScriptTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_MngScriptTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_MngScriptTableLayout.Controls.Add(Me.Home_ScriptCopyBtn, 0, 1)
Me.Home_MngScriptTableLayout.Controls.Add(Me.Home_ScriptNewBtn, 0, 1)
Me.Home_MngScriptTableLayout.Controls.Add(Me.Home_ScriptBrkBtn, 3, 0)
Me.Home_MngScriptTableLayout.Controls.Add(Me.Home_ScriptUndoBtn, 0, 0)
Me.Home_MngScriptTableLayout.Controls.Add(Me.Home_ScriptIncTxtBtn, 1, 0)
Me.Home_MngScriptTableLayout.Controls.Add(Me.Home_ScriptDecTxtBtn, 2, 0)
Me.Home_MngScriptTableLayout.Controls.Add(Me.Home_ScriptExprtBtn, 4, 0)
Me.Home_MngScriptTableLayout.Dock = System.Windows.Forms.DockStyle.Bottom
Me.Home_MngScriptTableLayout.Location = New System.Drawing.Point(0, 19)
Me.Home_MngScriptTableLayout.Margin = New System.Windows.Forms.Padding(0)
Me.Home_MngScriptTableLayout.Name = "Home_MngScriptTableLayout"
Me.Home_MngScriptTableLayout.Padding = New System.Windows.Forms.Padding(0, 0, 0, 10)
Me.Home_MngScriptTableLayout.RowCount = 2
Me.Home_MngScriptTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 61.0!))
Me.Home_MngScriptTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.Home_MngScriptTableLayout.Size = New System.Drawing.Size(450, 135)
Me.Home_MngScriptTableLayout.TabIndex = 0
'
'Home_ScriptCopyBtn
'
Me.Home_ScriptCopyBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_ScriptCopyBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_ScriptCopyBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_ScriptCopyBtn.Image = CType(resources.GetObject("Home_ScriptCopyBtn.Image"), System.Drawing.Image)
Me.Home_ScriptCopyBtn.Location = New System.Drawing.Point(3, 64)
Me.Home_ScriptCopyBtn.Name = "Home_ScriptCopyBtn"
Me.Home_ScriptCopyBtn.Size = New System.Drawing.Size(84, 58)
Me.Home_ScriptCopyBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_ScriptCopyBtn.TabIndex = 17
Me.Home_ScriptCopyBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_ScriptCopyBtn, "Copy To Clipboard")
'
'Home_ScriptNewBtn
'
Me.Home_ScriptNewBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_ScriptNewBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_ScriptNewBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_ScriptNewBtn.Image = CType(resources.GetObject("Home_ScriptNewBtn.Image"), System.Drawing.Image)
Me.Home_ScriptNewBtn.Location = New System.Drawing.Point(93, 64)
Me.Home_ScriptNewBtn.Name = "Home_ScriptNewBtn"
Me.Home_ScriptNewBtn.Size = New System.Drawing.Size(84, 58)
Me.Home_ScriptNewBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_ScriptNewBtn.TabIndex = 16
Me.Home_ScriptNewBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_ScriptNewBtn, "New")
'
'Home_ScriptBrkBtn
'
Me.Home_ScriptBrkBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_ScriptBrkBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_ScriptBrkBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_ScriptBrkBtn.Image = CType(resources.GetObject("Home_ScriptBrkBtn.Image"), System.Drawing.Image)
Me.Home_ScriptBrkBtn.Location = New System.Drawing.Point(273, 3)
Me.Home_ScriptBrkBtn.Name = "Home_ScriptBrkBtn"
Me.Home_ScriptBrkBtn.Size = New System.Drawing.Size(84, 55)
Me.Home_ScriptBrkBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_ScriptBrkBtn.TabIndex = 15
Me.Home_ScriptBrkBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_ScriptBrkBtn, "Break")
'
'Home_ScriptUndoBtn
'
Me.Home_ScriptUndoBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_ScriptUndoBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_ScriptUndoBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_ScriptUndoBtn.Image = CType(resources.GetObject("Home_ScriptUndoBtn.Image"), System.Drawing.Image)
Me.Home_ScriptUndoBtn.Location = New System.Drawing.Point(3, 3)
Me.Home_ScriptUndoBtn.Name = "Home_ScriptUndoBtn"
Me.Home_ScriptUndoBtn.Size = New System.Drawing.Size(84, 55)
Me.Home_ScriptUndoBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_ScriptUndoBtn.TabIndex = 14
Me.Home_ScriptUndoBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_ScriptUndoBtn, "Undo last line")
'
'Home_ScriptIncTxtBtn
'
Me.Home_ScriptIncTxtBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_ScriptIncTxtBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_ScriptIncTxtBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_ScriptIncTxtBtn.Image = CType(resources.GetObject("Home_ScriptIncTxtBtn.Image"), System.Drawing.Image)
Me.Home_ScriptIncTxtBtn.Location = New System.Drawing.Point(93, 3)
Me.Home_ScriptIncTxtBtn.Name = "Home_ScriptIncTxtBtn"
Me.Home_ScriptIncTxtBtn.Size = New System.Drawing.Size(84, 55)
Me.Home_ScriptIncTxtBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_ScriptIncTxtBtn.TabIndex = 13
Me.Home_ScriptIncTxtBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_ScriptIncTxtBtn, "Increaese Text Size")
'
'Home_ScriptDecTxtBtn
'
Me.Home_ScriptDecTxtBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_ScriptDecTxtBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_ScriptDecTxtBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_ScriptDecTxtBtn.Image = CType(resources.GetObject("Home_ScriptDecTxtBtn.Image"), System.Drawing.Image)
Me.Home_ScriptDecTxtBtn.Location = New System.Drawing.Point(183, 3)
Me.Home_ScriptDecTxtBtn.Name = "Home_ScriptDecTxtBtn"
Me.Home_ScriptDecTxtBtn.Size = New System.Drawing.Size(84, 55)
Me.Home_ScriptDecTxtBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_ScriptDecTxtBtn.TabIndex = 12
Me.Home_ScriptDecTxtBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_ScriptDecTxtBtn, "Decrease Text Size")
'
'Home_ScriptExprtBtn
'
Me.Home_ScriptExprtBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_ScriptExprtBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_ScriptExprtBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_ScriptExprtBtn.Image = CType(resources.GetObject("Home_ScriptExprtBtn.Image"), System.Drawing.Image)
Me.Home_ScriptExprtBtn.Location = New System.Drawing.Point(363, 3)
Me.Home_ScriptExprtBtn.Name = "Home_ScriptExprtBtn"
Me.Home_ScriptExprtBtn.Padding = New System.Windows.Forms.Padding(10)
Me.Home_ScriptExprtBtn.Size = New System.Drawing.Size(84, 55)
Me.Home_ScriptExprtBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_ScriptExprtBtn.TabIndex = 11
Me.Home_ScriptExprtBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_ScriptExprtBtn, "Export Script")
'
'Home_InfoTableLayout
'
Me.Home_InfoTableLayout.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None
Me.Home_InfoTableLayout.ColumnCount = 5
Me.Home_InfoTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_InfoTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_InfoTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_InfoTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_InfoTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20.0!))
Me.Home_InfoTableLayout.Controls.Add(Me.Home_FeedbackBtn, 3, 0)
Me.Home_InfoTableLayout.Controls.Add(Me.Home_InfoBtn, 4, 0)
Me.Home_InfoTableLayout.Dock = System.Windows.Forms.DockStyle.Bottom
Me.Home_InfoTableLayout.Location = New System.Drawing.Point(3, 609)
Me.Home_InfoTableLayout.Margin = New System.Windows.Forms.Padding(0)
Me.Home_InfoTableLayout.Name = "Home_InfoTableLayout"
Me.Home_InfoTableLayout.Padding = New System.Windows.Forms.Padding(0, 0, 0, 10)
Me.Home_InfoTableLayout.RowCount = 1
Me.Home_InfoTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 64.0!))
Me.Home_InfoTableLayout.Size = New System.Drawing.Size(450, 74)
Me.Home_InfoTableLayout.TabIndex = 2
'
'Home_FeedbackBtn
'
Me.Home_FeedbackBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_FeedbackBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_FeedbackBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_FeedbackBtn.Image = CType(resources.GetObject("Home_FeedbackBtn.Image"), System.Drawing.Image)
Me.Home_FeedbackBtn.Location = New System.Drawing.Point(273, 3)
Me.Home_FeedbackBtn.Name = "Home_FeedbackBtn"
Me.Home_FeedbackBtn.Padding = New System.Windows.Forms.Padding(10)
Me.Home_FeedbackBtn.Size = New System.Drawing.Size(84, 58)
Me.Home_FeedbackBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_FeedbackBtn.TabIndex = 12
Me.Home_FeedbackBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_FeedbackBtn, "Leave Feedback")
'
'Home_InfoBtn
'
Me.Home_InfoBtn.BackColor = System.Drawing.Color.Transparent
Me.Home_InfoBtn.Cursor = System.Windows.Forms.Cursors.Hand
Me.Home_InfoBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.Home_InfoBtn.Image = CType(resources.GetObject("Home_InfoBtn.Image"), System.Drawing.Image)
Me.Home_InfoBtn.Location = New System.Drawing.Point(363, 3)
Me.Home_InfoBtn.Name = "Home_InfoBtn"
Me.Home_InfoBtn.Padding = New System.Windows.Forms.Padding(10)
Me.Home_InfoBtn.Size = New System.Drawing.Size(84, 58)
Me.Home_InfoBtn.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Home_InfoBtn.TabIndex = 11
Me.Home_InfoBtn.TabStop = False
Me.Tip.SetToolTip(Me.Home_InfoBtn, "About")
'
'DatabasePage
'
Me.DatabasePage.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.DatabasePage.Controls.Add(Me.DatabaseTableLayout)
Me.DatabasePage.Location = New System.Drawing.Point(4, 22)
Me.DatabasePage.Name = "DatabasePage"
Me.DatabasePage.Padding = New System.Windows.Forms.Padding(3)
Me.DatabasePage.Size = New System.Drawing.Size(456, 686)
Me.DatabasePage.TabIndex = 1
Me.DatabasePage.Text = "Database"
'
'DatabaseTableLayout
'
Me.DatabaseTableLayout.ColumnCount = 1
Me.DatabaseTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.DatabaseTableLayout.Controls.Add(Me.Database_NameGrp, 0, 0)
Me.DatabaseTableLayout.Controls.Add(Me.Database_ButtonTableLayout, 0, 1)
Me.DatabaseTableLayout.Dock = System.Windows.Forms.DockStyle.Fill
Me.DatabaseTableLayout.Location = New System.Drawing.Point(3, 3)
Me.DatabaseTableLayout.Name = "DatabaseTableLayout"
Me.DatabaseTableLayout.RowCount = 12
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.DatabaseTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.DatabaseTableLayout.Size = New System.Drawing.Size(450, 680)
Me.DatabaseTableLayout.TabIndex = 46
'
'Database_NameGrp
'
Me.Database_NameGrp.Controls.Add(Me.Database_NameLbl)
Me.Database_NameGrp.Controls.Add(Me.Database_NameFld)
Me.Database_NameGrp.Dock = System.Windows.Forms.DockStyle.Fill
Me.Database_NameGrp.Location = New System.Drawing.Point(3, 3)
Me.Database_NameGrp.Name = "Database_NameGrp"
Me.Database_NameGrp.Size = New System.Drawing.Size(444, 50)
Me.Database_NameGrp.TabIndex = 0
'
'Database_NameLbl
'
Me.Database_NameLbl.AutoSize = True
Me.Database_NameLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.Database_NameLbl.Location = New System.Drawing.Point(167, 5)
Me.Database_NameLbl.Name = "Database_NameLbl"
Me.Database_NameLbl.Size = New System.Drawing.Size(112, 13)
Me.Database_NameLbl.TabIndex = 41
Me.Database_NameLbl.Text = "Enter Database Name"
'
'Database_NameFld
'
Me.Database_NameFld.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.Database_NameFld.Depth = 0
Me.Database_NameFld.Hint = ""
Me.Database_NameFld.Location = New System.Drawing.Point(10, 21)
Me.Database_NameFld.MouseState = MaterialSkin.MouseState.HOVER
Me.Database_NameFld.Name = "Database_NameFld"
Me.Database_NameFld.PasswordChar = Global.Microsoft.VisualBasic.ChrW(0)
Me.Database_NameFld.SelectedText = ""
Me.Database_NameFld.SelectionLength = 0
Me.Database_NameFld.SelectionStart = 0
Me.Database_NameFld.Size = New System.Drawing.Size(418, 23)
Me.Database_NameFld.TabIndex = 37
Me.Database_NameFld.UseSystemPasswordChar = False
'
'Database_ButtonTableLayout
'
Me.Database_ButtonTableLayout.ColumnCount = 3
Me.Database_ButtonTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.Database_ButtonTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.Database_ButtonTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.Database_ButtonTableLayout.Controls.Add(Me.Database_SelectBtn, 2, 0)
Me.Database_ButtonTableLayout.Controls.Add(Me.Database_CreateBtn, 0, 0)
Me.Database_ButtonTableLayout.Controls.Add(Me.Database_DeleteBtn, 1, 0)
Me.Database_ButtonTableLayout.Dock = System.Windows.Forms.DockStyle.Fill
Me.Database_ButtonTableLayout.Location = New System.Drawing.Point(3, 59)
Me.Database_ButtonTableLayout.Name = "Database_ButtonTableLayout"
Me.Database_ButtonTableLayout.RowCount = 1
Me.Database_ButtonTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.Database_ButtonTableLayout.Size = New System.Drawing.Size(444, 50)
Me.Database_ButtonTableLayout.TabIndex = 1
'
'Database_SelectBtn
'
Me.Database_SelectBtn.AutoSize = True
Me.Database_SelectBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.Database_SelectBtn.BackColor = System.Drawing.Color.White
Me.Database_SelectBtn.Depth = 0
Me.Database_SelectBtn.Location = New System.Drawing.Point(300, 6)
Me.Database_SelectBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.Database_SelectBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.Database_SelectBtn.Name = "Database_SelectBtn"
Me.Database_SelectBtn.Primary = False
Me.Database_SelectBtn.Size = New System.Drawing.Size(133, 36)
Me.Database_SelectBtn.TabIndex = 1
Me.Database_SelectBtn.Text = "Select Database"
Me.Database_SelectBtn.UseVisualStyleBackColor = False
'
'Database_CreateBtn
'
Me.Database_CreateBtn.AutoSize = True
Me.Database_CreateBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.Database_CreateBtn.BackColor = System.Drawing.Color.White
Me.Database_CreateBtn.Depth = 0
Me.Database_CreateBtn.Location = New System.Drawing.Point(4, 6)
Me.Database_CreateBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.Database_CreateBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.Database_CreateBtn.Name = "Database_CreateBtn"
Me.Database_CreateBtn.Primary = False
Me.Database_CreateBtn.Size = New System.Drawing.Size(135, 36)
Me.Database_CreateBtn.TabIndex = 3
Me.Database_CreateBtn.Text = "Create Database"
Me.Database_CreateBtn.UseVisualStyleBackColor = False
'
'Database_DeleteBtn
'
Me.Database_DeleteBtn.AutoSize = True
Me.Database_DeleteBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.Database_DeleteBtn.BackColor = System.Drawing.Color.White
Me.Database_DeleteBtn.Depth = 0
Me.Database_DeleteBtn.Location = New System.Drawing.Point(152, 6)
Me.Database_DeleteBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.Database_DeleteBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.Database_DeleteBtn.Name = "Database_DeleteBtn"
Me.Database_DeleteBtn.Primary = False
Me.Database_DeleteBtn.Size = New System.Drawing.Size(133, 36)
Me.Database_DeleteBtn.TabIndex = 2
Me.Database_DeleteBtn.Text = "Delete Database"
Me.Database_DeleteBtn.UseVisualStyleBackColor = False
'
'CreateTablePage
'
Me.CreateTablePage.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.CreateTablePage.Controls.Add(Me.CreateActionLayout)
Me.CreateTablePage.Location = New System.Drawing.Point(4, 22)
Me.CreateTablePage.Name = "CreateTablePage"
Me.CreateTablePage.Padding = New System.Windows.Forms.Padding(3)
Me.CreateTablePage.Size = New System.Drawing.Size(456, 686)
Me.CreateTablePage.TabIndex = 2
Me.CreateTablePage.Text = "Create Table"
'
'CreateActionLayout
'
Me.CreateActionLayout.ColumnCount = 1
Me.CreateActionLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.CreateActionLayout.Controls.Add(Me.CreateTable_NameGrp, 0, 0)
Me.CreateActionLayout.Controls.Add(Me.FieldDetails, 0, 2)
Me.CreateActionLayout.Controls.Add(Me.CreateTable_BtbTableLayout, 0, 1)
Me.CreateActionLayout.Dock = System.Windows.Forms.DockStyle.Fill
Me.CreateActionLayout.Location = New System.Drawing.Point(3, 3)
Me.CreateActionLayout.Name = "CreateActionLayout"
Me.CreateActionLayout.RowCount = 11
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.CreateActionLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.CreateActionLayout.Size = New System.Drawing.Size(450, 680)
Me.CreateActionLayout.TabIndex = 0
'
'CreateTable_NameGrp
'
Me.CreateTable_NameGrp.Controls.Add(Me.CreateTable_NameLbl)
Me.CreateTable_NameGrp.Controls.Add(Me.CreateTable_CreateBtn)
Me.CreateTable_NameGrp.Controls.Add(Me.CreateTable_NameFld)
Me.CreateTable_NameGrp.Dock = System.Windows.Forms.DockStyle.Fill
Me.CreateTable_NameGrp.Location = New System.Drawing.Point(3, 3)
Me.CreateTable_NameGrp.Name = "CreateTable_NameGrp"
Me.CreateTable_NameGrp.Size = New System.Drawing.Size(444, 55)
Me.CreateTable_NameGrp.TabIndex = 5
'
'CreateTable_NameLbl
'
Me.CreateTable_NameLbl.AutoSize = True
Me.CreateTable_NameLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.CreateTable_NameLbl.Location = New System.Drawing.Point(176, 5)
Me.CreateTable_NameLbl.Name = "CreateTable_NameLbl"
Me.CreateTable_NameLbl.Size = New System.Drawing.Size(93, 13)
Me.CreateTable_NameLbl.TabIndex = 41
Me.CreateTable_NameLbl.Text = "Enter Table Name"
'
'CreateTable_CreateBtn
'
Me.CreateTable_CreateBtn.Anchor = System.Windows.Forms.AnchorStyles.Right
Me.CreateTable_CreateBtn.AutoSize = True
Me.CreateTable_CreateBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.CreateTable_CreateBtn.Depth = 0
Me.CreateTable_CreateBtn.Location = New System.Drawing.Point(373, 9)
Me.CreateTable_CreateBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.CreateTable_CreateBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.CreateTable_CreateBtn.Name = "CreateTable_CreateBtn"
Me.CreateTable_CreateBtn.Primary = False
Me.CreateTable_CreateBtn.Size = New System.Drawing.Size(62, 36)
Me.CreateTable_CreateBtn.TabIndex = 39
Me.CreateTable_CreateBtn.Text = "Create"
Me.CreateTable_CreateBtn.UseVisualStyleBackColor = True
'
'CreateTable_NameFld
'
Me.CreateTable_NameFld.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.CreateTable_NameFld.Depth = 0
Me.CreateTable_NameFld.Hint = ""
Me.CreateTable_NameFld.Location = New System.Drawing.Point(12, 22)
Me.CreateTable_NameFld.MouseState = MaterialSkin.MouseState.HOVER
Me.CreateTable_NameFld.Name = "CreateTable_NameFld"
Me.CreateTable_NameFld.PasswordChar = Global.Microsoft.VisualBasic.ChrW(0)
Me.CreateTable_NameFld.SelectedText = ""
Me.CreateTable_NameFld.SelectionLength = 0
Me.CreateTable_NameFld.SelectionStart = 0
Me.CreateTable_NameFld.Size = New System.Drawing.Size(346, 23)
Me.CreateTable_NameFld.TabIndex = 37
Me.CreateTable_NameFld.UseSystemPasswordChar = False
'
'FieldDetails
'
Me.FieldDetails.Controls.Add(Me.CreateTable_ActionDetailContainerPnl)
Me.FieldDetails.Controls.Add(Me.CreateTable_ActionDetailContainerPnl2)
Me.FieldDetails.Dock = System.Windows.Forms.DockStyle.Fill
Me.FieldDetails.Location = New System.Drawing.Point(3, 125)
Me.FieldDetails.Name = "FieldDetails"
Me.CreateActionLayout.SetRowSpan(Me.FieldDetails, 9)
Me.FieldDetails.Size = New System.Drawing.Size(444, 552)
Me.FieldDetails.TabIndex = 0
'
'CreateTable_ActionDetailContainerPnl
'
Me.CreateTable_ActionDetailContainerPnl.Controls.Add(Me.FieldGroup)
Me.CreateTable_ActionDetailContainerPnl.Controls.Add(Me.FieldDetails_ForeignKeyGrp)
Me.CreateTable_ActionDetailContainerPnl.Controls.Add(Me.FieldDetails_PrimyGrp)
Me.CreateTable_ActionDetailContainerPnl.Dock = System.Windows.Forms.DockStyle.Top
Me.CreateTable_ActionDetailContainerPnl.Location = New System.Drawing.Point(0, 0)
Me.CreateTable_ActionDetailContainerPnl.Name = "CreateTable_ActionDetailContainerPnl"
Me.CreateTable_ActionDetailContainerPnl.Size = New System.Drawing.Size(444, 160)
Me.CreateTable_ActionDetailContainerPnl.TabIndex = 13
'
'FieldGroup
'
Me.FieldGroup.Controls.Add(Me.FieldDetails_ColumnLbl)
Me.FieldGroup.Controls.Add(Me.FieldDetails_FormulaChkbx)
Me.FieldGroup.Controls.Add(Me.FieldDetails_ColumnTYpeCmbo)
Me.FieldGroup.Controls.Add(Me.FieldDetails_DefFld)
Me.FieldGroup.Controls.Add(Me.FieldDetails_ColumnNameLbl)
Me.FieldGroup.Controls.Add(Me.FieldDetails_DefValChkbx)
Me.FieldGroup.Controls.Add(Me.FieldDetails_ColumnNameFld)
Me.FieldGroup.Controls.Add(Me.FieldDetails_Precision)
Me.FieldGroup.Controls.Add(Me.FieldDetails_PreScleLbl)
Me.FieldGroup.Controls.Add(Me.FieldDetails_SizeLbl)
Me.FieldGroup.Controls.Add(Me.FieldDetails_TypeLbl)
Me.FieldGroup.Controls.Add(Me.FieldDetails_Size)
Me.FieldGroup.Controls.Add(Me.FieldDetails_Scale)
Me.FieldGroup.Dock = System.Windows.Forms.DockStyle.Fill
Me.FieldGroup.Enabled = False
Me.FieldGroup.Location = New System.Drawing.Point(0, 0)
Me.FieldGroup.Margin = New System.Windows.Forms.Padding(0)
Me.FieldGroup.Name = "FieldGroup"
Me.FieldGroup.Size = New System.Drawing.Size(444, 160)
Me.FieldGroup.TabIndex = 8
'
'FieldDetails_ColumnLbl
'
Me.FieldDetails_ColumnLbl.AutoSize = True
Me.FieldDetails_ColumnLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FieldDetails_ColumnLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.FieldDetails_ColumnLbl.Location = New System.Drawing.Point(6, 5)
Me.FieldDetails_ColumnLbl.Name = "FieldDetails_ColumnLbl"
Me.FieldDetails_ColumnLbl.Size = New System.Drawing.Size(84, 15)
Me.FieldDetails_ColumnLbl.TabIndex = 67
Me.FieldDetails_ColumnLbl.Text = "Add Column"
'
'FieldDetails_FormulaChkbx
'
Me.FieldDetails_FormulaChkbx.AccessibleDescription = "Formula"
Me.FieldDetails_FormulaChkbx.AutoSize = True
Me.FieldDetails_FormulaChkbx.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.FieldDetails_FormulaChkbx.Location = New System.Drawing.Point(111, 128)
Me.FieldDetails_FormulaChkbx.Name = "FieldDetails_FormulaChkbx"
Me.FieldDetails_FormulaChkbx.Size = New System.Drawing.Size(63, 17)
Me.FieldDetails_FormulaChkbx.TabIndex = 66
Me.FieldDetails_FormulaChkbx.Text = "Formula"
Me.FieldDetails_FormulaChkbx.UseVisualStyleBackColor = True
'
'FieldDetails_ColumnTYpeCmbo
'
Me.FieldDetails_ColumnTYpeCmbo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.FieldDetails_ColumnTYpeCmbo.FormattingEnabled = True
Me.FieldDetails_ColumnTYpeCmbo.ImeMode = System.Windows.Forms.ImeMode.Off
Me.FieldDetails_ColumnTYpeCmbo.Items.AddRange(New Object() {"CHAR", "VARCHAR", "BIT", "INTEGER", "SMALLINT", "DECIMAL", "NUMERIC", "REAL", "FLOAT", "DATE", "TIME"})
Me.FieldDetails_ColumnTYpeCmbo.Location = New System.Drawing.Point(11, 85)
Me.FieldDetails_ColumnTYpeCmbo.Name = "FieldDetails_ColumnTYpeCmbo"
Me.FieldDetails_ColumnTYpeCmbo.Size = New System.Drawing.Size(127, 21)
Me.FieldDetails_ColumnTYpeCmbo.TabIndex = 42
'
'FieldDetails_DefFld
'
Me.FieldDetails_DefFld.Enabled = False
Me.FieldDetails_DefFld.Location = New System.Drawing.Point(187, 125)
Me.FieldDetails_DefFld.Name = "FieldDetails_DefFld"
Me.FieldDetails_DefFld.Size = New System.Drawing.Size(241, 20)
Me.FieldDetails_DefFld.TabIndex = 65
'
'FieldDetails_ColumnNameLbl
'
Me.FieldDetails_ColumnNameLbl.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.FieldDetails_ColumnNameLbl.AutoSize = True
Me.FieldDetails_ColumnNameLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_ColumnNameLbl.Location = New System.Drawing.Point(161, 18)
Me.FieldDetails_ColumnNameLbl.Name = "FieldDetails_ColumnNameLbl"
Me.FieldDetails_ColumnNameLbl.Size = New System.Drawing.Size(101, 13)
Me.FieldDetails_ColumnNameLbl.TabIndex = 40
Me.FieldDetails_ColumnNameLbl.Text = "Enter Column Name"
'
'FieldDetails_DefValChkbx
'
Me.FieldDetails_DefValChkbx.AutoSize = True
Me.FieldDetails_DefValChkbx.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.FieldDetails_DefValChkbx.Location = New System.Drawing.Point(15, 127)
Me.FieldDetails_DefValChkbx.Name = "FieldDetails_DefValChkbx"
Me.FieldDetails_DefValChkbx.Size = New System.Drawing.Size(90, 17)
Me.FieldDetails_DefValChkbx.TabIndex = 64
Me.FieldDetails_DefValChkbx.Text = "Default Value"
Me.FieldDetails_DefValChkbx.UseVisualStyleBackColor = True
'
'FieldDetails_ColumnNameFld
'
Me.FieldDetails_ColumnNameFld.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.FieldDetails_ColumnNameFld.Depth = 0
Me.FieldDetails_ColumnNameFld.Hint = ""
Me.FieldDetails_ColumnNameFld.Location = New System.Drawing.Point(11, 34)
Me.FieldDetails_ColumnNameFld.MouseState = MaterialSkin.MouseState.HOVER
Me.FieldDetails_ColumnNameFld.Name = "FieldDetails_ColumnNameFld"
Me.FieldDetails_ColumnNameFld.PasswordChar = Global.Microsoft.VisualBasic.ChrW(0)
Me.FieldDetails_ColumnNameFld.SelectedText = ""
Me.FieldDetails_ColumnNameFld.SelectionLength = 0
Me.FieldDetails_ColumnNameFld.SelectionStart = 0
Me.FieldDetails_ColumnNameFld.Size = New System.Drawing.Size(424, 23)
Me.FieldDetails_ColumnNameFld.TabIndex = 41
Me.FieldDetails_ColumnNameFld.UseSystemPasswordChar = False
'
'FieldDetails_Precision
'
Me.FieldDetails_Precision.Location = New System.Drawing.Point(340, 85)
Me.FieldDetails_Precision.Name = "FieldDetails_Precision"
Me.FieldDetails_Precision.Size = New System.Drawing.Size(41, 20)
Me.FieldDetails_Precision.TabIndex = 63
'
'FieldDetails_PreScleLbl
'
Me.FieldDetails_PreScleLbl.AutoSize = True
Me.FieldDetails_PreScleLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_PreScleLbl.Location = New System.Drawing.Point(337, 66)
Me.FieldDetails_PreScleLbl.Name = "FieldDetails_PreScleLbl"
Me.FieldDetails_PreScleLbl.Size = New System.Drawing.Size(91, 13)
Me.FieldDetails_PreScleLbl.TabIndex = 60
Me.FieldDetails_PreScleLbl.Text = "(Presision , Scale)"
'
'FieldDetails_SizeLbl
'
Me.FieldDetails_SizeLbl.AutoSize = True
Me.FieldDetails_SizeLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_SizeLbl.Location = New System.Drawing.Point(189, 69)
Me.FieldDetails_SizeLbl.Name = "FieldDetails_SizeLbl"
Me.FieldDetails_SizeLbl.Size = New System.Drawing.Size(27, 13)
Me.FieldDetails_SizeLbl.TabIndex = 45
Me.FieldDetails_SizeLbl.Text = "Size"
'
'FieldDetails_TypeLbl
'
Me.FieldDetails_TypeLbl.AutoSize = True
Me.FieldDetails_TypeLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_TypeLbl.Location = New System.Drawing.Point(9, 69)
Me.FieldDetails_TypeLbl.Name = "FieldDetails_TypeLbl"
Me.FieldDetails_TypeLbl.Size = New System.Drawing.Size(31, 13)
Me.FieldDetails_TypeLbl.TabIndex = 43
Me.FieldDetails_TypeLbl.Text = "Type"
'
'FieldDetails_Size
'
Me.FieldDetails_Size.Enabled = False
Me.FieldDetails_Size.Location = New System.Drawing.Point(187, 85)
Me.FieldDetails_Size.Maximum = New Decimal(New Integer() {9999, 0, 0, 0})
Me.FieldDetails_Size.Name = "FieldDetails_Size"
Me.FieldDetails_Size.Size = New System.Drawing.Size(85, 20)
Me.FieldDetails_Size.TabIndex = 46
'
'FieldDetails_Scale
'
Me.FieldDetails_Scale.Location = New System.Drawing.Point(387, 85)
Me.FieldDetails_Scale.Name = "FieldDetails_Scale"
Me.FieldDetails_Scale.Size = New System.Drawing.Size(41, 20)
Me.FieldDetails_Scale.TabIndex = 62
'
'FieldDetails_ForeignKeyGrp
'
Me.FieldDetails_ForeignKeyGrp.Controls.Add(Me.FieldDetails_ForeignKeyLbl)
Me.FieldDetails_ForeignKeyGrp.Controls.Add(Me.FieldDetails_ForeignKeyFld)
Me.FieldDetails_ForeignKeyGrp.Dock = System.Windows.Forms.DockStyle.Fill
Me.FieldDetails_ForeignKeyGrp.Location = New System.Drawing.Point(0, 0)
Me.FieldDetails_ForeignKeyGrp.Name = "FieldDetails_ForeignKeyGrp"
Me.FieldDetails_ForeignKeyGrp.Size = New System.Drawing.Size(444, 160)
Me.FieldDetails_ForeignKeyGrp.TabIndex = 0
Me.FieldDetails_ForeignKeyGrp.Visible = False
'
'FieldDetails_ForeignKeyLbl
'
Me.FieldDetails_ForeignKeyLbl.AutoSize = True
Me.FieldDetails_ForeignKeyLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FieldDetails_ForeignKeyLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.FieldDetails_ForeignKeyLbl.Location = New System.Drawing.Point(7, 0)
Me.FieldDetails_ForeignKeyLbl.Name = "FieldDetails_ForeignKeyLbl"
Me.FieldDetails_ForeignKeyLbl.Size = New System.Drawing.Size(111, 15)
Me.FieldDetails_ForeignKeyLbl.TabIndex = 68
Me.FieldDetails_ForeignKeyLbl.Text = "Add Foreign Key"
'
'FieldDetails_ForeignKeyFld
'
Me.FieldDetails_ForeignKeyFld.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.FieldDetails_ForeignKeyFld.Location = New System.Drawing.Point(4, 23)
Me.FieldDetails_ForeignKeyFld.Multiline = True
Me.FieldDetails_ForeignKeyFld.Name = "FieldDetails_ForeignKeyFld"
Me.FieldDetails_ForeignKeyFld.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.FieldDetails_ForeignKeyFld.Size = New System.Drawing.Size(434, 134)
Me.FieldDetails_ForeignKeyFld.TabIndex = 54
Me.Tip.SetToolTip(Me.FieldDetails_ForeignKeyFld, "Enter 1 Item Per Line")
Me.FieldDetails_ForeignKeyFld.WordWrap = False
'
'FieldDetails_PrimyGrp
'
Me.FieldDetails_PrimyGrp.Controls.Add(Me.FieldDetails_PrimLbl)
Me.FieldDetails_PrimyGrp.Controls.Add(Me.FieldDetails_PrimFld)
Me.FieldDetails_PrimyGrp.Dock = System.Windows.Forms.DockStyle.Fill
Me.FieldDetails_PrimyGrp.Location = New System.Drawing.Point(0, 0)
Me.FieldDetails_PrimyGrp.Name = "FieldDetails_PrimyGrp"
Me.FieldDetails_PrimyGrp.Size = New System.Drawing.Size(444, 160)
Me.FieldDetails_PrimyGrp.TabIndex = 0
Me.Tip.SetToolTip(Me.FieldDetails_PrimyGrp, "Enter 1 Item Per Line")
Me.FieldDetails_PrimyGrp.Visible = False
'
'FieldDetails_PrimLbl
'
Me.FieldDetails_PrimLbl.AutoSize = True
Me.FieldDetails_PrimLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FieldDetails_PrimLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.FieldDetails_PrimLbl.Location = New System.Drawing.Point(7, 0)
Me.FieldDetails_PrimLbl.Name = "FieldDetails_PrimLbl"
Me.FieldDetails_PrimLbl.Size = New System.Drawing.Size(111, 15)
Me.FieldDetails_PrimLbl.TabIndex = 69
Me.FieldDetails_PrimLbl.Text = "Add Primary Key"
'
'FieldDetails_PrimFld
'
Me.FieldDetails_PrimFld.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.FieldDetails_PrimFld.Location = New System.Drawing.Point(4, 23)
Me.FieldDetails_PrimFld.Multiline = True
Me.FieldDetails_PrimFld.Name = "FieldDetails_PrimFld"
Me.FieldDetails_PrimFld.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.FieldDetails_PrimFld.Size = New System.Drawing.Size(434, 134)
Me.FieldDetails_PrimFld.TabIndex = 54
Me.FieldDetails_PrimFld.WordWrap = False
'
'CreateTable_ActionDetailContainerPnl2
'
Me.CreateTable_ActionDetailContainerPnl2.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.CreateTable_ActionDetailContainerPnl2.Controls.Add(Me.FieldDetails_CheckGrp)
Me.CreateTable_ActionDetailContainerPnl2.Controls.Add(Me.FieldDetails_RefConsTableLayout)
Me.CreateTable_ActionDetailContainerPnl2.Controls.Add(Me.FieldDetails_CreateFieldBtn)
Me.CreateTable_ActionDetailContainerPnl2.Location = New System.Drawing.Point(0, 163)
Me.CreateTable_ActionDetailContainerPnl2.Margin = New System.Windows.Forms.Padding(0)
Me.CreateTable_ActionDetailContainerPnl2.Name = "CreateTable_ActionDetailContainerPnl2"
Me.CreateTable_ActionDetailContainerPnl2.Size = New System.Drawing.Size(444, 335)
Me.CreateTable_ActionDetailContainerPnl2.TabIndex = 12
'
'FieldDetails_CheckGrp
'
Me.FieldDetails_CheckGrp.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.FieldDetails_CheckGrp.Controls.Add(Me.FieldDetails_CheckHelp)
Me.FieldDetails_CheckGrp.Controls.Add(Me.FieldDetails_CheckLbl)
Me.FieldDetails_CheckGrp.Controls.Add(Me.FieldDetails_CheckChkbx)
Me.FieldDetails_CheckGrp.Controls.Add(Me.FieldDetails_CheckTypeLbl)
Me.FieldDetails_CheckGrp.Controls.Add(Me.FieldDetails_CheckTypeCmbo)
Me.FieldDetails_CheckGrp.Controls.Add(Me.FieldDetails_StringPstnLbl)
Me.FieldDetails_CheckGrp.Controls.Add(Me.FieldDetails_CheckPstnCmbo)
Me.FieldDetails_CheckGrp.Controls.Add(Me.FieldDetails_CheckFld)
Me.FieldDetails_CheckGrp.Location = New System.Drawing.Point(0, 110)
Me.FieldDetails_CheckGrp.Margin = New System.Windows.Forms.Padding(0)
Me.FieldDetails_CheckGrp.Name = "FieldDetails_CheckGrp"
Me.FieldDetails_CheckGrp.Size = New System.Drawing.Size(441, 174)
Me.FieldDetails_CheckGrp.TabIndex = 74
'
'FieldDetails_CheckLbl
'
Me.FieldDetails_CheckLbl.AutoSize = True
Me.FieldDetails_CheckLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FieldDetails_CheckLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.FieldDetails_CheckLbl.Location = New System.Drawing.Point(6, 3)
Me.FieldDetails_CheckLbl.Name = "FieldDetails_CheckLbl"
Me.FieldDetails_CheckLbl.Size = New System.Drawing.Size(46, 15)
Me.FieldDetails_CheckLbl.TabIndex = 70
Me.FieldDetails_CheckLbl.Text = "Check"
'
'FieldDetails_CheckChkbx
'
Me.FieldDetails_CheckChkbx.AutoSize = True
Me.FieldDetails_CheckChkbx.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_CheckChkbx.Location = New System.Drawing.Point(5, 37)
Me.FieldDetails_CheckChkbx.Name = "FieldDetails_CheckChkbx"
Me.FieldDetails_CheckChkbx.Size = New System.Drawing.Size(57, 17)
Me.FieldDetails_CheckChkbx.TabIndex = 56
Me.FieldDetails_CheckChkbx.Text = "Check"
Me.FieldDetails_CheckChkbx.UseVisualStyleBackColor = True
'
'FieldDetails_CheckTypeLbl
'
Me.FieldDetails_CheckTypeLbl.AutoSize = True
Me.FieldDetails_CheckTypeLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_CheckTypeLbl.Location = New System.Drawing.Point(67, 16)
Me.FieldDetails_CheckTypeLbl.Name = "FieldDetails_CheckTypeLbl"
Me.FieldDetails_CheckTypeLbl.Size = New System.Drawing.Size(65, 13)
Me.FieldDetails_CheckTypeLbl.TabIndex = 50
Me.FieldDetails_CheckTypeLbl.Text = "Check Type"
'
'FieldDetails_CheckTypeCmbo
'
Me.FieldDetails_CheckTypeCmbo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.FieldDetails_CheckTypeCmbo.Enabled = False
Me.FieldDetails_CheckTypeCmbo.FormattingEnabled = True
Me.FieldDetails_CheckTypeCmbo.ImeMode = System.Windows.Forms.ImeMode.Off
Me.FieldDetails_CheckTypeCmbo.Items.AddRange(New Object() {"LIKE", "IN", "Numeric/Logical Expresion/Other"})
Me.FieldDetails_CheckTypeCmbo.Location = New System.Drawing.Point(67, 35)
Me.FieldDetails_CheckTypeCmbo.Name = "FieldDetails_CheckTypeCmbo"
Me.FieldDetails_CheckTypeCmbo.Size = New System.Drawing.Size(156, 21)
Me.FieldDetails_CheckTypeCmbo.TabIndex = 55
'
'FieldDetails_StringPstnLbl
'
Me.FieldDetails_StringPstnLbl.AutoSize = True
Me.FieldDetails_StringPstnLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_StringPstnLbl.Location = New System.Drawing.Point(236, 16)
Me.FieldDetails_StringPstnLbl.Name = "FieldDetails_StringPstnLbl"
Me.FieldDetails_StringPstnLbl.Size = New System.Drawing.Size(74, 13)
Me.FieldDetails_StringPstnLbl.TabIndex = 52
Me.FieldDetails_StringPstnLbl.Text = "String Position"
'
'FieldDetails_CheckPstnCmbo
'
Me.FieldDetails_CheckPstnCmbo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.FieldDetails_CheckPstnCmbo.Enabled = False
Me.FieldDetails_CheckPstnCmbo.FormattingEnabled = True
Me.FieldDetails_CheckPstnCmbo.ImeMode = System.Windows.Forms.ImeMode.Off
Me.FieldDetails_CheckPstnCmbo.Items.AddRange(New Object() {"Before any string", "After any string", "Between any string", "Other/Specific"})
Me.FieldDetails_CheckPstnCmbo.Location = New System.Drawing.Point(239, 35)
Me.FieldDetails_CheckPstnCmbo.Name = "FieldDetails_CheckPstnCmbo"
Me.FieldDetails_CheckPstnCmbo.Size = New System.Drawing.Size(156, 21)
Me.FieldDetails_CheckPstnCmbo.TabIndex = 51
'
'FieldDetails_CheckFld
'
Me.FieldDetails_CheckFld.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.FieldDetails_CheckFld.Enabled = False
Me.FieldDetails_CheckFld.Location = New System.Drawing.Point(6, 70)
Me.FieldDetails_CheckFld.Multiline = True
Me.FieldDetails_CheckFld.Name = "FieldDetails_CheckFld"
Me.FieldDetails_CheckFld.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.FieldDetails_CheckFld.Size = New System.Drawing.Size(435, 104)
Me.FieldDetails_CheckFld.TabIndex = 53
Me.Tip.SetToolTip(Me.FieldDetails_CheckFld, "Enter 1 Item Per Line")
Me.FieldDetails_CheckFld.WordWrap = False
'
'FieldDetails_RefConsTableLayout
'
Me.FieldDetails_RefConsTableLayout.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.FieldDetails_RefConsTableLayout.ColumnCount = 2
Me.FieldDetails_RefConsTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 60.0!))
Me.FieldDetails_RefConsTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 40.0!))
Me.FieldDetails_RefConsTableLayout.Controls.Add(Me.FieldDetails_ReferenceGrp, 0, 0)
Me.FieldDetails_RefConsTableLayout.Controls.Add(Me.FieldDetails_ConstraintGrp, 1, 0)
Me.FieldDetails_RefConsTableLayout.Location = New System.Drawing.Point(0, 0)
Me.FieldDetails_RefConsTableLayout.Name = "FieldDetails_RefConsTableLayout"
Me.FieldDetails_RefConsTableLayout.RowCount = 1
Me.FieldDetails_RefConsTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.FieldDetails_RefConsTableLayout.Size = New System.Drawing.Size(447, 110)
Me.FieldDetails_RefConsTableLayout.TabIndex = 73
'
'FieldDetails_ReferenceGrp
'
Me.FieldDetails_ReferenceGrp.Controls.Add(Me.FieldDetails_ReferentialLbl)
Me.FieldDetails_ReferenceGrp.Controls.Add(Me.FieldDetails_OnDeleteCmbo)
Me.FieldDetails_ReferenceGrp.Controls.Add(Me.FieldDetails_ReferenceChkBx)
Me.FieldDetails_ReferenceGrp.Controls.Add(Me.FieldDetails_OnUpdateCmbo)
Me.FieldDetails_ReferenceGrp.Controls.Add(Me.FieldDetails_ReferenceFld)
Me.FieldDetails_ReferenceGrp.Controls.Add(Me.FieldDetails_OnDeleteChkbx)
Me.FieldDetails_ReferenceGrp.Controls.Add(Me.FieldDetails_OnUpdateChkBx)
Me.FieldDetails_ReferenceGrp.Dock = System.Windows.Forms.DockStyle.Fill
Me.FieldDetails_ReferenceGrp.Location = New System.Drawing.Point(0, 0)
Me.FieldDetails_ReferenceGrp.Margin = New System.Windows.Forms.Padding(0)
Me.FieldDetails_ReferenceGrp.Name = "FieldDetails_ReferenceGrp"
Me.FieldDetails_ReferenceGrp.Size = New System.Drawing.Size(268, 110)
Me.FieldDetails_ReferenceGrp.TabIndex = 67
'
'FieldDetails_ReferentialLbl
'
Me.FieldDetails_ReferentialLbl.AutoSize = True
Me.FieldDetails_ReferentialLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FieldDetails_ReferentialLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.FieldDetails_ReferentialLbl.Location = New System.Drawing.Point(6, -3)
Me.FieldDetails_ReferentialLbl.Name = "FieldDetails_ReferentialLbl"
Me.FieldDetails_ReferentialLbl.Size = New System.Drawing.Size(78, 15)
Me.FieldDetails_ReferentialLbl.TabIndex = 70
Me.FieldDetails_ReferentialLbl.Text = "Referential"
'
'FieldDetails_OnDeleteCmbo
'
Me.FieldDetails_OnDeleteCmbo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.FieldDetails_OnDeleteCmbo.Enabled = False
Me.FieldDetails_OnDeleteCmbo.FormattingEnabled = True
Me.FieldDetails_OnDeleteCmbo.ImeMode = System.Windows.Forms.ImeMode.Off
Me.FieldDetails_OnDeleteCmbo.Items.AddRange(New Object() {"CASCADE", "SET NULL", "SET DEFAULT", "NO ACTION"})
Me.FieldDetails_OnDeleteCmbo.Location = New System.Drawing.Point(89, 83)
Me.FieldDetails_OnDeleteCmbo.Name = "FieldDetails_OnDeleteCmbo"
Me.FieldDetails_OnDeleteCmbo.Size = New System.Drawing.Size(124, 21)
Me.FieldDetails_OnDeleteCmbo.TabIndex = 61
'
'FieldDetails_ReferenceChkBx
'
Me.FieldDetails_ReferenceChkBx.AutoSize = True
Me.FieldDetails_ReferenceChkBx.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_ReferenceChkBx.Location = New System.Drawing.Point(9, 25)
Me.FieldDetails_ReferenceChkBx.Name = "FieldDetails_ReferenceChkBx"
Me.FieldDetails_ReferenceChkBx.Size = New System.Drawing.Size(81, 17)
Me.FieldDetails_ReferenceChkBx.TabIndex = 54
Me.FieldDetails_ReferenceChkBx.Text = "References"
Me.FieldDetails_ReferenceChkBx.UseVisualStyleBackColor = True
'
'FieldDetails_OnUpdateCmbo
'
Me.FieldDetails_OnUpdateCmbo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.FieldDetails_OnUpdateCmbo.Enabled = False
Me.FieldDetails_OnUpdateCmbo.FormattingEnabled = True
Me.FieldDetails_OnUpdateCmbo.ImeMode = System.Windows.Forms.ImeMode.Off
Me.FieldDetails_OnUpdateCmbo.Items.AddRange(New Object() {"CASCADE", "SET NULL", "SET DEFAULT", "NO ACTION"})
Me.FieldDetails_OnUpdateCmbo.Location = New System.Drawing.Point(90, 51)
Me.FieldDetails_OnUpdateCmbo.Name = "FieldDetails_OnUpdateCmbo"
Me.FieldDetails_OnUpdateCmbo.Size = New System.Drawing.Size(124, 21)
Me.FieldDetails_OnUpdateCmbo.TabIndex = 60
'
'FieldDetails_ReferenceFld
'
Me.FieldDetails_ReferenceFld.Enabled = False
Me.FieldDetails_ReferenceFld.Location = New System.Drawing.Point(91, 22)
Me.FieldDetails_ReferenceFld.Name = "FieldDetails_ReferenceFld"
Me.FieldDetails_ReferenceFld.Size = New System.Drawing.Size(153, 20)
Me.FieldDetails_ReferenceFld.TabIndex = 55
'
'FieldDetails_OnDeleteChkbx
'
Me.FieldDetails_OnDeleteChkbx.AutoSize = True
Me.FieldDetails_OnDeleteChkbx.Enabled = False
Me.FieldDetails_OnDeleteChkbx.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_OnDeleteChkbx.Location = New System.Drawing.Point(9, 87)
Me.FieldDetails_OnDeleteChkbx.Name = "FieldDetails_OnDeleteChkbx"
Me.FieldDetails_OnDeleteChkbx.Size = New System.Drawing.Size(74, 17)
Me.FieldDetails_OnDeleteChkbx.TabIndex = 59
Me.FieldDetails_OnDeleteChkbx.Text = "On Delete"
Me.FieldDetails_OnDeleteChkbx.UseVisualStyleBackColor = True
'
'FieldDetails_OnUpdateChkBx
'
Me.FieldDetails_OnUpdateChkBx.AutoSize = True
Me.FieldDetails_OnUpdateChkBx.Enabled = False
Me.FieldDetails_OnUpdateChkBx.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_OnUpdateChkBx.Location = New System.Drawing.Point(9, 55)
Me.FieldDetails_OnUpdateChkBx.Name = "FieldDetails_OnUpdateChkBx"
Me.FieldDetails_OnUpdateChkBx.Size = New System.Drawing.Size(78, 17)
Me.FieldDetails_OnUpdateChkBx.TabIndex = 57
Me.FieldDetails_OnUpdateChkBx.Text = "On Update"
Me.FieldDetails_OnUpdateChkBx.UseVisualStyleBackColor = True
'
'FieldDetails_ConstraintGrp
'
Me.FieldDetails_ConstraintGrp.Controls.Add(Me.FieldDetails_ConstraintsLbl)
Me.FieldDetails_ConstraintGrp.Controls.Add(Me.FieldDetails_ForeignChkbx)
Me.FieldDetails_ConstraintGrp.Controls.Add(Me.FieldDetails_NotNullChkbx)
Me.FieldDetails_ConstraintGrp.Controls.Add(Me.FieldDetails_UniqueChkbx)
Me.FieldDetails_ConstraintGrp.Controls.Add(Me.FieldDetails_PrimChkbx)
Me.FieldDetails_ConstraintGrp.Dock = System.Windows.Forms.DockStyle.Fill
Me.FieldDetails_ConstraintGrp.Location = New System.Drawing.Point(268, 0)
Me.FieldDetails_ConstraintGrp.Margin = New System.Windows.Forms.Padding(0)
Me.FieldDetails_ConstraintGrp.Name = "FieldDetails_ConstraintGrp"
Me.FieldDetails_ConstraintGrp.Size = New System.Drawing.Size(179, 110)
Me.FieldDetails_ConstraintGrp.TabIndex = 68
'
'FieldDetails_ConstraintsLbl
'
Me.FieldDetails_ConstraintsLbl.AutoSize = True
Me.FieldDetails_ConstraintsLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FieldDetails_ConstraintsLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.FieldDetails_ConstraintsLbl.Location = New System.Drawing.Point(0, -3)
Me.FieldDetails_ConstraintsLbl.Name = "FieldDetails_ConstraintsLbl"
Me.FieldDetails_ConstraintsLbl.Size = New System.Drawing.Size(79, 15)
Me.FieldDetails_ConstraintsLbl.TabIndex = 70
Me.FieldDetails_ConstraintsLbl.Text = "Constraints"
'
'FieldDetails_ForeignChkbx
'
Me.FieldDetails_ForeignChkbx.AutoSize = True
Me.FieldDetails_ForeignChkbx.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_ForeignChkbx.Location = New System.Drawing.Point(3, 45)
Me.FieldDetails_ForeignChkbx.Name = "FieldDetails_ForeignChkbx"
Me.FieldDetails_ForeignChkbx.Size = New System.Drawing.Size(98, 17)
Me.FieldDetails_ForeignChkbx.TabIndex = 58
Me.FieldDetails_ForeignChkbx.Text = "FOREIGN KEY"
Me.FieldDetails_ForeignChkbx.UseVisualStyleBackColor = True
'
'FieldDetails_NotNullChkbx
'
Me.FieldDetails_NotNullChkbx.AutoSize = True
Me.FieldDetails_NotNullChkbx.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_NotNullChkbx.Location = New System.Drawing.Point(3, 68)
Me.FieldDetails_NotNullChkbx.Name = "FieldDetails_NotNullChkbx"
Me.FieldDetails_NotNullChkbx.Size = New System.Drawing.Size(80, 17)
Me.FieldDetails_NotNullChkbx.TabIndex = 54
Me.FieldDetails_NotNullChkbx.Text = "NOT NULL"
Me.FieldDetails_NotNullChkbx.UseVisualStyleBackColor = True
'
'FieldDetails_UniqueChkbx
'
Me.FieldDetails_UniqueChkbx.AutoSize = True
Me.FieldDetails_UniqueChkbx.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_UniqueChkbx.Location = New System.Drawing.Point(3, 91)
Me.FieldDetails_UniqueChkbx.Name = "FieldDetails_UniqueChkbx"
Me.FieldDetails_UniqueChkbx.Size = New System.Drawing.Size(68, 17)
Me.FieldDetails_UniqueChkbx.TabIndex = 57
Me.FieldDetails_UniqueChkbx.Text = "UNIQUE"
Me.FieldDetails_UniqueChkbx.UseVisualStyleBackColor = True
'
'FieldDetails_PrimChkbx
'
Me.FieldDetails_PrimChkbx.AutoSize = True
Me.FieldDetails_PrimChkbx.ForeColor = System.Drawing.SystemColors.WindowText
Me.FieldDetails_PrimChkbx.Location = New System.Drawing.Point(3, 24)
Me.FieldDetails_PrimChkbx.Name = "FieldDetails_PrimChkbx"
Me.FieldDetails_PrimChkbx.Size = New System.Drawing.Size(99, 17)
Me.FieldDetails_PrimChkbx.TabIndex = 44
Me.FieldDetails_PrimChkbx.Text = "PRIMARY KEY"
Me.FieldDetails_PrimChkbx.UseVisualStyleBackColor = True
'
'FieldDetails_CreateFieldBtn
'
Me.FieldDetails_CreateFieldBtn.AutoSize = True
Me.FieldDetails_CreateFieldBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.FieldDetails_CreateFieldBtn.Depth = 0
Me.FieldDetails_CreateFieldBtn.Location = New System.Drawing.Point(9, 293)
Me.FieldDetails_CreateFieldBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.FieldDetails_CreateFieldBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.FieldDetails_CreateFieldBtn.Name = "FieldDetails_CreateFieldBtn"
Me.FieldDetails_CreateFieldBtn.Primary = False
Me.FieldDetails_CreateFieldBtn.Size = New System.Drawing.Size(48, 36)
Me.FieldDetails_CreateFieldBtn.TabIndex = 72
Me.FieldDetails_CreateFieldBtn.Text = "Done"
Me.FieldDetails_CreateFieldBtn.UseVisualStyleBackColor = True
'
'CreateTable_BtbTableLayout
'
Me.CreateTable_BtbTableLayout.ColumnCount = 4
Me.CreateTable_BtbTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.CreateTable_BtbTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.CreateTable_BtbTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.CreateTable_BtbTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.CreateTable_BtbTableLayout.Controls.Add(Me.CreateTable_AddPrimKeyBtn, 1, 0)
Me.CreateTable_BtbTableLayout.Controls.Add(Me.CreateTable_CompleteTableBtn, 3, 0)
Me.CreateTable_BtbTableLayout.Controls.Add(Me.CreateTable_AddColumnBtn, 0, 0)
Me.CreateTable_BtbTableLayout.Controls.Add(Me.CreateTable_AddForeignKeyBtn, 2, 0)
Me.CreateTable_BtbTableLayout.Dock = System.Windows.Forms.DockStyle.Fill
Me.CreateTable_BtbTableLayout.Location = New System.Drawing.Point(3, 64)
Me.CreateTable_BtbTableLayout.Name = "CreateTable_BtbTableLayout"
Me.CreateTable_BtbTableLayout.RowCount = 1
Me.CreateTable_BtbTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.CreateTable_BtbTableLayout.Size = New System.Drawing.Size(444, 55)
Me.CreateTable_BtbTableLayout.TabIndex = 6
'
'CreateTable_AddPrimKeyBtn
'
Me.CreateTable_AddPrimKeyBtn.AutoSize = True
Me.CreateTable_AddPrimKeyBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.CreateTable_AddPrimKeyBtn.Depth = 0
Me.CreateTable_AddPrimKeyBtn.Enabled = False
Me.CreateTable_AddPrimKeyBtn.Location = New System.Drawing.Point(115, 6)
Me.CreateTable_AddPrimKeyBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.CreateTable_AddPrimKeyBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.CreateTable_AddPrimKeyBtn.Name = "CreateTable_AddPrimKeyBtn"
Me.CreateTable_AddPrimKeyBtn.Primary = False
Me.CreateTable_AddPrimKeyBtn.Size = New System.Drawing.Size(103, 36)
Me.CreateTable_AddPrimKeyBtn.TabIndex = 65
Me.CreateTable_AddPrimKeyBtn.Text = "Add Primary Key"
Me.CreateTable_AddPrimKeyBtn.UseVisualStyleBackColor = True
'
'CreateTable_CompleteTableBtn
'
Me.CreateTable_CompleteTableBtn.AutoSize = True
Me.CreateTable_CompleteTableBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.CreateTable_CompleteTableBtn.Depth = 0
Me.CreateTable_CompleteTableBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.CreateTable_CompleteTableBtn.Enabled = False
Me.CreateTable_CompleteTableBtn.Location = New System.Drawing.Point(337, 6)
Me.CreateTable_CompleteTableBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.CreateTable_CompleteTableBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.CreateTable_CompleteTableBtn.Name = "CreateTable_CompleteTableBtn"
Me.CreateTable_CompleteTableBtn.Primary = False
Me.CreateTable_CompleteTableBtn.Size = New System.Drawing.Size(103, 43)
Me.CreateTable_CompleteTableBtn.TabIndex = 68
Me.CreateTable_CompleteTableBtn.Text = "complete Statement"
Me.CreateTable_CompleteTableBtn.UseVisualStyleBackColor = True
'
'CreateTable_AddColumnBtn
'
Me.CreateTable_AddColumnBtn.AutoSize = True
Me.CreateTable_AddColumnBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.CreateTable_AddColumnBtn.Depth = 0
Me.CreateTable_AddColumnBtn.Dock = System.Windows.Forms.DockStyle.Fill
Me.CreateTable_AddColumnBtn.Enabled = False
Me.CreateTable_AddColumnBtn.Location = New System.Drawing.Point(4, 6)
Me.CreateTable_AddColumnBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.CreateTable_AddColumnBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.CreateTable_AddColumnBtn.Name = "CreateTable_AddColumnBtn"
Me.CreateTable_AddColumnBtn.Primary = False
Me.CreateTable_AddColumnBtn.Size = New System.Drawing.Size(103, 43)
Me.CreateTable_AddColumnBtn.TabIndex = 66
Me.CreateTable_AddColumnBtn.Text = "Add Column"
Me.CreateTable_AddColumnBtn.UseVisualStyleBackColor = True
'
'CreateTable_AddForeignKeyBtn
'
Me.CreateTable_AddForeignKeyBtn.AutoSize = True
Me.CreateTable_AddForeignKeyBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.CreateTable_AddForeignKeyBtn.Depth = 0
Me.CreateTable_AddForeignKeyBtn.Enabled = False
Me.CreateTable_AddForeignKeyBtn.Location = New System.Drawing.Point(226, 6)
Me.CreateTable_AddForeignKeyBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.CreateTable_AddForeignKeyBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.CreateTable_AddForeignKeyBtn.Name = "CreateTable_AddForeignKeyBtn"
Me.CreateTable_AddForeignKeyBtn.Primary = False
Me.CreateTable_AddForeignKeyBtn.Size = New System.Drawing.Size(103, 36)
Me.CreateTable_AddForeignKeyBtn.TabIndex = 67
Me.CreateTable_AddForeignKeyBtn.Text = "Add Foreign Key"
Me.CreateTable_AddForeignKeyBtn.UseVisualStyleBackColor = True
'
'AlterTablePage
'
Me.AlterTablePage.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.AlterTablePage.Controls.Add(Me.AlterTableLayoutPanel)
Me.AlterTablePage.Location = New System.Drawing.Point(4, 22)
Me.AlterTablePage.Name = "AlterTablePage"
Me.AlterTablePage.Padding = New System.Windows.Forms.Padding(3)
Me.AlterTablePage.Size = New System.Drawing.Size(456, 686)
Me.AlterTablePage.TabIndex = 3
Me.AlterTablePage.Text = "Alter Table"
'
'AlterTableLayoutPanel
'
Me.AlterTableLayoutPanel.ColumnCount = 1
Me.AlterTableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.AlterTableLayoutPanel.Controls.Add(Me.AlterTable_TableNamePnl, 0, 0)
Me.AlterTableLayoutPanel.Controls.Add(Me.AlterTable_ActionContainerPnl, 0, 2)
Me.AlterTableLayoutPanel.Controls.Add(Me.AlterTable_BtnTableLayout, 0, 1)
Me.AlterTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.AlterTableLayoutPanel.Location = New System.Drawing.Point(3, 3)
Me.AlterTableLayoutPanel.Name = "AlterTableLayoutPanel"
Me.AlterTableLayoutPanel.RowCount = 11
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.090908!))
Me.AlterTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.AlterTableLayoutPanel.Size = New System.Drawing.Size(450, 680)
Me.AlterTableLayoutPanel.TabIndex = 48
'
'AlterTable_TableNamePnl
'
Me.AlterTable_TableNamePnl.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.AlterTable_TableNamePnl.Controls.Add(Me.AlterTable_TableNamaLbl)
Me.AlterTable_TableNamePnl.Controls.Add(Me.AlterTable_TableNameFld)
Me.AlterTable_TableNamePnl.Location = New System.Drawing.Point(3, 6)
Me.AlterTable_TableNamePnl.Name = "AlterTable_TableNamePnl"
Me.AlterTable_TableNamePnl.Size = New System.Drawing.Size(444, 49)
Me.AlterTable_TableNamePnl.TabIndex = 1
'
'AlterTable_TableNamaLbl
'
Me.AlterTable_TableNamaLbl.AutoSize = True
Me.AlterTable_TableNamaLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.AlterTable_TableNamaLbl.Location = New System.Drawing.Point(176, 2)
Me.AlterTable_TableNamaLbl.Name = "AlterTable_TableNamaLbl"
Me.AlterTable_TableNamaLbl.Size = New System.Drawing.Size(93, 13)
Me.AlterTable_TableNamaLbl.TabIndex = 41
Me.AlterTable_TableNamaLbl.Text = "Enter Table Name"
'
'AlterTable_TableNameFld
'
Me.AlterTable_TableNameFld.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.AlterTable_TableNameFld.Depth = 0
Me.AlterTable_TableNameFld.Hint = ""
Me.AlterTable_TableNameFld.Location = New System.Drawing.Point(9, 19)
Me.AlterTable_TableNameFld.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_TableNameFld.Name = "AlterTable_TableNameFld"
Me.AlterTable_TableNameFld.PasswordChar = Global.Microsoft.VisualBasic.ChrW(0)
Me.AlterTable_TableNameFld.SelectedText = ""
Me.AlterTable_TableNameFld.SelectionLength = 0
Me.AlterTable_TableNameFld.SelectionStart = 0
Me.AlterTable_TableNameFld.Size = New System.Drawing.Size(418, 23)
Me.AlterTable_TableNameFld.TabIndex = 37
Me.AlterTable_TableNameFld.UseSystemPasswordChar = False
'
'AlterTable_ActionContainerPnl
'
Me.AlterTable_ActionContainerPnl.Controls.Add(Me.AlterTable_RenamePnl)
Me.AlterTable_ActionContainerPnl.Controls.Add(Me.AlterTable_DeleteColumnPnl)
Me.AlterTable_ActionContainerPnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.AlterTable_ActionContainerPnl.Location = New System.Drawing.Point(0, 122)
Me.AlterTable_ActionContainerPnl.Margin = New System.Windows.Forms.Padding(0)
Me.AlterTable_ActionContainerPnl.Name = "AlterTable_ActionContainerPnl"
Me.AlterTable_ActionContainerPnl.Size = New System.Drawing.Size(450, 61)
Me.AlterTable_ActionContainerPnl.TabIndex = 40
'
'AlterTable_RenamePnl
'
Me.AlterTable_RenamePnl.Controls.Add(Me.AlterTable_RenameLbl)
Me.AlterTable_RenamePnl.Controls.Add(Me.AlterTable_RenameConfirmBtn)
Me.AlterTable_RenamePnl.Controls.Add(Me.AlterTable_RenameFld)
Me.AlterTable_RenamePnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.AlterTable_RenamePnl.Location = New System.Drawing.Point(0, 0)
Me.AlterTable_RenamePnl.Name = "AlterTable_RenamePnl"
Me.AlterTable_RenamePnl.Size = New System.Drawing.Size(450, 61)
Me.AlterTable_RenamePnl.TabIndex = 6
Me.AlterTable_RenamePnl.Visible = False
'
'AlterTable_RenameLbl
'
Me.AlterTable_RenameLbl.AutoSize = True
Me.AlterTable_RenameLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.AlterTable_RenameLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.AlterTable_RenameLbl.Location = New System.Drawing.Point(13, 8)
Me.AlterTable_RenameLbl.Name = "AlterTable_RenameLbl"
Me.AlterTable_RenameLbl.Size = New System.Drawing.Size(101, 15)
Me.AlterTable_RenameLbl.TabIndex = 57
Me.AlterTable_RenameLbl.Text = "Rename Table"
'
'AlterTable_RenameConfirmBtn
'
Me.AlterTable_RenameConfirmBtn.Anchor = System.Windows.Forms.AnchorStyles.Right
Me.AlterTable_RenameConfirmBtn.AutoSize = True
Me.AlterTable_RenameConfirmBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.AlterTable_RenameConfirmBtn.BackColor = System.Drawing.Color.White
Me.AlterTable_RenameConfirmBtn.Depth = 0
Me.AlterTable_RenameConfirmBtn.ForeColor = System.Drawing.Color.Transparent
Me.AlterTable_RenameConfirmBtn.Location = New System.Drawing.Point(382, 26)
Me.AlterTable_RenameConfirmBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.AlterTable_RenameConfirmBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_RenameConfirmBtn.Name = "AlterTable_RenameConfirmBtn"
Me.AlterTable_RenameConfirmBtn.Primary = False
Me.AlterTable_RenameConfirmBtn.Size = New System.Drawing.Size(48, 36)
Me.AlterTable_RenameConfirmBtn.TabIndex = 39
Me.AlterTable_RenameConfirmBtn.Text = "Done"
Me.AlterTable_RenameConfirmBtn.UseVisualStyleBackColor = False
'
'AlterTable_RenameFld
'
Me.AlterTable_RenameFld.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.AlterTable_RenameFld.Depth = 0
Me.AlterTable_RenameFld.Hint = ""
Me.AlterTable_RenameFld.Location = New System.Drawing.Point(7, 33)
Me.AlterTable_RenameFld.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_RenameFld.Name = "AlterTable_RenameFld"
Me.AlterTable_RenameFld.PasswordChar = Global.Microsoft.VisualBasic.ChrW(0)
Me.AlterTable_RenameFld.SelectedText = ""
Me.AlterTable_RenameFld.SelectionLength = 0
Me.AlterTable_RenameFld.SelectionStart = 0
Me.AlterTable_RenameFld.Size = New System.Drawing.Size(364, 23)
Me.AlterTable_RenameFld.TabIndex = 38
Me.AlterTable_RenameFld.UseSystemPasswordChar = False
'
'AlterTable_DeleteColumnPnl
'
Me.AlterTable_DeleteColumnPnl.Controls.Add(Me.AlterTable_DeleteColumnLbl)
Me.AlterTable_DeleteColumnPnl.Controls.Add(Me.AlterTable_DeleteColumnFld)
Me.AlterTable_DeleteColumnPnl.Controls.Add(Me.AlterTable_DeleteColumnConfirmBtn)
Me.AlterTable_DeleteColumnPnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.AlterTable_DeleteColumnPnl.Location = New System.Drawing.Point(0, 0)
Me.AlterTable_DeleteColumnPnl.Name = "AlterTable_DeleteColumnPnl"
Me.AlterTable_DeleteColumnPnl.Size = New System.Drawing.Size(450, 61)
Me.AlterTable_DeleteColumnPnl.TabIndex = 5
Me.AlterTable_DeleteColumnPnl.Visible = False
'
'AlterTable_DeleteColumnLbl
'
Me.AlterTable_DeleteColumnLbl.AutoSize = True
Me.AlterTable_DeleteColumnLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.AlterTable_DeleteColumnLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.AlterTable_DeleteColumnLbl.Location = New System.Drawing.Point(12, 8)
Me.AlterTable_DeleteColumnLbl.Name = "AlterTable_DeleteColumnLbl"
Me.AlterTable_DeleteColumnLbl.Size = New System.Drawing.Size(102, 15)
Me.AlterTable_DeleteColumnLbl.TabIndex = 57
Me.AlterTable_DeleteColumnLbl.Text = "Delete Column"
'
'AlterTable_DeleteColumnFld
'
Me.AlterTable_DeleteColumnFld.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.AlterTable_DeleteColumnFld.Depth = 0
Me.AlterTable_DeleteColumnFld.Hint = ""
Me.AlterTable_DeleteColumnFld.Location = New System.Drawing.Point(15, 33)
Me.AlterTable_DeleteColumnFld.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_DeleteColumnFld.Name = "AlterTable_DeleteColumnFld"
Me.AlterTable_DeleteColumnFld.PasswordChar = Global.Microsoft.VisualBasic.ChrW(0)
Me.AlterTable_DeleteColumnFld.SelectedText = ""
Me.AlterTable_DeleteColumnFld.SelectionLength = 0
Me.AlterTable_DeleteColumnFld.SelectionStart = 0
Me.AlterTable_DeleteColumnFld.Size = New System.Drawing.Size(364, 23)
Me.AlterTable_DeleteColumnFld.TabIndex = 38
Me.AlterTable_DeleteColumnFld.UseSystemPasswordChar = False
'
'AlterTable_DeleteColumnConfirmBtn
'
Me.AlterTable_DeleteColumnConfirmBtn.Anchor = System.Windows.Forms.AnchorStyles.Right
Me.AlterTable_DeleteColumnConfirmBtn.AutoSize = True
Me.AlterTable_DeleteColumnConfirmBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.AlterTable_DeleteColumnConfirmBtn.BackColor = System.Drawing.Color.White
Me.AlterTable_DeleteColumnConfirmBtn.Depth = 0
Me.AlterTable_DeleteColumnConfirmBtn.Location = New System.Drawing.Point(395, 23)
Me.AlterTable_DeleteColumnConfirmBtn.Margin = New System.Windows.Forms.Padding(0)
Me.AlterTable_DeleteColumnConfirmBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_DeleteColumnConfirmBtn.Name = "AlterTable_DeleteColumnConfirmBtn"
Me.AlterTable_DeleteColumnConfirmBtn.Primary = False
Me.AlterTable_DeleteColumnConfirmBtn.Size = New System.Drawing.Size(48, 36)
Me.AlterTable_DeleteColumnConfirmBtn.TabIndex = 39
Me.AlterTable_DeleteColumnConfirmBtn.Text = "Done"
Me.AlterTable_DeleteColumnConfirmBtn.UseVisualStyleBackColor = False
'
'AlterTable_BtnTableLayout
'
Me.AlterTable_BtnTableLayout.ColumnCount = 4
Me.AlterTable_BtnTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.AlterTable_BtnTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.AlterTable_BtnTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.AlterTable_BtnTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.0!))
Me.AlterTable_BtnTableLayout.Controls.Add(Me.AlterTable_ModifyColumnBtn, 3, 0)
Me.AlterTable_BtnTableLayout.Controls.Add(Me.AlterTable_RenameBtn, 0, 0)
Me.AlterTable_BtnTableLayout.Controls.Add(Me.AlterTable_DeleteColumnBtn, 2, 0)
Me.AlterTable_BtnTableLayout.Controls.Add(Me.AlterTable_AddColumnBtn, 1, 0)
Me.AlterTable_BtnTableLayout.Dock = System.Windows.Forms.DockStyle.Fill
Me.AlterTable_BtnTableLayout.Location = New System.Drawing.Point(3, 64)
Me.AlterTable_BtnTableLayout.Name = "AlterTable_BtnTableLayout"
Me.AlterTable_BtnTableLayout.RowCount = 1
Me.AlterTable_BtnTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.AlterTable_BtnTableLayout.Size = New System.Drawing.Size(444, 55)
Me.AlterTable_BtnTableLayout.TabIndex = 6
'
'AlterTable_ModifyColumnBtn
'
Me.AlterTable_ModifyColumnBtn.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.AlterTable_ModifyColumnBtn.AutoSize = True
Me.AlterTable_ModifyColumnBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.AlterTable_ModifyColumnBtn.Depth = 0
Me.AlterTable_ModifyColumnBtn.Location = New System.Drawing.Point(337, 6)
Me.AlterTable_ModifyColumnBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.AlterTable_ModifyColumnBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_ModifyColumnBtn.Name = "AlterTable_ModifyColumnBtn"
Me.AlterTable_ModifyColumnBtn.Primary = False
Me.AlterTable_ModifyColumnBtn.Size = New System.Drawing.Size(103, 43)
Me.AlterTable_ModifyColumnBtn.TabIndex = 10
Me.AlterTable_ModifyColumnBtn.Text = "Modify Column"
Me.AlterTable_ModifyColumnBtn.UseVisualStyleBackColor = True
'
'AlterTable_RenameBtn
'
Me.AlterTable_RenameBtn.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.AlterTable_RenameBtn.AutoSize = True
Me.AlterTable_RenameBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.AlterTable_RenameBtn.Depth = 0
Me.AlterTable_RenameBtn.Location = New System.Drawing.Point(4, 6)
Me.AlterTable_RenameBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.AlterTable_RenameBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_RenameBtn.Name = "AlterTable_RenameBtn"
Me.AlterTable_RenameBtn.Primary = False
Me.AlterTable_RenameBtn.Size = New System.Drawing.Size(103, 43)
Me.AlterTable_RenameBtn.TabIndex = 7
Me.AlterTable_RenameBtn.Text = "Rename Table"
Me.AlterTable_RenameBtn.UseVisualStyleBackColor = True
'
'AlterTable_DeleteColumnBtn
'
Me.AlterTable_DeleteColumnBtn.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.AlterTable_DeleteColumnBtn.AutoSize = True
Me.AlterTable_DeleteColumnBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.AlterTable_DeleteColumnBtn.Depth = 0
Me.AlterTable_DeleteColumnBtn.Location = New System.Drawing.Point(226, 6)
Me.AlterTable_DeleteColumnBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.AlterTable_DeleteColumnBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_DeleteColumnBtn.Name = "AlterTable_DeleteColumnBtn"
Me.AlterTable_DeleteColumnBtn.Primary = False
Me.AlterTable_DeleteColumnBtn.Size = New System.Drawing.Size(103, 43)
Me.AlterTable_DeleteColumnBtn.TabIndex = 9
Me.AlterTable_DeleteColumnBtn.Text = "Delete Column"
Me.AlterTable_DeleteColumnBtn.UseVisualStyleBackColor = True
'
'AlterTable_AddColumnBtn
'
Me.AlterTable_AddColumnBtn.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.AlterTable_AddColumnBtn.AutoSize = True
Me.AlterTable_AddColumnBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.AlterTable_AddColumnBtn.Depth = 0
Me.AlterTable_AddColumnBtn.Location = New System.Drawing.Point(115, 6)
Me.AlterTable_AddColumnBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.AlterTable_AddColumnBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.AlterTable_AddColumnBtn.Name = "AlterTable_AddColumnBtn"
Me.AlterTable_AddColumnBtn.Primary = False
Me.AlterTable_AddColumnBtn.Size = New System.Drawing.Size(103, 43)
Me.AlterTable_AddColumnBtn.TabIndex = 8
Me.AlterTable_AddColumnBtn.Text = "Add Column"
Me.AlterTable_AddColumnBtn.UseVisualStyleBackColor = True
'
'InsertPage
'
Me.InsertPage.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.InsertPage.Controls.Add(Me.InsertTableLayout)
Me.InsertPage.Location = New System.Drawing.Point(4, 22)
Me.InsertPage.Name = "InsertPage"
Me.InsertPage.Padding = New System.Windows.Forms.Padding(3)
Me.InsertPage.Size = New System.Drawing.Size(456, 686)
Me.InsertPage.TabIndex = 4
Me.InsertPage.Text = "Insert"
'
'InsertTableLayout
'
Me.InsertTableLayout.ColumnCount = 1
Me.InsertTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.InsertTableLayout.Controls.Add(Me.Insert_TableNamePnl, 0, 0)
Me.InsertTableLayout.Controls.Add(Me.Insert_ConfirmPnl, 0, 9)
Me.InsertTableLayout.Controls.Add(Me.Insert_SpecifyColumnPnl, 0, 1)
Me.InsertTableLayout.Controls.Add(Me.Insert_DataItemsPnl, 0, 5)
Me.InsertTableLayout.Dock = System.Windows.Forms.DockStyle.Fill
Me.InsertTableLayout.Location = New System.Drawing.Point(3, 3)
Me.InsertTableLayout.Name = "InsertTableLayout"
Me.InsertTableLayout.RowCount = 11
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 15.4775!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.45225!))
Me.InsertTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.InsertTableLayout.Size = New System.Drawing.Size(450, 680)
Me.InsertTableLayout.TabIndex = 44
'
'Insert_TableNamePnl
'
Me.Insert_TableNamePnl.Controls.Add(Me.Insert_TableNameLbl)
Me.Insert_TableNamePnl.Controls.Add(Me.Insert_TableNameFld)
Me.Insert_TableNamePnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.Insert_TableNamePnl.Location = New System.Drawing.Point(3, 3)
Me.Insert_TableNamePnl.Name = "Insert_TableNamePnl"
Me.Insert_TableNamePnl.Size = New System.Drawing.Size(444, 51)
Me.Insert_TableNamePnl.TabIndex = 0
'
'Insert_TableNameLbl
'
Me.Insert_TableNameLbl.AutoSize = True
Me.Insert_TableNameLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.Insert_TableNameLbl.Location = New System.Drawing.Point(176, 5)
Me.Insert_TableNameLbl.Name = "Insert_TableNameLbl"
Me.Insert_TableNameLbl.Size = New System.Drawing.Size(93, 13)
Me.Insert_TableNameLbl.TabIndex = 41
Me.Insert_TableNameLbl.Text = "Enter Table Name"
'
'Insert_TableNameFld
'
Me.Insert_TableNameFld.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.Insert_TableNameFld.Depth = 0
Me.Insert_TableNameFld.Hint = ""
Me.Insert_TableNameFld.Location = New System.Drawing.Point(10, 21)
Me.Insert_TableNameFld.MouseState = MaterialSkin.MouseState.HOVER
Me.Insert_TableNameFld.Name = "Insert_TableNameFld"
Me.Insert_TableNameFld.PasswordChar = Global.Microsoft.VisualBasic.ChrW(0)
Me.Insert_TableNameFld.SelectedText = ""
Me.Insert_TableNameFld.SelectionLength = 0
Me.Insert_TableNameFld.SelectionStart = 0
Me.Insert_TableNameFld.Size = New System.Drawing.Size(418, 23)
Me.Insert_TableNameFld.TabIndex = 37
Me.Insert_TableNameFld.UseSystemPasswordChar = False
'
'Insert_ConfirmPnl
'
Me.Insert_ConfirmPnl.Controls.Add(Me.Insert_DataItemsConfirmBtn)
Me.Insert_ConfirmPnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.Insert_ConfirmPnl.Location = New System.Drawing.Point(3, 564)
Me.Insert_ConfirmPnl.Name = "Insert_ConfirmPnl"
Me.Insert_ConfirmPnl.Size = New System.Drawing.Size(444, 51)
Me.Insert_ConfirmPnl.TabIndex = 44
'
'Insert_DataItemsConfirmBtn
'
Me.Insert_DataItemsConfirmBtn.AutoSize = True
Me.Insert_DataItemsConfirmBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.Insert_DataItemsConfirmBtn.Depth = 0
Me.Insert_DataItemsConfirmBtn.Location = New System.Drawing.Point(9, 2)
Me.Insert_DataItemsConfirmBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.Insert_DataItemsConfirmBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.Insert_DataItemsConfirmBtn.Name = "Insert_DataItemsConfirmBtn"
Me.Insert_DataItemsConfirmBtn.Primary = False
Me.Insert_DataItemsConfirmBtn.Size = New System.Drawing.Size(48, 36)
Me.Insert_DataItemsConfirmBtn.TabIndex = 39
Me.Insert_DataItemsConfirmBtn.Text = "Done"
Me.Insert_DataItemsConfirmBtn.UseVisualStyleBackColor = True
'
'Insert_SpecifyColumnPnl
'
Me.Insert_SpecifyColumnPnl.Controls.Add(Me.Insert_Help)
Me.Insert_SpecifyColumnPnl.Controls.Add(Me.Insert_SpecifyColumnLbl)
Me.Insert_SpecifyColumnPnl.Controls.Add(Me.Insert_SpecifyColumnChkbx)
Me.Insert_SpecifyColumnPnl.Controls.Add(Me.Insert_SpecifyColumnFld)
Me.Insert_SpecifyColumnPnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.Insert_SpecifyColumnPnl.Location = New System.Drawing.Point(3, 60)
Me.Insert_SpecifyColumnPnl.Name = "Insert_SpecifyColumnPnl"
Me.InsertTableLayout.SetRowSpan(Me.Insert_SpecifyColumnPnl, 4)
Me.Insert_SpecifyColumnPnl.Size = New System.Drawing.Size(444, 270)
Me.Insert_SpecifyColumnPnl.TabIndex = 45
'
'Insert_SpecifyColumnLbl
'
Me.Insert_SpecifyColumnLbl.AutoSize = True
Me.Insert_SpecifyColumnLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Insert_SpecifyColumnLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.Insert_SpecifyColumnLbl.Location = New System.Drawing.Point(7, 13)
Me.Insert_SpecifyColumnLbl.Name = "Insert_SpecifyColumnLbl"
Me.Insert_SpecifyColumnLbl.Size = New System.Drawing.Size(113, 15)
Me.Insert_SpecifyColumnLbl.TabIndex = 56
Me.Insert_SpecifyColumnLbl.Text = "Specify Columns"
'
'Insert_SpecifyColumnChkbx
'
Me.Insert_SpecifyColumnChkbx.AutoSize = True
Me.Insert_SpecifyColumnChkbx.ForeColor = System.Drawing.SystemColors.WindowText
Me.Insert_SpecifyColumnChkbx.Location = New System.Drawing.Point(10, 40)
Me.Insert_SpecifyColumnChkbx.Name = "Insert_SpecifyColumnChkbx"
Me.Insert_SpecifyColumnChkbx.Size = New System.Drawing.Size(157, 17)
Me.Insert_SpecifyColumnChkbx.TabIndex = 55
Me.Insert_SpecifyColumnChkbx.Text = "Insert Into Specific Columns"
Me.Insert_SpecifyColumnChkbx.UseVisualStyleBackColor = True
'
'Insert_SpecifyColumnFld
'
Me.Insert_SpecifyColumnFld.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.Insert_SpecifyColumnFld.Enabled = False
Me.Insert_SpecifyColumnFld.Location = New System.Drawing.Point(10, 63)
Me.Insert_SpecifyColumnFld.Multiline = True
Me.Insert_SpecifyColumnFld.Name = "Insert_SpecifyColumnFld"
Me.Insert_SpecifyColumnFld.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.Insert_SpecifyColumnFld.Size = New System.Drawing.Size(425, 188)
Me.Insert_SpecifyColumnFld.TabIndex = 54
Me.Tip.SetToolTip(Me.Insert_SpecifyColumnFld, "Enter 1 Item Per Line")
Me.Insert_SpecifyColumnFld.WordWrap = False
'
'Insert_DataItemsPnl
'
Me.Insert_DataItemsPnl.Controls.Add(Me.Insert_DataItemsLbl)
Me.Insert_DataItemsPnl.Controls.Add(Me.Insert_DataItemsFld)
Me.Insert_DataItemsPnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.Insert_DataItemsPnl.Location = New System.Drawing.Point(3, 336)
Me.Insert_DataItemsPnl.Name = "Insert_DataItemsPnl"
Me.InsertTableLayout.SetRowSpan(Me.Insert_DataItemsPnl, 4)
Me.Insert_DataItemsPnl.Size = New System.Drawing.Size(444, 222)
Me.Insert_DataItemsPnl.TabIndex = 46
'
'Insert_DataItemsLbl
'
Me.Insert_DataItemsLbl.AutoSize = True
Me.Insert_DataItemsLbl.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Insert_DataItemsLbl.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.Insert_DataItemsLbl.Location = New System.Drawing.Point(7, 0)
Me.Insert_DataItemsLbl.Name = "Insert_DataItemsLbl"
Me.Insert_DataItemsLbl.Size = New System.Drawing.Size(76, 15)
Me.Insert_DataItemsLbl.TabIndex = 57
Me.Insert_DataItemsLbl.Text = "Data Items"
'
'Insert_DataItemsFld
'
Me.Insert_DataItemsFld.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.Insert_DataItemsFld.Location = New System.Drawing.Point(10, 22)
Me.Insert_DataItemsFld.Multiline = True
Me.Insert_DataItemsFld.Name = "Insert_DataItemsFld"
Me.Insert_DataItemsFld.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.Insert_DataItemsFld.Size = New System.Drawing.Size(425, 197)
Me.Insert_DataItemsFld.TabIndex = 54
Me.Tip.SetToolTip(Me.Insert_DataItemsFld, "Enter 1 Item Per Line")
Me.Insert_DataItemsFld.WordWrap = False
'
'DeleteTablePage
'
Me.DeleteTablePage.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.DeleteTablePage.Controls.Add(Me.DropTableLayout)
Me.DeleteTablePage.Location = New System.Drawing.Point(4, 22)
Me.DeleteTablePage.Name = "DeleteTablePage"
Me.DeleteTablePage.Padding = New System.Windows.Forms.Padding(3)
Me.DeleteTablePage.Size = New System.Drawing.Size(456, 686)
Me.DeleteTablePage.TabIndex = 5
Me.DeleteTablePage.Text = "Delete Table"
'
'DropTableLayout
'
Me.DropTableLayout.ColumnCount = 1
Me.DropTableLayout.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.DropTableLayout.Controls.Add(Me.Delete_TableNamePnl, 0, 0)
Me.DropTableLayout.Controls.Add(Me.Delete_ConfirmPnl, 0, 1)
Me.DropTableLayout.Dock = System.Windows.Forms.DockStyle.Fill
Me.DropTableLayout.Location = New System.Drawing.Point(3, 3)
Me.DropTableLayout.Name = "DropTableLayout"
Me.DropTableLayout.RowCount = 12
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8.333333!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.DropTableLayout.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.DropTableLayout.Size = New System.Drawing.Size(450, 680)
Me.DropTableLayout.TabIndex = 47
'
'Delete_TableNamePnl
'
Me.Delete_TableNamePnl.Controls.Add(Me.Delete_TableNamePnlLbl)
Me.Delete_TableNamePnl.Controls.Add(Me.Delete_TableNameFld)
Me.Delete_TableNamePnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.Delete_TableNamePnl.Location = New System.Drawing.Point(3, 3)
Me.Delete_TableNamePnl.Name = "Delete_TableNamePnl"
Me.Delete_TableNamePnl.Size = New System.Drawing.Size(444, 50)
Me.Delete_TableNamePnl.TabIndex = 0
'
'Delete_TableNamePnlLbl
'
Me.Delete_TableNamePnlLbl.AutoSize = True
Me.Delete_TableNamePnlLbl.ForeColor = System.Drawing.SystemColors.WindowText
Me.Delete_TableNamePnlLbl.Location = New System.Drawing.Point(176, 5)
Me.Delete_TableNamePnlLbl.Name = "Delete_TableNamePnlLbl"
Me.Delete_TableNamePnlLbl.Size = New System.Drawing.Size(93, 13)
Me.Delete_TableNamePnlLbl.TabIndex = 41
Me.Delete_TableNamePnlLbl.Text = "Enter Table Name"
'
'Delete_TableNameFld
'
Me.Delete_TableNameFld.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.Delete_TableNameFld.Depth = 0
Me.Delete_TableNameFld.Hint = ""
Me.Delete_TableNameFld.Location = New System.Drawing.Point(10, 21)
Me.Delete_TableNameFld.MouseState = MaterialSkin.MouseState.HOVER
Me.Delete_TableNameFld.Name = "Delete_TableNameFld"
Me.Delete_TableNameFld.PasswordChar = Global.Microsoft.VisualBasic.ChrW(0)
Me.Delete_TableNameFld.SelectedText = ""
Me.Delete_TableNameFld.SelectionLength = 0
Me.Delete_TableNameFld.SelectionStart = 0
Me.Delete_TableNameFld.Size = New System.Drawing.Size(418, 23)
Me.Delete_TableNameFld.TabIndex = 37
Me.Delete_TableNameFld.UseSystemPasswordChar = False
'
'Delete_ConfirmPnl
'
Me.Delete_ConfirmPnl.Controls.Add(Me.Delete_ConfirmBtn)
Me.Delete_ConfirmPnl.Dock = System.Windows.Forms.DockStyle.Fill
Me.Delete_ConfirmPnl.Location = New System.Drawing.Point(3, 59)
Me.Delete_ConfirmPnl.Name = "Delete_ConfirmPnl"
Me.Delete_ConfirmPnl.Size = New System.Drawing.Size(444, 50)
Me.Delete_ConfirmPnl.TabIndex = 44
'
'Delete_ConfirmBtn
'
Me.Delete_ConfirmBtn.AutoSize = True
Me.Delete_ConfirmBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.Delete_ConfirmBtn.BackColor = System.Drawing.Color.White
Me.Delete_ConfirmBtn.Depth = 0
Me.Delete_ConfirmBtn.Location = New System.Drawing.Point(10, 6)
Me.Delete_ConfirmBtn.Margin = New System.Windows.Forms.Padding(4, 6, 4, 6)
Me.Delete_ConfirmBtn.MouseState = MaterialSkin.MouseState.HOVER
Me.Delete_ConfirmBtn.Name = "Delete_ConfirmBtn"
Me.Delete_ConfirmBtn.Primary = False
Me.Delete_ConfirmBtn.Size = New System.Drawing.Size(105, 36)
Me.Delete_ConfirmBtn.TabIndex = 2
Me.Delete_ConfirmBtn.Text = "Delete Table"
Me.Delete_ConfirmBtn.UseVisualStyleBackColor = False
'
'MainTableLayoutPanel
'
Me.MainTableLayoutPanel.ColumnCount = 1
Me.Home_Main_Layout.SetColumnSpan(Me.MainTableLayoutPanel, 6)
Me.MainTableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.MainTableLayoutPanel.Controls.Add(Me.ScriptGrp, 0, 0)
Me.MainTableLayoutPanel.Controls.Add(Me.ToolStrip, 0, 1)
Me.MainTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.MainTableLayoutPanel.Location = New System.Drawing.Point(467, 3)
Me.MainTableLayoutPanel.Name = "MainTableLayoutPanel"
Me.MainTableLayoutPanel.RowCount = 2
Me.Home_Main_Layout.SetRowSpan(Me.MainTableLayoutPanel, 10)
Me.MainTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.MainTableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30.0!))
Me.MainTableLayoutPanel.Size = New System.Drawing.Size(694, 706)
Me.MainTableLayoutPanel.TabIndex = 7
'
'ScriptGrp
'
Me.ScriptGrp.Controls.Add(Me.Sequence)
Me.ScriptGrp.Dock = System.Windows.Forms.DockStyle.Fill
Me.ScriptGrp.Location = New System.Drawing.Point(0, 0)
Me.ScriptGrp.Margin = New System.Windows.Forms.Padding(0)
Me.ScriptGrp.Name = "ScriptGrp"
Me.ScriptGrp.Size = New System.Drawing.Size(694, 676)
Me.ScriptGrp.TabIndex = 7
Me.ScriptGrp.TabStop = False
Me.ScriptGrp.Text = "Script"
'
'Sequence
'
Me.Sequence.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Sequence.Dock = System.Windows.Forms.DockStyle.Fill
Me.Sequence.Font = New System.Drawing.Font("Lucida Console", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Sequence.FormattingEnabled = True
Me.Sequence.HorizontalScrollbar = True
Me.Sequence.Location = New System.Drawing.Point(3, 16)
Me.Sequence.Name = "Sequence"
Me.Sequence.ScrollAlwaysVisible = True
Me.Sequence.SelectionMode = System.Windows.Forms.SelectionMode.None
Me.Sequence.Size = New System.Drawing.Size(688, 657)
Me.Sequence.TabIndex = 0
Me.Tip.SetToolTip(Me.Sequence, "Clear Script")
'
'ToolStrip
'
Me.ToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden
Me.ToolStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStrip_Line, Me.ToolStripSeparator1, Me.ToolStrip_FontSize})
Me.ToolStrip.Location = New System.Drawing.Point(0, 676)
Me.ToolStrip.Name = "ToolStrip"
Me.ToolStrip.Size = New System.Drawing.Size(694, 25)
Me.ToolStrip.TabIndex = 8
Me.ToolStrip.Text = "ToolStrip1"
'
'ToolStrip_Line
'
Me.ToolStrip_Line.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right
Me.ToolStrip_Line.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.ToolStrip_Line.Name = "ToolStrip_Line"
Me.ToolStrip_Line.Size = New System.Drawing.Size(43, 22)
Me.ToolStrip_Line.Text = "0 Lines"
'
'ToolStripSeparator1
'
Me.ToolStripSeparator1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right
Me.ToolStripSeparator1.Name = "ToolStripSeparator1"
Me.ToolStripSeparator1.Size = New System.Drawing.Size(6, 25)
'
'ToolStrip_FontSize
'
Me.ToolStrip_FontSize.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right
Me.ToolStrip_FontSize.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.ToolStrip_FontSize.Name = "ToolStrip_FontSize"
Me.ToolStrip_FontSize.Size = New System.Drawing.Size(108, 22)
Me.ToolStrip_FontSize.Text = "Sequence.Font.Size"
Me.ToolStrip_FontSize.TextAlign = System.Drawing.ContentAlignment.MiddleRight
Me.ToolStrip_FontSize.ToolTipText = "Click to reset font size."
'
'MaterialTabSelector
'
Me.MaterialTabSelector.BaseTabControl = Me.MaterialTabControl
Me.MaterialTabSelector.Cursor = System.Windows.Forms.Cursors.Hand
Me.MaterialTabSelector.Depth = 0
Me.MaterialTabSelector.Location = New System.Drawing.Point(181, 25)
Me.MaterialTabSelector.MouseState = MaterialSkin.MouseState.HOVER
Me.MaterialTabSelector.Name = "MaterialTabSelector"
Me.MaterialTabSelector.Size = New System.Drawing.Size(906, 39)
Me.MaterialTabSelector.TabIndex = 2
Me.MaterialTabSelector.Text = "MaterialTabSelector1"
'
'Insert_Help
'
Me.Insert_Help.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.Insert_Help.BackColor = System.Drawing.Color.Transparent
Me.Insert_Help.Cursor = System.Windows.Forms.Cursors.Help
Me.Insert_Help.Image = CType(resources.GetObject("Insert_Help.Image"), System.Drawing.Image)
Me.Insert_Help.Location = New System.Drawing.Point(396, 13)
Me.Insert_Help.Name = "Insert_Help"
Me.Insert_Help.Size = New System.Drawing.Size(39, 34)
Me.Insert_Help.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.Insert_Help.TabIndex = 57
Me.Insert_Help.TabStop = False
Me.Tip.SetToolTip(Me.Insert_Help, "Enter 1 Item Per Line" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Separate each items by changing lines, for example:" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Ite" &
"m 1" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Item 2" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Item 3" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Field autodetects numeric values." & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10))
'
'FieldDetails_CheckHelp
'
Me.FieldDetails_CheckHelp.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.FieldDetails_CheckHelp.BackColor = System.Drawing.Color.Transparent
Me.FieldDetails_CheckHelp.Cursor = System.Windows.Forms.Cursors.Help
Me.FieldDetails_CheckHelp.Image = CType(resources.GetObject("FieldDetails_CheckHelp.Image"), System.Drawing.Image)
Me.FieldDetails_CheckHelp.Location = New System.Drawing.Point(401, 20)
Me.FieldDetails_CheckHelp.Name = "FieldDetails_CheckHelp"
Me.FieldDetails_CheckHelp.Size = New System.Drawing.Size(39, 34)
Me.FieldDetails_CheckHelp.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.FieldDetails_CheckHelp.TabIndex = 71
Me.FieldDetails_CheckHelp.TabStop = False
Me.Tip.SetToolTip(Me.FieldDetails_CheckHelp, "Enter 1 Item Per Line" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Separate each items by changing lines, for example:" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Ite" &
"m 1" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Item 2" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Item 3" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Field autodetects numeric values.")
'
'Home
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.ClientSize = New System.Drawing.Size(1164, 765)
Me.Controls.Add(Me.MaterialTabSelector)
Me.Controls.Add(Me.Home_Main_Layout)
Me.ForeColor = System.Drawing.SystemColors.Control
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Margin = New System.Windows.Forms.Padding(2, 3, 2, 3)
Me.Name = "Home"
Me.Text = "SQL Script Generator"
Me.Home_Main_Layout.ResumeLayout(False)
Me.TabContainerPanel.ResumeLayout(False)
Me.MaterialTabControl.ResumeLayout(False)
Me.HomePage.ResumeLayout(False)
Me.Home_MngScriptGrp.ResumeLayout(False)
Me.Home_MngScriptGrp.PerformLayout()
Me.Home_MngScriptTableLayout.ResumeLayout(False)
CType(Me.Home_ScriptCopyBtn, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.Home_ScriptNewBtn, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.Home_ScriptBrkBtn, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.Home_ScriptUndoBtn, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.Home_ScriptIncTxtBtn, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.Home_ScriptDecTxtBtn, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.Home_ScriptExprtBtn, System.ComponentModel.ISupportInitialize).EndInit()
Me.Home_InfoTableLayout.ResumeLayout(False)
CType(Me.Home_FeedbackBtn, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.Home_InfoBtn, System.ComponentModel.ISupportInitialize).EndInit()
Me.DatabasePage.ResumeLayout(False)
Me.DatabaseTableLayout.ResumeLayout(False)
Me.Database_NameGrp.ResumeLayout(False)
Me.Database_NameGrp.PerformLayout()
Me.Database_ButtonTableLayout.ResumeLayout(False)
Me.Database_ButtonTableLayout.PerformLayout()
Me.CreateTablePage.ResumeLayout(False)
Me.CreateActionLayout.ResumeLayout(False)
Me.CreateTable_NameGrp.ResumeLayout(False)
Me.CreateTable_NameGrp.PerformLayout()
Me.FieldDetails.ResumeLayout(False)
Me.CreateTable_ActionDetailContainerPnl.ResumeLayout(False)
Me.FieldGroup.ResumeLayout(False)
Me.FieldGroup.PerformLayout()
CType(Me.FieldDetails_Precision, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.FieldDetails_Size, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.FieldDetails_Scale, System.ComponentModel.ISupportInitialize).EndInit()
Me.FieldDetails_ForeignKeyGrp.ResumeLayout(False)
Me.FieldDetails_ForeignKeyGrp.PerformLayout()
Me.FieldDetails_PrimyGrp.ResumeLayout(False)
Me.FieldDetails_PrimyGrp.PerformLayout()
Me.CreateTable_ActionDetailContainerPnl2.ResumeLayout(False)
Me.CreateTable_ActionDetailContainerPnl2.PerformLayout()
Me.FieldDetails_CheckGrp.ResumeLayout(False)
Me.FieldDetails_CheckGrp.PerformLayout()
Me.FieldDetails_RefConsTableLayout.ResumeLayout(False)
Me.FieldDetails_ReferenceGrp.ResumeLayout(False)
Me.FieldDetails_ReferenceGrp.PerformLayout()
Me.FieldDetails_ConstraintGrp.ResumeLayout(False)
Me.FieldDetails_ConstraintGrp.PerformLayout()
Me.CreateTable_BtbTableLayout.ResumeLayout(False)
Me.CreateTable_BtbTableLayout.PerformLayout()
Me.AlterTablePage.ResumeLayout(False)
Me.AlterTableLayoutPanel.ResumeLayout(False)
Me.AlterTable_TableNamePnl.ResumeLayout(False)
Me.AlterTable_TableNamePnl.PerformLayout()
Me.AlterTable_ActionContainerPnl.ResumeLayout(False)
Me.AlterTable_RenamePnl.ResumeLayout(False)
Me.AlterTable_RenamePnl.PerformLayout()
Me.AlterTable_DeleteColumnPnl.ResumeLayout(False)
Me.AlterTable_DeleteColumnPnl.PerformLayout()
Me.AlterTable_BtnTableLayout.ResumeLayout(False)
Me.AlterTable_BtnTableLayout.PerformLayout()
Me.InsertPage.ResumeLayout(False)
Me.InsertTableLayout.ResumeLayout(False)
Me.Insert_TableNamePnl.ResumeLayout(False)
Me.Insert_TableNamePnl.PerformLayout()
Me.Insert_ConfirmPnl.ResumeLayout(False)
Me.Insert_ConfirmPnl.PerformLayout()
Me.Insert_SpecifyColumnPnl.ResumeLayout(False)
Me.Insert_SpecifyColumnPnl.PerformLayout()
Me.Insert_DataItemsPnl.ResumeLayout(False)
Me.Insert_DataItemsPnl.PerformLayout()
Me.DeleteTablePage.ResumeLayout(False)
Me.DropTableLayout.ResumeLayout(False)
Me.Delete_TableNamePnl.ResumeLayout(False)
Me.Delete_TableNamePnl.PerformLayout()
Me.Delete_ConfirmPnl.ResumeLayout(False)
Me.Delete_ConfirmPnl.PerformLayout()
Me.MainTableLayoutPanel.ResumeLayout(False)
Me.MainTableLayoutPanel.PerformLayout()
Me.ScriptGrp.ResumeLayout(False)
Me.ToolStrip.ResumeLayout(False)
Me.ToolStrip.PerformLayout()
CType(Me.Insert_Help, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.FieldDetails_CheckHelp, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Home_Main_Layout As TableLayoutPanel
Friend WithEvents Tip As ToolTip
Friend WithEvents Home_MngScriptTableLayout As TableLayoutPanel
Friend WithEvents Home_ScriptBrkBtn As PictureBox
Friend WithEvents Home_ScriptUndoBtn As PictureBox
Friend WithEvents Home_ScriptIncTxtBtn As PictureBox
Friend WithEvents Home_ScriptDecTxtBtn As PictureBox
Friend WithEvents Home_ScriptExprtBtn As PictureBox
Friend WithEvents CreateActionLayout As TableLayoutPanel
Friend WithEvents CreateTable_NameGrp As Panel
Friend WithEvents CreateTable_NameLbl As Label
Friend WithEvents CreateTable_CreateBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents CreateTable_NameFld As MaterialSkin.Controls.MaterialSingleLineTextField
Friend WithEvents FieldDetails As Panel
Friend WithEvents CreateTable_ActionDetailContainerPnl2 As Panel
Friend WithEvents FieldDetails_RefConsTableLayout As TableLayoutPanel
Friend WithEvents FieldDetails_ForeignChkbx As CheckBox
Friend WithEvents FieldDetails_UniqueChkbx As CheckBox
Friend WithEvents FieldDetails_NotNullChkbx As CheckBox
Friend WithEvents FieldDetails_PrimChkbx As CheckBox
Friend WithEvents FieldDetails_OnDeleteCmbo As ComboBox
Friend WithEvents FieldDetails_OnUpdateCmbo As ComboBox
Friend WithEvents FieldDetails_OnDeleteChkbx As CheckBox
Friend WithEvents FieldDetails_OnUpdateChkBx As CheckBox
Friend WithEvents FieldDetails_ReferenceChkBx As CheckBox
Friend WithEvents FieldDetails_ReferenceFld As TextBox
Friend WithEvents FieldDetails_CreateFieldBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents FieldDetails_CheckChkbx As CheckBox
Friend WithEvents FieldDetails_CheckTypeCmbo As ComboBox
Friend WithEvents FieldDetails_CheckTypeLbl As Label
Friend WithEvents FieldDetails_CheckFld As TextBox
Friend WithEvents FieldDetails_CheckPstnCmbo As ComboBox
Friend WithEvents FieldDetails_StringPstnLbl As Label
Friend WithEvents CreateTable_BtbTableLayout As TableLayoutPanel
Friend WithEvents CreateTable_AddForeignKeyBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents CreateTable_AddPrimKeyBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents CreateTable_CompleteTableBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents CreateTable_AddColumnBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents AlterTableLayoutPanel As TableLayoutPanel
Friend WithEvents AlterTable_TableNamePnl As Panel
Friend WithEvents AlterTable_TableNamaLbl As Label
Friend WithEvents AlterTable_TableNameFld As MaterialSkin.Controls.MaterialSingleLineTextField
Friend WithEvents AlterTable_DeleteColumnPnl As Panel
Friend WithEvents AlterTable_DeleteColumnFld As MaterialSkin.Controls.MaterialSingleLineTextField
Friend WithEvents AlterTable_DeleteColumnConfirmBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents AlterTable_RenameConfirmBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents AlterTable_RenameFld As MaterialSkin.Controls.MaterialSingleLineTextField
Friend WithEvents AlterTable_BtnTableLayout As TableLayoutPanel
Friend WithEvents AlterTable_ModifyColumnBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents AlterTable_RenameBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents AlterTable_DeleteColumnBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents AlterTable_AddColumnBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents DropTableLayout As TableLayoutPanel
Friend WithEvents Delete_TableNamePnl As Panel
Friend WithEvents Delete_TableNamePnlLbl As Label
Friend WithEvents Delete_TableNameFld As MaterialSkin.Controls.MaterialSingleLineTextField
Friend WithEvents Delete_ConfirmPnl As Panel
Friend WithEvents Delete_ConfirmBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents DatabaseTableLayout As TableLayoutPanel
Friend WithEvents Database_NameGrp As Panel
Friend WithEvents Database_NameLbl As Label
Friend WithEvents Database_NameFld As MaterialSkin.Controls.MaterialSingleLineTextField
Friend WithEvents Database_ButtonTableLayout As TableLayoutPanel
Friend WithEvents Database_SelectBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents Database_CreateBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents Database_DeleteBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents InsertTableLayout As TableLayoutPanel
Friend WithEvents Insert_DataItemsFld As TextBox
Friend WithEvents Insert_SpecifyColumnChkbx As CheckBox
Friend WithEvents Insert_SpecifyColumnFld As TextBox
Friend WithEvents Insert_TableNamePnl As Panel
Friend WithEvents Insert_TableNameLbl As Label
Friend WithEvents Insert_TableNameFld As MaterialSkin.Controls.MaterialSingleLineTextField
Friend WithEvents Insert_ConfirmPnl As Panel
Friend WithEvents Insert_DataItemsConfirmBtn As MaterialSkin.Controls.MaterialFlatButton
Friend WithEvents MainTableLayoutPanel As TableLayoutPanel
Friend WithEvents ScriptGrp As GroupBox
Friend WithEvents ToolStrip As ToolStrip
Friend WithEvents ToolStrip_Line As ToolStripLabel
Friend WithEvents ToolStripSeparator1 As ToolStripSeparator
Friend WithEvents ToolStrip_FontSize As ToolStripLabel
Friend WithEvents SaveFileDialog As SaveFileDialog
Friend WithEvents MaterialTabControl As MaterialSkin.Controls.MaterialTabControl
Friend WithEvents HomePage As TabPage
Friend WithEvents DatabasePage As TabPage
Friend WithEvents MaterialTabSelector As MaterialSkin.Controls.MaterialTabSelector
Friend WithEvents CreateTablePage As TabPage
Friend WithEvents AlterTablePage As TabPage
Friend WithEvents InsertPage As TabPage
Friend WithEvents DeleteTablePage As TabPage
Friend WithEvents TabContainerPanel As Panel
Friend WithEvents Home_InfoTableLayout As TableLayoutPanel
Friend WithEvents Home_InfoBtn As PictureBox
Friend WithEvents Home_ScriptNewBtn As PictureBox
Friend WithEvents Home_MngScriptLlb As Label
Friend WithEvents Home_MngScriptGrp As Panel
Friend WithEvents Insert_SpecifyColumnPnl As Panel
Friend WithEvents Insert_SpecifyColumnLbl As Label
Friend WithEvents Insert_DataItemsPnl As Panel
Friend WithEvents Insert_DataItemsLbl As Label
Friend WithEvents AlterTable_RenamePnl As Panel
Friend WithEvents AlterTable_RenameLbl As Label
Friend WithEvents AlterTable_DeleteColumnLbl As Label
Friend WithEvents AlterTable_ActionContainerPnl As Panel
Friend WithEvents FieldDetails_ReferenceGrp As Panel
Friend WithEvents FieldDetails_ReferentialLbl As Label
Friend WithEvents FieldDetails_ConstraintGrp As Panel
Friend WithEvents FieldDetails_ConstraintsLbl As Label
Friend WithEvents FieldDetails_CheckGrp As Panel
Friend WithEvents FieldDetails_CheckLbl As Label
Friend WithEvents CreateTable_ActionDetailContainerPnl As Panel
Friend WithEvents FieldGroup As Panel
Friend WithEvents FieldDetails_ColumnLbl As Label
Friend WithEvents FieldDetails_FormulaChkbx As CheckBox
Friend WithEvents FieldDetails_ColumnTYpeCmbo As ComboBox
Friend WithEvents FieldDetails_DefFld As TextBox
Friend WithEvents FieldDetails_ColumnNameLbl As Label
Friend WithEvents FieldDetails_DefValChkbx As CheckBox
Friend WithEvents FieldDetails_ColumnNameFld As MaterialSkin.Controls.MaterialSingleLineTextField
Friend WithEvents FieldDetails_Precision As NumericUpDown
Friend WithEvents FieldDetails_PreScleLbl As Label
Friend WithEvents FieldDetails_SizeLbl As Label
Friend WithEvents FieldDetails_TypeLbl As Label
Friend WithEvents FieldDetails_Size As NumericUpDown
Friend WithEvents FieldDetails_Scale As NumericUpDown
Friend WithEvents FieldDetails_ForeignKeyGrp As Panel
Friend WithEvents FieldDetails_ForeignKeyLbl As Label
Friend WithEvents FieldDetails_ForeignKeyFld As TextBox
Friend WithEvents FieldDetails_PrimyGrp As Panel
Friend WithEvents FieldDetails_PrimLbl As Label
Friend WithEvents FieldDetails_PrimFld As TextBox
Friend WithEvents Sequence As ListBox
Friend WithEvents Home_FeedbackBtn As PictureBox
Friend WithEvents Home_ScriptCopyBtn As PictureBox
Friend WithEvents Insert_Help As PictureBox
Friend WithEvents FieldDetails_CheckHelp As PictureBox
End Class
|
arwinneil/Why-Write-SQL
|
SQL Generator/Home.Designer.vb
|
Visual Basic
|
mit
| 147,553
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.296
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.hangman.My.MySettings
Get
Return Global.hangman.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
LeeSkiBee/LeeSkiBee-School-Hangman-Game
|
My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,918
|
Public Class Doktor_Forma
Private Sub Doktor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'IbolnicaDataSet.odjeljenje' table. You can move, or remove it, as needed.
Me.OdjeljenjeTableAdapter.Fill(Me.IbolnicaDataSet.odjeljenje)
'TODO: This line of code loads data into the 'IbolnicaDataSet.doktor' table. You can move, or remove it, as needed.
Me.DoktorTableAdapter.Fill(Me.IbolnicaDataSet.doktor)
End Sub
Private Sub BtnNoviDoktor_Click(sender As Object, e As EventArgs) Handles BtnNoviDoktor.Click
Try
Me.DoktorBindingSource.AddNew()
Catch ex As Exception
MsgBox("Morate unijeti sva polja")
End Try
End Sub
Private Sub BtnDodajDoktora_Click(sender As Object, e As EventArgs) Handles BtnDodajDoktora.Click
Me.Validate()
Me.DoktorBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.IbolnicaDataSet)
End Sub
Private Sub BtnUredi_Click(sender As Object, e As EventArgs) Handles BtnUredi.Click
Me.Validate()
Me.DoktorBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.IbolnicaDataSet)
End Sub
Private Sub BtnIzbrisi_Click(sender As Object, e As EventArgs) Handles BtnIzbrisi.Click
Try
Me.DoktorBindingSource.RemoveCurrent()
Me.TableAdapterManager.UpdateAll(Me.IbolnicaDataSet)
Catch ex As Exception
MsgBox("Morate selektovati sva polja")
End Try
End Sub
Private Sub BtnZatvori_Click(sender As Object, e As EventArgs) Handles BtnZatvori.Click
Me.Close()
End Sub
End Class
|
error505/iHospital
|
iBolnica/Doktor.vb
|
Visual Basic
|
mit
| 1,697
|
Public Class FormSistemaHospital
Private Sub btnAdministrarPersonal_Click(sender As Object, e As EventArgs) Handles btnAdministrarPersonal.Click
formAdministrarPersonal.Show()
End Sub
Private Sub btnAdministrarPacientes_Click(sender As Object, e As EventArgs) Handles btnAdminstrarPacientes.Click
tb_direccion.Show()
End Sub
Private Sub btnAdminitrarDepartamentos_Click(sender As Object, e As EventArgs) Handles btnAdminitrarDepartamentos.Click
FormAdministrarDepartamentos.Show()
End Sub
Private Sub btnAdminstrarcamillas_Click(sender As Object, e As EventArgs) Handles btnAdministrarCamillas.Click
FormAdministrarCamillas.Show()
End Sub
Private Sub btnDiagnostico_Click(sender As Object, e As EventArgs) Handles btnDiagnostico.Click
FormDiagnostico.Show()
End Sub
Private Sub btnFormasPago_Click(sender As Object, e As EventArgs) Handles btnFormasPago.Click
FormFormadePago.Show()
End Sub
Private Sub btnSalir_Click(sender As Object, e As EventArgs) Handles btnSalir.Click
Me.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Login.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FormContactoAdmin.Show()
End Sub
End Class
|
Canterini/tsiHospital
|
WindowsApplication2/FormSistemaHospital.vb
|
Visual Basic
|
mit
| 1,384
|
Partial Class Partner_ViewWebsites
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
txtCID.Text = Session("pid")
End If
End Sub
End Class
|
aminnagpure/matrimonydatingcommunity1.0
|
lovenmarry - EmptyFreeCode/Partner/ViewWebsites.aspx.vb
|
Visual Basic
|
mit
| 278
|
Namespace YahooManaged.Finance.Screener.StockCriterias
''' <summary>
''' Criteria class for average daily volume
''' </summary>
''' <remarks></remarks>
Public Class AverageDailyVolumeCriteria
Inherits StockDigitCriteriaDefinition
Public Overrides ReadOnly Property DisplayName As String
Get
Return "Average Daily Volume Criteria"
End Get
End Property
Public Overrides ReadOnly Property CriteriaName As String
Get
Return "Average Daily Volume"
End Get
End Property
Public Overrides ReadOnly Property CriteriaGroup As StockScreenerCriteriaGroup
Get
Return StockScreenerCriteriaGroup.TradingAndVolume
End Get
End Property
Public Overrides ReadOnly Property ProvidedQuoteProperties As QuoteProperty()
Get
Return {QuoteProperty.Symbol, _
QuoteProperty.Name, _
QuoteProperty.LastTradePriceOnly, _
QuoteProperty.LastTradeTime, _
QuoteProperty.MarketCapitalization}
End Get
End Property
Public Overrides ReadOnly Property ProvidedScreenerProperties As StockScreenerProperty()
Get
Return {StockScreenerProperty.ReturnOnEquity, _
StockScreenerProperty.ReturnOnAssets, _
StockScreenerProperty.ForwardPriceToEarningsRatio}
End Get
End Property
Public Sub New()
MyBase.New("u"c)
End Sub
End Class
''' <summary>
''' Criteria class for volume
''' </summary>
''' <remarks></remarks>
Public Class VolumeCriteria
Inherits StockDigitCriteriaDefinition
Public Overrides ReadOnly Property DisplayName As String
Get
Return "Volume Criteria"
End Get
End Property
Public Overrides ReadOnly Property CriteriaName As String
Get
Return "Volume"
End Get
End Property
Public Overrides ReadOnly Property CriteriaGroup As StockScreenerCriteriaGroup
Get
Return StockScreenerCriteriaGroup.TradingAndVolume
End Get
End Property
Public Overrides ReadOnly Property ProvidedQuoteProperties As QuoteProperty()
Get
Return {QuoteProperty.Symbol, _
QuoteProperty.Name, _
QuoteProperty.LastTradePriceOnly, _
QuoteProperty.LastTradeTime, _
QuoteProperty.MarketCapitalization}
End Get
End Property
Public Overrides ReadOnly Property ProvidedScreenerProperties As StockScreenerProperty()
Get
Return {StockScreenerProperty.ReturnOnEquity, _
StockScreenerProperty.ReturnOnAssets, _
StockScreenerProperty.ForwardPriceToEarningsRatio}
End Get
End Property
Public Sub New()
MyBase.New("d"c)
End Sub
End Class
''' <summary>
''' Criteria class for Beta value
''' </summary>
''' <remarks></remarks>
Public Class BetaCriteria
Inherits StockDigitCriteriaDefinition
Public Overrides ReadOnly Property DisplayName As String
Get
Return "Beta Criteria"
End Get
End Property
Public Overrides ReadOnly Property CriteriaName As String
Get
Return "Beta"
End Get
End Property
Public Overrides ReadOnly Property CriteriaGroup As StockScreenerCriteriaGroup
Get
Return StockScreenerCriteriaGroup.TradingAndVolume
End Get
End Property
Public Overrides ReadOnly Property ProvidedQuoteProperties As QuoteProperty()
Get
Return {QuoteProperty.Symbol, _
QuoteProperty.Name, _
QuoteProperty.LastTradePriceOnly, _
QuoteProperty.LastTradeTime, _
QuoteProperty.MarketCapitalization}
End Get
End Property
Public Overrides ReadOnly Property ProvidedScreenerProperties As StockScreenerProperty()
Get
Return {StockScreenerProperty.ReturnOnEquity, _
StockScreenerProperty.ReturnOnAssets, _
StockScreenerProperty.ForwardPriceToEarningsRatio, _
StockScreenerProperty.Beta}
End Get
End Property
Public Sub New()
MyBase.New("7"c)
End Sub
End Class
End Namespace
|
agassan/YahooManaged
|
MaasOne.YahooManaged/YahooManaged/Finance/Screener/StockScreenerCriterias/TradingAndVolumeCriterias.vb
|
Visual Basic
|
apache-2.0
| 4,875
|
' 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.MakeMethodSynchronous
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.MakeMethodSynchronous
Public Class MakeMethodSynchronousTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New VisualBasicMakeMethodSynchronousCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestTaskReturnType() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks
Class C
Async Function [|Goo|]() As Task
End Function
End Class",
"Imports System.Threading.Tasks
Class C
Sub Goo()
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestTaskOfTReturnType() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks
Class C
Async Function [|Goo|]() As Task(of String)
End Function
End Class",
"Imports System.Threading.Tasks
Class C
Function Goo() As String
End Function
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestSecondModifier() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks
Class C
Public Async Function [|Goo|]() As Task
End Function
End Class",
"Imports System.Threading.Tasks
Class C
Public Sub Goo()
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestFirstModifier() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks
Class C
Async Public Function [|Goo|]() As Task
End Function
End Class",
"Imports System.Threading.Tasks
Class C
Public Sub Goo()
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestRenameMethod() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks
Class C
Async Sub [|GooAsync|]()
End Sub
End Class",
"Imports System.Threading.Tasks
Class C
Sub Goo()
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestRenameMethod1() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks
Class C
Async Sub [|GooAsync|]()
End Sub
Sub Bar()
GooAsync()
End Sub
End Class",
"Imports System.Threading.Tasks
Class C
Sub Goo()
End Sub
Sub Bar()
Goo()
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestSingleLineSubLambda() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Threading.Tasks
Class C
Sub Goo()
dim f as Action(of Task) =
Async [|Sub|]() Return
End Sub
End Class",
"Imports System
Imports System.Threading.Tasks
Class C
Sub Goo()
dim f as Action(of Task) =
Sub() Return
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestSingleLineFunctionLambda() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Threading.Tasks
Class C
Sub Goo()
dim f as Func(of Task) =
Async [|Function|]() 1
End Sub
End Class",
"Imports System
Imports System.Threading.Tasks
Class C
Sub Goo()
dim f as Func(of Task) =
Function() 1
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestMultiLineSubLambda() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Threading.Tasks
Class C
Sub Goo()
dim f as Action(of Task) =
Async [|Sub|]()
Return
End Sub
End Sub
End Class",
"Imports System
Imports System.Threading.Tasks
Class C
Sub Goo()
dim f as Action(of Task) =
Sub()
Return
End Sub
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
Public Async Function TestMultiLineFunctionLambda() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Threading.Tasks
Class C
Sub Goo()
dim f as Func(of Task) =
Async [|Function|]()
Return 1
End Function
End Sub
End Class",
"Imports System
Imports System.Threading.Tasks
Class C
Sub Goo()
dim f as Func(of Task) =
Function()
Return 1
End Function
End Sub
End Class",
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
<WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")>
Public Async Function TestRemoveAwaitFromCaller1() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks;
Public Class Class1
Async Function [|GooAsync|]() As Task
End Function
Async Sub BarAsync()
Await GooAsync()
End Sub
End Class",
"Imports System.Threading.Tasks;
Public Class Class1
Sub Goo()
End Sub
Async Sub BarAsync()
Goo()
End Sub
End Class", ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
<WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")>
Public Async Function TestRemoveAwaitFromCaller2() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks;
Public Class Class1
Async Function [|GooAsync|]() As Task
End Function
Async Sub BarAsync()
Await GooAsync().ConfigureAwait(false)
End Sub
End Class",
"Imports System.Threading.Tasks;
Public Class Class1
Sub Goo()
End Sub
Async Sub BarAsync()
Goo()
End Sub
End Class", ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
<WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")>
Public Async Function TestRemoveAwaitFromCaller3() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks;
Public Class Class1
Async Function [|GooAsync|]() As Task
End Function
Async Sub BarAsync()
Await Me.GooAsync()
End Sub
End Class",
"Imports System.Threading.Tasks;
Public Class Class1
Sub Goo()
End Sub
Async Sub BarAsync()
Me.Goo()
End Sub
End Class", ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
<WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")>
Public Async Function TestRemoveAwaitFromCaller4() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks;
Public Class Class1
Async Function [|GooAsync|]() As Task
End Function
Async Sub BarAsync()
Await Me.GooAsync().ConfigureAwait(false)
End Sub
End Class",
"Imports System.Threading.Tasks;
Public Class Class1
Sub Goo()
End Sub
Async Sub BarAsync()
Me.Goo()
End Sub
End Class", ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
<WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")>
Public Async Function TestRemoveAwaitFromCallerNested1() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks;
Public Class Class1
Async Function [|GooAsync|](i As Integer) As Task(Of Integer)
End Function
Async Sub BarAsync()
Await GooAsync(Await GooAsync(0))
End Sub
End Class",
"Imports System.Threading.Tasks;
Public Class Class1
Function Goo(i As Integer) As Integer
End Function
Async Sub BarAsync()
Goo(Goo(0))
End Sub
End Class", ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)>
<WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")>
Public Async Function TestRemoveAwaitFromCallerNested2() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Threading.Tasks;
Public Class Class1
Async Function [|GooAsync|](i As Integer) As Task(Of Integer)
End Function
Async Sub BarAsync()
Await Me.GooAsync(Await Me.GooAsync(0).ConfigureAwait(false)).ConfigureAwait(false)
End Sub
End Class",
"Imports System.Threading.Tasks;
Public Class Class1
Function Goo(i As Integer) As Integer
End Function
Async Sub BarAsync()
Me.Goo(Me.Goo(0))
End Sub
End Class", ignoreTrivia:=False)
End Function
End Class
End Namespace
|
kelltrick/roslyn
|
src/EditorFeatures/VisualBasicTest/Diagnostics/MakeMethodSynchronous/MakeMethodSynchronousTests.vb
|
Visual Basic
|
apache-2.0
| 10,061
|
Option Strict On
Namespace Xeora.Web.Shared.ControlResult
<Serializable()>
Public Class Conditional
Private _Result As Conditions
Public Sub New(ByVal Result As Conditions)
Me._Result = Result
End Sub
Public Enum Conditions As Byte
[False] = 0
[True] = 1
[UnKnown] = 99
End Enum
Public ReadOnly Property Result() As Conditions
Get
Return Me._Result
End Get
End Property
End Class
End Namespace
|
xeora/XeoraCube
|
Framework/Xeora.Web.Shared/ControlResult/Conditional.vb
|
Visual Basic
|
mit
| 556
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
Public Class TypeNameSimplifierTest
Inherits AbstractSimplificationTests
#Region "Normal CSharp Tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyTypeName()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
class A
{
{|SimplifyParent:System.Exception|} c;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyReceiver1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M(C other)
{
{|SimplifyParent:other.M|}(null);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
void M(C other)
{
other.M(null);
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyReceiver2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M(C other)
{
{|SimplifyParent:this.M|}(null);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
void M(C other)
{
M(null);
}
}
</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyNestedType()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.X.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Preserve.X.Y;
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyNestedType2()
' Simplified type is in a different namespace.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
static class M
{
public static void Main()
{
int k = P.NonGeneric.{|SimplifyParent:X|}.Y;
}
} </Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
static class M
{
public static void Main()
{
int k = N1.Preserve.X.Y;
}
}</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyNestedType3()
' Simplified type is in a different namespace, whose names have been imported with a usings statement.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
namespace R
{
using N1;
static class M
{
public static void Main()
{
int k = P.NonGeneric.{|SimplifyParent:X|}.Y;
}
}
} </Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
namespace R
{
using N1;
static class M
{
public static void Main()
{
int k = Preserve.X.Y;
}
}
}</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyNestedType4()
' Highly nested type simplified to another highly nested type.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
namespace P2
{
public class NonGeneric : N1.N2.Outer.Preserve
{
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Generic<int>.{|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
namespace P2
{
public class NonGeneric : N1.N2.Outer.Preserve
{
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using Q1.Q2;
static class M
{
public static void Main()
{
int k = N1.N2.Outer.Preserve.X.Y;
}
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyNestedType5()
' Name requiring multiple iterations of nested type simplification.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
using N1.N2;
namespace P2
{
public class NonGeneric : Outer
{
public class NonGenericInner : Outer.Preserve
{
}
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using N1.N2;
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Generic<int>.NonGenericInner.{|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
using N1.N2;
namespace P2
{
public class NonGeneric : Outer
{
public class NonGenericInner : Outer.Preserve
{
}
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using N1.N2;
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Outer.Preserve.X.Y;
}
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyStaticMemberAccess()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Preserve.Y;
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyQualifiedName()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class A
{
public static class B { }
}
class C : A
{
}
namespace N1
{
static class M
{
public static {|SimplifyParent:C.B|} F()
{
return null;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
public static class B { }
}
class C : A
{
}
namespace N1
{
static class M
{
public static A.B F()
{
return null;
}
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyAllNodes_SimplifyAliasStaticMemberAccess()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class NonGeneric : Preserve
{
}
namespace N1
{
using X = NonGeneric;
static class M
{
public static void Main()
{
int k = {|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class NonGeneric : Preserve
{
}
namespace N1
{
using X = NonGeneric;
static class M
{
public static void Main()
{
int k = Preserve.Y;
}
}
}]]></text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyNot_Delegate1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
static void Del() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del(A.{|SimplifyParent:Del|});
A.{|SimplifyParent:Del|}();
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
static void Del() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del(A.Del);
Del();
}
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyNot_Delegate2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
static void Bar() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del(A.{|SimplifyParent:Bar|});
A.{|SimplifyParent:Bar|}();
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
static void Bar() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del(A.Bar);
A.Bar();
}
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyNot_Delegate3()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
delegate void Del(Del a);
static void Boo(Del a) { }
class B
{
Del Boo = new Del(A.Boo);
void Foo()
{
Boo(A.{|SimplifyParent:Boo|});
A.Boo(Boo);
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
delegate void Del(Del a);
static void Boo(Del a) { }
class B
{
Del Boo = new Del(A.Boo);
void Foo()
{
Boo(A.Boo);
A.Boo(Boo);
}
}
}
</text>
Test(input, expected)
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(552722)>
Public Sub TestSimplifyNot_Action()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
static Action<int> Bar = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Foo()
{
A.{|SimplifyParent:Bar|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
static Action<int> Bar = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Foo()
{
A.Bar(3);
}
}
}]]>
</text>
Test(input, expected)
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(552722)>
Public Sub TestSimplifyNot_Func()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
static Func<int,int> Bar = (int x) => { return x; };
class B
{
Func<int,int> Bar = (int x) => { return x; };
void Foo()
{
A.{|SimplifyParent:Bar|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
static Func<int,int> Bar = (int x) => { return x; };
class B
{
Func<int,int> Bar = (int x) => { return x; };
void Foo()
{
A.Bar(3);
}
}
}]]>
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyNot_Inheritance()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
public virtual void f() { }
}
class B : A
{
public override void f()
{
base.{|SimplifyParent:f|}();
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
public virtual void f() { }
}
class B : A
{
public override void f()
{
base.f();
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyDoNothingWithFailedOverloadResolution()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Console;
class A
{
public void f()
{
Console.{|SimplifyParent:ReadLine|}("Boo!");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
using System.Console;
class A
{
public void f()
{
Console.ReadLine("Boo!");
}
}
</text>
Test(input, expected)
End Sub
<WorkItem(609496)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharpDoNotSimplifyNameInNamespaceDeclaration()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace System.{|SimplifyParent:Foo|}
{}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace System.Foo
{}
</text>
Test(input, expected)
End Sub
<WorkItem(608197)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CS_EscapeAliasReplacementIfNeeded()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using @if = System.Runtime.InteropServices.InAttribute;
class C
{
void foo()
{
var x = new System.Runtime.InteropServices.{|SimplifyParent:InAttribute|}() // Simplify Type Name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using @if = System.Runtime.InteropServices.InAttribute;
class C
{
void foo()
{
var x = new @if() // Simplify Type Name
}
}
</Code>
Test(input, expected)
End Sub
<WorkItem(529989)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CS_AliasReplacementKeepsUnicodeEscaping()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using B\u0061r = System.Console;
class Program
{
static void Main(string[] args)
{
System.Console.{|SimplifyParent:WriteLine|}("");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using B\u0061r = System.Console;
class Program
{
static void Main(string[] args)
{
B\u0061r.WriteLine("");
}
}
</Code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Simplify_Cast_Type_Name()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
class C
{
void M()
{
var a = 1;
Console.WriteLine((System.Collections.Generic.{|SimplifyParent:IEnumerable<int>|})a);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
using System.Collections.Generic;
class C
{
void M()
{
var a = 1;
Console.WriteLine((IEnumerable<int>)a);
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestAliasedNameWithMethod()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using foo = System.Console;
class Program
{
static void Main(string[] args)
{
{|SimplifyExtension:System.Console.WriteLine|}("test");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
using System.Collections.Generic;
using foo = System.Console;
class Program
{
static void Main(string[] args)
{
foo.WriteLine("test");
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(554010)>
Public Sub TestSimplificationForDelegateCreation()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
static void Main(string[] args)
{
Action b = (Action)Console.WriteLine + {|SimplifyParent:System.Console.WriteLine|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Test
{
static void Main(string[] args)
{
Action b = (Action)Console.WriteLine + Console.WriteLine;
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(554010)>
Public Sub TestSimplificationForDelegateCreation2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
Action b = (Action)Console.WriteLine + {|SimplifyParent:System.Console.WriteLine|};
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Test
{
Action b = (Action)Console.WriteLine + Console.WriteLine;
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970)>
Public Sub TestCSRemoveThisWouldBeConsideredACast_1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
Action A { get; set; }
void Foo()
{
(this.{|SimplifyParent:A|})(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
Action A { get; set; }
void Foo()
{
(this.A)(); // Simplify type name
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970)>
Public Sub TestCSRemoveThisWouldBeConsideredACast_2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
Action A { get; set; }
void Foo()
{
((this.{|SimplifyParent:A|}))(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
Action A { get; set; }
void Foo()
{
((A))(); // Simplify type name
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970)>
Public Sub TestCSRemoveThisWouldBeConsideredACast_3()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
public class C
{
public class D
{
public Action A { get; set; }
}
public D d = new D();
void Foo()
{
(this.{|SimplifyParent:d|}.A)(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
public class C
{
public class D
{
public Action A { get; set; }
}
public D d = new D();
void Foo()
{
(this.d.A)(); // Simplify type name
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(50, "https://github.com/dotnet/roslyn/issues/50")>
Public Sub TestCSRemoveThisPreservesTrivia()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C1
{
int _field;
void M()
{
this /*comment 1*/ . /* comment 2 */ {|SimplifyParent:_field|} /* comment 3 */ = 0;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C1
{
int _field;
void M()
{
/*comment 1*/ /* comment 2 */ _field /* comment 3 */ = 0;
}
}
</code>
Test(input, expected)
End Sub
<WorkItem(649385)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharpSimplifyToVarCorrect()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
using I = N.C;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
{|Simplify:int|} i = 0;
for ({|Simplify:int|} j = 0; ;) { }
{|Simplify:D|} d = new D();
foreach ({|Simplify:int|} item in new List<int>()) { }
using ({|Simplify:StreamReader|} file = new StreamReader("C:\\myfile.txt")) {}
{|Simplify:int|} x = Foo();
}
static int Foo() { return 1; }
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System.IO;
using I = N.C;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
var i = 0;
for (var j = 0; ;) { }
var d = new D();
foreach (var item in new List<int>()) { }
using (var file = new StreamReader("C:\\myfile.txt")) {}
var x = Foo();
}
static int Foo() { return 1; }
}
</code>
Test(input, expected, simplificationOption)
End Sub
<WorkItem(734445)>
<WorkItem(649385)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharpSimplifyToVarCorrect_QualifiedTypeNames()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
{|SimplifyParent:N.C|} z = new N.C();
{|SimplifyParent:System.Int32|} i = 1;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System.IO;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
var z = new N.C();
var i = 1;
}
}
</code>
Test(input, expected, simplificationOption)
End Sub
<WorkItem(649385)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharpSimplifyToVarDontSimplify()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Program
{
{|Simplify:int|} x;
static void Main(string[] args)
{
{|Simplify:int|} i = (i = 20);
{|Simplify:object|} o = null;
{|Simplify:Action<string[]>|} m = Main;
{|Simplify:int|} ij = 0, k = 0;
{|Simplify:int|} j;
{|Simplify:dynamic|} d = 1;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Program
{
int x;
static void Main(string[] args)
{
int i = (i = 20);
object o = null;
Action<string[]> m = Main;
int ij = 0, k = 0;
int j;
dynamic d = 1;
}
}
</code>
Test(input, expected, simplificationOption)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyTypeNameWhenParentHasSimplifyAnnotation()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyTypeNameWithExplicitSimplifySpan_MutuallyExclusive()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
{|SpanToSimplify:using System;|}
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
System.Exception c;
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyTypeNameWithExplicitSimplifySpan_Inclusive()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
{|SpanToSimplify:using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
|}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingPositive()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
{|SpanToSimplify:System.Exception|} c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingNegative()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception {|SpanToSimplify:c;|}
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
System.Exception c;
}
}
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification), WorkItem(864735)>
Public Sub BugFix864735_CSharp_SimplifyNameInIncompleteIsExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
static int F;
void M(C other)
{
Console.WriteLine({|SimplifyParent:C.F|} is
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
static int F;
void M(C other)
{
Console.WriteLine(F is
}
}
</text>
Test(input, expected)
End Sub
<WorkItem(813566)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyQualifiedCref()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
/// <summary>
/// <see cref="{|Simplify:System.Object|}"/>
/// </summary>
class Program
{
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
using System;
/// <summary>
/// <see cref="object"/>
/// </summary>
class Program
{
}]]>
</text>
Test(input, expected)
End Sub
<WorkItem(838109)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub DontSimplifyToGenericNameCSharp()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
{|SimplifyParent:C.D|}.F();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
C.D.F();
}
}]]>
</text>
Test(input, expected)
End Sub
<WorkItem(838109)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub DoSimplifyToGenericName()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.AllowSimplificationToGenericType, True}}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
{|SimplifyParent:C.D|}.F();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
C<int>.D.F();
}
}]]>
</text>
Test(input, expected, simplificationOption)
End Sub
<Fact, WorkItem(838109), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestDontSimplifyAllNodes_SimplifyNestedType()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.AllowSimplificationToBaseType, False}}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.X.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Z<float>.X.Y;
}
}]]></text>
Test(input, expected, simplificationOption)
End Sub
<Fact, WorkItem(838109), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestDontSimplifyAwayThisExpression()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{New OptionKey(SimplificationOptions.QualifyMemberAccessWithThisOrMe, LanguageNames.CSharp), True}}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Program
{
private int s;
static void Main(string[] args)
{
}
public int give()
{
return {|SimplifyParent:this.s|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Program
{
private int s;
static void Main(string[] args)
{
}
public int give()
{
return this.s;
}
}]]></text>
Test(input, expected, simplificationOption)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyTypeNameInCodeWithSyntaxErrors()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
private int x;
void F(int y) {}
void M()
{
C
// some comment
F({|SimplifyParent:this.x|});
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
private int x;
void F(int y) {}
void M()
{
C
// some comment
F(x);
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(653601), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestCrefSimplification_1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="{|Simplify:A.Program|}"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="Program"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(653601), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestCrefSimplification_2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="{|Simplify:A.Program.B|}"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="B"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(966633), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DontSimplifyNullableQualifiedName()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
{|SimplifyParent:Nullable<long>|}.Value x;
void M({|SimplifyParent:Nullable<int>|} a, ref {|SimplifyParent:System.Nullable<int>|} b, ref {|SimplifyParent:Nullable<long>|}.Something c) { }
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
Nullable<long>.Value x;
void M(int? a, ref int? b, ref Nullable<long>.Something c) { }
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(965240), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DontSimplifyOpenGenericNullable()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
void M()
{
var x = typeof({|SimplifyParent:System.Nullable<>|});
var y = (typeof({|SimplifyParent:System.Nullable<long>|}));
var z = (typeof({|SimplifyParent:System.Nullable|}));
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
void M()
{
var x = typeof(Nullable<>);
var y = (typeof(long?));
var z = (typeof(Nullable));
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(1067214), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_SimplifyTypeNameInExpressionBody_Property()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X => ({|SimplifyParent:N.Program|})x;
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X => (Program)x;
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(1067214), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_SimplifyTypeNameInExpressionBody_Method()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X() => ({|SimplifyParent:N.Program|})x;
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X() => (Program)x;
}
}]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(2232, "https://github.com/dotnet/roslyn/issues/2232"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DontSimplifyToPredefinedTypeNameInQualifiedName()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N
{
class Program
{
void Main()
{
var x = new {|SimplifyParent:System.Int32|}.Blah;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N
{
class Program
{
void Main()
{
var x = new Int32.Blah;
}
}
}]]></text>
Test(input, expected)
End Sub
<WorkItem(4859, "https://github.com/dotnet/roslyn/issues/4859")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DontSimplifyNullableInNameOfExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
void M()
{
var s = nameof({|Simplify:Nullable<int>|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
void M()
{
var s = nameof(Nullable<int>);
}
}
]]></text>
Test(input, expected)
End Sub
#End Region
#Region "Normal Visual Basic Tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyTypeName()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
Class A
Private e As {|SimplifyParent:System.Exception|}
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Private e As Exception
End Class
End Namespace
</text>
Test(input, expected)
End Sub
<WorkItem(547117)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestGetChanges_SimplifyTypeName_Array_1()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Dim Foo() As Integer
Sub Main(args As String())
{|SimplifyParent:Program|}.Foo(23) = 23
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Module Program
Dim Foo() As Integer
Sub Main(args As String())
Foo(23) = 23
End Sub
End Module
</text>
Test(input, expected)
End Sub
<WorkItem(547117)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestGetChanges_SimplifyTypeName_Array_2()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Dim Bar() As Action(Of Integer)
Sub Main(args As String())
{|SimplifyParent:Program.Bar|}(2)(2)
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Module Program
Dim Bar() As Action(Of Integer)
Sub Main(args As String())
Bar(2)(2)
End Sub
End Module
</text>
Test(input, expected)
End Sub
<WorkItem(547117)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestGetChanges_SimplifyTypeName_Receiver1()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M(other As C)
{|SimplifyParent:other.M|}(Nothing)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class C
Sub M(other As C)
other.M(Nothing)
End Sub
End Class
</text>
Test(input, expected)
End Sub
<WorkItem(547117)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestGetChanges_SimplifyTypeName_Receiver2()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M(other As C)
{|SimplifyParent:Me.M|}(Nothing)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class C
Sub M(other As C)
M(Nothing)
End Sub
End Class
</text>
Test(input, expected)
End Sub
<WorkItem(547117)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestGetChanges_SimplifyTypeName_Receiver3()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Public Shared B As Action
Public Sub M(ab As A)
{|SimplifyParent:ab.B|}()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Public Shared B As Action
Public Sub M(ab As A)
ab.B()
End Sub
End Class
</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyNestedType()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim {|SimplifyParent:Z(Of Integer).X.Y(1)|}
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim [Preserve].X.Y(1)
End Sub
End Class]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyNestedType2()
' Simplified type is in a different namespace.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
NotInheritable Class M
Public Shared Sub Main()
ReDim P.NonGeneric.{|SimplifyParent:X|}.Y(1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
NotInheritable Class M
Public Shared Sub Main()
ReDim N1.Preserve.X.Y(1)
End Sub
End Class</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyNestedType3()
' Simplified type is in a different namespace, whose names have been imported with an Imports statement.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports N1
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Redim P.NonGeneric.{|SimplifyParent:X|}.Y(1)
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports N1
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].X.Y(1)
End Sub
End Class
End Namespace</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyNestedType4()
' Highly nested type simplified to another highly nested type.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits N1.N2.Outer.Preserve
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Generic(Of Integer).{|SimplifyParent:X|}.Y
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits N1.N2.Outer.Preserve
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = N1.N2.Outer.Preserve.X.Y
End Sub
End Class
End Namespace</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyNestedType5()
' Name requiring multiple iterations of nested type simplification.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports N1.N2
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits Outer
Public Class NonGenericInner
Inherits Outer.Preserve
End Class
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Generic(Of Integer).NonGenericInner.{|SimplifyParent:X|}.Y
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports N1.N2
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits Outer
Public Class NonGenericInner
Inherits Outer.Preserve
End Class
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Outer.Preserve.X.Y
End Sub
End Class
End Namespace</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyStaticMemberAccess()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Preserve
Public Shared Y
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
Redim {|SimplifyParent:Z(Of Single).Y(1)|}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class Preserve
Public Shared Y
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].Y(1)
End Sub
End Class</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyQualifiedName()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Public NotInheritable Class B
End Class
End Class
Class C
Inherits A
End Class
Namespace N1
NotInheritable Class M
Public Shared Function F() As {|SimplifyParent:C.B|}
Return Nothing
End Function
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Public NotInheritable Class B
End Class
End Class
Class C
Inherits A
End Class
Namespace N1
NotInheritable Class M
Public Shared Function F() As A.B
Return Nothing
End Function
End Class
End Namespace</text>
Test(input, expected)
End Sub
<Fact, WorkItem(551040), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyAllNodes_SimplifyAliasStaticMemberAccess()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports X = NonGeneric
Class Preserve
Public Shared Y
End Class
Class NonGeneric
Inherits Preserve
End Class
Namespace N1
NotInheritable Class M
Public Shared Sub Main()
Redim {|SimplifyParent:X.Y(1)|}
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports X = NonGeneric
Class Preserve
Public Shared Y
End Class
Class NonGeneric
Inherits Preserve
End Class
Namespace N1
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].Y(1)
End Sub
End Class
End Namespace</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyNot_Delegate1_VB()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Shared Sub Del()
End Sub
Class B
Delegate Sub Del()
Sub Boo()
Dim d As Del = New Del(AddressOf A.{|SimplifyParent:Del|})
A.{|SimplifyParent:Del|}()
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Shared Sub Del()
End Sub
Class B
Delegate Sub Del()
Sub Boo()
Dim d As Del = New Del(AddressOf A.Del)
A.Del()
End Sub
End Class
End Class
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyNot_Delegate2_VB()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Shared Sub Bar()
End Sub
Class B
Delegate Sub Del()
Sub Bar()
End Sub
Sub Boo()
Dim d As Del = New Del(AddressOf A.{|SimplifyParent:Bar|})
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Shared Sub Bar()
End Sub
Class B
Delegate Sub Del()
Sub Bar()
End Sub
Sub Boo()
Dim d As Del = New Del(AddressOf A.Bar)
End Sub
End Class
End Class
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(570986)>
<WorkItem(552722)>
Public Sub TestSimplifyNot_Action_VB()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class A
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Class B
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Sub Foo()
A.{|SimplifyParent:Bar|}(3)
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Class A
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Class B
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Sub Foo()
A.Bar(3)
End Sub
End Class
End Class
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestSimplifyBaseInheritanceVB()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
MustInherit Class A
Public MustOverride Sub Foo()
Public Sub Boo()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub Foo()
MyBase.{|SimplifyParent:Boo|}()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
MustInherit Class A
Public MustOverride Sub Foo()
Public Sub Boo()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub Foo()
Boo()
End Sub
End Class
</text>
Test(input, expected)
End Sub
<WorkItem(588099)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_EscapeReservedNamesInAttributes()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
<Global.Assembly.{|SimplifyParent:Foo|}>
Module Assembly
Class FooAttribute
Inherits Attribute
End Class
End Module
Module M
Class FooAttribute
Inherits Attribute
End Class
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
<[Assembly].Foo>
Module Assembly
Class FooAttribute
Inherits Attribute
End Class
End Module
Module M
Class FooAttribute
Inherits Attribute
End Class
End Module
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_OmitModuleNameInMemberAccess()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace foo
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
Namespace bar
Module b
Sub m()
foo.Program.{|SimplifyParent:Main|}(Nothing)
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Namespace foo
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
Namespace bar
Module b
Sub m()
foo.Main(Nothing)
End Sub
End Module
End Namespace
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_OmitModuleNameInQualifiedName()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace foo
Module Program
Sub Main(args As String())
End Sub
Class C1
End Class
End Module
End Namespace
Namespace bar
Module b
Sub m()
Dim x as foo.Program.{|SimplifyParent:C1|}
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Namespace foo
Module Program
Sub Main(args As String())
End Sub
Class C1
End Class
End Module
End Namespace
Namespace bar
Module b
Sub m()
Dim x as foo.C1
End Sub
End Module
End Namespace
</code>
Test(input, expected)
End Sub
<WorkItem(601160)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub TestExpandMultilineLambdaWithImports()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
{|Expand:Sub Main(args As String())
Task.Run(Sub()
Imports System
End Sub)
End Sub|}
End Module
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspaceFactory.CreateWorkspace(input)
Dim hostDocument = workspace.Documents.Single()
Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single()
Dim root = document.GetSyntaxRootAsync().Result
For Each span In hostDocument.AnnotatedSpans("Expand")
Dim node = root.FindToken(span.Start).Parent.Parent
If TypeOf node Is MethodBlockBaseSyntax Then
node = DirectCast(node, MethodBlockBaseSyntax).Statements.Single()
End If
Assert.True(TypeOf node Is ExpressionStatementSyntax)
Dim result = Simplifier.ExpandAsync(node, document).Result
Assert.NotEqual(0, result.ToString().Count)
Next
End Using
End Sub
<WorkItem(609496)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VB_DoNotReduceNamesInNamespaceDeclarations()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace System.{|SimplifyParent:Foo|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Imports System
Namespace System.Foo
End Namespace
</Code>
Test(input, expected)
End Sub
<WorkItem(608197)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VB_EscapeAliasReplacementIfNeeded()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports [In] = System.Runtime.InteropServices.InAttribute
Module M
Dim x = New System.Runtime.InteropServices.{|SimplifyParent:InAttribute|}() ' Simplify Type Name
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Imports [In] = System.Runtime.InteropServices.InAttribute
Module M
Dim x = New [In]() ' Simplify Type Name
End Module
</Code>
Test(input, expected)
End Sub
<WorkItem(608197)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VB_NoNREForOmittedReceiverInWithBlock()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Sub M()
With New B()
Dim x = .P.{|SimplifyParent:MaxValue|}
End With
End Sub
End Class
Public Class B
Public Property P As Integer
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Public Class A
Public Sub M()
With New B()
Dim x = .P.MaxValue
End With
End Sub
End Class
Public Class B
Public Property P As Integer
End Class
</Code>
Test(input, expected)
End Sub
<WorkItem(639971)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub BugFix639971_VisualBasic_FalseUnnecessaryBaseQualifier()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Z
Public Function Bar() As String
Return MyBase.{|SimplifyParent:ToString|}()
End Function
End Class
Class Y
Inherits Z
Public Overrides Function ToString() As String
Return ""
End Function
Public Sub Baz()
Console.WriteLine(New Y().Bar())
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Class Z
Public Function Bar() As String
Return MyBase.ToString()
End Function
End Class
Class Y
Inherits Z
Public Overrides Function ToString() As String
Return ""
End Function
Public Sub Baz()
Console.WriteLine(New Y().Bar())
End Sub
End Class
</Code>
Test(input, expected)
End Sub
<WorkItem(639971)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub BugFix639971_CSharp_FalseUnnecessaryBaseQualifier()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
public string InvokeBaseToString()
{
return base.{|SimplifyParent:ToString|}();
}
}
class D : C
{
public override string ToString()
{
return "";
}
static void Main()
{
Console.WriteLine(new D().InvokeBaseToString());
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using System;
class C
{
public string InvokeBaseToString()
{
return base.ToString();
}
}
class D : C
{
public override string ToString()
{
return "";
}
static void Main()
{
Console.WriteLine(new D().InvokeBaseToString());
}
}
</Code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyTypeNameWhenParentHasSimplifyAnnotation()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_MutuallyExclusive()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
{|SpanToSimplify:Imports System|}
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As System.Exception
End Class
End Namespace
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_Inclusive()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
{|SpanToSimplify:Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
|}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingPositive()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As {|SpanToSimplify:System.Exception|}
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingNegative()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
{|SpanToSimplify:Dim c|} As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As System.Exception
End Class
End Namespace
</text>
Test(input, expected)
End Sub
<WorkItem(769354)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyTypeNameInCrefCausesConflict()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Base
Public Sub New(x As Integer)
End Sub
End Class
Class Derived : Inherits Base
''' <summary>
''' <see cref="{|SimplifyParent:Global.Base|}.New(Integer)"/>
''' </summary>
''' <param name="x"></param>
Public Sub New(x As Integer)
MyBase.New(x)
End Sub
Public Sub Base(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Base
Public Sub New(x As Integer)
End Sub
End Class
Class Derived : Inherits Base
''' <summary>
''' <see cref="Base.New(Integer)"/>
''' </summary>
''' <param name="x"></param>
Public Sub New(x As Integer)
MyBase.New(x)
End Sub
Public Sub Base(x As Integer)
End Sub
End Class]]>
</text>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification), WorkItem(864735)>
Public Sub BugFix864735_VisualBasic_SimplifyNameInIncompleteIsExpression()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Shared Public F As Integer
Shared Sub Main()
Console.WriteLine(TypeOf {|SimplifyParent:C.F|} Is
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Class C
Shared Public F As Integer
Shared Sub Main()
Console.WriteLine(TypeOf F Is
End Sub
End Class
</text>
Test(input, expected)
End Sub
<WorkItem(813566)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestSimplifyQualifiedCref()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
''' <summary>
''' <see cref="{|Simplify:System.Object|}"/>
''' </summary>
Class Program
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
''' <summary>
''' <see cref="Object"/>
''' </summary>
Class Program
End Class]]>
</text>
Test(input, expected)
End Sub
<WorkItem(838109)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DontSimplifyToGenericName()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Sub Main(args As String())
{|SimplifyParent:C.D|}.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Program
Sub Main(args As String())
C.D.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</text>
Test(input, expected)
End Sub
<WorkItem(838109)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoSimplifyToGenericName()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.AllowSimplificationToGenericType, True}}
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Sub Main(args As String())
{|SimplifyParent:C.D|}.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Program
Sub Main(args As String())
C(OfInteger).D.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</text>
Test(input, expected, simplificationOption)
End Sub
<Fact, WorkItem(838109), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestDontSimplifyAllNodes_SimplifyNestedType()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.AllowSimplificationToBaseType, False}}
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim {|SimplifyParent:Z(Of Integer).X.Y(1)|}
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim Z(Of Integer).X.Y(1)
End Sub
End Class]]></text>
Test(input, expected, simplificationOption)
End Sub
<Fact, WorkItem(838109), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_TestDontSimplifyAwayMeExpression()
Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {{New OptionKey(SimplificationOptions.QualifyMemberAccessWithThisOrMe, LanguageNames.VisualBasic), True}}
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class Program
Private s As Integer
Shared Sub Main(args As String())
End Sub
Public Function give() As Integer
Return {|SimplifyParent:Me.s|}
End Function
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class Program
Private s As Integer
Shared Sub Main(args As String())
End Sub
Public Function give() As Integer
Return Me.s
End Function
End Class]]></text>
Test(input, expected, simplificationOption)
End Sub
<Fact, WorkItem(881746), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_SimplyToAlias()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<{|SimplifyParent:Attribute|}>
Class A
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<AttributeAttributeAttribute>
Class A
End Class]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(881746), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DontSimplifyAlias()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<{|SimplifyParent:AttributeAttributeAttribute|}>
Class A
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<AttributeAttributeAttribute>
Class A
End Class]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(966633), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DontSimplifyNullableQualifiedName()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x as {|SimplifyParent:Nullable(Of Integer)|}.Value
End Sub
Sub M(a as {|SimplifyParent:Nullable(Of Integer)|}, byref b as {|SimplifyParent:System.Nullable(Of Integer)|}, byref c as {|SimplifyParent:Nullable(Of Integer)|}.Value)
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x as Nullable(Of Integer).Value
End Sub
Sub M(a as Integer?, byref b as Integer?, byref c as Nullable(Of Integer).Value)
End Sub
End Module]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(965240), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DontSimplifyOpenGenericNullable()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = GetType({|SimplifyParent:System.Nullable(Of )|})
Dim y = (GetType({|SimplifyParent:System.Nullable(Of Long)|}))
Dim z = (GetType({|SimplifyParent:System.Nullable|}))
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = GetType(Nullable(Of ))
Dim y = (GetType(Long?))
Dim z = (GetType(Nullable))
End Sub
End Module]]></text>
Test(input, expected)
End Sub
<Fact(Skip:="1019361"), WorkItem(1019361), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Bug1019361()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports N
Namespace N
Class A
Public Const X As Integer = 1
End Class
End Namespace
Module Program
Sub Main()
Dim x = {|SimplifyParent:N.A|}.X ' Simplify type name 'N.A'
Dim a As A = Nothing
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports N
Namespace N
Class A
Public Const X As Integer = 1
End Class
End Namespace
Module Program
Sub Main()
Dim x = N.A.X ' Simplify type name 'N.A'
Dim a As A = Nothing
End Sub
End Module]]></text>
Test(input, expected)
End Sub
<Fact, WorkItem(2232, "https://github.com/dotnet/roslyn/issues/2232"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DontSimplifyToPredefinedTypeNameInQualifiedName()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = New {|SimplifyParent:System.Int32|}.Blah
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = New System.Int32.Blah
End Sub
End Module]]></text>
Test(input, expected)
End Sub
<WorkItem(4859, "https://github.com/dotnet/roslyn/issues/4859")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DontSimplifyNullableInNameOfExpression()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Sub M()
Dim s = NameOf({|Simplify:Nullable(Of Integer)|})
End Sum
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Sub M()
Dim s = NameOf(Nullable(Of Integer))
End Sum
End Class
]]></text>
Test(input, expected)
End Sub
#End Region
End Class
End Namespace
|
dovzhikova/roslyn
|
src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb
|
Visual Basic
|
apache-2.0
| 99,088
|
' 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
Imports System.Collections.Generic
Public Module Extensions_2
''' <summary>
''' An ICollection<T> extension method that adds only if the value satisfies the predicate.
''' </summary>
''' <typeparam name="T">Generic type parameter.</typeparam>
''' <param name="this">The @this to act on.</param>
''' <param name="predicate">The predicate.</param>
''' <param name="value">The value.</param>
''' <returns>true if it succeeds, false if it fails.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function AddIf(Of T)(this As ICollection(Of T), predicate As Func(Of T, Boolean), value As T) As Boolean
If predicate(value) Then
this.Add(value)
Return True
End If
Return False
End Function
End Module
|
zzzprojects/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Collections/System.Collections.Generic.ICollection[T]/ICollection[T].AddIf.vb
|
Visual Basic
|
mit
| 1,125
|
' 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
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundUnaryOperator
Public Sub New(
syntax As SyntaxNode,
operatorKind As UnaryOperatorKind,
operand As BoundExpression,
checked As Boolean,
type As TypeSymbol,
Optional hasErrors As Boolean = False
)
Me.New(syntax, operatorKind, operand, checked, constantValueOpt:=Nothing, type:=type, hasErrors:=hasErrors OrElse operand.HasErrors())
End Sub
#If DEBUG Then
Private Sub Validate()
ValidateConstantValue()
Operand.AssertRValue()
Debug.Assert(HasErrors OrElse Type.IsSameTypeIgnoringCustomModifiers(Operand.Type))
End Sub
#End If
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
If (OperatorKind And UnaryOperatorKind.Error) = 0 Then
Dim opName As String = OverloadResolution.TryGetOperatorName(OperatorKind)
If opName IsNot Nothing Then
Dim op As UnaryOperatorKind = (OperatorKind And UnaryOperatorKind.OpMask)
Dim operandType = DirectCast(Operand.Type.GetNullableUnderlyingTypeOrSelf(), NamedTypeSymbol)
Return New SynthesizedIntrinsicOperatorSymbol(operandType,
opName,
Type.GetNullableUnderlyingTypeOrSelf(),
Checked AndAlso operandType.IsIntegralType() AndAlso
op = UnaryOperatorKind.Minus)
End If
End If
Return Nothing
End Get
End Property
End Class
End Namespace
|
ljw1004/roslyn
|
src/Compilers/VisualBasic/Portable/BoundTree/BoundUnaryOperator.vb
|
Visual Basic
|
apache-2.0
| 2,230
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
Public Class CastSimplificationTests
Inherits AbstractSimplificationTests
#Region "CSharp tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_IntToInt()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
int x = {|Simplify:(int)0|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
int x = 0;
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_ByteToInt()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
int x = {|Simplify:(byte)0|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
int x = 0;
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_ByteToVar()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var x = {|Simplify:(byte)0|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
var x = (byte)0;
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_UncheckedByteToInt()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
int x = unchecked({|Simplify:(byte)257|});
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
int x = unchecked((byte)257);
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_UncheckedByteToVar()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var x = unchecked({|Simplify:(byte)257|});
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
var x = unchecked((byte)257);
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_UncheckedByteToIntToVar()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var x = int(unchecked({|Simplify:(byte)257|}));
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
var x = int(unchecked((byte)257));
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_IntToObjectInInvocation()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(object o) { }
void M()
{
int x = Foo({|Simplify:(object)1|});
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void Foo(object o) { }
void M()
{
int x = Foo(1);
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_IntToObject_Overloads1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(object o) { }
void Foo(int i) { }
void M()
{
int x = Foo({|Simplify:(object)1|});
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void Foo(object o) { }
void Foo(int i) { }
void M()
{
int x = Foo((object)1);
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_IntToObject_Overloads2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(object o) { }
void Foo(int i) { }
void M()
{
int x = Foo({|Simplify:(object)(1 + 2)|});
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void Foo(object o) { }
void Foo(int i) { }
void M()
{
int x = Foo((object)(1 + 2));
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_IntToDouble1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
string s = ({|Simplify:(double)3|}).ToString();
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
string s = ((double)3).ToString();
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_LambdaToDelegateType1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
System.Action a = {|Simplify:(System.Action)(() => { })|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
System.Action a = (() => { });
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_LambdaToDelegateType2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
System.Action a = null;
a = {|Simplify:(System.Action)(() => { })|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
System.Action a = null;
a = (() => { });
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_LambdaToDelegateTypeInInvocation1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
Foo({|Simplify:(System.Func<string>)(() => "Foo")|});
}
void Foo<T>(System.Func<T> f) { }
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
Foo((() => "Foo"));
}
void Foo<T>(System.Func<T> f) { }
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_LambdaToDelegateTypeInInvocation2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
Foo(f: {|Simplify:(System.Func<string>)(() => "Foo")|});
}
void Foo<T>(System.Func<T> f) { }
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
Foo(f: (() => "Foo"));
}
void Foo<T>(System.Func<T> f) { }
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_LambdaToDelegateTypeWithVar()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = {|Simplify:(System.Action)(() => { })|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
var a = (System.Action)(() => { });
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_LambdaToDelegateTypeWhenInvoked()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var x = ({|Simplify:(System.Func<int>)(() => 1)|})();
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
var x = ((System.Func<int>)(() => 1))();
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_MethodGroupToDelegateTypeWhenInvoked()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M(object o)
{
({|Simplify:(Action<object>)Main|})(null);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M(object o)
{
((Action<object>)Main)(null);
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_AnonymousFunctionToDelegateTypeInNullCoalescingExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
System.Action y = {|Simplify:(System.Action)delegate { }|} ?? null;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
System.Action y = (System.Action)delegate { } ?? null;
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_MethodGroupToDelegateTypeInDelegateCombineExpression1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
System.Action<string> g = null;
var h = {|Simplify:(System.Action<string>)(Foo<string>)|} + g;
}
static void Foo<T>(T y) { }
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
System.Action<string> g = null;
var h = (Foo<string>) + g;
}
static void Foo<T>(T y) { }
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_MethodGroupToDelegateTypeInDelegateCombineExpression2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
System.Action<string> g = null;
var h = ({|Simplify:(System.Action<string>)Foo<string>|}) + g;
}
static void Foo<T>(T y) { }
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C
{
void M()
{
System.Action<string> g = null;
var h = (Foo<string>) + g;
}
static void Foo<T>(T y) { }
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_NullLiteralToStringInInvocation()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
void M()
{
Console.WriteLine({|Simplify:(string)null|});
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
void M()
{
Console.WriteLine((string)null);
}
}
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529816)>
Public Sub CSharp_DoNotRemove_QuerySelectMethodChanges()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
int Select(Func<int, long> x) { return 1; }
int Select(Func<int, int> x) { return 2; }
static void Main()
{
Console.WriteLine(from y in new A() select {|Simplify:(long)0|});
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class A
{
int Select(Func<int, long> x) { return 1; }
int Select(Func<int, int> x) { return 2; }
static void Main()
{
Console.WriteLine(from y in new A() select (long)0);
}
}]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529816)>
Public Sub CSharp_DoNotRemove_QueryOrderingMethodChanges()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Linq;
public class A
{
IOrderedEnumerable<int> OrderByDescending(Func<int, long> keySelector) { Console.WriteLine("long"); return null; }
IOrderedEnumerable<int> OrderByDescending(Func<int, int> keySelector) { Console.WriteLine("int"); return null; }
IOrderedEnumerable<int> OrderByDescending(Func<int, object> keySelector) { Console.WriteLine("object"); return null; }
public static void Main()
{
var q1 =
from x in new A()
orderby
{|Simplify:(long)x descending|},
{|Simplify:(string)x.ToString() ascending|},
{|Simplify:(int)x descending|}
select x;
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
using System.Linq;
public class A
{
IOrderedEnumerable<int> OrderByDescending(Func<int, long> keySelector) { Console.WriteLine("long"); return null; }
IOrderedEnumerable<int> OrderByDescending(Func<int, int> keySelector) { Console.WriteLine("int"); return null; }
IOrderedEnumerable<int> OrderByDescending(Func<int, object> keySelector) { Console.WriteLine("object"); return null; }
public static void Main()
{
var q1 =
from x in new A()
orderby
(long)x descending,
x.ToString() ascending,
x descending
select x;
}
}]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529816)>
Public Sub CSharp_DoNotRemove_QueryClauseChanges()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Linq;
using System.Collections.Generic;
class A
{
A Select(Func<int, long> x) { return this; }
A Select(Func<int, int> x) { return this; }
static void Main()
{
var qie = from x3 in new int[] { 0 }
join x7 in (new int[] { 1 }) on 5 equals {|Simplify:(long)5|} into x8
select x8;
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
using System.Linq;
using System.Collections.Generic;
class A
{
A Select(Func<int, long> x) { return this; }
A Select(Func<int, int> x) { return this; }
static void Main()
{
var qie = from x3 in new int[] { 0 }
join x7 in (new int[] { 1 }) on 5 equals (long)5 into x8
select x8;
}
}]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529842)>
Public Sub CSharp_DoNotRemove_CastInTernary()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
public static implicit operator string (X x)
{
return x.ToString();
}
static void Main()
{
bool b = true;
X x = new X();
Console.WriteLine(b ? {|Simplify:(string)null|} : x);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class X
{
public static implicit operator string (X x)
{
return x.ToString();
}
static void Main()
{
bool b = true;
X x = new X();
Console.WriteLine(b ? (string)null : x);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529855)>
Public Sub CSharp_Remove_UnnecessaryCastInIsExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections;
static class A
{
static void Foo(IEnumerable x)
{
if ({|Simplify:(object)x|} is string)
{
}
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System.Collections;
static class A
{
static void Foo(IEnumerable x)
{
if (x is string)
{
}
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529843)>
Public Sub CSharp_Remove_CastToObjectTypeInRefenceComparison()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
static void Foo<T, S>(T x, S y)
where T : class
where S : class
{
if (x == {|Simplify:(object)y|}) { }
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
static void Foo<T, S>(T x, S y)
where T : class
where S : class
{
if (x == y) { }
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529914)>
Public Sub CSharp_Remove_TypeParameterToEffectiveBaseType()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Foo<T, S>(T x, S y)
where T : Exception
where S : Exception
{
if (x == {|Simplify:(Exception)y|}) { }
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Foo<T, S>(T x, S y)
where T : Exception
where S : Exception
{
if (x == y) { }
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529917)>
Public Sub CSharp_Remove_NullableTypeToInterfaceTypeInNullComparison()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
int? x = null;
var y = {|Simplify:(IComparable)x|} == null;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
int? x = null;
var y = x == null;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(530745)>
Public Sub CSharp_DoNotRemove_RequiredExplicitNullableCast1()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
var x = {|Simplify:(long?){|Simplify:(int?)long.MaxValue|}|};
Console.WriteLine(x);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
var x = (long?)(int?)long.MaxValue;
Console.WriteLine(x);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(531431)>
Public Sub CSharp_DoNotRemove_RequiredExplicitNullableCast2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
Console.WriteLine((int){|Simplify:(float?)(int?)2147483647|}); // Prints -2147483648
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
Console.WriteLine((int)(float?)(int?)2147483647); // Prints -2147483648
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(531431)>
Public Sub CSharp_Remove_UnnecessaryExplicitNullableCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
Console.WriteLine((int)(float?){|Simplify:(int?)2147483647|}); // Prints -2147483648
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
Console.WriteLine((int)(float?)2147483647); // Prints -2147483648
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(531431)>
Public Sub CSharp_DoNotRemove_RequiredExplicitNullableCast_And_Remove_UnnecessaryExplicitNullableCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
Console.WriteLine({|Simplify:(int){|Simplify:(float?){|Simplify:(int?)2147483647|}|}|}); // Prints -2147483648
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
Console.WriteLine((int)(float?)2147483647); // Prints -2147483648
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(530248)>
Public Sub CSharp_DoNotRemove_NeccessaryCastInTernaryExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Base { }
class Derived1 : Base { }
class Derived2 : Base { }
class Test
{
public Base F(bool flag, Derived1 d1, Derived2 d2)
{
return flag ? d1 : {|Simplify:(Base)d2|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Base { }
class Derived1 : Base { }
class Derived2 : Base { }
class Test
{
public Base F(bool flag, Derived1 d1, Derived2 d2)
{
return flag ? d1 : (Base)d2;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(530248)>
Public Sub CSharp_DoNotRemove_NeccessaryCastInTernaryExpression2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Base { }
class Derived1 : Base { }
class Derived2 : Base { }
class Test
{
public Base F(bool flag, Derived1 d1, Derived2 d2)
{
return flag ? {|Simplify:(Base)d1|} : d2;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Base { }
class Derived1 : Base { }
class Derived2 : Base { }
class Test
{
public Base F(bool flag, Derived1 d1, Derived2 d2)
{
return flag ? (Base)d1 : d2;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(530085)>
Public Sub CSharp_DoNotRemove_NeccessaryCastInTernaryExpression3()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
static void Main(string[] args)
{
bool b = true;
long value = 0;
long? a = b ? {|Simplify:(long?)value|} : null;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
static void Main(string[] args)
{
bool b = true;
long value = 0;
long? a = b ? (long?)value : null;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529985)>
Public Sub CSharp_DoNotRemove_NeccessaryCastInMemberAccessExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C
{
static void Main()
{
C c = null;
Console.WriteLine(({|Simplify:(Attribute)c|}).GetType());
}
public static implicit operator Attribute(C x)
{
return new ObsoleteAttribute();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C
{
static void Main()
{
C c = null;
Console.WriteLine(((Attribute)c).GetType());
}
public static implicit operator Attribute(C x)
{
return new ObsoleteAttribute();
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529956)>
Public Sub CSharp_DoNotRemove_NeccessaryCastInForEachExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections;
class C
{
static void Main()
{
foreach (C x in {|Simplify:(IEnumerable) new string[] { null }|})
{
Console.WriteLine(x == null);
}
}
public static implicit operator C(string s)
{
return new C();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
using System.Collections;
class C
{
static void Main()
{
foreach (C x in (IEnumerable) new string[] { null })
{
Console.WriteLine(x == null);
}
}
public static implicit operator C(string s)
{
return new C();
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529956)>
Public Sub CSharp_DoNotRemove_NeccessaryCastInForEachExpressionInsideLambda()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections;
class C
{
static void Main()
{
Action a = () =>
{
foreach (C x in {|Simplify:(IEnumerable)new string[] { null }|})
{
Console.WriteLine(x == null);
}
};
}
public static implicit operator C(string s)
{
return new C();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
using System.Collections;
class C
{
static void Main()
{
Action a = () =>
{
foreach (C x in (IEnumerable)new string[] { null })
{
Console.WriteLine(x == null);
}
};
}
public static implicit operator C(string s)
{
return new C();
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529844)>
Public Sub CSharp_DoNotRemove_NeccessaryCastInNumericConversion()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
int x = int.MaxValue;
double y = x;
double z = {|Simplify:(float)x|};
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.WriteLine(y == z);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
int x = int.MaxValue;
double y = x;
double z = (float)x;
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.WriteLine(y == z);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(662196)>
Public Sub CSharp_DoNotRemove_NeccessaryCastInDynamicInvocation()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void Foo(string x) { }
void Foo(string[] x) { }
static void Main()
{
dynamic c = new C();
c.Foo({|Simplify:(string)null|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class C
{
void Foo(string x) { }
void Foo(string[] x) { }
static void Main()
{
dynamic c = new C();
c.Foo((string)null);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529962)>
Public Sub CSharp_Remove_UnneccessaryCastInIsExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections;
class C
{
static void Main()
{
string[] x = { };
Console.WriteLine({|Simplify:(IEnumerable)x|} is object[]);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
using System.Collections;
class C
{
static void Main()
{
string[] x = { };
Console.WriteLine(x is object[]);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(662196)>
Public Sub CSharp_Remove_UnneccessaryCastInAsExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections;
class C
{
static void Main()
{
string[] x = { };
Console.WriteLine({|Simplify:(IEnumerable)x|} as object[]);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
using System.Collections;
class C
{
static void Main()
{
string[] x = { };
Console.WriteLine(x as object[]);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529973)>
Public Sub CSharp_DoNotRemove_NeccessaryCastToDelegateInIsExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
var x = checked({|Simplify:(Action)delegate { }|}) is object;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
var x = checked((Action)delegate { }) is object;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529973)>
Public Sub CSharp_DoNotRemove_NeccessaryCastToDelegateInAsExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
var x = checked({|Simplify:(Action)delegate { }|}) as object;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
var x = checked((Action)delegate { }) as object;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529968)>
Public Sub CSharp_DoNotRemove_NeccessaryCastForParamsArgument()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
static void Main()
{
Foo({|Simplify:(object) new A()|});
}
static void Foo(params object[] x)
{
Console.WriteLine(x == null);
}
public static implicit operator object[](A a)
{
return null;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class A
{
static void Main()
{
Foo((object) new A());
}
static void Foo(params object[] x)
{
Console.WriteLine(x == null);
}
public static implicit operator object[](A a)
{
return null;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529968)>
Public Sub CSharp_Remove_UnneccessaryCastsForParamsArguments()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
static void Main()
{
Foo({|Simplify:(object)new A()|}, {|Simplify:(object)new A()|});
}
static void Foo(params object[] x)
{
Console.WriteLine(x == null);
}
public static implicit operator object[](A a)
{
return null;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class A
{
static void Main()
{
Foo(new A(), new A());
}
static void Foo(params object[] x)
{
Console.WriteLine(x == null);
}
public static implicit operator object[](A a)
{
return null;
}
}
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(530083)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_DoNotRemove_InsideThrowStatement()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
public static void Main()
{
object ex = new Exception();
throw {|Simplify:(Exception)ex|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
public static void Main()
{
object ex = new Exception();
throw (Exception)ex;
}
}
</code>
Test(input, expected)
End Sub
<WorkItem(530083)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub CSharp_Remove_InsideThrowStatement()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
public static void Main()
{
var ex = new ArgumentException();
throw {|Simplify:(Exception)ex|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
public static void Main()
{
var ex = new ArgumentException();
throw ex;
}
}
</code>
Test(input, expected)
End Sub
<WorkItem(530083)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_Remove_InsideThrowStatement2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
public static void Main()
{
Exception ex = new ArgumentException();
throw {|Simplify:(ArgumentException)ex|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
public static void Main()
{
Exception ex = new ArgumentException();
throw ex;
}
}
</code>
Test(input, expected)
End Sub
<WorkItem(529919)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_Remove_DelegateVarianceConversions()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
Action<object> a = Console.WriteLine;
Action<string> b = {|Simplify:(Action<string>)a|};
({|Simplify:(Action<string>)a|})("A");
({|Simplify:(Action<string>)a|}).Invoke("A");
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
Action<object> a = Console.WriteLine;
Action<string> b = a;
(a)("A");
(a).Invoke("A");
}
}]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529884)>
<WorkItem(1043494, "DevDiv")>
<Fact(Skip:="1043494"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_DoNotRemove_ParamDefaultValueNegativeZero()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
interface I
{
void Foo(double x = +0.0);
}
sealed class C : I
{
public void Foo(double x = -0.0)
{
Console.WriteLine(1 / x > 0);
}
static void Main()
{
({|Simplify:(I)new C()|}).Foo();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
interface I
{
void Foo(double x = +0.0);
}
sealed class C : I
{
public void Foo(double x = -0.0)
{
Console.WriteLine(1 / x > 0);
}
static void Main()
{
((I)new C()).Foo();
}
}]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529884)>
<WorkItem(1043494, "DevDiv")>
<Fact(Skip:="1043494"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_DoNotRemove_ParamDefaultValueNegativeZero2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
interface I
{
void Foo(double x = -(-0.0));
}
sealed class C : I
{
public void Foo(double x = -0.0)
{
Console.WriteLine(1 / x > 0);
}
static void Main()
{
({|Simplify:(I)new C()|}).Foo();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
interface I
{
void Foo(double x = -(-0.0));
}
sealed class C : I
{
public void Foo(double x = -0.0)
{
Console.WriteLine(1 / x > 0);
}
static void Main()
{
((I)new C()).Foo();
}
}]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529884)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_Remove_ParamDefaultValueZero()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
interface I
{
void Foo(double x = +0.0);
}
sealed class C : I
{
public void Foo(double x = -(-0.0))
{
Console.WriteLine(1 / x > 0);
}
static void Main()
{
({|Simplify:(I)new C()|}).Foo();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
interface I
{
void Foo(double x = +0.0);
}
sealed class C : I
{
public void Foo(double x = -(-0.0))
{
Console.WriteLine(1 / x > 0);
}
static void Main()
{
(new C()).Foo();
}
}]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529791)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_Remove_UnnecessaryImplicitNullableCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class X
{
static void Foo()
{
object x = {|Simplify:(string)null|};
object y = {|Simplify:(int?)null|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class X
{
static void Foo()
{
object x = null;
object y = null;
}
}
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(530744)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_Remove_UnnecessaryImplicitEnumerationCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
DayOfWeek? x = {|Simplify:(DayOfWeek)0|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
DayOfWeek? x = 0;
}
}
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529831)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_Remove_UnnecessaryInterfaceCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
interface IIncrementable
{
int Value { get; }
void Increment();
}
struct S : IIncrementable
{
public int Value { get; private set; }
public void Increment() { Value++; }
}
class C : IIncrementable
{
public int Value { get; private set; }
public void Increment() { Value++; }
}
static class Program
{
static void Main()
{
Foo(new S(), new C(), new C(), new C());
}
static void Foo<TAny, TClass, TClass2, TClass3>(TAny x, TClass y, TClass2 z, TClass3 t)
where TAny : IIncrementable // Can be a value type
where TClass : class, IIncrementable, new() // Always a reference type because of explicit 'class' constraint
where TClass2 : IIncrementable // Always a reference type because used as a constraint for TClass3
where TClass3 : TClass, TClass2 // Always a reference type because its constraint TClass cannot be an interface (because of the new() constraint), object, System.ValueType or System.Enum (because of the IIncrementable constraint)
{
({|Simplify:(IIncrementable)x|}).Increment(); // Necessary cast
({|Simplify:(IIncrementable)y|}).Increment(); // Unnecessary Cast - OK
({|Simplify:(IIncrementable)z|}).Increment(); // Necessary cast
({|Simplify:(IIncrementable)t|}).Increment(); // Necessary cast
Console.WriteLine(x.Value);
Console.WriteLine(y.Value);
Console.WriteLine(z.Value);
Console.WriteLine(t.Value);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
interface IIncrementable
{
int Value { get; }
void Increment();
}
struct S : IIncrementable
{
public int Value { get; private set; }
public void Increment() { Value++; }
}
class C : IIncrementable
{
public int Value { get; private set; }
public void Increment() { Value++; }
}
static class Program
{
static void Main()
{
Foo(new S(), new C(), new C(), new C());
}
static void Foo<TAny, TClass, TClass2, TClass3>(TAny x, TClass y, TClass2 z, TClass3 t)
where TAny : IIncrementable // Can be a value type
where TClass : class, IIncrementable, new() // Always a reference type because of explicit 'class' constraint
where TClass2 : IIncrementable // Always a reference type because used as a constraint for TClass3
where TClass3 : TClass, TClass2 // Always a reference type because its constraint TClass cannot be an interface (because of the new() constraint), object, System.ValueType or System.Enum (because of the IIncrementable constraint)
{
((IIncrementable)x).Increment(); // Necessary cast
(y).Increment(); // Unnecessary Cast - OK
((IIncrementable)z).Increment(); // Necessary cast
((IIncrementable)t).Increment(); // Necessary cast
Console.WriteLine(x.Value);
Console.WriteLine(y.Value);
Console.WriteLine(z.Value);
Console.WriteLine(t.Value);
}
}
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529877)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub Csharp_Remove_UnnecessarySealedClassToInterfaceCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C : IDisposable
{
public void Dispose() { }
}
sealed class D : C
{
static void Main()
{
D s = new D();
({|Simplify:(IDisposable)s|}).Dispose();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C : IDisposable
{
public void Dispose() { }
}
sealed class D : C
{
static void Main()
{
D s = new D();
(s).Dispose();
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529887)>
Public Sub Csharp_Remove_UnnecessaryReadOnlyValueTypeToInterfaceCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
interface IIncrementable
{
int Value { get; }
void Increment();
}
struct S : IIncrementable
{
public int Value { get; private set; }
public void Increment() { Value++; }
static readonly S s = new S();
static void Main()
{
// Note: readonly modifier guarantees that a copy of a value type is always made before modification, so a boxing is not observable.
({|Simplify:(IIncrementable)s|}).Increment();
Console.WriteLine(s.Value);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
interface IIncrementable
{
int Value { get; }
void Increment();
}
struct S : IIncrementable
{
public int Value { get; private set; }
public void Increment() { Value++; }
static readonly S s = new S();
static void Main()
{
// Note: readonly modifier guarantees that a copy of a value type is always made before modification, so a boxing is not observable.
(s).Increment();
Console.WriteLine(s.Value);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529888)>
Public Sub Csharp_Remove_UnnecessaryObjectCreationToInterfaceCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
struct Y : IDisposable
{
public void Dispose() { }
}
class X : IDisposable
{
static void Main()
{
({|Simplify:(IDisposable)new X()|}).Dispose();
({|Simplify:(IDisposable)new Y()|}).Dispose();
}
public void Dispose() { }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
struct Y : IDisposable
{
public void Dispose() { }
}
class X : IDisposable
{
static void Main()
{
(new X()).Dispose();
(new Y()).Dispose();
}
public void Dispose() { }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529912)>
Public Sub Csharp_Remove_UnnecessaryEffectivelySealedClassToInterfaceCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C : IDisposable
{
private C() { }
public void Dispose() { }
static void Main()
{
var x = new C();
({|Simplify:(IDisposable)x|}).Dispose();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C : IDisposable
{
private C() { }
public void Dispose() { }
static void Main()
{
var x = new C();
(x).Dispose();
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529912)>
Public Sub Csharp_Remove_UnnecessaryEffectivelySealedClassToInterfaceCast2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C : IDisposable
{
private C() { }
public void Dispose() { }
static void Main()
{
var x = new C();
({|Simplify:(IDisposable)x|}).Dispose();
}
}
struct D : IDisposable
{
public void Dispose() { }
}
class E: C, IDisposable
{
public void Dispose() { }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C : IDisposable
{
private C() { }
public void Dispose() { }
static void Main()
{
var x = new C();
(x).Dispose();
}
}
struct D : IDisposable
{
public void Dispose() { }
}
class E: C, IDisposable
{
public void Dispose() { }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529912)>
Public Sub Csharp_Remove_UnnecessaryEffectivelySealedClassToInterfaceCast3()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C : IDisposable
{
private C() { }
public void Dispose() { }
static void Main()
{
var x = new C();
({|Simplify:(IDisposable)x|}).Dispose();
}
interface I { }
}
struct D : IDisposable
{
public void Dispose() { }
}
class E: C, IDisposable
{
public void Dispose() { }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C : IDisposable
{
private C() { }
public void Dispose() { }
static void Main()
{
var x = new C();
(x).Dispose();
}
interface I { }
}
struct D : IDisposable
{
public void Dispose() { }
}
class E: C, IDisposable
{
public void Dispose() { }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529913)>
Public Sub Csharp_Remove_UnnecessaryEffectivelySealedClassToInterface4()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
class C : IDisposable
{
public void Dispose() { }
static void Main()
{
var x = new C();
({|Simplify:(IDisposable)x|}).Dispose();
}
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class A
{
class C : IDisposable
{
public void Dispose() { }
static void Main()
{
var x = new C();
(x).Dispose();
}
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529913)>
Public Sub Csharp_Remove_UnnecessaryEffectivelySealedClassToInterfaceCast5()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
class C : IDisposable
{
public void Dispose() { }
static void Main()
{
var x = new C();
({|Simplify:(IDisposable)x|}).Dispose();
}
}
}
struct D : IDisposable
{
public void Dispose() { }
}
class E: C, IDisposable
{
public void Dispose() { }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class A
{
class C : IDisposable
{
public void Dispose() { }
static void Main()
{
var x = new C();
(x).Dispose();
}
}
}
struct D : IDisposable
{
public void Dispose() { }
}
class E: C, IDisposable
{
public void Dispose() { }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529912)>
Public Sub Csharp_DoNotRemove_NecessaryClassToInterfaceCast()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C : IDisposable
{
private C() { }
public void Dispose() { }
static void Main()
{
var x = new C();
({|Simplify:(IDisposable)x|}).Dispose();
}
class E: C, IDisposable
{
public void Dispose() { }
}
}
struct D : IDisposable
{
public void Dispose() { }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C : IDisposable
{
private C() { }
public void Dispose() { }
static void Main()
{
var x = new C();
((IDisposable)x).Dispose();
}
class E: C, IDisposable
{
public void Dispose() { }
}
}
struct D : IDisposable
{
public void Dispose() { }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529913)>
Public Sub Csharp_DoNotRemove_NecessaryClassToInterfaceCast2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
class C : IDisposable
{
public void Dispose() { }
static void Main()
{
var x = new C();
({|Simplify:(IDisposable)x|}).Dispose();
}
class E: C, IDisposable
{
public void Dispose() { }
}
}
}
struct D : IDisposable
{
public void Dispose() { }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class A
{
class C : IDisposable
{
public void Dispose() { }
static void Main()
{
var x = new C();
((IDisposable)x).Dispose();
}
class E: C, IDisposable
{
public void Dispose() { }
}
}
}
struct D : IDisposable
{
public void Dispose() { }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529889)>
Public Sub Csharp_Remove_UnnecessaryCastFromImmutableValueTypeToInterface()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main()
{
int x = 1;
var y = ({|Simplify:(IComparable<int>)x|}).CompareTo(0);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main()
{
int x = 1;
var y = (x).CompareTo(0);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_DoNotRemove_NecessaryCastInDelegateCreationExpression()
' Note: Removing the cast changes the lambda parameter type and invocation method symbol.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>({|Simplify:(Action<object>)(y => y.Foo())|})(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>((Action<object>)(y => y.Foo()))(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_DoNotRemove_NecessaryCastInDelegateCreationExpression2()
' Note: Removing the cast changes the lambda parameter type and invocation method symbol.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>({|Simplify:(Action<object>)((y) => { y.Foo(); })|})(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>((Action<object>)((y) => { y.Foo(); }))(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_Remove_UnnecessaryCastInDelegateCreationExpression3()
' Note: Removing the cast changes the lambda parameter type, but doesn't change the semantics of the lambda body.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>({|Simplify:(Action<object>)(y => Foo(1))|})(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>((y => Foo(1)))(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_Remove_UnnecessaryCastInDelegateCreationExpression4()
' Note: Removing the cast changes the lambda parameter type, but doesn't change the semantics of the lambda body.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>({|Simplify:(Action<object>)((y) => { string x = y; x.Foo(); })|})(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>(((y) => { string x = y; x.Foo(); }))(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_DoNotRemove_NecessaryCastInDelegateCreationExpression5()
' Note: Removing the cast changes the lambda parameter type and hence changes the inferred type of lambda local "x".
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>({|Simplify:(Action<object>)((y) => { var x = y; x.Foo(); })|})(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string>((Action<object>)((y) => { var x = y; x.Foo(); }))(null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_DoNotRemove_NecessaryCastInDelegateCreationExpression6()
' Note: Removing the cast changes the parameter type of lambda parameter "z"
' and changes the method symbol Foo invoked in the lambda body.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<object, string>({|Simplify:(Action<object, object>)((y, z) => { z.Foo(); })|})(null, null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<object, string>((Action<object, object>)((y, z) => { z.Foo(); }))(null, null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_Remove_UnnecessaryCastInDelegateCreationExpression7()
' Note: Removing the cast changes the parameter type of lambda parameter "z"
' but not that of parameter "y" and hence the semantics of the lambda body aren't changed.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string, object>({|Simplify:(Action<object, object>)((y, z) => { object x = y; z.Foo(); })|})(null, null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string, object>(((y, z) => { object x = y; z.Foo(); }))(null, null);
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_DoNotRemove_NecessaryCastInDelegateCreationExpression8()
' Note: Removing the cast changes the parameter type of lambda parameter "y"
' and changes the built in operator invoked for "y + z".
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string, string>({|Simplify:(Action<object, string>)((y, z) => { Console.WriteLine(y + z); })|})("Hi", "Hello");
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string, string>((Action<object, string>)((y, z) => { Console.WriteLine(y + z); }))("Hi", "Hello");
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub Csharp_DoNotRemove_NecessaryCastInDelegateCreationExpression9()
' Note: Removing the cast changes the parameter type of lambda parameter "y"
' and changes the semantics of nested lambda body.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string, string>({|Simplify:(Action<object, string>)((y, z) =>
{ Action<string> a = (w) => { y.Foo(); }; }
)|})("Hi", "Hello");
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
static class Program
{
static void Main()
{
new Action<string, string>((Action<object, string>)((y, z) =>
{ Action<string> a = (w) => { y.Foo(); }; }
))("Hi", "Hello");
}
static void Foo(this object x) { Console.WriteLine(1); }
static void Foo(this string x) { Console.WriteLine(2); }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529982)>
Public Sub Csharp_Remove_UnnecessaryExplicitCastForLambdaExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main(string[] args)
{
Func<Exception> f = {|Simplify:(Func<Exception>)(() => new ArgumentException())|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class Program
{
static void Main(string[] args)
{
Func<Exception> f = (() => new ArgumentException());
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(835671)>
Public Sub Csharp_DoNotRemove_NecessaryCastInUnaryExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void Method(double d)
{
Method({|Simplify:(int)d|}); // not flagged because the cast changes the semantics
Method(-{|Simplify:(int)d|}); // should not be flagged
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class C
{
void Method(double d)
{
Method((int)d); // not flagged because the cast changes the semantics
Method(-(int)d); // should not be flagged
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(838107)>
Public Sub Csharp_DoNotRemove_NecessaryCastInPointerExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
unsafe class C
{
internal static uint F(byte* ptr)
{
return *{|Simplify:(ushort*)ptr|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
unsafe class C
{
internal static uint F(byte* ptr)
{
return *(ushort*)ptr;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(835537)>
Public Sub Csharp_DoNotRemove_NecessaryExplicitCastInReferenceComparision()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
void F()
{
object x = string.Intern("Hi!");
bool wasInterned = {|Simplify:(object)x|} == "Hi!";
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
void F()
{
object x = string.Intern("Hi!");
bool wasInterned = (object)x == "Hi!";
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(835537)>
Public Sub Csharp_DoNotRemove_NecessaryExplicitCastInReferenceComparision2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
void F()
{
object x = string.Intern("Hi!");
bool wasInterned = x == {|Simplify:(object)"Hi!"|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
void F()
{
object x = string.Intern("Hi!");
bool wasInterned = x == (object)"Hi!";
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(835537)>
Public Sub Csharp_Remove_UnnecessaryExplicitCastInReferenceComparision()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
void F()
{
object x = string.Intern("Hi!");
bool wasInterned = {|Simplify:(object)x|} == (object)"Hi!";
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
void F()
{
object x = string.Intern("Hi!");
bool wasInterned = x == (object)"Hi!";
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(835537), WorkItem(902508)>
Public Sub Csharp_Remove_UnnecessaryExplicitCastInReferenceComparision2()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
public class Class1
{
void F(Class1 c)
{
if ({|Simplify:(Class1)c|} != null)
{
var x = {|Simplify:(Class1)c|};
}
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
public class Class1
{
void F(Class1 c)
{
if (c != null)
{
var x = c;
}
}
}]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529858)>
Public Sub Csharp_Remove_UnnecessaryCastFromEnumTypeToUnderlyingType()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C
{
static void Main()
{
DayOfWeek x = DayOfWeek.Monday;
if ({|Simplify:(int)x|} == 0) { }
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C
{
static void Main()
{
DayOfWeek x = DayOfWeek.Monday;
if (x == 0) { }
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(889341)>
Public Sub CSharp_DoNotRemove_CastInErroneousCode()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M()
{
object x = null;
M({|Simplify:(string)x|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class C
{
void M()
{
object x = null;
M((string)x);
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(870550)>
Public Sub CSharp_Remove_CastThatBreaksParentSyntaxUnlessParenthesized()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
static void Main()
{
var x = 1;
object y = x;
int i = 1;
Foo(x < {|Simplify:(int)i|}, x > (int)y); // Remove Unnecessary Cast
}
static void Foo(bool a, bool b) { }
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
static void Main()
{
var x = 1;
object y = x;
int i = 1;
Foo((x < i), x > (int)y); // Remove Unnecessary Cast
}
static void Foo(bool a, bool b) { }
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529787)>
Public Sub CSharp_DoNotRemove_RequiredCastInCollectionInitializer()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class X : List<int>
{
void Add(object x) { Console.WriteLine(1); }
void Add(string x) { Console.WriteLine(2); }
static void Main()
{
var z = new X { {|Simplify:(object)""|} };
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
using System.Collections.Generic;
class X : List<int>
{
void Add(object x) { Console.WriteLine(1); }
void Add(string x) { Console.WriteLine(2); }
static void Main()
{
var z = new X { (object)"" };
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(923296)>
Public Sub CSharp_DoNotRemove_RequiredCastInIfCondition()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
public static int Main()
{
object a = false, b = false;
if ({|Simplify:(bool)a|})
{
return {|Simplify:(bool)b|} ? 0 : 1;
}
else if ({|Simplify:(bool)b|})
{
return 2;
}
else
{
return 3;
}
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
public static int Main()
{
object a = false, b = false;
if ((bool)a)
{
return (bool)b ? 0 : 1;
}
else if ((bool)b)
{
return 2;
}
else
{
return 3;
}
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(995855)>
Public Sub CSharp_DoNotRemove_RequiredCastInConditionalExpression()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C
{
static void Main(string[] args)
{
byte s = 0;
int i = 0;
s += i == 0 ? {|Simplify:(byte)0|} : {|Simplify:(byte)0|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C
{
static void Main(string[] args)
{
byte s = 0;
int i = 0;
s += i == 0 ? (byte)0 : (byte)0;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(995855)>
Public Sub CSharp_DoNotRemove_RequiredCastInConversion()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class C
{
static void Main(string[] args)
{
byte b = 254;
ushort u = (ushort){|Simplify:(sbyte)b|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
using System;
class C
{
static void Main(string[] args)
{
byte b = 254;
ushort u = (ushort)(sbyte)b;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(1007371)>
Public Sub CSharp_Remove_UnncessaryCastAndParens()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
bool F(string a, string b)
{
return {|Simplify:(object)a == (object)b ? true : false|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
bool F(string a, string b)
{
return a == (object)b ? true : false;
}
}
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(1067214)>
Public Sub CSharp_Remove_UnncessaryCastInExpressionBody_Property()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
public int X => {|Simplify:(int)0|};
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
public int X => 0;
}
]]>
</code>
Test(input, expected)
End SUb
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(1067214)>
Public Sub CSharp_Remove_UnncessaryCastInExpressionBody_Method()
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
public int X() => {|Simplify:(int)0|};
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
class Program
{
public int X() => 0;
}
]]>
</code>
Test(input, expected)
End Sub
#End Region
#Region "Visual Basic tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DontRemove_IntToObj_Overloads1()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub Foo(o As Object)
End Sub
Sub Foo(i As Integer)
End Sub
Sub Test()
Foo({|Simplify:CObj(1)|})
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Class C
Sub Foo(o As Object)
End Sub
Sub Foo(i As Integer)
End Sub
Sub Test()
Foo(CObj(1))
End Sub
End Class
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DontRemove_IntToLng_Overloads2()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub Foo(l As Long)
End Sub
Sub Foo(i As Integer)
End Sub
Sub Test()
Foo({|Simplify:CLng(1)|})
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Class C
Sub Foo(l As Long)
End Sub
Sub Foo(i As Integer)
End Sub
Sub Test()
Foo(CLng(1))
End Sub
End Class
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_IntToByte()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim b As Integer = {|Simplify:CByte(0)|}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Class C
Sub M()
Dim b As Integer = 0
End Sub
End Class
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_IntToByteToInferred()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim b = {|Simplify:CByte(0)|}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Class C
Sub M()
Dim b = CByte(0)
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(530080)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_ForEachExpression()
' Cast removal will change the GetEnumerator method being invoked.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class Program
Shared Sub Main()
Dim o As Object = {"1"}
For Each i In {|Simplify:CType(o, Array)|}
Console.WriteLine(i)
Next
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class Program
Shared Sub Main()
Dim o As Object = {"1"}
For Each i In CType(o, Array)
Console.WriteLine(i)
Next
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(529954)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_InsideCollectionInitializer()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Class Program
Shared Sub Main()
Dim col = New List(Of Double) From {{|Simplify:CType(1, Double)|}}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Imports System.Collections.Generic
Class Program
Shared Sub Main()
Dim col = New List(Of Double) From {1}
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(530083)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_InsideThrowStatement()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Shared Sub Main()
Dim ex As Object = New Exception()
Throw {|Simplify:DirectCast(ex, Exception)|}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class C
Shared Sub Main()
Dim ex As Object = New Exception()
Throw DirectCast(ex, Exception)
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(530083)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_InsideThrowStatement()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Shared Sub Main()
Dim ex = New ArgumentException()
Throw {|Simplify:DirectCast(ex, Exception)|}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class C
Shared Sub Main()
Dim ex = New ArgumentException()
Throw ex
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(530083)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_InsideThrowStatement2()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Shared Sub Main()
Dim ex As Exception = New ArgumentException()
Throw {|Simplify:DirectCast(ex, ArgumentException)|}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class C
Shared Sub Main()
Dim ex As Exception = New ArgumentException()
Throw ex
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(530931)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_InsideLateBoundInvocation()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict Off
Option Infer On
Imports System
Module M
Sub Main()
Try
Dim x = 1
Foo({|Simplify:CObj(x)|})
Catch
Console.WriteLine("Catch")
End Try
End Sub
Sub Foo(Of T, S)(x As Func(Of T))
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Option Strict Off
Option Infer On
Imports System
Module M
Sub Main()
Try
Dim x = 1
Foo(CObj(x))
Catch
Console.WriteLine("Catch")
End Try
End Sub
Sub Foo(Of T, S)(x As Func(Of T))
End Sub
End Module
</code>
Test(input, expected)
End Sub
<WorkItem(604316)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_RequiredDefaultValueConversionToDate()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class X
Sub Foo(Optional x As Object = {|Simplify:CDate(Nothing)|})
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class X
Sub Foo(Optional x As Object = CDate(Nothing))
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(604316)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_RequiredDefaultValueConversionToNumericType()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class X
Sub Foo(Optional x As Object = {|Simplify:CInt(Nothing)|})
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class X
Sub Foo(Optional x As Object = CInt(Nothing))
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(604316)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_RequiredDefaultValueConversionToBooleanType()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class X
Sub Foo()
Dim x As Object = {|Simplify:DirectCast(Nothing, Boolean)|}
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class X
Sub Foo()
Dim x As Object = DirectCast(Nothing, Boolean)
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(604316)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_UnnecessaryDefaultValueConversionToDate()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class X
Sub Foo(Optional x As DateTime = {|Simplify:CDate(Nothing)|})
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class X
Sub Foo(Optional x As DateTime = Nothing)
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(604316)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_UnnecessaryDefaultValueConversionToNumericType()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class X
Sub Foo(Optional x As Double = {|Simplify:CInt(Nothing)|})
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class X
Sub Foo(Optional x As Double = Nothing)
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(604316)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_UnnecessaryDefaultValueConversionToBooleanType()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class X
Sub Foo()
Dim x As Integer = {|Simplify:DirectCast(Nothing, Boolean)|}
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class X
Sub Foo()
Dim x As Integer = Nothing
Console.WriteLine(x)
End Sub
Public Shared Sub Main()
Dim y = New X()
y.Foo()
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(529956)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_NeccessaryCastInForEachExpression()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.Collections
Class C
Private Shared Sub Main()
For Each x As C In {|Simplify:DirectCast(New String() {Nothing}, IEnumerable)|}
Console.WriteLine(x Is Nothing)
Next
End Sub
Public Shared Widening Operator CType(s As String) As C
Return New C()
End Operator
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System.Collections
Class C
Private Shared Sub Main()
For Each x As C In DirectCast(New String() {Nothing}, IEnumerable)
Console.WriteLine(x Is Nothing)
Next
End Sub
Public Shared Widening Operator CType(s As String) As C
Return New C()
End Operator
End Class
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529968)>
Public Sub VisualBasic_DoNotRemove_NeccessaryCastForParamsArgument()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class A
Public Shared Sub Main()
Foo({|Simplify:DirectCast(New A(), Object)|})
End Sub
Private Shared Sub Foo(ParamArray x As Object())
Console.WriteLine(x Is Nothing)
End Sub
Public Shared Widening Operator CType(a As A) As Object()
Return Nothing
End Operator
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class A
Public Shared Sub Main()
Foo(DirectCast(New A(), Object))
End Sub
Private Shared Sub Foo(ParamArray x As Object())
Console.WriteLine(x Is Nothing)
End Sub
Public Shared Widening Operator CType(a As A) As Object()
Return Nothing
End Operator
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529968)>
Public Sub VisualBasic_Remove_UnneccessaryCastsForParamsArguments()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class A
Public Shared Sub Main()
Foo({|Simplify:DirectCast(New A(), Object)|}, {|Simplify:DirectCast(New A(), Object)|})
End Sub
Private Shared Sub Foo(ParamArray x As Object())
Console.WriteLine(x Is Nothing)
End Sub
Public Shared Widening Operator CType(a As A) As Object()
Return Nothing
End Operator
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class A
Public Shared Sub Main()
Foo(New A(), New A())
End Sub
Private Shared Sub Foo(ParamArray x As Object())
Console.WriteLine(x Is Nothing)
End Sub
Public Shared Widening Operator CType(a As A) As Object()
Return Nothing
End Operator
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529985)>
Public Sub VisualBasic_DoNotRemove_NeccessaryCastInMemberAccessExpression()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class C
Private Shared Sub Main()
Dim c As C = Nothing
Console.WriteLine({|Simplify:CType(c, Attribute)|}.GetType())
End Sub
Public Shared Widening Operator CType(x As C) As Attribute
Return New ObsoleteAttribute()
End Operator
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class C
Private Shared Sub Main()
Dim c As C = Nothing
Console.WriteLine(CType(c, Attribute).GetType())
End Sub
Public Shared Widening Operator CType(x As C) As Attribute
Return New ObsoleteAttribute()
End Operator
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529844)>
Public Sub VisualBasic_DoNotRemove_NeccessaryCastInNumericConversion()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Private Shared Sub Main()
Dim x As Integer = Integer.MaxValue
Dim y As Double = x
Dim z As Double = {|Simplify:CSng(x)|}
Console.WriteLine(x)
Console.WriteLine(y)
Console.WriteLine(z)
Console.WriteLine(y = z)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class Program
Private Shared Sub Main()
Dim x As Integer = Integer.MaxValue
Dim y As Double = x
Dim z As Double = CSng(x)
Console.WriteLine(x)
Console.WriteLine(y)
Console.WriteLine(z)
Console.WriteLine(y = z)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529851)>
Public Sub VisualBasic_Remove_TryCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Interface I1
Sub foo()
End Interface
Module Program
Sub Main(args As String())
End Sub
Sub foo(o As I1)
Dim i As I1 = {|Simplify:TryCast(o, I1)|}
End Sub
End Module
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Interface I1
Sub foo()
End Interface
Module Program
Sub Main(args As String())
End Sub
Sub foo(o As I1)
Dim i As I1 = o
End Sub
End Module
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529919)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_DelegateVarianceConversions()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class Program
Private Shared Sub Main()
Dim a As Action(Of Object) = AddressOf Console.WriteLine
Dim b As Action(Of String) = {|Simplify:DirectCast(a, Action (Of String))|}
Call {|Simplify:DirectCast(a, Action(Of String))|}("A")
Call {|Simplify:DirectCast(a, Action(Of String))|}.Invoke("A")
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Class Program
Private Shared Sub Main()
Dim a As Action(Of Object) = AddressOf Console.WriteLine
Dim b As Action(Of String) = a
Call a("A")
Call a.Invoke("A")
End Sub
End Class
</code>
Test(input, expected)
End Sub
<WorkItem(529884)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_ParamDefaultValueNegativeZero()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Interface I
Sub Foo(Optional x As Double = +0.0)
End Interface
NotInheritable Class C
Implements I
Public Sub Foo(Optional x As Double = -0.0) Implements I.Foo
Console.WriteLine(1 / x > 0)
End Sub
Private Shared Sub Main()
{|Simplify:DirectCast(New C(), I)|}.Foo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Interface I
Sub Foo(Optional x As Double = +0.0)
End Interface
NotInheritable Class C
Implements I
Public Sub Foo(Optional x As Double = -0.0) Implements I.Foo
Console.WriteLine(1 / x > 0)
End Sub
Private Shared Sub Main()
DirectCast(New C(), I).Foo()
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529884)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_ParamDefaultValueNegativeZero2()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Interface I
Sub Foo(Optional x As Double = -(-0.0))
End Interface
NotInheritable Class C
Implements I
Public Sub Foo(Optional x As Double = -0.0) Implements I.Foo
Console.WriteLine(1 / x > 0)
End Sub
Private Shared Sub Main()
{|Simplify:DirectCast(New C(), I)|}.Foo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Interface I
Sub Foo(Optional x As Double = -(-0.0))
End Interface
NotInheritable Class C
Implements I
Public Sub Foo(Optional x As Double = -0.0) Implements I.Foo
Console.WriteLine(1 / x > 0)
End Sub
Private Shared Sub Main()
DirectCast(New C(), I).Foo()
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529884), WorkItem(529927)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_ParamDefaultValueZero()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Interface I
Sub Foo(Optional x As Double = +0.0)
End Interface
NotInheritable Class C
Implements I
Public Sub Foo(Optional x As Double = -(-0.0)) Implements I.Foo
Console.WriteLine(1 / x > 0)
End Sub
Private Shared Sub Main()
Call {|Simplify:DirectCast(New C(), I)|}.Foo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Interface I
Sub Foo(Optional x As Double = +0.0)
End Interface
NotInheritable Class C
Implements I
Public Sub Foo(Optional x As Double = -(-0.0)) Implements I.Foo
Console.WriteLine(1 / x > 0)
End Sub
Private Shared Sub Main()
Call New C().Foo()
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529791)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_UnnecessaryImplicitNullableCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class X
Private Shared Sub Foo()
Dim x As Object = {|Simplify:DirectCast(Nothing, String)|}
Dim y As Object = {|Simplify:CType(Nothing, System.Nullable(Of Integer))|}
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Class X
Private Shared Sub Foo()
Dim x As Object = Nothing
Dim y As Object = Nothing
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529963)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_NecessaryCastInQueryForCollectionRangeVariable()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Try
Dim q1 As IEnumerable(Of Object) = From i In {1} Select o = {|Simplify:CObj(i)|}
Catch
Finally
End Try
End Sub
End Module
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Option Strict On
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Try
Dim q1 As IEnumerable(Of Object) = From i In {1} Select o = CObj(i)
Catch
Finally
End Try
End Sub
End Module
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(530072)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_DoNotRemove_NecessaryCastInQueryForSelectMethod()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><) As String
Return "Long"
End Function
Function [Select](x As Func(Of Integer, Integer)) As String
Return "Integer"
End Function
Shared Sub Main()
Dim query = From i In New C() Select {|Simplify:CType(i, Long)|}
Console.WriteLine(query)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><) As String
Return "Long"
End Function
Function [Select](x As Func(Of Integer, Integer)) As String
Return "Integer"
End Function
Shared Sub Main()
Dim query = From i In New C() Select CType(i, Long)
Console.WriteLine(query)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529831)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_UnnecessaryInterfaceCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Interface IIncrementable
ReadOnly Property Value() As Integer
Sub Increment()
End Interface
Structure S
Implements IIncrementable
Public Property Value() As Integer Implements IIncrementable.Value
Get
Return m_Value
End Get
Private Set
m_Value = Value
End Set
End Property
Private m_Value As Integer
Public Sub Increment() Implements IIncrementable.Increment
Value += 1
End Sub
End Structure
Class C
Implements IIncrementable
Public Property Value() As Integer Implements IIncrementable.Value
Get
Return m_Value
End Get
Private Set
m_Value = Value
End Set
End Property
Private m_Value As Integer
Public Sub Increment() Implements IIncrementable.Increment
Value += 1
End Sub
End Class
NotInheritable Class Program
Private Sub New()
End Sub
Private Shared Sub Main()
Foo(New S(), New C(), New C(), New C())
End Sub
Private Shared Sub Foo(Of TAny As IIncrementable, TClass As {Class, IIncrementable, New}, TClass2 As IIncrementable, TClass3 As {TClass, TClass2})(x As TAny, y As TClass, z As TClass2, t As TClass3)
Call {|Simplify:DirectCast(x, IIncrementable)|}.Increment() ' Necessary cast
Call {|Simplify:DirectCast(y, IIncrementable)|}.Increment() ' Unnecessary Cast - OK
Call {|Simplify:DirectCast(z, IIncrementable)|}.Increment() ' Necessary cast
Call {|Simplify:DirectCast(t, IIncrementable)|}.Increment() ' Necessary cast
Console.WriteLine(x.Value)
Console.WriteLine(y.Value)
Console.WriteLine(z.Value)
Console.WriteLine(t.Value)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Interface IIncrementable
ReadOnly Property Value() As Integer
Sub Increment()
End Interface
Structure S
Implements IIncrementable
Public Property Value() As Integer Implements IIncrementable.Value
Get
Return m_Value
End Get
Private Set
m_Value = Value
End Set
End Property
Private m_Value As Integer
Public Sub Increment() Implements IIncrementable.Increment
Value += 1
End Sub
End Structure
Class C
Implements IIncrementable
Public Property Value() As Integer Implements IIncrementable.Value
Get
Return m_Value
End Get
Private Set
m_Value = Value
End Set
End Property
Private m_Value As Integer
Public Sub Increment() Implements IIncrementable.Increment
Value += 1
End Sub
End Class
NotInheritable Class Program
Private Sub New()
End Sub
Private Shared Sub Main()
Foo(New S(), New C(), New C(), New C())
End Sub
Private Shared Sub Foo(Of TAny As IIncrementable, TClass As {Class, IIncrementable, New}, TClass2 As IIncrementable, TClass3 As {TClass, TClass2})(x As TAny, y As TClass, z As TClass2, t As TClass3)
Call DirectCast(x, IIncrementable).Increment() ' Necessary cast
Call y.Increment() ' Unnecessary Cast - OK
Call DirectCast(z, IIncrementable).Increment() ' Necessary cast
Call DirectCast(t, IIncrementable).Increment() ' Necessary cast
Console.WriteLine(x.Value)
Console.WriteLine(y.Value)
Console.WriteLine(z.Value)
Console.WriteLine(t.Value)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<WorkItem(529877)>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Sub VisualBasic_Remove_UnnecessarySealedClassToInterfaceCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
NotInheritable Class D
Inherits C
Private Shared Sub Main()
Dim s As New D()
Call {|Simplify:DirectCast(s, IDisposable)|}.Dispose()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
NotInheritable Class D
Inherits C
Private Shared Sub Main()
Dim s As New D()
Call s.Dispose()
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529887)>
Public Sub VisualBasic_Remove_UnnecessaryReadOnlyValueTypeToInterfaceCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Interface IIncrementable
ReadOnly Property Value() As Integer
Sub Increment()
End Interface
Structure S
Implements IIncrementable
Public Property Value() As Integer Implements IIncrementable.Value
Get
Return m_Value
End Get
Private Set
m_Value = Value
End Set
End Property
Private m_Value As Integer
Public Sub Increment() Implements IIncrementable.Increment
Value += 1
End Sub
Shared ReadOnly s As New S()
Private Shared Sub Main()
' Note: readonly modifier guarantees that a copy of a value type is always made before modification, so a boxing is not observable.
Call {|Simplify:DirectCast(s, IIncrementable)|}.Increment()
Console.WriteLine(s.Value)
End Sub
End Structure
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Interface IIncrementable
ReadOnly Property Value() As Integer
Sub Increment()
End Interface
Structure S
Implements IIncrementable
Public Property Value() As Integer Implements IIncrementable.Value
Get
Return m_Value
End Get
Private Set
m_Value = Value
End Set
End Property
Private m_Value As Integer
Public Sub Increment() Implements IIncrementable.Increment
Value += 1
End Sub
Shared ReadOnly s As New S()
Private Shared Sub Main()
' Note: readonly modifier guarantees that a copy of a value type is always made before modification, so a boxing is not observable.
Call s.Increment()
Console.WriteLine(s.Value)
End Sub
End Structure
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529888)>
Public Sub VisualBasic_Remove_UnnecessaryObjectCreationToInterfaceCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Structure Y
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
Class X
Implements IDisposable
Private Shared Sub Main()
Call {|Simplify:DirectCast(New X(), IDisposable)|}.Dispose()
Call {|Simplify:DirectCast(New Y(), IDisposable)|}.Dispose()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Structure Y
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
Class X
Implements IDisposable
Private Shared Sub Main()
Call New X().Dispose()
Call New Y().Dispose()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529912)>
Public Sub VisualBasic_Remove_UnnecessaryEffectivelySealedClassToInterfaceCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class C
Implements IDisposable
Private Sub New()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call {|Simplify:DirectCast(x, IDisposable)|}.Dispose()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class C
Implements IDisposable
Private Sub New()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call x.Dispose()
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529912)>
Public Sub VisualBasic_Remove_UnnecessaryEffectivelySealedClassToInterfaceCast2()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class C
Implements IDisposable
Private Sub New()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call {|Simplify:DirectCast(x, IDisposable)|}.Dispose()
End Sub
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
Class E
Inherits C
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class C
Implements IDisposable
Private Sub New()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call x.Dispose()
End Sub
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
Class E
Inherits C
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529912)>
Public Sub VisualBasic_Remove_UnnecessaryEffectivelySealedClassToInterfaceCast3()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class C
Implements IDisposable
Private Sub New()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call {|Simplify:DirectCast(x, IDisposable)|}.Dispose()
End Sub
Private Interface I
End Interface
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
Class E
Inherits C
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class C
Implements IDisposable
Private Sub New()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call x.Dispose()
End Sub
Private Interface I
End Interface
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
Class E
Inherits C
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529913)>
Public Sub VisualBasic_Remove_UnnecessaryEffectivelySealedClassToInterface4()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class A
Private Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call {|Simplify:DirectCast(x, IDisposable)|}.Dispose()
End Sub
End Class
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class A
Private Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call x.Dispose()
End Sub
End Class
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529913)>
Public Sub VisualBasic_Remove_UnnecessaryEffectivelySealedClassToInterfaceCast5()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class A
Private Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call {|Simplify:DirectCast(x, IDisposable)|}.Dispose()
End Sub
End Class
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
Class E
Inherits C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class A
Private Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call x.Dispose()
End Sub
End Class
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
Class E
Inherits C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529912)>
Public Sub VisualBasic_DoNotRemove_NecessaryClassToInterfaceCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class C
Implements IDisposable
Private Sub New()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call {|Simplify:DirectCast(x, IDisposable)|}.Dispose()
End Sub
Private Class E
Inherits C
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class C
Implements IDisposable
Private Sub New()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call DirectCast(x, IDisposable).Dispose()
End Sub
Private Class E
Inherits C
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529913)>
Public Sub VisualBasic_DoNotRemove_NecessaryClassToInterfaceCast2()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class A
Private Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call {|Simplify:DirectCast(x, IDisposable)|}.Dispose()
End Sub
Private Class E
Inherits C
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Class
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Class A
Private Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Shared Sub Main()
Dim x = New C()
Call DirectCast(x, IDisposable).Dispose()
End Sub
Private Class E
Inherits C
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Class
End Class
Structure D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529889)>
Public Sub VisualBasic_Remove_UnnecessaryCastFromImmutableValueTypeToInterface()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Private Shared Sub Main()
Dim x As Integer = 1
Dim y = {|Simplify:DirectCast(x, IComparable(Of Integer))|}.CompareTo(0)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Class Program
Private Shared Sub Main()
Dim x As Integer = 1
Dim y = x.CompareTo(0)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529927)>
Public Sub VisualBasic_Remove_UnnecessaryCastFromImplementingClassToInterface()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Interface I1
Sub Foo()
End Interface
Class M
Implements I1
Shared Sub Main()
Call {|Simplify:CType(New M(), I1)|}.Foo()
End Sub
Public Sub Foo() Implements I1.Foo
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Interface I1
Sub Foo()
End Interface
Class M
Implements I1
Shared Sub Main()
Call New M().Foo()
End Sub
Public Sub Foo() Implements I1.Foo
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_DoNotRemove_NecessaryCastInDelegateCreationExpression()
' Note: Removing the cast changes the lambda parameter type and invocation method symbol.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Sub(y) Call New X().Foo(y)), Action(Of Object))|}, Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast(DirectCast((Sub(y) Call New X().Foo(y)), Action(Of Object)), Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_DoNotRemove_NecessaryCastInDelegateCreationExpression2()
' Note: Removing the cast changes the lambda parameter type and invocation method symbol.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Sub(y)
Call New X().Foo(y)
End Sub), Action(Of Object))|}, Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast(DirectCast((Sub(y)
Call New X().Foo(y)
End Sub), Action(Of Object)), Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_Remove_UnnecessaryCastInDelegateCreationExpression3()
' Note: Removing the cast changes the lambda parameter type, but doesn't change the semantics of the lambda body.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Sub(y) Call New X().Foo(1)), Action(Of Object))|}, Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast((Sub(y) Call New X().Foo(1)), Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_Remove_UnnecessaryCastInDelegateCreationExpression4()
' Note: Removing the cast changes the lambda parameter type, but doesn't change the semantics of the lambda body.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Sub(y)
Call New X().Foo(1)
End Sub), Action(Of Object))|}, Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast((Sub(y)
Call New X().Foo(1)
End Sub), Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_DoNotRemove_NecessaryCastInDelegateCreationExpression5()
' Note: Removing the cast changes the lambda parameter type and hence changes the inferred type of lambda local "x".
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Sub(y)
Dim x = y
Call New X().Foo(x)
End Sub), Action(Of Object))|}, Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast(DirectCast((Sub(y)
Dim x = y
Call New X().Foo(x)
End Sub), Action(Of Object)), Action(Of String))("HI")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_DoNotRemove_NecessaryCastInDelegateCreationExpression6()
' Note: Removing the cast changes the parameter type of lambda parameter "z"
' and changes the method symbol Foo invoked in the lambda body.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Sub(y, z)
Call New X().Foo(z)
End Sub), Action(Of Object, Object))|}, Action(Of String, String))("HI", "HELLO")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast(DirectCast((Sub(y, z)
Call New X().Foo(z)
End Sub), Action(Of Object, Object)), Action(Of String, String))("HI", "HELLO")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_Remove_UnnecessaryCastInDelegateCreationExpression7()
' Note: Removing the cast changes the parameter type of lambda parameter "z"
' but not that of parameter "y" and hence the semantics of the lambda body aren't changed.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Sub(y, z)
Dim x as Object = y
Call New X().Foo(z)
End Sub), Action(Of Object, Object))|}, Action(Of String, Object))("HI", "HELLO")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast((Sub(y, z)
Dim x as Object = y
Call New X().Foo(z)
End Sub), Action(Of String, Object))("HI", "HELLO")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_Remove_UnnecessaryCastInDelegateCreationExpression8()
' Note: Removing the cast changes the parameter type of lambda parameter "y"
' but doesn't change the built in operator invoked for "y + z".
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Sub(y, z)
Console.WriteLine(y + z)
End Sub), Action(Of Object, Object))|}, Action(Of Object, String))("HI", "HELLO")
End Sub
End Module
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast((Sub(y, z)
Console.WriteLine(y + z)
End Sub), Action(Of Object, String))("HI", "HELLO")
End Sub
End Module
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529988)>
Public Sub VisualBasic_DoNotRemove_NecessaryCastInDelegateCreationExpression9()
' Note: Removing the cast changes the parameter type of lambda parameter "y"
' and changes the semantics of nested lambda body.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast({|Simplify:DirectCast((Function(y, z)
Dim a = (Sub(w)
Call New X().Foo(y)
End Sub)
Return a
End Function), Action(Of Object, Object))|}, Action(Of String, Object))("HI", "HELLO")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Module Program
Public Sub Main()
Call DirectCast(DirectCast((Function(y, z)
Dim a = (Sub(w)
Call New X().Foo(y)
End Sub)
Return a
End Function), Action(Of Object, Object)), Action(Of String, Object))("HI", "HELLO")
End Sub
End Module
Public Class X
Public Sub Foo(x As Object)
Console.WriteLine(1)
End Sub
Public Sub Foo(x As String)
Console.WriteLine(2)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529982)>
Public Sub VisualBasic_Remove_UnnecessaryExplicitCastForLambdaExpression_DirectCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Module Module1
Sub Main()
Dim l As Func(Of Exception) = {|Simplify:DirectCast(Function()
Return New ArgumentException
End Function, Func(Of ArgumentException))|}
End Sub
End Module
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Option Strict On
Imports System
Module Module1
Sub Main()
Dim l As Func(Of Exception) = Function()
Return New ArgumentException
End Function
End Sub
End Module
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529982)>
Public Sub VisualBasic_Remove_UnnecessaryExplicitCastForLambdaExpression_TryCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Module Module1
Sub Main()
Dim l As Func(Of Exception) = {|Simplify:TryCast(Function()
Return New ArgumentException
End Function, Func(Of ArgumentException))|}
End Sub
End Module
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Option Strict On
Imports System
Module Module1
Sub Main()
Dim l As Func(Of Exception) = Function()
Return New ArgumentException
End Function
End Sub
End Module
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(680657)>
Public Sub VisualBasic_Remove_UnnecessaryCastWithinAsNewExpression()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Public Class X
Dim field As New X({|Simplify:DirectCast(0, Integer)|})
Property prop As New X({|Simplify:DirectCast(0, Integer)|})
Public Sub New(i As Integer)
Dim local As New X({|Simplify:DirectCast(0, Integer)|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Public Class X
Dim field As New X(0)
Property prop As New X(0)
Public Sub New(i As Integer)
Dim local As New X(0)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(835671)>
Public Sub VisualBasic_DoNotRemove_NecessaryCastInUnaryExpression()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
Private Sub Method(d As Double)
Method({|Simplify:CInt(d)|}) ' not flagged because the cast changes the semantics
Method(-{|Simplify:CInt(d)|}) ' should not be flagged
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Class C
Private Sub Method(d As Double)
Method(CInt(d)) ' not flagged because the cast changes the semantics
Method(-CInt(d)) ' should not be flagged
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(889341)>
Public Sub VisualBasic_DoNotRemove_CastInErroneousCode()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
Private Sub M()
Dim x As Object = Nothing
M({|Simplify:DirectCast(x, String)|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Class C
Private Sub M()
Dim x As Object = Nothing
M(DirectCast(x, String))
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(529787)>
Public Sub VisualBasic_DoNotRemove_RequiredCastInCollectionInitializer()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Imports System.Collections.Generic
Class X
Inherits List(Of Integer)
Private Overloads Sub Add(x As Object)
Console.WriteLine(1)
End Sub
Private Overloads Sub Add(x As String)
Console.WriteLine(2)
End Sub
Private Shared Sub Main()
Dim z = New X() From { {|Simplify:DirectCast("", Object)|} }
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Imports System
Imports System.Collections.Generic
Class X
Inherits List(Of Integer)
Private Overloads Sub Add(x As Object)
Console.WriteLine(1)
End Sub
Private Overloads Sub Add(x As String)
Console.WriteLine(2)
End Sub
Private Shared Sub Main()
Dim z = New X() From { DirectCast("", Object) }
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(995855)>
Public Sub VisualBasic_Remove_UnncessaryCastInTernaryExpression()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
Private Shared Sub Main(args As String())
Dim s As Byte = 0
Dim i As Integer = 0
s += If(i = 0, {|Simplify:CByte(0)|}, {|Simplify:CByte(0)|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Class C
Private Shared Sub Main(args As String())
Dim s As Byte = 0
Dim i As Integer = 0
s += If(i = 0, 0, 0)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(1031406)>
Public Sub VisualBasic_DoNotRemove_NecessaryTryCast()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class Program
Sub Main(args As String())
Dim p As Object = 0
Console.Write({|Simplify:TryCast(p, String)|} IsNot Nothing)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<code><![CDATA[
Class Program
Sub Main(args As String())
Dim p As Object = 0
Console.Write(TryCast(p, String) IsNot Nothing)
End Sub
End Class
]]>
</code>
Test(input, expected)
End Sub
#End Region
End Class
End Namespace
|
mono/roslyn
|
src/EditorFeatures/Test2/Simplification/CastSimplificationTests.vb
|
Visual Basic
|
apache-2.0
| 147,857
|
' 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 FieldDeclarationOutlinerTests
Inherits AbstractVisualBasicSyntaxNodeOutlinerTests(Of FieldDeclarationSyntax)
Friend Overrides Function CreateOutliner() As AbstractSyntaxOutliner
Return New FieldDeclarationOutliner()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestVariableMemberDeclarationWithComments() As Task
Const code = "
Class C
{|span:'Hello
'World|}
Dim $$x As Integer
End Class
"
Await VerifyRegionsAsync(code,
Region("span", "' Hello ...", autoCollapse:=True))
End Function
End Class
End Namespace
|
ericfe-ms/roslyn
|
src/EditorFeatures/VisualBasicTest/Outlining/FieldDeclarationOutlinerTests.vb
|
Visual Basic
|
apache-2.0
| 1,131
|
#If _MyType <> "Empty" Then
Namespace My
''' <summary>
''' Module used to define the properties that are available in the My Namespace for Web projects.
''' </summary>
''' <remarks></remarks>
<Global.Microsoft.VisualBasic.HideModuleName()> _
Module MyWebExtension
Private s_Computer As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.Devices.ServerComputer)
Private s_User As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.ApplicationServices.WebUser)
Private s_Log As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.Logging.AspLog)
Private s_Application As New ThreadSafeObjectProvider(Of MyApplication)
''' <summary>
''' Returns information about the current application.
''' </summary>
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
Friend ReadOnly Property Application() As MyApplication
Get
Return s_Application.GetInstance()
End Get
End Property
''' <summary>
''' Returns information about the host computer.
''' </summary>
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
Friend ReadOnly Property Computer() As Global.Microsoft.VisualBasic.Devices.ServerComputer
Get
Return s_Computer.GetInstance()
End Get
End Property
''' <summary>
''' Returns information for the current Web user.
''' </summary>
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
Friend ReadOnly Property User() As Global.Microsoft.VisualBasic.ApplicationServices.WebUser
Get
Return s_User.GetInstance()
End Get
End Property
''' <summary>
''' Returns Request object.
''' </summary>
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
<Global.System.ComponentModel.Design.HelpKeyword("My.Request")> _
Friend ReadOnly Property Request() As Global.System.Web.HttpRequest
<Global.System.Diagnostics.DebuggerHidden()> _
Get
Dim CurrentContext As Global.System.Web.HttpContext = Global.System.Web.HttpContext.Current
If CurrentContext IsNot Nothing Then
Return CurrentContext.Request
End If
Return Nothing
End Get
End Property
''' <summary>
''' Returns Response object.
''' </summary>
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
<Global.System.ComponentModel.Design.HelpKeyword("My.Response")> _
Friend ReadOnly Property Response() As Global.System.Web.HttpResponse
<Global.System.Diagnostics.DebuggerHidden()> _
Get
Dim CurrentContext As Global.System.Web.HttpContext = Global.System.Web.HttpContext.Current
If CurrentContext IsNot Nothing Then
Return CurrentContext.Response
End If
Return Nothing
End Get
End Property
''' <summary>
''' Returns the Asp log object.
''' </summary>
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
Friend ReadOnly Property Log() As Global.Microsoft.VisualBasic.Logging.AspLog
<Global.System.Diagnostics.DebuggerHidden()> _
Get
Return s_Log.GetInstance()
End Get
End Property
''' <summary>
''' Provides access to WebServices added to this project.
''' </summary>
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
<Global.System.ComponentModel.Design.HelpKeyword("My.WebServices")> _
Friend ReadOnly Property WebServices() As MyWebServices
<Global.System.Diagnostics.DebuggerHidden()> _
Get
Return m_MyWebServicesObjectProvider.GetInstance()
End Get
End Property
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _
<Global.Microsoft.VisualBasic.MyGroupCollection("System.Web.Services.Protocols.SoapHttpClientProtocol", "Create__Instance__", "Dispose__Instance__", "")> _
<Global.System.Runtime.CompilerServices.CompilerGenerated()> _
Friend NotInheritable Class MyWebServices
<Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _
Public Overrides Function Equals(ByVal o As Object) As Boolean
Return MyBase.Equals(o)
End Function
<Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode
End Function
<Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _
Friend Overloads Function [GetType]() As Global.System.Type
Return GetType(MyWebServices)
End Function
<Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _
Public Overrides Function ToString() As String
Return MyBase.ToString
End Function
<Global.System.Diagnostics.DebuggerHidden()> _
Private Shared Function Create__Instance__(Of T As {New})(ByVal instance As T) As T
If instance Is Nothing Then
Return New T()
Else
Return instance
End If
End Function
<Global.System.Diagnostics.DebuggerHidden()> _
Private Sub Dispose__Instance__(Of T)(ByRef instance As T)
instance = Nothing
End Sub
<Global.System.Diagnostics.DebuggerHidden()> _
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _
Public Sub New()
MyBase.New()
End Sub
End Class
<Global.System.Runtime.CompilerServices.CompilerGenerated()> Private ReadOnly m_MyWebServicesObjectProvider As New ThreadSafeObjectProvider(Of MyWebServices)
End Module
<Global.System.Runtime.CompilerServices.CompilerGenerated(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> Partial Friend Class MyApplication
Inherits Global.Microsoft.VisualBasic.ApplicationServices.ApplicationBase
End Class
End Namespace
#End If
|
WillSams/CustomerOrders-NancyFX-VB
|
src/My Project/MyExtensions/MyWebExtension.vb
|
Visual Basic
|
apache-2.0
| 7,464
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.