Search is not available for this dataset
text
stringlengths
0
1.63M
Imports System.Configuration Partial Friend NotInheritable Class TestInfo #Region " DEVICE INFORMATION " ''' <summary> Gets the auto zero settings. </summary> ''' <value> The auto zero settings. </value> Public Shared ReadOnly Property AutoZero As Integer Get Return Convert.ToInt32(ConfigurationManager.AppSettings(NameOf(TestInfo.AutoZero))) End Get End Property ''' <summary> Gets the Sense Function settings. </summary> ''' <value> The Sense Function settings. </value> Public Shared ReadOnly Property SenseFunction As Integer Get Return Convert.ToInt32(ConfigurationManager.AppSettings(NameOf(TestInfo.SenseFunction))) End Get End Property ''' <summary> Gets the power line cycles settings. </summary> ''' <value> The power line cycles settings. </value> Public Shared ReadOnly Property PowerLineCycles As Double Get Return Convert.ToInt32(ConfigurationManager.AppSettings(NameOf(TestInfo.PowerLineCycles))) End Get End Property ''' <summary> Gets the math mode settings. </summary> ''' <value> The math mode settings. </value> Public Shared ReadOnly Property MathMode As Integer Get Return Convert.ToInt32(ConfigurationManager.AppSettings(NameOf(TestInfo.MathMode))) End Get End Property ''' <summary> Gets the store mathematics register. </summary> ''' <value> The store mathematics register. </value> Public Shared ReadOnly Property StoreMathRegister As Integer Get Return Convert.ToInt32(ConfigurationManager.AppSettings(NameOf(TestInfo.StoreMathRegister))) End Get End Property ''' <summary> Gets the store math value settings. </summary> ''' <value> The store math value settings. </value> Public Shared ReadOnly Property StoreMathValue As Double Get Return Convert.ToInt32(ConfigurationManager.AppSettings(NameOf(TestInfo.StoreMathValue))) End Get End Property #End Region End Class
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports System.Xml.Linq Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenWinMdDelegates Inherits BasicTestBase ''' <summary> ''' When the output type is .winmdobj, delegate types shouldn't output Begin/End invoke ''' members. ''' </summary> <Fact()> Public Sub SimpleDelegateMembersTest() Dim libSrc = <compilation> <file name="c.vb"> <![CDATA[ Namespace Test Public Delegate Sub SubDelegate() End Namespace]]> </file> </compilation> Dim getValidator = Function(expectedMembers As String()) Return Sub(m As ModuleSymbol) Dim actualMembers = m.GlobalNamespace.GetMember(Of NamespaceSymbol)("Test"). GetMember(Of NamedTypeSymbol)("SubDelegate").GetMembers().ToArray() AssertEx.SetEqual((From s In actualMembers Select s.Name), expectedMembers) End Sub End Function Dim verify = Sub(winmd As Boolean, expected As String()) Dim validator = getValidator(expected) ' We should see the same members from both source and metadata Dim verifier = CompileAndVerify( libSrc, sourceSymbolValidator:=validator, symbolValidator:=validator, options:=If(winmd, TestOptions.ReleaseWinMD, TestOptions.ReleaseDll)) verifier.VerifyDiagnostics() End Sub ' Test winmd verify(True, New String() { WellKnownMemberNames.InstanceConstructorName, WellKnownMemberNames.DelegateInvokeName}) ' Test normal verify(False, New String() { WellKnownMemberNames.InstanceConstructorName, WellKnownMemberNames.DelegateInvokeName, WellKnownMemberNames.DelegateBeginInvokeName, WellKnownMemberNames.DelegateEndInvokeName}) End Sub <Fact()> Public Sub AnonymousDelegate() Dim src = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub S() Dim x = Function(y As Integer) y End Sub Public F = Function(x As Integer) x End Class]]> </file> </compilation> Dim srcValidator = Sub(m As ModuleSymbol) Dim comp = m.DeclaringCompilation Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of ModifiedIdentifierSyntax).First() Dim nodeSymbol = DirectCast(model.GetDeclaredSymbol(node), LocalSymbol).Type Assert.True(nodeSymbol.IsAnonymousType) AssertEx.SetEqual((From member In nodeSymbol.GetMembers() Select member.Name), {WellKnownMemberNames.InstanceConstructorName, "Invoke"}) End Sub Dim mdValidator = Sub(m As ModuleSymbol) Dim members = m.GlobalNamespace End Sub Dim verifier = CompileAndVerify( src, sourceSymbolValidator:=srcValidator, symbolValidator:=mdValidator, options:=TestOptions.ReleaseWinMD) End Sub <Fact()> Public Sub TestAllDelegates() Dim winRtDelegateLibrarySrc = <compilation> <file name="WinRTDelegateLibrary.vb"><![CDATA[ Namespace WinRTDelegateLibrary Public Structure S1 End Structure Public Enum E1 alpha = 1 bravo charlie delta End Enum Public Class C1 End Class Public Interface I1 End Interface ''' ''' These are the interesting types ''' Public Delegate Sub SubSubDelegate() Public Delegate Function intintDelegate(a As Integer) As Integer Public Delegate Function structDelegate(s As S1) As S1 Public Delegate Function enumDelegate(e As E1) As E1 Public Delegate Function classDelegate(c As C1) As C1 Public Delegate Function stringDelegate(s As string) As string Public Delegate Function decimalDelegate(d As Decimal) As Decimal Public Delegate Function WinRTDelegate(d As SubSubDelegate) as SubSubDelegate Public Delegate Function nullableDelegate(a As Integer?) As Integer? Public Delegate Function genericDelegate(Of T)(t As T) As T Public Delegate Function genericDelegate2(Of T As New)(t As T) As T Public Delegate Function genericDelegate3(Of T As Class)(t As T) As T Public Delegate Function genericDelegate4(Of T As Structure)(t As T) As T Public Delegate Function genericDelegate5(Of T As I1)(t As T) As T Public Delegate Function arrayDelegate(arr as Integer()) As Integer() Public Delegate Function interfaceDelegate(i As I1) As I1 End Namespace ]]> </file> </compilation> ' We need the 4.5 refs here Dim coreRefs45 = { MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929} Dim winRtDelegateLibrary = CompilationUtils.CreateEmptyCompilationWithReferences( winRtDelegateLibrarySrc, references:=coreRefs45, options:=TestOptions.ReleaseWinMD).EmitToImageReference() Dim fileElement = winRtDelegateLibrarySrc.<file>.Single() fileElement.ReplaceAttributes(New XAttribute("name", "NonWinRTDelegateLibrary.vb")) fileElement.SetValue(fileElement.Value.Replace("WinRTDelegateLibrary", "NonWinRTDelegateLibrary")) Dim nonWinRtDelegateLibrary = CompilationUtils.CreateEmptyCompilationWithReferences( winRtDelegateLibrarySrc, references:=coreRefs45, options:=TestOptions.ReleaseDll).EmitToImageReference() Dim allDelegates = <compilation> <file name="c.vb"> <![CDATA[ Imports WinRT = WinRTDelegateLibrary Imports NonWinRT = NonWinRTDelegateLibrary Class Test Public d001 As WinRT.SubSubDelegate Public d101 As NonWinRT.SubSubDelegate Public d002 As WinRT.intintDelegate Public d102 As NonWinRT.intintDelegate Public d003 As WinRT.structDelegate Public d103 As NonWinRT.structDelegate Public d004 As WinRT.enumDelegate Public d104 As NonWinRT.enumDelegate Public d005 As WinRT.classDelegate Public d105 As NonWinRT.classDelegate Public d006 As WinRT.stringDelegate Public d106 As NonWinRT.stringDelegate Public d007 As WinRT.decimalDelegate Public d107 As NonWinRT.decimalDelegate Public d008 As WinRT.WinRTDelegate Public d108 As NonWinRT.WinRTDelegate Public d009 As WinRT.nullableDelegate Public d109 As NonWinRT.nullableDelegate Public d010 As WinRT.genericDelegate(Of Single) Public d110 As NonWinRT.genericDelegate(Of Single) Public d011 As WinRT.genericDelegate2(Of Object) Public d111 As NonWinRT.genericDelegate2(Of Object) Public d012 As WinRT.genericDelegate3(Of WinRT.C1) Public d112 As NonWinRT.genericDelegate3(Of NonWinRT.C1) Public d013 As WinRT.genericDelegate4(Of WinRT.S1) Public d113 As NonWinRT.genericDelegate4(Of NonWinRT.S1) Public d014 As WinRT.genericDelegate5(Of WinRT.I1) Public d114 As NonWinRT.genericDelegate5(Of NonWinRT.I1) Public d015 As WinRT.arrayDelegate Public d115 As NonWinRT.arrayDelegate Public d016 As WinRT.interfaceDelegate Public d116 As NonWinRT.interfaceDelegate End Class ]]> </file> </compilation> Dim isWinRt = Function(field As FieldSymbol) Dim fieldType = field.Type If DirectCast(fieldType, Object) Is Nothing Then Return False End If If Not fieldType.IsDelegateType() Then Return False End If For Each member In fieldType.GetMembers() Select Case member.Name Case WellKnownMemberNames.DelegateBeginInvokeName Case WellKnownMemberNames.DelegateEndInvokeName Return False End Select Next Return True End Function Dim validator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) Dim type = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim fields = type.GetMembers() For Each field In fields Dim fieldSymbol = TryCast(field, FieldSymbol) If DirectCast(fieldSymbol, Object) IsNot Nothing Then If fieldSymbol.Name.Contains("d1") Then Assert.False(isWinRt(fieldSymbol)) Else Assert.True(isWinRt(fieldSymbol)) End If End If Next End Sub Dim verifier = CompileAndVerify( allDelegates, references:={ winRtDelegateLibrary, nonWinRtDelegateLibrary}, symbolValidator:=validator) verifier.VerifyDiagnostics() End Sub End Class End Namespace
Imports GalaSoft.MvvmLight Namespace ViewModels Public Class Blank7ViewModel Inherits ViewModelBase Public Sub New() End Sub End Class End Namespace
'*******************************************************************************************' ' ' ' Download Free Evaluation Version From: https://bytescout.com/download/web-installer ' ' ' ' Also available as Web API! Free Trial Sign Up: https://secure.bytescout.com/users/sign_up ' ' ' ' Copyright © 2017-2018 ByteScout Inc. All rights reserved. ' ' http://www.bytescout.com ' ' ' '*******************************************************************************************' Imports Bytescout.PDFRenderer Class Program Friend Shared Sub Main(args As String()) ' Create an instance of Bytescout.PDFRenderer.RasterRenderer object and register it. Dim renderer As New RasterRenderer() renderer.RegistrationName = "demo" renderer.RegistrationKey = "demo" ' Load PDF document. renderer.LoadDocumentFromFile("multipage.pdf") Dim renderingOptions As New RenderingOptions() ' Set pixel format to 1-bit renderingOptions.ImageBitsPerPixel = ImageBitsPerPixel.BPP1 For i As Integer = 0 To renderer.GetPageCount() - 1 ' Save 1-bit image to file renderer.Save("image" & i & ".bmp", RasterImageFormat.BMP, i, 200, renderingOptions) Next ' Cleanup renderer.Dispose() ' Open the first output file in default image viewer. System.Diagnostics.Process.Start("image0.bmp") End Sub End Class
' Copyright (c) Microsoft Open Technologies, Inc. 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.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' A wrapper around RootSingleNamespaceDeclaration. The namespace declaration ''' is evaluated lazily to avoid evaluating the namespace and associated SyntaxTree ''' for embedded syntax trees before we can determine whether the syntax tree is needed. ''' </summary> Friend NotInheritable Class DeclarationTableEntry Public ReadOnly Root As Lazy(Of RootSingleNamespaceDeclaration) Public ReadOnly IsEmbedded As Boolean Public Sub New(root As Lazy(Of RootSingleNamespaceDeclaration), isEmbedded As Boolean) Me.Root = root Me.IsEmbedded = isEmbedded End Sub End Class ''' <summary> ''' A declaration table is a device which keeps track of type and namespace declarations from ''' parse trees. It is optimized for the case where there is one set of declarations that stays ''' constant, and a specific root namespace declaration corresponding to the currently edited ''' file which is being added and removed repeatedly. It maintains a cache of information for ''' "merging" the root declarations into one big summary declaration; this cache is efficiently ''' re-used provided that the pattern of adds and removes is as we expect. ''' </summary> Partial Friend Class DeclarationTable Public Shared ReadOnly Empty As DeclarationTable = New DeclarationTable( ImmutableHashSet.Create(Of DeclarationTableEntry)(), latestLazyRootDeclaration:=Nothing, cache:=Nothing) ' All our root declarations. We split these so we can separate out the unchanging 'older' ' declarations from the constantly changing 'latest' declaration. Private ReadOnly _allOlderRootDeclarations As ImmutableHashSet(Of DeclarationTableEntry) Private ReadOnly _latestLazyRootDeclaration As DeclarationTableEntry ' The cache of computed values for the old declarations. Private ReadOnly _cache As Cache ' The lazily computed total merged declaration. Private ReadOnly _mergedRoot As Lazy(Of MergedNamespaceDeclaration) Private ReadOnly _typeNames As Lazy(Of ICollection(Of String)) Private ReadOnly _namespaceNames As Lazy(Of ICollection(Of String)) Private ReadOnly _referenceDirectives As Lazy(Of ICollection(Of ReferenceDirective)) ' Stores diagnostics related to #r directives Private ReadOnly _referenceDirectiveDiagnostics As Lazy(Of ICollection(Of Diagnostic)) Private _lazyAllRootDeclarations As ImmutableArray(Of RootSingleNamespaceDeclaration) Private Sub New(allOlderRootDeclarations As ImmutableHashSet(Of DeclarationTableEntry), latestLazyRootDeclaration As DeclarationTableEntry, cache As Cache) Me._allOlderRootDeclarations = allOlderRootDeclarations Me._latestLazyRootDeclaration = latestLazyRootDeclaration Me._cache = If(cache, New Cache(Me)) Me._mergedRoot = New Lazy(Of MergedNamespaceDeclaration)(AddressOf GetMergedRoot) Me._typeNames = New Lazy(Of ICollection(Of String))(AddressOf GetMergedTypeNames) Me._namespaceNames = New Lazy(Of ICollection(Of String))(AddressOf GetMergedNamespaceNames) Me._referenceDirectives = New Lazy(Of ICollection(Of ReferenceDirective))(AddressOf GetMergedReferenceDirectives) Me._referenceDirectiveDiagnostics = New Lazy(Of ICollection(Of Diagnostic))(AddressOf GetMergedDiagnostics) End Sub Public Function AddRootDeclaration(lazyRootDeclaration As DeclarationTableEntry) As DeclarationTable ' We can only re-use the cache if we don't already have a 'latest' item for the decl ' table. If _latestLazyRootDeclaration Is Nothing Then Return New DeclarationTable(_allOlderRootDeclarations, lazyRootDeclaration, Me._cache) Else ' we already had a 'latest' item. This means we're hearing about a change to a ' different tree. Realize the old latest item, add it to the 'older' collection ' and don't reuse the cache. Return New DeclarationTable(_allOlderRootDeclarations.Add(_latestLazyRootDeclaration), lazyRootDeclaration, Cache:=Nothing) End If End Function Public Function RemoveRootDeclaration(lazyRootDeclaration As DeclarationTableEntry) As DeclarationTable ' We can only reuse the cache if we're removing the decl that was just added. If _latestLazyRootDeclaration Is lazyRootDeclaration Then Return New DeclarationTable(_allOlderRootDeclarations, latestLazyRootDeclaration:=Nothing, Cache:=Me._cache) Else ' We're removing a different tree than the latest one added. We need to realize the ' passed in root and remove that from our 'older' list. We also can't reuse the ' cache. ' ' Note: we can keep around the 'latestLazyRootDeclaration'. There's no need to ' realize it if we don't have to. Return New DeclarationTable(_allOlderRootDeclarations.Remove(lazyRootDeclaration), _latestLazyRootDeclaration, Cache:=Nothing) End If End Function Public Function AllRootNamespaces() As ImmutableArray(Of RootSingleNamespaceDeclaration) If _lazyAllRootDeclarations.IsDefault Then Dim builder = ArrayBuilder(Of RootSingleNamespaceDeclaration).GetInstance() GetOlderNamespaces(builder) Dim declOpt = GetLatestRootDeclarationIfAny(includeEmbedded:=True) If declOpt IsNot Nothing Then builder.Add(declOpt) End If ImmutableInterlocked.InterlockedInitialize(_lazyAllRootDeclarations, builder.ToImmutableAndFree()) End If Return _lazyAllRootDeclarations End Function Private Sub GetOlderNamespaces(builder As ArrayBuilder(Of RootSingleNamespaceDeclaration)) For Each olderRootDeclaration In _allOlderRootDeclarations Dim declOpt = olderRootDeclaration.Root.Value If declOpt IsNot Nothing Then builder.Add(declOpt) End If Next End Sub Private Function MergeOlderNamespaces() As MergedNamespaceDeclaration Dim builder = ArrayBuilder(Of RootSingleNamespaceDeclaration).GetInstance() GetOlderNamespaces(builder) Dim result = MergedNamespaceDeclaration.Create(builder) builder.Free() Return result End Function Private Function SelectManyFromOlderDeclarationsNoEmbedded(Of T)(selector As Func(Of RootSingleNamespaceDeclaration, ImmutableArray(Of T))) As ImmutableArray(Of T) Return _allOlderRootDeclarations.Where(Function(d) Not d.IsEmbedded AndAlso d.Root.Value IsNot Nothing).SelectMany(Function(d) selector(d.Root.Value)).AsImmutable() End Function #If False Then Public Function FindNamespace(ByVal name As String) As Declaration ' Linear search of contexts to find the first one with a ' namespace of this name. Return FindNamespaces(name).FirstOrDefault() End Function Public Function FindNamespaces(ByVal name As String) As IEnumerable(Of Declaration) ' Not optimized. Could build a memoizer for the old items in the set and re-use that memoizer across edits. Return From root In AllRootNamespaces(), ns In root.GetNamespaces(name) Select ns End Function Public Function FindType(ByVal name As String) As Declaration Return FindTypes(name).FirstOrDefault() End Function Public Function FindType(ByVal name As String, ByVal arity As Integer) As Declaration Return FindTypes(name, arity).FirstOrDefault() End Function Public Function FindTypes(ByVal name As String) As IEnumerable(Of Declaration) ' Not optimized. Could build a memoizer for the old items in the set and re-use that memoizer across edits. Return From root In AllRootNamespaces(), t In root.GetTypes(name) Select t End Function Public Function FindTypes(ByVal name As String, ByVal arity As Integer) As IEnumerable(Of Declaration) ' Linear search of root declarations to find one with a type of this name, ' and then linear filtering of results. Assumption here is that ' there will not be very many types of wrong arity but same name. ' Is this assumption valid? Consider types like Func, Tuple, and so on. Return From type In FindTypes(name) Where type.Arity = arity Select type End Function Public Function FindParent(ByVal name As String) As Declaration Debug.Assert(name IsNot Nothing) Return FindParents(name).FirstOrDefault() End Function ' Find all declarations which have a member of the given name. Public Function FindParents(ByVal name As String) As IEnumerable(Of Declaration) ' Not optimized. Could build a memoizer for the old items in the set and re-use that memoizer across edits. Return From root In AllRootNamespaces(), d In root.GetParents(name) Select d End Function Private Function AllParentsCore(ByVal context As RootDeclaration, ByVal firstParent As Declaration) As List(Of Declaration) Dim list As New List(Of Declaration) Dim parent As Declaration = firstParent While parent IsNot Nothing list.Add(parent) parent = context.GetParent(parent) End While Return list End Function Public Function AllParents(ByVal child As Declaration) As IEnumerable(Of Declaration) Dim parent As Declaration = Nothing ' Not optimized. Could build a memoizer for the old items in the set and re-use that memoizer across edits. For Each root In AllRootNamespaces() If root.TryGetParent(child, parent) Then Return AllParentsCore(root, parent) End If Next Debug.Fail("Someone is searching for a declaration that does not exist in this declaration table.") Return Enumerable.Empty(Of Declaration)() End Function #End If ' The merged-tree-reuse story goes like this. We have a "forest" of old declarations, and ' possibly a lone tree of new declarations. We construct a merged declaration by merging ' together everything in the forest. This we can re-use from edit to edit, provided that ' nothing is added to or removed from the forest. We construct a merged declaration from the ' lone tree if there is one. (The lone tree might have nodes inside it that need merging, if ' there are two halves of one partial class.) Once we have two merged trees, we construct ' the full merged tree by merging them both together. So, diagrammatically, we have: ' ' MergedRoot ' / \ ' old merged root new merged root ' / | | | \ \ ' old singles forest new single tree Private Function GetMergedRoot() As MergedNamespaceDeclaration Dim oldRoot = Me._cache.MergedRoot.Value Dim latestRoot = GetLatestRootDeclarationIfAny(includeEmbedded:=True) If latestRoot Is Nothing Then Return oldRoot ElseIf oldRoot Is Nothing Then Return MergedNamespaceDeclaration.Create(latestRoot) Else Return MergedNamespaceDeclaration.Create(oldRoot, latestRoot) End If End Function Private Function GetMergedTypeNames() As ICollection(Of String) Dim cachedTypeNames = Me._cache.TypeNames.Value Dim latestRoot = GetLatestRootDeclarationIfAny(includeEmbedded:=True) If latestRoot Is Nothing Then Return cachedTypeNames Else Return UnionCollection(Of String).Create(cachedTypeNames, GetTypeNames(latestRoot)) End If End Function Private Function GetMergedNamespaceNames() As ICollection(Of String) Dim cachedNamespaceNames = Me._cache.NamespaceNames.Value Dim latestRoot = GetLatestRootDeclarationIfAny(includeEmbedded:=True) If latestRoot Is Nothing Then Return cachedNamespaceNames Else Return UnionCollection(Of String).Create(cachedNamespaceNames, GetNamespaceNames(latestRoot)) End If End Function Private Function GetMergedReferenceDirectives() As ICollection(Of ReferenceDirective) Dim cachedReferenceDirectives = _cache.ReferenceDirectives.Value Dim latestRoot = GetLatestRootDeclarationIfAny(includeEmbedded:=False) If latestRoot Is Nothing Then Return cachedReferenceDirectives Else Return UnionCollection(Of ReferenceDirective).Create(cachedReferenceDirectives, latestRoot.ReferenceDirectives) End If End Function Private Function GetMergedDiagnostics() As ICollection(Of Diagnostic) Dim cachedDiagnostics = _cache.ReferenceDirectiveDiagnostics.Value Dim latestRoot = GetLatestRootDeclarationIfAny(includeEmbedded:=False) If latestRoot Is Nothing Then Return cachedDiagnostics Else Return UnionCollection(Of Diagnostic).Create(cachedDiagnostics, latestRoot.ReferenceDirectiveDiagnostics) End If End Function Private Function GetLatestRootDeclarationIfAny(includeEmbedded As Boolean) As RootSingleNamespaceDeclaration Return If((_latestLazyRootDeclaration IsNot Nothing) AndAlso (includeEmbedded OrElse Not _latestLazyRootDeclaration.IsEmbedded), _latestLazyRootDeclaration.Root.Value, Nothing) End Function Private Shared ReadOnly IsNamespacePredicate As Predicate(Of Declaration) = Function(d) d.Kind = DeclarationKind.Namespace Private Shared ReadOnly IsTypePredicate As Predicate(Of Declaration) = Function(d) d.Kind <> DeclarationKind.Namespace Private Shared Function GetTypeNames(declaration As Declaration) As ICollection(Of String) Return GetNames(declaration, IsTypePredicate) End Function Private Shared Function GetNamespaceNames(declaration As Declaration) As ICollection(Of String) Return GetNames(declaration, IsNamespacePredicate) End Function Private Shared Function GetNames(declaration As Declaration, predicate As Predicate(Of Declaration)) As ICollection(Of String) Dim result = New IdentifierCollection Dim stack = New Stack(Of Declaration)() stack.Push(declaration) While stack.Count > 0 Dim current = stack.Pop() If current Is Nothing Then Continue While End If If predicate(current) Then result.AddIdentifier(current.Name) End If For Each child In current.Children stack.Push(child) Next End While Return result.AsCaseInsensitiveCollection() End Function Public ReadOnly Property MergedRoot As MergedNamespaceDeclaration Get Return _mergedRoot.Value End Get End Property Public ReadOnly Property TypeNames As ICollection(Of String) Get Return _typeNames.Value End Get End Property Public ReadOnly Property NamespaceNames As ICollection(Of String) Get Return _namespaceNames.Value End Get End Property Public ReadOnly Property ReferenceDirectives As ICollection(Of ReferenceDirective) Get Return _referenceDirectives.Value End Get End Property Public ReadOnly Property ReferenceDirectiveDiagnostics As ICollection(Of Diagnostic) Get Return _referenceDirectiveDiagnostics.Value End Get End Property End Class End Namespace
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.Carecroft.My.MySettings Get Return Global.Carecroft.My.MySettings.Default End Get End Property End Module End Namespace
' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("The prefix for the member variables.")> _ Public Property MemberPrefix() As String Get Return m_MemberPrefix End Get Set(ByVal Value As String) m_MemberPrefix = Value End Set End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Namespace.")> _ Public Property ObjectNameSpace() As String Get Return m_NameSpace End Get Set(ByVal Value As String) m_NameSpace = Value End Set End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Camel-case member variables.")> _ Public Property CamelCaseMemberVars() As Boolean Get Return m_CamelCaseMemberVars End Get Set(ByVal Value As Boolean) m_CamelCaseMemberVars = Value End Set End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Use SmartDate instead of Date.")> _ Public Property UseSmartDate() As Boolean Get Return m_UseSmartDate End Get Set(ByVal Value As Boolean) m_UseSmartDate = Value End Set End Property ' ' The variable referenced in this property is defined in the CSLAHelper20.vb file ' <Category(" General Options - Business Object"), _ ' Description("Business object reacts to non-zero return values from stored procedures.")> _ ' Public Property UseSP_ReturnValue() As Boolean ' Get ' Return m_UseSP_ReturnValue ' End Get ' Set(ByVal Value As Boolean) ' m_UseSP_ReturnValue = Value ' End Set ' End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Generate Business Object Class.")> _ Public Property Generate_Class() As Boolean Get Return m_GenClass End Get Set(ByVal Value As Boolean) m_GenClass = Value End Set End Property ' ' The variable referenced in this property is defined in the CSLAHelper20.vb file ' <Category(" General Options - Business Object"), _ ' Description("Create an Exists method within the Business Object.")> _ ' Public Property Implement_Exists() As Boolean ' Get ' Return m_Implement_Exists ' End Get ' Set(ByVal Value As Boolean) ' m_Implement_Exists = Value ' End Set ' End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Allow anonymous access when no access controls exist.")> _ Public Property AnonymousAccess() As Boolean Get Return m_AnonymousAccess End Get Set(ByVal Value As Boolean) m_AnonymousAccess = Value End Set End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Add comments to generated code.")> _ Public Property AddComments() As Boolean Get Return m_AddComments End Get Set(ByVal Value As Boolean) m_AddComments = Value End Set End Property
Imports System.Collections.Generic Imports SDVariable = org.nd4j.autodiff.samediff.SDVariable Imports SameDiff = org.nd4j.autodiff.samediff.SameDiff Imports INDArray = org.nd4j.linalg.api.ndarray.INDArray Imports BaseReduceBoolOp = org.nd4j.linalg.api.ops.BaseReduceBoolOp ' ' * ****************************************************************************** ' * * ' * * ' * * This program and the accompanying materials are made available under the ' * * terms of the Apache License, Version 2.0 which is available at ' * * https://www.apache.org/licenses/LICENSE-2.0. ' * * ' * * See the NOTICE file distributed with this work for additional ' * * information regarding copyright ownership. ' * * 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. ' * * ' * * SPDX-License-Identifier: Apache-2.0 ' * ***************************************************************************** ' Namespace org.nd4j.linalg.api.ops.impl.reduce.bool Public Class All Inherits BaseReduceBoolOp Public Sub New(ByVal sameDiff As SameDiff, ByVal i_v As SDVariable, ByVal dimensions() As Integer) MyBase.New(sameDiff, i_v, dimensions) End Sub Public Sub New(ByVal x As INDArray, ByVal z As INDArray, ByVal keepDims As Boolean, ByVal dimensions() As Integer) MyBase.New(x, z, keepDims, dimensions) End Sub Public Sub New() End Sub Public Sub New(ByVal x As INDArray, ByVal y As INDArray, ByVal z As INDArray, ByVal keepDims As Boolean, ByVal dimensions() As Integer) MyBase.New(x, y, z, keepDims, dimensions) End Sub Public Sub New(ByVal x As INDArray) MyBase.New(x) End Sub Public Sub New(ByVal x As INDArray, ParamArray ByVal axis() As Integer) MyBase.New(x, axis) End Sub Public Sub New(ByVal x As INDArray, ByVal keepDims As Boolean, ParamArray ByVal dimensions() As Integer) MyBase.New(x, keepDims, dimensions) End Sub Public Sub New(ByVal x As INDArray, ByVal z As INDArray, ParamArray ByVal dimensions() As Integer) MyBase.New(x, z, dimensions) End Sub Public Sub New(ByVal x As INDArray, ByVal y As INDArray, ByVal z As INDArray, ParamArray ByVal dimensions() As Integer) MyBase.New(x, y, z, dimensions) End Sub Public Sub New(ByVal sameDiff As SameDiff) MyBase.New(sameDiff) End Sub Public Sub New(ByVal sameDiff As SameDiff, ByVal i_v As SDVariable, ByVal i_v2 As SDVariable, ByVal dimensions As SDVariable) MyBase.New(sameDiff, i_v, i_v2, dimensions) End Sub Public Sub New(ByVal sameDiff As SameDiff, ByVal i_v As SDVariable, ByVal i_v2 As SDVariable, ByVal dimensions() As Integer) MyBase.New(sameDiff, i_v, i_v2, dimensions) End Sub Public Sub New(ByVal sameDiff As SameDiff, ByVal i_v As SDVariable, ByVal keepDims As Boolean) MyBase.New(sameDiff, i_v, keepDims) End Sub Public Sub New(ByVal sameDiff As SameDiff, ByVal i_v As SDVariable, ByVal dimensions As SDVariable, ByVal keepDims As Boolean) MyBase.New(sameDiff, i_v, dimensions, keepDims) End Sub Public Sub New(ByVal sameDiff As SameDiff, ByVal i_v As SDVariable, ByVal i_v2 As SDVariable) MyBase.New(sameDiff, i_v, i_v2) End Sub Public Sub New(ByVal sameDiff As SameDiff, ByVal input As SDVariable, ByVal dimensions() As Integer, ByVal keepDims As Boolean) MyBase.New(sameDiff, input, dimensions, keepDims) End Sub Public Sub New(ByVal sameDiff As SameDiff, ByVal i_v As SDVariable, ByVal i_v2 As SDVariable, ByVal dimensions() As Integer, ByVal keepDims As Boolean) MyBase.New(sameDiff, i_v, i_v2, dimensions, keepDims) End Sub Public Sub New(ByVal sameDiff As SameDiff, ByVal i_v As SDVariable) MyBase.New(sameDiff, i_v) End Sub Public Overrides Function opNum() As Integer Return 1 End Function Public Overrides Function opName() As String Return "all" End Function Public Overrides Function doDiff(ByVal f1 As IList(Of SDVariable)) As IList(Of SDVariable) Return Collections.singletonList(sameDiff.zerosLike(arg())) End Function Public Overrides Function onnxName() As String Return "All" End Function Public Overrides Function tensorflowName() As String Return "All" End Function Public Overrides Function emptyValue() As Boolean Return True End Function End Class End Namespace
Imports System.IO Public Class ConvertForm Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click OpenFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*" OpenFileDialog1.FilterIndex = 1 OpenFileDialog1.FileName = "" OpenFileDialog1.RestoreDirectory = True Try LabelInfo.Text = "" LabelInfo.Tag = "" LabelInfo.Cursor = Cursors.Arrow DebugTextBox.Text = "" PARSER.STATS.Clear() If OpenFileDialog1.ShowDialog <> 1 Then Exit Sub Dim data As List(Of Class_SubLineBlock) = PARSER._TranslateToSource(OpenFileDialog1.FileName) Dim Debug As String = Nothing Dim FileIn As String = OpenFileDialog1.FileName Dim FileOut As String = OpenFileDialog1.FileName & ".out" UpdateStats() If Len(FileIn) > 5 Then If My.Computer.FileSystem.FileExists(FileOut) Then Kill(FileOut) End If Using sw As StreamWriter = New StreamWriter(FileOut, True, System.Text.Encoding.UTF8) For Each elem In data If elem.Err = True Then If Len(elem.Source) > 0 Then Debug = Debug & elem.Line.ToString & ": " & vbTab & elem.Source & vbNewLine Else If elem.Publish = True Then If elem.Ru = False Then sw.Write(elem.LeftString.sKey & "=" & elem.LeftString.sValue & vbCrLf) Else sw.Write(elem.RightString.sKey & "=" & elem.RightString.sValue & vbCrLf) End If End If End If Next sw.Close() End Using DebugTextBox.Text = Debug LabelInfo.Cursor = Cursors.Hand LabelInfo.Text = "Output file: " & FileOut LabelInfo.Tag = FileOut Catch ex As Exception MsgBox(ex.Message, vbCritical) End Try End Sub Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load UpdateStats() End Sub Sub UpdateStats() LabelInfo.Cursor = Cursors.Arrow ToolStripStatusLabel1.Text = "Source lines (not empty): " & PARSER.STATS.LinesIn ToolStripStatusLabel2.Text = "Verified lines: " & PARSER.STATS.LinesOut ToolStripStatusLabel3.Text = "Source lines with err: " & PARSER.STATS.LinesWithError End Sub Private Sub LabelInfo_Click(sender As Object, e As EventArgs) Handles LabelInfo.Click If LabelInfo.Tag <> "" Then Process.Start("explorer.exe", Path.GetDirectoryName(LabelInfo.Tag)) End If End Sub End Class
Public Class MultiContainerTest 'メニューが表示されたとき Dim ContextMenuStripBaseControl As Control Private Sub ContextMenuStripPublic_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ContextMenuStripPublic.Click Dim menu As ContextMenuStrip = DirectCast(sender, ContextMenuStrip) 'メニューが起動された時の対象コントロールを保持 ContextMenuStripBaseControl = DirectCast(menu.SourceControl, Control) End Sub Private Sub 左右分割ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 左右分割ToolStripMenuItem.Click Call Separate(ContextMenuStripBaseControl, False) End Sub Private Sub 上下分割ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 上下分割ToolStripMenuItem.Click Call Separate(ContextMenuStripBaseControl, True) End Sub Private Sub Separate(ByVal BaseControl As Control, ByVal IsHorizontal As Boolean) '新しいコンテナを追加 Dim NewContainer As New MultiContainer(BaseControl.Parent, IsHorizontal) NewContainer.Panel1.Controls.Add(BaseControl) Dim WrkPicBox As New PictureBox WrkPicBox.Dock = DockStyle.Fill WrkPicBox.ContextMenuStrip = ContextMenuStripPublic WrkPicBox.BackColor = Color.FromArgb(Rnd() * 255, Rnd() * 255, Rnd() * 255) NewContainer.Panel2.Controls.Add(WrkPicBox) End Sub Private Sub 削除ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 削除ToolStripMenuItem.Click Dim DeleteSideSplitterPanel As SplitterPanel '削除側のパネル DeleteSideSplitterPanel = DirectCast(ContextMenuStripBaseControl.Parent, SplitterPanel) Dim DeleteContainer As MultiContainer DeleteContainer = DirectCast(DeleteSideSplitterPanel.Parent, MultiContainer) Dim BaseControl As Control BaseControl = DirectCast(DeleteContainer.Parent, Control) 'Call DeleteSplitterPanel(DeleteContainer, BaseControl, DeleteSideSplitterPanel) Call DeleteContainer.Delete(BaseControl, DeleteSideSplitterPanel) End Sub 'Private Sub DeleteSplitterPanel(ByVal DeleteContainer As MultiContainer, ByVal BaseControl As Control, ByVal DeleteSideSplitterPanel As SplitterPanel) ' ' Dim RetentionSideSplitterPanel As SplitterPanel '保持側のパネル ' If DeleteContainer.Panel1 Is DeleteSideSplitterPanel Then ' RetentionSideSplitterPanel = DeleteContainer.Panel2 ' Else ' RetentionSideSplitterPanel = DeleteContainer.Panel1 ' End If ' ' For Each WrkCont As Control In RetentionSideSplitterPanel.Controls ' BaseControl.Controls.Add(WrkCont) ' Next ' DeleteContainer.Dispose() ' 'End Sub End Class
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Imports System.Collections.Immutable Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Runtime.InteropServices Imports System.Text Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_WellKnownAttributes Inherits BasicTestBase #Region "InteropAttributes Miscellaneous Tests" <Fact> Public Sub TestInteropAttributes01() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ComCompatibleVersion(1, 2, 3, 4)> <ComImport(), Guid("ABCDEF5D-2448-447A-B786-64682CBEF123")> <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> <TypeLibImportClass(GetType(Object)), TypeLibType(TypeLibTypeFlags.FAggregatable)> <BestFitMapping(False, ThrowOnUnmappableChar:=True)> Public Interface IFoo <AllowReversePInvokeCalls()> Sub DoSomething() <ComRegisterFunction()> Sub Register(o As Object) <ComUnregisterFunction()> Sub UnRegister() <TypeLibFunc(TypeLibFuncFlags.FDefaultBind)> Sub LibFunc() End Interface ]]> </file> </compilation> Dim attributeValidator = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) Dim assembly = m.ContainingAssembly Dim compilation = m.DeclaringCompilation Dim globalNS = If(compilation Is Nothing, assembly.CorLibrary.GlobalNamespace, compilation.GlobalNamespace) Dim sysNS = globalNS.GetMember(Of NamespaceSymbol)("System") Dim runtimeNS = DirectCast(sysNS.GetMember("Runtime"), NamespaceSymbol) Dim interopNS = DirectCast(runtimeNS.GetMember("InteropServices"), NamespaceSymbol) Dim comCompatibleSym As NamedTypeSymbol = interopNS.GetTypeMembers("ComCompatibleVersionAttribute").First() ' Assembly Dim attrs = assembly.GetAttributes(comCompatibleSym) Assert.Equal(1, attrs.Count) Dim attrSym = attrs.First() Assert.Equal("ComCompatibleVersionAttribute", attrSym.AttributeClass.Name) Assert.Equal(4, attrSym.CommonConstructorArguments.Length) Assert.Equal(0, attrSym.CommonNamedArguments.Length) Assert.Equal(3, attrSym.CommonConstructorArguments(2).Value) ' get expected attr symbol Dim guidSym = DirectCast(interopNS.GetTypeMember("GuidAttribute"), NamedTypeSymbol) Dim ciSym = DirectCast(interopNS.GetTypeMember("ComImportAttribute"), NamedTypeSymbol) Dim iTypeSym = DirectCast(interopNS.GetTypeMember("InterfaceTypeAttribute"), NamedTypeSymbol) Dim itCtor = DirectCast(iTypeSym.Constructors.First(), MethodSymbol) Dim tLibSym = DirectCast(interopNS.GetTypeMember("TypeLibImportClassAttribute"), NamedTypeSymbol) Dim tLTypeSym = DirectCast(interopNS.GetTypeMember("TypeLibTypeAttribute"), NamedTypeSymbol) Dim bfmSym = DirectCast(interopNS.GetTypeMember("BestFitMappingAttribute"), NamedTypeSymbol) ' IFoo Dim ifoo = DirectCast(m.GlobalNamespace.GetTypeMember("IFoo"), NamedTypeSymbol) Assert.True(ifoo.IsComImport) ' ComImportAttribute is a pseudo-custom attribute, which is not emitted. If Not isFromSource Then Assert.Equal(5, ifoo.GetAttributes().Length) Else Assert.Equal(6, ifoo.GetAttributes().Length) ' get attr by NamedTypeSymbol attrSym = ifoo.GetAttribute(ciSym) Assert.Equal("ComImportAttribute", attrSym.AttributeClass.Name) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) Assert.Equal(0, attrSym.CommonNamedArguments.Length) End If attrSym = ifoo.GetAttribute(guidSym) Assert.Equal("String", attrSym.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("ABCDEF5D-2448-447A-B786-64682CBEF123", attrSym.CommonConstructorArguments(0).Value) ' get attr by ctor attrSym = ifoo.GetAttribute(itCtor) Assert.Equal("System.Runtime.InteropServices.ComInterfaceType", attrSym.CommonConstructorArguments(0).Type.ToDisplayString()) Assert.Equal(ComInterfaceType.InterfaceIsIUnknown, CType(attrSym.CommonConstructorArguments(0).Value, ComInterfaceType)) attrSym = ifoo.GetAttribute(tLibSym) Assert.Equal("Object", CType(attrSym.CommonConstructorArguments(0).Value, Symbol).ToDisplayString()) attrSym = ifoo.GetAttribute(tLTypeSym) Assert.Equal(TypeLibTypeFlags.FAggregatable, CType(attrSym.CommonConstructorArguments(0).Value, TypeLibTypeFlags)) attrSym = ifoo.GetAttribute(bfmSym) Assert.Equal(False, attrSym.CommonConstructorArguments(0).Value) Assert.Equal(1, attrSym.CommonNamedArguments.Length) Assert.Equal("Boolean", attrSym.CommonNamedArguments(0).Value.Type.ToDisplayString) Assert.Equal("ThrowOnUnmappableChar", attrSym.CommonNamedArguments(0).Key) Assert.Equal(True, attrSym.CommonNamedArguments(0).Value.Value) ' ============================= Dim mem = DirectCast(ifoo.GetMembers("DoSomething").First(), MethodSymbol) Assert.Equal(1, mem.GetAttributes().Length) attrSym = mem.GetAttributes().First() Assert.Equal("AllowReversePInvokeCallsAttribute", attrSym.AttributeClass.Name) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) mem = DirectCast(ifoo.GetMembers("Register").First(), MethodSymbol) attrSym = mem.GetAttributes().First() Assert.Equal("ComRegisterFunctionAttribute", attrSym.AttributeClass.Name) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) mem = DirectCast(ifoo.GetMembers("UnRegister").First(), MethodSymbol) Assert.Equal(1, mem.GetAttributes().Length) mem = DirectCast(ifoo.GetMembers("LibFunc").First(), MethodSymbol) attrSym = mem.GetAttributes().First() Assert.Equal(1, attrSym.CommonConstructorArguments.Length) Assert.Equal(TypeLibFuncFlags.FDefaultBind, CType(attrSym.CommonConstructorArguments(0).Value, TypeLibFuncFlags)) ' 32 End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator(True), symbolValidator:=attributeValidator(False)) End Sub <Fact> Public Sub TestInteropAttributes02() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(1, 2)> <Assembly: Guid("1234C65D-1234-447A-B786-64682CBEF136")> <ComVisibleAttribute(False)> <UnmanagedFunctionPointerAttribute(CallingConvention.StdCall, BestFitMapping:=True, CharSet:=CharSet.Ansi, SetLastError:=True, ThrowOnUnmappableChar:=True)> Public Delegate Sub DFoo(p1 As Char, p2 As SByte) <ComDefaultInterface(GetType(Object)), ProgId("ProgId")> Public Class CFoo <DispIdAttribute(123)> <LCIDConversion(1), ComConversionLoss()> Sub Method(p1 As SByte, p2 As String) End Sub End Class <ComVisible(true), TypeIdentifier("1234C65D-1234-447A-B786-64682CBEF136", "EFoo, InteropAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")> Public Enum EFoo One <TypeLibVar(TypeLibVarFlags.FDisplayBind)> Two <Obsolete("message", false)> Three End Enum ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim assembly = m.ContainingAssembly Assert.Equal(ImmutableArray.Create(Of SyntaxReference)(), m.DeclaringSyntaxReferences) Dim compilation = m.DeclaringCompilation Dim globalNS = If(compilation Is Nothing, assembly.CorLibrary.GlobalNamespace, compilation.GlobalNamespace) Dim sysNS = globalNS.GetMember(Of NamespaceSymbol)("System") ' get expected attr symbol Dim runtimeNS = DirectCast(sysNS.GetMember("Runtime"), NamespaceSymbol) Dim interopNS = DirectCast(runtimeNS.GetMember("InteropServices"), NamespaceSymbol) Dim comvSym = DirectCast(interopNS.GetTypeMember("ComVisibleAttribute"), NamedTypeSymbol) Dim ufPtrSym = DirectCast(interopNS.GetTypeMember("UnmanagedFunctionPointerAttribute"), NamedTypeSymbol) Dim comdSym = DirectCast(interopNS.GetTypeMember("ComDefaultInterfaceAttribute"), NamedTypeSymbol) Dim pgidSym = DirectCast(interopNS.GetTypeMember("ProgIdAttribute"), NamedTypeSymbol) Dim tidSym = DirectCast(interopNS.GetTypeMember("TypeIdentifierAttribute"), NamedTypeSymbol) Dim dispSym = DirectCast(interopNS.GetTypeMember("DispIdAttribute"), NamedTypeSymbol) Dim lcidSym = DirectCast(interopNS.GetTypeMember("LCIDConversionAttribute"), NamedTypeSymbol) Dim comcSym = DirectCast(interopNS.GetTypeMember("ComConversionLossAttribute"), NamedTypeSymbol) Dim moduleGlobalNS = m.GlobalNamespace ' delegate DFoo Dim type1 = DirectCast(moduleGlobalNS.GetTypeMember("DFoo"), NamedTypeSymbol) Assert.Equal(2, type1.GetAttributes().Length) Dim attrSym = type1.GetAttribute(comvSym) Assert.Equal(False, attrSym.CommonConstructorArguments(0).Value) attrSym = type1.GetAttribute(ufPtrSym) Assert.Equal(1, attrSym.CommonConstructorArguments.Length) Assert.Equal(CallingConvention.StdCall, CType(attrSym.CommonConstructorArguments(0).Value, CallingConvention)) ' 3 Assert.Equal(4, attrSym.CommonNamedArguments.Length) Assert.Equal("BestFitMapping", attrSym.CommonNamedArguments(0).Key) Assert.Equal(True, attrSym.CommonNamedArguments(0).Value.Value) Assert.Equal("CharSet", attrSym.CommonNamedArguments(1).Key) Assert.Equal(CharSet.Ansi, CType(attrSym.CommonNamedArguments(1).Value.Value, CharSet)) Assert.Equal("SetLastError", attrSym.CommonNamedArguments(2).Key) Assert.Equal(True, attrSym.CommonNamedArguments(2).Value.Value) Assert.Equal("ThrowOnUnmappableChar", attrSym.CommonNamedArguments(3).Key) Assert.Equal(True, attrSym.CommonNamedArguments(3).Value.Value) ' class CFoo Dim type2 = DirectCast(moduleGlobalNS.GetTypeMember("CFoo"), NamedTypeSymbol) Assert.Equal(2, type2.GetAttributes().Length) attrSym = type2.GetAttribute(comdSym) Assert.Equal("Object", CType(attrSym.CommonConstructorArguments(0).Value, Symbol).ToDisplayString()) attrSym = type2.GetAttribute(pgidSym) Assert.Equal("String", attrSym.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("ProgId", attrSym.CommonConstructorArguments(0).Value) Dim method = DirectCast(type2.GetMembers("Method").First(), MethodSymbol) attrSym = method.GetAttribute(dispSym) Assert.Equal(123, attrSym.CommonConstructorArguments(0).Value) attrSym = method.GetAttribute(lcidSym) Assert.Equal(1, attrSym.CommonConstructorArguments(0).Value) attrSym = method.GetAttribute(comcSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) '' enum EFoo If compilation IsNot Nothing Then ' Because this is a nopia local type it is only visible from the source assembly. Dim type3 = DirectCast(globalNS.GetTypeMember("EFoo"), NamedTypeSymbol) Assert.Equal(2, type3.GetAttributes().Length) attrSym = type3.GetAttribute(comvSym) Assert.Equal(True, attrSym.CommonConstructorArguments(0).Value) attrSym = type3.GetAttribute(tidSym) Assert.Equal(2, attrSym.CommonConstructorArguments.Length) Assert.Equal("EFoo, InteropAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", attrSym.CommonConstructorArguments(1).Value) Dim field = DirectCast(type3.GetMembers("one").First(), FieldSymbol) Assert.Equal(0, field.GetAttributes().Length) field = DirectCast(type3.GetMembers("two").First(), FieldSymbol) Assert.Equal(1, field.GetAttributes().Length) attrSym = field.GetAttributes.First Assert.Equal("TypeLibVarAttribute", attrSym.AttributeClass.Name) Assert.Equal(TypeLibVarFlags.FDisplayBind, CType(attrSym.CommonConstructorArguments(0).Value, TypeLibVarFlags)) field = DirectCast(type3.GetMembers("three").First(), FieldSymbol) attrSym = field.GetAttributes().First() Assert.Equal("ObsoleteAttribute", attrSym.AttributeClass.Name) Assert.Equal(2, attrSym.CommonConstructorArguments.Length) Assert.Equal("message", attrSym.CommonConstructorArguments(0).Value) Assert.Equal(False, attrSym.CommonConstructorArguments(1).Value) End If End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(540573, "DevDiv")> <Fact()> Public Sub TestPseudoAttributes01() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports System.Runtime.CompilerServices <ComImport()> Public Interface IBar Function Method1(<OptionalAttribute(), DefaultParameterValue(99UL)> ByRef v As ULong) As ULong Function Method2(<InAttribute(), Out(), DefaultParameterValue("Ref")> ByRef v As String) As String Function Method3(<InAttribute(), OptionalAttribute(), DefaultParameterValue(" "c)> v1 As Char, <Out()> <OptionalAttribute()> <DefaultParameterValue(0.0F)> v2 As Single, <InAttribute()> <OptionalAttribute()> <DefaultParameterValue(Nothing)> v3 As String) <PreserveSig()> Sub Method4( <DateTimeConstant(123456)> p1 As DateTime, <DecimalConstant(0, 0, 100, 100, 100)> p2 As Decimal, <OptionalAttribute(), IDispatchConstant()> ByRef p3 As Object) End Interface <Serializable(), StructLayout(LayoutKind.Explicit, Size:=16, Pack:=8, CharSet:=System.Runtime.InteropServices.CharSet.Unicode)> Public Class CBar <NonSerialized(), MarshalAs(UnmanagedType.I8), FieldOffset(0)> Public field As Long End Class ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim assembly = m.ContainingSymbol Dim sourceAssembly = TryCast(assembly, SourceAssemblySymbol) Dim sysNS As NamespaceSymbol = Nothing If sourceAssembly IsNot Nothing Then sysNS = DirectCast(sourceAssembly.DeclaringCompilation.GlobalNamespace.GetMember("System"), NamespaceSymbol) Else Dim peAssembly = DirectCast(assembly, PEAssemblySymbol) sysNS = DirectCast(peAssembly.CorLibrary.GlobalNamespace.GetMember("System"), NamespaceSymbol) End If ' get expected attr symbol Dim runtimeNS = sysNS.GetNamespace("Runtime") Dim interopNS = runtimeNS.GetNamespace("InteropServices") Dim compsrvNS = runtimeNS.GetNamespace("CompilerServices") Dim serSym = sysNS.GetTypeMember("SerializableAttribute") Dim nosSym = sysNS.GetTypeMember("NonSerializedAttribute") Dim ciptSym = interopNS.GetTypeMember("ComImportAttribute") Dim laySym = interopNS.GetTypeMember("StructLayoutAttribute") Dim sigSym = interopNS.GetTypeMember("PreserveSigAttribute") Dim offSym = interopNS.GetTypeMember("FieldOffsetAttribute") Dim mshSym = interopNS.GetTypeMember("MarshalAsAttribute") Dim optSym = interopNS.GetTypeMember("OptionalAttribute") Dim inSym = interopNS.GetTypeMember("InAttribute") Dim outSym = interopNS.GetTypeMember("OutAttribute") ' non pseudo Dim dtcSym = compsrvNS.GetTypeMember("DateTimeConstantAttribute") Dim dmcSym = compsrvNS.GetTypeMember("DecimalConstantAttribute") Dim iscSym = compsrvNS.GetTypeMember("IDispatchConstantAttribute") Dim globalNS = m.GlobalNamespace ' Interface IBar Dim type1 = globalNS.GetTypeMember("IBar") Dim attrSym = type1.GetAttribute(ciptSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) Dim method As MethodSymbol Dim parm As ParameterSymbol If sourceAssembly IsNot Nothing Then ' Default attribute is in system.dll not mscorlib. Only do this check for source attributes. Dim defvSym = interopNS.GetTypeMember("DefaultParameterValueAttribute") method = type1.GetMember(Of MethodSymbol)("Method1") parm = method.Parameters(0) attrSym = parm.GetAttribute(defvSym) attrSym.VerifyValue(0, TypedConstantKind.Primitive, 99UL) attrSym = parm.GetAttribute(optSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) method = type1.GetMember(Of MethodSymbol)("Method2") parm = method.Parameters(0) Assert.Equal(3, parm.GetAttributes().Length) attrSym = parm.GetAttribute(defvSym) attrSym.VerifyValue(0, TypedConstantKind.Primitive, "Ref") attrSym = parm.GetAttribute(inSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) attrSym = parm.GetAttribute(outSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) method = type1.GetMember(Of MethodSymbol)("Method3") parm = method.Parameters(1) ' v2 Assert.Equal(3, parm.GetAttributes().Length) attrSym = parm.GetAttribute(defvSym) attrSym.VerifyValue(0, TypedConstantKind.Primitive, 0.0F) attrSym = parm.GetAttribute(optSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) attrSym = parm.GetAttribute(outSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) End If method = type1.GetMember(Of MethodSymbol)("Method4") attrSym = method.GetAttributes().First() Assert.Equal("PreserveSigAttribute", attrSym.AttributeClass.Name) parm = method.Parameters(0) attrSym = parm.GetAttributes().First() Assert.Equal("DateTimeConstantAttribute", attrSym.AttributeClass.Name) attrSym.VerifyValue(0, TypedConstantKind.Primitive, 123456) parm = method.Parameters(1) attrSym = parm.GetAttributes().First() Assert.Equal("DecimalConstantAttribute", attrSym.AttributeClass.Name) Assert.Equal(5, attrSym.CommonConstructorArguments.Length) attrSym.VerifyValue(2, TypedConstantKind.Primitive, 100) parm = method.Parameters(2) attrSym = parm.GetAttribute(iscSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) ' class CBar Dim type2 = DirectCast(globalNS.GetTypeMember("CBar"), NamedTypeSymbol) Assert.Equal(2, type2.GetAttributes().Length) attrSym = type2.GetAttribute(serSym) Assert.Equal("SerializableAttribute", attrSym.AttributeClass.Name) attrSym = type2.GetAttribute(laySym) attrSym.VerifyValue(0, TypedConstantKind.Enum, CInt(LayoutKind.Explicit)) Assert.Equal(3, attrSym.CommonNamedArguments.Length) attrSym.VerifyValue(0, "Size", TypedConstantKind.Primitive, 16) attrSym.VerifyValue(1, "Pack", TypedConstantKind.Primitive, 8) attrSym.VerifyValue(2, "CharSet", TypedConstantKind.Enum, CInt(CharSet.Unicode)) Dim field = DirectCast(type2.GetMembers("field").First(), FieldSymbol) Assert.Equal(3, field.GetAttributes().Length) attrSym = field.GetAttribute(nosSym) Assert.Equal(0, attrSym.CommonConstructorArguments.Length) attrSym = field.GetAttribute(mshSym) attrSym.VerifyValue(0, TypedConstantKind.Enum, CInt(UnmanagedType.I8)) attrSym = field.GetAttribute(offSym) attrSym.VerifyValue(0, TypedConstantKind.Primitive, 0) End Sub ' Verify attributes from source . CompileAndVerify(source, sourceSymbolValidator:=attributeValidator) End Sub <WorkItem(531121, "DevDiv")> <Fact()> Public Sub TestDecimalConstantAttribute() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices Imports System.Reflection Module Form1 Public Sub Main() For Each field In GetType(C).GetFields() PrintAttribute(field) Next End Sub Private Sub PrintAttribute(field As FieldInfo) Dim attr = field.GetCustomAttributesData()(0) Console.WriteLine("{0}, {1}, {2}, {3}, {4}", attr.ConstructorArguments(0), attr.ConstructorArguments(1), attr.ConstructorArguments(2), attr.ConstructorArguments(3), attr.ConstructorArguments(4)) End Sub End Module Public Class C Public Const _Min As Decimal = Decimal.MinValue Public Const _Max As Decimal = Decimal.MaxValue Public Const _One As Decimal = Decimal.One Public Const _MinusOne As Decimal = Decimal.MinusOne Public Const _Zero As Decimal = Decimal.Zero End Class ]]> </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ (Byte)0, (Byte)128, (UInt32)4294967295, (UInt32)4294967295, (UInt32)4294967295 (Byte)0, (Byte)0, (UInt32)4294967295, (UInt32)4294967295, (UInt32)4294967295 (Byte)0, (Byte)0, (UInt32)0, (UInt32)0, (UInt32)1 (Byte)0, (Byte)128, (UInt32)0, (UInt32)0, (UInt32)1 (Byte)0, (Byte)0, (UInt32)0, (UInt32)0, (UInt32)0 ]]>) End Sub #End Region #Region "DllImportAttribute, MethodImplAttribute, PreserveSigAttribute" ''' 6879: Pseudo DllImport looks very different in metadata Metadata: pinvokeimpl(...) + ''' PreserveSig <WorkItem(540573, "DevDiv")> <Fact> Public Sub TestPseudoDllImport() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports System.Runtime.CompilerServices ''' PreserveSigAttribute: automatically insert by compiler Public Class DllImportTest 'Metadata - .method public static pinvokeimpl("unmanaged.dll" lasterr fastcall) ' void DllImportSub() cil managed preservesig <DllImport("unmanaged.dll", CallingConvention:=CallingConvention.FastCall, SetLastError:=True)> Public Shared Sub DllImportSub() End Sub ' Metadata .method public static pinvokeimpl("user32.dll" unicode winapi) ' int32 MessageBox(native int hwnd, string t, string caption, uint32 t2) cil managed preservesig ' ' MSDN has table for 'default' ExactSpelling value ' C#|C++: always 'false' ' VB: true if CharSet is ANSI|UniCode; otherwise false <DllImport("user32.dll", CharSet:=CharSet.Unicode, ExactSpelling:=False, EntryPoint:="MessageBox")> _ Shared Function MessageBox(ByVal hwnd As IntPtr, ByVal t As String, ByVal caption As String, ByVal t2 As UInt32) As Integer End Function End Class ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim assembly = m.ContainingAssembly Dim compilation = m.DeclaringCompilation Dim globalNS = If(compilation Is Nothing, assembly.CorLibrary.GlobalNamespace, compilation.GlobalNamespace) Dim sysNS = globalNS.GetMember(Of NamespaceSymbol)("System") ' get expected attr symbol Dim runtimeNS = sysNS.GetNamespace("Runtime") Dim interopNS = runtimeNS.GetNamespace("InteropServices") Dim compsrvNS = runtimeNS.GetNamespace("CompilerServices") Dim type1 = m.GlobalNamespace.GetTypeMember("DllImportTest") Dim method As MethodSymbol method = type1.GetMember(Of MethodSymbol)("DllImportSub") Dim attrSym = method.GetAttributes().First() Assert.Equal("DllImportAttribute", attrSym.AttributeClass.Name) Assert.Equal("unmanaged.dll", attrSym.CommonConstructorArguments(0).Value) Assert.Equal("CallingConvention", attrSym.CommonNamedArguments(0).Key) Assert.Equal(TypedConstantKind.Enum, attrSym.CommonNamedArguments(0).Value.Kind) Assert.Equal(CallingConvention.FastCall, CType(attrSym.CommonNamedArguments(0).Value.Value, CallingConvention)) Assert.Equal("SetLastError", attrSym.CommonNamedArguments(1).Key) Assert.Equal(True, attrSym.CommonNamedArguments(1).Value.Value) method = DirectCast(type1.GetMembers("MessageBox").First(), MethodSymbol) attrSym = method.GetAttributes().First() Assert.Equal("DllImportAttribute", attrSym.AttributeClass.Name) Assert.Equal("user32.dll", attrSym.CommonConstructorArguments(0).Value) Assert.Equal("CharSet", attrSym.CommonNamedArguments(0).Key) Assert.Equal(TypedConstantKind.Enum, attrSym.CommonNamedArguments(0).Value.Kind) Assert.Equal(CharSet.Unicode, CType(attrSym.CommonNamedArguments(0).Value.Value, CharSet)) Assert.Equal("ExactSpelling", attrSym.CommonNamedArguments(1).Key) Assert.Equal(TypedConstantKind.Primitive, attrSym.CommonNamedArguments(1).Value.Kind) Assert.Equal(False, attrSym.CommonNamedArguments(1).Value.Value) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator) End Sub <Fact> Public Sub DllImport_AttributeRedefinition() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Namespace System.Runtime.InteropServices <DllImport> Public Class DllImportAttribute End Class End Namespace ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_AttributeMustInheritSysAttr, "DllImport").WithArguments("System.Runtime.InteropServices.DllImportAttribute")) End Sub <Fact> Public Sub DllImport_InvalidArgs1() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Class C <DllImport(Nothing)> Public Shared Sub F1() End Sub <DllImport("")> Public Shared Sub F2() End Sub <DllImport("foo", EntryPoint:=Nothing)> Public Shared Sub F3() End Sub <DllImport("foo", EntryPoint:="")> Public Shared Sub F4() End Sub <DllImport(Nothing, EntryPoint:=Nothing)> Public Shared Sub F5() End Sub <DllImport(ChrW(0))> Public Shared Sub Empty1() End Sub <DllImport(ChrW(0) & "b")> Public Shared Sub Empty2() End Sub <DllImport("b" & ChrW(0))> Public Shared Sub Empty3() End Sub <DllImport("x" & ChrW(0) & "y")> Public Shared Sub Empty4() End Sub <DllImport("x", EntryPoint:="x" & ChrW(0) & "y")> Public Shared Sub Empty5() End Sub <DllImport(ChrW(&H800))> Public Shared Sub LeadingSurrogate() End Sub <DllImport(ChrW(&HDC00))> Public Shared Sub TrailingSurrogate() End Sub <DllImport(ChrW(&HDC00) & ChrW(&HD800))> Public Shared Sub ReversedSurrogates1() End Sub <DllImport("x", EntryPoint:=ChrW(&HDC00) & ChrW(&HD800))> Public Shared Sub ReversedSurrogates2() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "Nothing").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, """""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=Nothing").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=""""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "Nothing").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=Nothing").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ChrW(0)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ChrW(0) & ""b""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, """b"" & ChrW(0)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, """x"" & ChrW(0) & ""y""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=""x"" & ChrW(0) & ""y""").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ChrW(&HDC00)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ChrW(&HDC00) & ChrW(&HD800)").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "EntryPoint:=ChrW(&HDC00) & ChrW(&HD800)").WithArguments("System.Runtime.InteropServices.DllImportAttribute")) End Sub <Fact> Public Sub DllImport_SpecialCharactersInName() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Class Program <DllImport(ChrW(&HFFFF))> Shared Sub InvalidCharacter() End Sub <DllImport(ChrW(&HD800) & ChrW(&HDC00))> Shared Sub SurrogatePairMin() End Sub <DllImport(ChrW(&HDBFF) & ChrW(&HDFFF))> Shared Sub SurrogatePairMax() End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() Assert.Equal(3, reader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(3, reader.GetTableRowCount(TableIndex.ImplMap)) For Each method In reader.GetImportedMethods() Dim import = method.GetImport() Dim moduleName As String = reader.GetString(reader.GetModuleReferenceName(import.Module)) Dim methodName As String = reader.GetString(method.Name) Select Case methodName Case "InvalidCharacter" Assert.Equal(ChrW(&HFFFF), moduleName) Case "SurrogatePairMin" Assert.Equal(ChrW(&HD800) & ChrW(&HDC00), moduleName) Case "SurrogatePairMax" Assert.Equal(ChrW(&HDBFF) & ChrW(&HDFFF), moduleName) Case Else Throw TestExceptionUtilities.UnexpectedValue(methodName) End Select Next End Sub) End Sub <Fact> Public Sub DllImport_TypeCharacterInName() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module Module1 <DllImport("user32.dll", CharSet:=CharSet.Unicode)> Function MessageBox%(hwnd As IntPtr, t As String, caption As String, t2 As UInt32) End Function End Module ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim type1 = m.GlobalNamespace.GetTypeMember("Module1") Dim method = DirectCast(type1.GetMembers("MessageBox").First(), MethodSymbol) Dim attrSym = method.GetAttributes().First() Assert.Equal("DllImportAttribute", attrSym.AttributeClass.Name) Assert.Equal("user32.dll", attrSym.CommonConstructorArguments(0).Value) Assert.Equal("CharSet", attrSym.CommonNamedArguments(0).Key) Assert.Equal(TypedConstantKind.Enum, attrSym.CommonNamedArguments(0).Value.Kind) Assert.Equal(CharSet.Unicode, CType(attrSym.CommonNamedArguments(0).Value.Value, CharSet)) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator) End Sub <Fact()> <WorkItem(544176, "DevDiv")> Public Sub TestPseudoAttributes_DllImport_AllTrue() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C <DllImport("mscorlib", EntryPoint:="bar", CallingConvention:=CallingConvention.Cdecl, CharSet:=CharSet.Unicode, ExactSpelling:=True, PreserveSig:=True, SetLastError:=True, BestFitMapping:=True, ThrowOnUnmappableChar:=True)> Public Shared Sub M() End Sub End Class ]]> </file> </compilation> Dim validator As Action(Of PEAssembly, EmitOptions) = Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() ' ModuleRef: Dim moduleRefName = reader.GetModuleReferenceName(reader.GetModuleReferences().Single()) Assert.Equal("mscorlib", reader.GetString(moduleRefName)) ' FileRef: ' Although the Metadata spec says there should be a File entry for each ModuleRef entry ' Dev10 compiler doesn't add it and peverify doesn't complain. Assert.Equal(0, reader.GetTableRowCount(TableIndex.File)) Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap)) ' ImplMap: Dim import = reader.GetImportedMethods().Single().GetImport() Assert.Equal("bar", reader.GetString(import.Name)) Assert.Equal(1, reader.GetRowNumber(import.Module)) Assert.Equal(MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetUnicode Or MethodImportAttributes.SetLastError Or MethodImportAttributes.CallingConventionCDecl Or MethodImportAttributes.BestFitMappingEnable Or MethodImportAttributes.ThrowOnUnmappableCharEnable, import.Attributes) ' MethodDef: Dim methodDefs As MethodHandle() = reader.MethodDefinitions.AsEnumerable().ToArray() Assert.Equal(2, methodDefs.Length) ' ctor, M Assert.Equal(MethodImplAttributes.PreserveSig, reader.GetMethod(methodDefs(1)).ImplAttributes) End Sub Dim symValidator As Action(Of ModuleSymbol) = Sub(peModule) Dim c = peModule.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim m = c.GetMember(Of MethodSymbol)("M") Dim info = m.GetDllImportData() Assert.Equal("mscorlib", info.ModuleName) Assert.Equal("bar", info.EntryPointName) Assert.Equal(CharSet.Unicode, info.CharacterSet) Assert.True(info.ExactSpelling) Assert.True(info.SetLastError) Assert.Equal(True, info.BestFitMapping) Assert.Equal(True, info.ThrowOnUnmappableCharacter) Assert.Equal( Cci.PInvokeAttributes.NoMangle Or Cci.PInvokeAttributes.CharSetUnicode Or Cci.PInvokeAttributes.SupportsLastError Or Cci.PInvokeAttributes.CallConvCdecl Or Cci.PInvokeAttributes.BestFitEnabled Or Cci.PInvokeAttributes.ThrowOnUnmappableCharEnabled, DirectCast(info, Cci.IPlatformInvokeInformation).Flags) End Sub CompileAndVerify(source, validator:=validator, symbolValidator:=symValidator) End Sub <Fact> <WorkItem(544601, "DevDiv")> Public Sub GetDllImportData_UnspecifiedProperties() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Class C <DllImport("mscorlib")> Shared Sub M() End Sub End Class ]]> </file> </compilation> Dim validator As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim c = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim m = c.GetMember(Of MethodSymbol)("M") Dim info = m.GetDllImportData() Assert.Equal("mscorlib", info.ModuleName) Assert.Equal(If(isFromSource, Nothing, "M"), info.EntryPointName) Assert.Equal(CharSet.None, info.CharacterSet) Assert.Equal(CallingConvention.Winapi, info.CallingConvention) Assert.False(info.ExactSpelling) Assert.False(info.SetLastError) Assert.Equal(Nothing, info.BestFitMapping) Assert.Equal(Nothing, info.ThrowOnUnmappableCharacter) End Sub CompileAndVerify(source, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub <Fact> <WorkItem(544601, "DevDiv")> Public Sub GetDllImportData_Declare() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Class C Declare Unicode Sub M1 Lib "foo"() Declare Unicode Sub M2 Lib "foo" Alias "bar"() End Class ]]> </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim c = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim info = c.GetMember(Of MethodSymbol)("M1").GetDllImportData() Assert.Equal("foo", info.ModuleName) Assert.Equal(If(isFromSource, Nothing, "M1"), info.EntryPointName) Assert.Equal(CharSet.Unicode, info.CharacterSet) Assert.Equal(CallingConvention.Winapi, info.CallingConvention) Assert.True(info.ExactSpelling) Assert.True(info.SetLastError) Assert.Equal(Nothing, info.BestFitMapping) Assert.Equal(Nothing, info.ThrowOnUnmappableCharacter) info = c.GetMember(Of MethodSymbol)("M2").GetDllImportData() Assert.Equal("foo", info.ModuleName) Assert.Equal("bar", info.EntryPointName) Assert.Equal(CharSet.Unicode, info.CharacterSet) Assert.Equal(CallingConvention.Winapi, info.CallingConvention) Assert.True(info.ExactSpelling) Assert.True(info.SetLastError) Assert.Equal(Nothing, info.BestFitMapping) Assert.Equal(Nothing, info.ThrowOnUnmappableCharacter) End Sub CompileAndVerify(source, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub <Fact> Public Sub TestPseudoAttributes_DllImport_Operators() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C <DllImport("foo")> Public Shared Operator +(a As C, b As C) As Integer End Operator End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap)) Dim method = reader.GetImportedMethods().Single() Dim import = method.GetImport() Dim moduleName As String = reader.GetString(reader.GetModuleReferenceName(import.Module)) Dim entryPointName As String = reader.GetString(method.Name) Assert.Equal("op_Addition", entryPointName) Assert.Equal("foo", moduleName) End Sub) End Sub <Fact> Public Sub TestPseudoAttributes_DllImport_Conversions() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C <DllImport("foo")> Public Shared Narrowing Operator CType(a As C) As Integer End Operator End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim peFileReader = assembly.GetMetadataReader() Assert.Equal(1, peFileReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(1, peFileReader.GetTableRowCount(TableIndex.ImplMap)) Dim method = peFileReader.GetImportedMethods().Single() Dim moduleName As String = peFileReader.GetString(peFileReader.GetModuleReferenceName(method.GetImport().Module)) Dim entryPointName As String = peFileReader.GetString(method.Name) Assert.Equal("op_Explicit", entryPointName) Assert.Equal("foo", moduleName) End Sub) End Sub <Fact> Public Sub DllImport_Partials() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C <DllImport("module name")> Shared Partial Private Sub foo() End Sub Shared Private Sub foo() End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap)) Dim method = reader.GetImportedMethods().Single() Dim moduleName As String = reader.GetString(reader.GetModuleReferenceName(method.GetImport().Module)) Dim entryPointName As String = reader.GetString(method.Name) Assert.Equal("module name", moduleName) Assert.Equal("foo", entryPointName) End Sub) End Sub <Fact> Public Sub DllImport_Partials_Errors() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class C <DllImport("module name")> Partial Private Sub foo() End Sub Private Sub foo() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_DllImportOnInstanceMethod, "DllImport")) End Sub <Fact> Public Sub DllImport_Partials_NonEmptyBody() Dim source = <compilation> <file><![CDATA[ Module Module1 <System.Runtime.InteropServices.DllImport("a")> Private Sub f1() End Sub Partial Private Sub f1() End Sub <System.Runtime.InteropServices.DllImport("a")> Partial Private Sub f2() End Sub Private Sub f2() System.Console.WriteLine() End Sub End Module ]]> </file> </compilation> CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_DllImportOnNonEmptySubOrFunction, "System.Runtime.InteropServices.DllImport")) End Sub <Fact> Public Sub TestPseudoAttributes_DllImport_NotAllowed() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class C Public Shared Property F As Integer <DllImport("a")> Get Return 1 End Get <DllImport(Nothing)> Set(value As Integer) End Set End Property Custom Event x As Action(Of Integer) <DllImport("foo")> AddHandler(value As Action(Of Integer)) End AddHandler <DllImport("foo")> RemoveHandler(value As Action(Of Integer)) End RemoveHandler <DllImport("foo")> RaiseEvent(obj As Integer) End RaiseEvent End Event <DllImport("foo")> Sub InstanceMethod End Sub <DllImport("foo")> Shared Sub NonEmptyBody System.Console.WriteLine() End Sub <DllImport("foo")> Shared Sub GenericMethod(Of T)() End Sub End Class Interface I <DllImport("foo")> Sub InterfaceMethod() End Interface Interface I(Of T) <DllImport("foo")> Sub InterfaceMethod() End Interface Class C(Of T) Interface Foo Class D <DllImport("foo")> Shared Sub MethodOnGenericType() End Sub End Class End Interface End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_DllImportNotLegalOnGetOrSet, "DllImport"), Diagnostic(ERRID.ERR_DllImportNotLegalOnGetOrSet, "DllImport"), Diagnostic(ERRID.ERR_DllImportNotLegalOnEventMethod, "DllImport"), Diagnostic(ERRID.ERR_DllImportNotLegalOnEventMethod, "DllImport"), Diagnostic(ERRID.ERR_DllImportNotLegalOnEventMethod, "DllImport"), Diagnostic(ERRID.ERR_DllImportOnInstanceMethod, "DllImport"), Diagnostic(ERRID.ERR_DllImportOnNonEmptySubOrFunction, "DllImport"), Diagnostic(ERRID.ERR_DllImportOnGenericSubOrFunction, "DllImport"), Diagnostic(ERRID.ERR_DllImportOnGenericSubOrFunction, "DllImport"), Diagnostic(ERRID.ERR_DllImportOnInterfaceMethod, "DllImport"), Diagnostic(ERRID.ERR_DllImportOnInterfaceMethod, "DllImport")) End Sub <Fact> Public Sub TestPseudoAttributes_DllImport_Flags() Dim cases = { New With {.n = 0, .attr = MakeDllImport(), .expected = MethodImportAttributes.CallingConventionWinApi}, New With {.n = 1, .attr = MakeDllImport(cc:=CallingConvention.Cdecl), .expected = MethodImportAttributes.CallingConventionCDecl}, New With {.n = 2, .attr = MakeDllImport(cc:=CallingConvention.FastCall), .expected = MethodImportAttributes.CallingConventionFastCall}, New With {.n = 3, .attr = MakeDllImport(cc:=CallingConvention.StdCall), .expected = MethodImportAttributes.CallingConventionStdCall}, New With {.n = 4, .attr = MakeDllImport(cc:=CallingConvention.ThisCall), .expected = MethodImportAttributes.CallingConventionThisCall}, New With {.n = 5, .attr = MakeDllImport(cc:=CallingConvention.Winapi), .expected = MethodImportAttributes.CallingConventionWinApi}, _ New With {.n = 6, .attr = MakeDllImport(), .expected = MethodImportAttributes.CallingConventionWinApi}, New With {.n = 7, .attr = MakeDllImport(charSet:=CharSet.None), .expected = MethodImportAttributes.CallingConventionWinApi}, New With {.n = 8, .attr = MakeDllImport(charSet:=CharSet.Ansi), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetAnsi}, New With {.n = 9, .attr = MakeDllImport(charSet:=CharSet.Unicode), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetUnicode}, New With {.n = 10, .attr = MakeDllImport(charSet:=CharSet.Auto), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetAuto}, _ New With {.n = 11, .attr = MakeDllImport(exactSpelling:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ExactSpelling}, New With {.n = 12, .attr = MakeDllImport(exactSpelling:=False), .expected = MethodImportAttributes.CallingConventionWinApi}, _ New With {.n = 13, .attr = MakeDllImport(charSet:=CharSet.Ansi, exactSpelling:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAnsi}, New With {.n = 14, .attr = MakeDllImport(charSet:=CharSet.Ansi, exactSpelling:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetAnsi}, New With {.n = 15, .attr = MakeDllImport(charSet:=CharSet.Unicode, exactSpelling:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetUnicode}, New With {.n = 16, .attr = MakeDllImport(charSet:=CharSet.Unicode, exactSpelling:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetUnicode}, New With {.n = 17, .attr = MakeDllImport(charSet:=CharSet.Auto, exactSpelling:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAuto}, New With {.n = 18, .attr = MakeDllImport(charSet:=CharSet.Auto, exactSpelling:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.CharSetAuto}, _ New With {.n = 19, .attr = MakeDllImport(preserveSig:=True), .expected = MethodImportAttributes.CallingConventionWinApi}, New With {.n = 20, .attr = MakeDllImport(preserveSig:=False), .expected = MethodImportAttributes.CallingConventionWinApi}, _ New With {.n = 21, .attr = MakeDllImport(setLastError:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError}, New With {.n = 22, .attr = MakeDllImport(setLastError:=False), .expected = MethodImportAttributes.CallingConventionWinApi}, _ New With {.n = 23, .attr = MakeDllImport(bestFitMapping:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.BestFitMappingEnable}, New With {.n = 24, .attr = MakeDllImport(bestFitMapping:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.BestFitMappingDisable}, _ New With {.n = 25, .attr = MakeDllImport(throwOnUnmappableChar:=True), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ThrowOnUnmappableCharEnable}, New With {.n = 26, .attr = MakeDllImport(throwOnUnmappableChar:=False), .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.ThrowOnUnmappableCharDisable}, _ New With {.n = 27, .attr = "<DllImport(""bar"", CharSet:=CType(15, CharSet), SetLastError:=True)>", .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError}, New With {.n = 28, .attr = "<DllImport(""bar"", CallingConvention:=CType(15, CallingConvention), SetLastError:=True)>", .expected = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError} } ' NOTE: case #28 - when an invalid calling convention is specified Dev10 compiler emits invalid metadata (calling convention 0). ' We emit calling convention WinAPI. Dim sb As StringBuilder = New StringBuilder( <text> Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C </text>.Value) For Each testCase In cases sb.Append(testCase.attr) sb.AppendLine() sb.AppendLine("Shared Sub M" & testCase.n & "()") sb.AppendLine("End Sub") Next sb.AppendLine("End Class") Dim code = <compilation><file name="attr.vb"><%= sb.ToString() %></file></compilation> CompileAndVerify(code, validator:= Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() Assert.Equal(cases.Length, reader.GetTableRowCount(TableIndex.ImplMap)) Dim j = 0 For Each method In reader.GetImportedMethods() Assert.Equal(cases(j).expected, method.GetImport().Attributes) j = j + 1 Next End Sub) End Sub Private Function MakeDllImport(Optional cc As CallingConvention? = Nothing, Optional charSet As CharSet? = Nothing, Optional exactSpelling As Boolean? = Nothing, Optional preserveSig As Boolean? = Nothing, Optional setLastError As Boolean? = Nothing, Optional bestFitMapping As Boolean? = Nothing, Optional throwOnUnmappableChar As Boolean? = Nothing) As String Dim sb As StringBuilder = New StringBuilder("<DllImport(""bar""") If cc IsNot Nothing Then sb.Append(", CallingConvention := CallingConvention.") sb.Append(cc.Value.ToString()) End If If charSet IsNot Nothing Then sb.Append(", CharSet := CharSet.") sb.Append(charSet.Value.ToString()) End If If exactSpelling IsNot Nothing Then sb.Append(", ExactSpelling := ") sb.Append(If(exactSpelling.Value, "True", "False")) End If If preserveSig IsNot Nothing Then sb.Append(", PreserveSig := ") sb.Append(If(preserveSig.Value, "True", "False")) End If If setLastError IsNot Nothing Then sb.Append(", SetLastError := ") sb.Append(If(setLastError.Value, "True", "False")) End If If bestFitMapping IsNot Nothing Then sb.Append(", BestFitMapping := ") sb.Append(If(bestFitMapping.Value, "True", "False")) End If If throwOnUnmappableChar IsNot Nothing Then sb.Append(", ThrowOnUnmappableChar := ") sb.Append(If(throwOnUnmappableChar.Value, "True", "False")) End If sb.Append(")>") Return sb.ToString() End Function <Fact> Public Sub TestMethodImplAttribute_VerifiableMD() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices MustInherit Class C <MethodImpl(MethodImplOptions.ForwardRef)> Public Shared Sub ForwardRef() System.Console.WriteLine(0) End Sub <MethodImpl(MethodImplOptions.NoInlining)> Public Shared Sub NoInlining() System.Console.WriteLine(1) End Sub <MethodImpl(MethodImplOptions.NoOptimization)> Public Shared Sub NoOptimization() System.Console.WriteLine(2) End Sub <MethodImpl(MethodImplOptions.Synchronized)> Public Shared Sub Synchronized() System.Console.WriteLine(3) End Sub <MethodImpl(MethodImplOptions.InternalCall)> ' ok, body ignored Public Shared Sub InternalCallStatic() System.Console.WriteLine(3) End Sub <MethodImpl(MethodImplOptions.InternalCall)> ' ok, body ignored Public Sub InternalCallInstance() System.Console.WriteLine(3) End Sub <MethodImpl(MethodImplOptions.InternalCall)> Public MustOverride Sub InternalCallAbstract() End Class ]]> </file> </compilation> Dim validator As Action(Of PEAssembly, EmitOptions) = Sub(assembly, options) Dim isRefEmit = options = EmitOptions.RefEmit Dim peReader = assembly.GetMetadataReader() For Each methodDef In peReader.MethodDefinitions Dim row = peReader.GetMethod(methodDef) Dim actualFlags = row.ImplAttributes Dim expectedFlags As MethodImplAttributes Select Case peReader.GetString(row.Name) Case "NoInlining" expectedFlags = MethodImplAttributes.NoInlining Case "NoOptimization" expectedFlags = MethodImplAttributes.NoOptimization Case "Synchronized" expectedFlags = MethodImplAttributes.Synchronized Case "InternalCallStatic", "InternalCallInstance", "InternalCallAbstract" ' workaround for a bug in ref.emit: expectedFlags = If(isRefEmit, MethodImplAttributes.Runtime Or MethodImplAttributes.InternalCall, MethodImplAttributes.InternalCall) Case "ForwardRef" ' workaround for a bug in ref.emit: expectedFlags = If(isRefEmit, Nothing, MethodImplAttributes.ForwardRef) Case ".ctor" expectedFlags = MethodImplAttributes.IL Case Else Throw TestExceptionUtilities.UnexpectedValue(peReader.GetString(row.Name)) End Select Assert.Equal(expectedFlags, actualFlags) Next End Sub CompileAndVerify(source, validator:=validator) End Sub <Fact> Public Sub TestMethodImplAttribute_UnverifiableMD() Dim compilation = CreateCompilationWithMscorlib( <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Class C <MethodImpl(MethodImplOptions.Unmanaged)> ' peverify: type load failed Public Shared Sub Unmanaged() System.Console.WriteLine(1) End Sub <MethodImpl(MethodCodeType:=MethodCodeType.Native)> ' peverify: type load failed Public Shared Sub Native() System.Console.WriteLine(2) End Sub <MethodImpl(MethodCodeType:=MethodCodeType.OPTIL)> ' peverify: type load failed Public Shared Sub OPTIL() System.Console.WriteLine(3) End Sub <MethodImpl(MethodCodeType:=MethodCodeType.Runtime)> ' peverify: type load failed Public Shared Sub Runtime() System.Console.WriteLine(4) End Sub <MethodImpl(MethodImplOptions.InternalCall)> Public Shared Sub InternalCallGeneric1(Of T)() ' peverify: type load failed (InternalCall method can't be generic) End Sub End Class Class C(Of T) <MethodImpl(MethodImplOptions.InternalCall)> Public Shared Sub InternalCallGeneric2() ' peverify: type load failed (InternalCall method can't be in a generic type) End Sub End Class ]]> </file> </compilation>) Dim image = compilation.EmitToArray() Dim peReader = ModuleMetadata.CreateFromImage(image).Module.GetMetadataReader() For Each methodDef In peReader.MethodDefinitions Dim row = peReader.GetMethod(methodDef) Dim actualFlags = row.ImplAttributes Dim actualHasBody = row.RelativeVirtualAddress <> 0 Dim expectedFlags As MethodImplAttributes Dim expectedHasBody As Boolean Select Case peReader.GetString(row.Name) Case "ForwardRef" expectedFlags = MethodImplAttributes.ForwardRef expectedHasBody = True Case "Unmanaged" expectedFlags = MethodImplAttributes.Unmanaged expectedHasBody = True Case "Native" expectedFlags = MethodImplAttributes.Native expectedHasBody = True Case "Runtime" expectedFlags = MethodImplAttributes.Runtime expectedHasBody = False Case "OPTIL" expectedFlags = MethodImplAttributes.OPTIL expectedHasBody = True Case "InternalCallStatic", "InternalCallGeneric1", "InternalCallGeneric2" expectedFlags = MethodImplAttributes.InternalCall expectedHasBody = False Case ".ctor" expectedFlags = MethodImplAttributes.IL expectedHasBody = True Case Else Throw TestExceptionUtilities.UnexpectedValue(peReader.GetString(row.Name)) End Select Assert.Equal(expectedFlags, actualFlags) Assert.Equal(expectedHasBody, actualHasBody) Next End Sub <Fact> Public Sub TestPseudoAttributes_DllImport_Declare() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class C <DllImport("Baz")> Declare Ansi Sub Foo Lib "Foo" Alias "bar" () End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_DllImportNotLegalOnDeclare, "DllImport")) End Sub <Fact> Public Sub ExternalExtensionMethods() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Module M <Extension()> <MethodImpl(MethodImplOptions.InternalCall)> Sub InternalCall(a As Integer) End Sub <Extension()> <DllImport("foo")> Sub DllImp(a As Integer) End Sub <Extension()> Declare Sub DeclareSub Lib "bar" (a As Integer) End Module Class C Shared Sub Main() Dim x = 1 x.DeclareSub() x.DllImp() x.InternalCall() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}).VerifyDiagnostics() End Sub <Fact> Public Sub TestMethodImplAttribute_PreserveSig() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices MustInherit Class C Sub New End Sub <PreserveSig> MustOverride Public Sub f0() <MethodImpl(MethodImplOptions.PreserveSig)> MustOverride Public Sub f1() <DllImport("foo")> Public Shared Sub f2() End Sub <DllImport("foo", PreserveSig:=True)> Public Shared Sub f3() End Sub <DllImport("foo", PreserveSig:=False)> Public Shared Sub f4() End Sub <MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=True)> Public Shared Sub f5() End Sub <MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=False)> Public Shared Sub f6() End Sub <MethodImpl(MethodImplOptions.PreserveSig), PreserveSig> MustOverride Public Sub f7() <DllImport("foo"), PreserveSig> Public Shared Sub f8() End Sub <PreserveSig, DllImport("foo", PreserveSig:=True)> Public Shared Sub f9() End Sub ' false <DllImport("foo", PreserveSig:=False), PreserveSig> Public Shared Sub f10() End Sub <MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=True), PreserveSig> Public Shared Sub f11() End Sub ' false <DllImport("foo", PreserveSig:=False), PreserveSig, MethodImpl(MethodImplOptions.PreserveSig)> Public Shared Sub f12() End Sub ' false <DllImport("foo", PreserveSig:=False), MethodImpl(MethodImplOptions.PreserveSig), PreserveSig> Public Shared Sub f13() End Sub <PreserveSig, DllImport("foo", PreserveSig:=False), MethodImpl(MethodImplOptions.PreserveSig)> Public Shared Sub f14() End Sub <PreserveSig, MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=False)> Public Shared Sub f15() End Sub <MethodImpl(MethodImplOptions.PreserveSig), PreserveSig, DllImport("foo", PreserveSig:=False)> Public Shared Sub f16() End Sub <MethodImpl(MethodImplOptions.PreserveSig), DllImport("foo", PreserveSig:=False), PreserveSig> Public Shared Sub f17() End Sub ' false Public Shared Sub f18() End Sub <MethodImpl(MethodImplOptions.Synchronized), DllImport("foo", PreserveSig:=False), PreserveSig> Public Shared Sub f19() End Sub <MethodImpl(MethodImplOptions.Synchronized), PreserveSig> Public Shared Sub f20() End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim peReader = assembly.GetMetadataReader() For Each methodDef In peReader.MethodDefinitions Dim row = peReader.GetMethod(methodDef) Dim actualFlags = row.ImplAttributes Dim expectedFlags As MethodImplAttributes Dim name = peReader.GetString(row.Name) Select Case name Case "f0", "f1", "f2", "f3", "f5", "f6", "f7", "f8", "f9", "f11", "f14", "f15", "f16", "f17" expectedFlags = MethodImplAttributes.PreserveSig Case "f4", "f10", "f12", "f13", "f18", ".ctor" expectedFlags = 0 Case "f19" expectedFlags = MethodImplAttributes.Synchronized Case "f20" expectedFlags = MethodImplAttributes.PreserveSig Or MethodImplAttributes.Synchronized Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Assert.Equal(expectedFlags, actualFlags) Next ' no custom attributes applied on methods: For Each ca In peReader.CustomAttributes Dim parent = peReader.GetCustomAttribute(ca).Parent Assert.NotEqual(parent.HandleType, HandleType.Method) Next End Sub) End Sub <Fact> Public Sub MethodImplAttribute_Errors() Dim source = <compilation> <file><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Class Program1 <MethodImpl(CShort(0))> Sub f0() End Sub <MethodImpl(CShort(1))> Sub f1() End Sub <MethodImpl(CShort(2))> Sub f2() End Sub <MethodImpl(CShort(3))> Sub f3() End Sub <MethodImpl(CShort(4))> Sub f4() End Sub <MethodImpl(CShort(5))> Sub f5() End Sub <MethodImpl(CType(2, MethodImplOptions))> Sub f6() End Sub <MethodImpl(CShort(4), MethodCodeType:=CType(8, MethodCodeType), MethodCodeType:=CType(9, MethodCodeType))> Sub f7() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<![CDATA[ BC30127: Attribute 'System.Runtime.CompilerServices.MethodImplAttribute' is not valid: Incorrect argument value. <MethodImpl(CShort(1))> ~~~~~~~~~ BC30127: Attribute 'System.Runtime.CompilerServices.MethodImplAttribute' is not valid: Incorrect argument value. <MethodImpl(CShort(2))> ~~~~~~~~~ BC30127: Attribute 'System.Runtime.CompilerServices.MethodImplAttribute' is not valid: Incorrect argument value. <MethodImpl(CShort(3))> ~~~~~~~~~ BC30127: Attribute 'System.Runtime.CompilerServices.MethodImplAttribute' is not valid: Incorrect argument value. <MethodImpl(CShort(5))> ~~~~~~~~~ BC30127: Attribute 'System.Runtime.CompilerServices.MethodImplAttribute' is not valid: Incorrect argument value. <MethodImpl(CType(2, MethodImplOptions))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30127: Attribute 'System.Runtime.CompilerServices.MethodImplAttribute' is not valid: Incorrect argument value. <MethodImpl(CShort(4), MethodCodeType:=CType(8, MethodCodeType), MethodCodeType:=CType(9, MethodCodeType))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30127: Attribute 'System.Runtime.CompilerServices.MethodImplAttribute' is not valid: Incorrect argument value. <MethodImpl(CShort(4), MethodCodeType:=CType(8, MethodCodeType), MethodCodeType:=CType(9, MethodCodeType))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>) End Sub Private Sub DisableJITOptimizationTestHelper( assembly As PEAssembly, methods As String(), implFlags As MethodImplAttributes() ) Dim m = assembly.Modules(0) Dim dissableOptDef As TypeHandle = Nothing Dim name As String = Nothing For Each typeDef In m.GetMetadataReader().TypeDefinitions name = m.GetTypeDefNameOrThrow(typeDef) If name.Equals("DisableJITOptimization") Then dissableOptDef = typeDef Exit For End If Next Assert.NotEqual(Nothing, dissableOptDef) Dim map As New Dictionary(Of String, MethodHandle)() For Each methodDef In m.GetMethodsOfTypeOrThrow(dissableOptDef) map.Add(m.GetMethodDefNameOrThrow(methodDef), methodDef) Next For i As Integer = 0 To methods.Length - 1 Dim actualFlags As MethodImplAttributes m.GetMethodDefPropsOrThrow(map(methods(i)), name, actualFlags, Nothing, Nothing) Assert.Equal(implFlags(i), actualFlags) Next End Sub <Fact> Public Sub DisableJITOptimization_01() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports Microsoft.VisualBasic Public Module DisableJITOptimization Sub Main() Err.Raise(0) End Sub Sub Main2() Dim x = Sub() Err.Raise(0) End Sub End Module ]]> </file> </compilation> Dim validator As Action(Of PEAssembly, EmitOptions) = Sub(assembly, _omitted) Const implFlags As MethodImplAttributes = MethodImplAttributes.IL Or MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization DisableJITOptimizationTestHelper(assembly, {"Main", "Main2", "_Lambda$__1"}, {implFlags, 0, implFlags}) End Sub CompileAndVerify(source, validator:=validator) End Sub #End Region #Region "DefaultCharSetAttribute" <Fact, WorkItem(544518, "DevDiv")> Public Sub DllImport_DefaultCharSet1() Dim source = <compilation> <file><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices <Module:DefaultCharSet(CharSet.Ansi)> MustInherit Class C <DllImport("foo")> Shared Sub f1() End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, emitOptions:=EmitOptions.CCI, validator:= Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap)) Assert.False(FindCustomAttribute(reader, "DefaultCharSetAttribute").IsNil) Dim import = reader.GetImportedMethods().Single().GetImport() Assert.Equal(MethodImportAttributes.CharSetAnsi, import.Attributes And MethodImportAttributes.CharSetMask) End Sub) End Sub <Fact> Public Sub DllImport_DefaultCharSet2() Dim source = <compilation> <file><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices <Module:DefaultCharSet(CharSet.None)> <StructLayout(LayoutKind.Explicit)> MustInherit Class C <DllImport("foo")> Shared Sub f1() End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, emitOptions:=EmitOptions.CCI, validator:= Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(1, reader.GetTableRowCount(TableIndex.ImplMap)) Assert.False(FindCustomAttribute(reader, "DefaultCharSetAttribute").IsNil) Dim import = reader.GetImportedMethods().Single().GetImport() Assert.Equal(MethodImportAttributes.None, import.Attributes And MethodImportAttributes.CharSetMask) For Each typeDef In reader.TypeDefinitions Dim def = reader.GetTypeDefinition(typeDef) Dim name = reader.GetString(def.Name) Select Case name Case "C" Assert.Equal(TypeAttributes.ExplicitLayout Or TypeAttributes.Abstract, def.Attributes) Case "<Module>" Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next End Sub) End Sub <Fact> Public Sub DllImport_DefaultCharSet_Errors() Dim source = <compilation> <file><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices <Module:DefaultCharSet(DirectCast(Integer.MaxValue, CharSet))> ]]> </file> </compilation> CreateCompilationWithMscorlib(source).AssertTheseDiagnostics(<![CDATA[ BC30127: Attribute 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid: Incorrect argument value. <Module:DefaultCharSet(DirectCast(Integer.MaxValue, CharSet))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub DefaultCharSet_Types() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Runtime.CompilerServices <Module:DefaultCharSet(CharSet.Unicode)> Class C Class D Dim arr As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0} Sub foo() Dim a As Integer = 1 Dim b As Integer = 2 Dim q = New With {.f = 1, .g = 2} Dim z = New Action(Sub() Console.WriteLine(a + arr(b))) End Sub End Class Event Foo(a As Integer, b As String) End Class <SpecialName> Public Class Special End Class <StructLayout(LayoutKind.Sequential, Pack:=4, Size:=10)> Public Structure SeqLayout End Structure Structure S End Structure Enum E A End Enum Interface I End Interface Delegate Sub D() <Microsoft.VisualBasic.ComClass("", "", "")> Public Class CC Public Sub F() End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, emitOptions:=EmitOptions.CCI, validator:= Sub(assembly, _omitted) Dim peFileReader = assembly.GetMetadataReader() For Each typeDef In peFileReader.TypeDefinitions Dim row = peFileReader.GetTypeDefinition(typeDef) Dim name = peFileReader.GetString(row.Name) Dim actual = row.Attributes And TypeAttributes.StringFormatMask If name = "<Module>" OrElse name.StartsWith("__StaticArrayInitTypeSize=", StringComparison.Ordinal) OrElse name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal) Then Assert.Equal(TypeAttributes.AnsiClass, actual) Else Assert.Equal(TypeAttributes.UnicodeClass, actual) End If Next End Sub) End Sub ''' <summary> ''' DefaultCharSet is not applied on embedded types. ''' </summary> <WorkItem(546644, "DevDiv")> <Fact> Public Sub DefaultCharSet_EmbeddedTypes() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic <Module:DefaultCharSet(CharSet.Unicode)> Friend Class C Public Sub Foo(x As Integer) Console.WriteLine(ChrW(x)) End Sub End Class ]]> </file> </compilation> Dim c = CompilationUtils.CreateCompilationWithReferences(source, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompileAndVerify(c, validator:= Sub(assembly, _omitted) Dim peFileReader = assembly.GetMetadataReader() For Each typeDef In peFileReader.TypeDefinitions Dim row = peFileReader.GetTypeDefinition(typeDef) Dim name = peFileReader.GetString(row.Name) Dim actual = row.Attributes And TypeAttributes.StringFormatMask If name = "C" Then Assert.Equal(TypeAttributes.UnicodeClass, actual) Else ' embedded types should not be affected Assert.Equal(TypeAttributes.AnsiClass, actual) End If Next End Sub) End Sub #End Region #Region "Declare Method PInvoke Flags" <Fact> Public Sub TestPseudoAttributes_Declare_DefaultFlags() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Declare Sub Bar Lib "Foo" () End Class ]]> </file> </compilation> Dim validator As Action(Of PEAssembly, EmitOptions) = Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() ' ModuleRef: Dim moduleRefName = reader.GetModuleReferenceName(reader.GetModuleReferences().Single()) Assert.Equal("Foo", reader.GetString(moduleRefName)) ' FileRef: ' Although the Metadata spec says there should be a File entry for each ModuleRef entry ' Dev10 compiler doesn't add it and peverify doesn't complain. Assert.Equal(0, reader.GetTableRowCount(TableIndex.File)) Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef)) ' ImplMap: Dim import = reader.GetImportedMethods().Single().GetImport() Assert.Equal("Bar", reader.GetString(import.Name)) Assert.Equal(1, reader.GetRowNumber(import.Module)) Assert.Equal(MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAnsi Or MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError, import.Attributes) ' MethodDef: Dim methodDefs As MethodHandle() = reader.MethodDefinitions.AsEnumerable().ToArray() Assert.Equal(2, methodDefs.Length) ' ctor, M Assert.Equal(MethodImplAttributes.PreserveSig, reader.GetMethod(methodDefs(1)).ImplAttributes) End Sub CompileAndVerify(source, validator:=validator) End Sub <Fact> Public Sub TestPseudoAttributes_Declare_Flags() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Declare Ansi Sub _Ansi Lib "a" () Declare Unicode Sub _Unicode Lib "b" () Declare Auto Sub _Auto Lib "c" () Declare Function _Alias Lib "d" Alias "Baz" () As Integer End Class ]]> </file> </compilation> Const declareFlags = MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError Dim validator As Action(Of PEAssembly, EmitOptions) = Sub(assembly, _omitted) Dim peFileReader = assembly.GetMetadataReader() Assert.Equal(4, peFileReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(4, peFileReader.GetTableRowCount(TableIndex.ImplMap)) For Each method In peFileReader.GetImportedMethods() Dim import = method.GetImport() Dim moduleName As String = peFileReader.GetString(peFileReader.GetModuleReferenceName(import.Module)) Dim entryPointName As String = peFileReader.GetString(method.Name) Dim importname As String = peFileReader.GetString(import.Name) Select Case entryPointName Case "_Ansi" Assert.Equal("a", moduleName) Assert.Equal("_Ansi", importname) Assert.Equal(declareFlags Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAnsi, import.Attributes) Case "_Unicode" Assert.Equal("b", moduleName) Assert.Equal("_Unicode", importname) Assert.Equal(declareFlags Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetUnicode, import.Attributes) Case "_Auto" Assert.Equal("c", moduleName) Assert.Equal("_Auto", importname) Assert.Equal(declareFlags Or MethodImportAttributes.CharSetAuto, import.Attributes) Case "_Alias" Assert.Equal("d", moduleName) Assert.Equal("Baz", importname) Assert.Equal(declareFlags Or MethodImportAttributes.ExactSpelling Or MethodImportAttributes.CharSetAnsi, import.Attributes) Case Else Throw TestExceptionUtilities.UnexpectedValue(entryPointName) End Select Next End Sub CompileAndVerify(source, validator:=validator) End Sub <Fact> Public Sub TestPseudoAttributes_Declare_Modifiers() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Public Class D Shared Declare Sub F1 Lib "d" () Static Declare Sub F2 Lib "d" () ReadOnly Declare Sub F3 Lib "d" () WriteOnly Declare Sub F4 Lib "d" () Overrides Declare Sub F5 Lib "d" () Overridable Declare Sub F6 Lib "d" () MustOverride Declare Sub F7 Lib "d" () NotOverridable Declare Sub F8 Lib "d" () Overloads Declare Sub F9 Lib "d" () Shadows Declare Sub F10 Lib "d" () Dim Declare Sub F11 Lib "d" () Const Declare Sub F12 Lib "d" () Static Declare Sub F13 Lib "d" () Default Declare Sub F14 Lib "d" () WithEvents Declare Sub F17 Lib "d" () Widening Declare Sub F18 Lib "d" () Narrowing Declare Sub F19 Lib "d" () Partial Declare Sub F20 Lib "d" () MustInherit Declare Sub F21 Lib "d" () NotInheritable Declare Sub F22 Lib "d" () End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadDeclareFlags1, "Shared").WithArguments("Shared"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Static").WithArguments("Static"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "ReadOnly").WithArguments("ReadOnly"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "WriteOnly").WithArguments("WriteOnly"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Overrides").WithArguments("Overrides"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Overridable").WithArguments("Overridable"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "MustOverride").WithArguments("MustOverride"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "NotOverridable").WithArguments("NotOverridable"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Dim").WithArguments("Dim"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Const").WithArguments("Const"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Static").WithArguments("Static"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Default").WithArguments("Default"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "WithEvents").WithArguments("WithEvents"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Widening").WithArguments("Widening"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Narrowing").WithArguments("Narrowing"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "Partial").WithArguments("Partial"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "MustInherit").WithArguments("MustInherit"), Diagnostic(ERRID.ERR_BadDeclareFlags1, "NotInheritable").WithArguments("NotInheritable") ) End Sub <Fact> Public Sub TestPseudoAttributes_Declare_Missing1() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Public Class D Declare Sub Lib "d" () End Class ]]> </file> </compilation> ' TODO (tomat): Dev10 only reports ERR_InvalidUseOfKeyword CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Lib"), Diagnostic(ERRID.ERR_MissingLibInDeclare, "") ) End Sub <Fact> Public Sub TestPseudoAttributes_Declare_Missing2() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Public Class D Declare Sub $42 Lib "d" () End Class ]]> </file> </compilation> ' TODO (tomat): Dev10 only reports ERR_IllegalChar CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_IllegalChar, "$") ) End Sub #End Region #Region "InAttribute, OutAttribute" <Fact()> Public Sub InOutAttributes() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.InteropServices Class C Public Shared Sub M1(<[In]> ByRef a As Integer, <[In]> b As Integer, <[In]> ParamArray c As Object()) End Sub Public Shared Sub M2(<Out> ByRef d As Integer, <Out> e As Integer, <Out> ParamArray f As Object()) End Sub Public Shared Sub M3(<[In], Out> ByRef g As Integer, <[In], Out> h As Integer, <[In], [Out]> ParamArray i As Object()) End Sub Public Shared Sub M4(<[In]>Optional j As Integer = 1, <[Out]>Optional k As Integer = 2, <[In], [Out]>Optional l As Integer = 3) End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() Assert.Equal(12, reader.GetTableRowCount(TableIndex.Param)) For Each paramDef In reader.GetParameters() Dim row = reader.GetParameter(paramDef) Dim name As String = reader.GetString(row.Name) Dim expectedFlags As ParameterAttributes Select Case name Case "a", "b", "c" expectedFlags = ParameterAttributes.In Case "d", "e", "f" expectedFlags = ParameterAttributes.Out Case "g", "h", "i" expectedFlags = ParameterAttributes.In Or ParameterAttributes.Out Case "j" expectedFlags = ParameterAttributes.In Or ParameterAttributes.HasDefault Or ParameterAttributes.Optional Case "k" expectedFlags = ParameterAttributes.Out Or ParameterAttributes.HasDefault Or ParameterAttributes.Optional Case "l" expectedFlags = ParameterAttributes.In Or ParameterAttributes.Out Or ParameterAttributes.HasDefault Or ParameterAttributes.Optional Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Assert.Equal(expectedFlags, row.Attributes) Next End Sub) End Sub <Fact()> Public Sub InOutAttributes_Properties() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Imports System.Runtime.InteropServices Class C Public Property P1(<[In], Out>a As String, <[In]>b As String, <Out>c As String) As String Get Return Nothing End Get Set(<[In], Out>value As String) End Set End Property End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim reader = assembly.GetMetadataReader() ' property parameters are copied for both getter and setter Assert.Equal(3 + 3 + 1, reader.GetTableRowCount(TableIndex.Param)) For Each paramDef In reader.GetParameters() Dim row = reader.GetParameter(paramDef) Dim name As String = reader.GetString(row.Name) Dim expectedFlags As ParameterAttributes Select Case name Case "a", "value" expectedFlags = ParameterAttributes.In Or ParameterAttributes.Out Case "b" expectedFlags = ParameterAttributes.In Case "c" expectedFlags = ParameterAttributes.Out Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Assert.Equal(expectedFlags, row.Attributes) Next End Sub) End Sub #End Region #Region "ParamArrayAttribute" <WorkItem(529684, "DevDiv")> <Fact> Public Sub TestParamArrayAttributeForParams2() Dim source = <compilation> <file name="TestParamArrayAttributeForParams"><![CDATA[ imports System Module M1 Public Sub Lang(ParamArray list As Integer()) End Sub Public Sub Both(<[ParamArray]>ParamArray list As Integer()) End Sub Public Sub Custom(<[ParamArray]>list As Integer()) End Sub Public Sub None(list As Integer()) End Sub End Module ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) Dim attributeValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("M1"), NamedTypeSymbol) Dim lang = DirectCast(type.GetMember("Lang"), MethodSymbol) Dim both = DirectCast(type.GetMember("Both"), MethodSymbol) Dim custom = DirectCast(type.GetMember("Custom"), MethodSymbol) Dim none = DirectCast(type.GetMember("None"), MethodSymbol) Dim attrsLang = lang.Parameters(0).GetAttributes("System", "ParamArrayAttribute") Dim attrsBoth = both.Parameters(0).GetAttributes("System", "ParamArrayAttribute") Dim attrsCustom = custom.Parameters(0).GetAttributes("System", "ParamArrayAttribute") Dim attrsNone = none.Parameters(0).GetAttributes("System", "ParamArrayAttribute") If TypeOf type Is PENamedTypeSymbol Then ' An attribute is created when loading from metadata Assert.Equal(0, attrsLang.Count) Assert.Equal(0, attrsBoth.Count) Assert.Equal(0, attrsCustom.Count) Assert.Equal(0, attrsNone.Count) Assert.Equal(True, lang.Parameters(0).IsParamArray) Assert.Equal(True, both.Parameters(0).IsParamArray) Assert.Equal(True, custom.Parameters(0).IsParamArray) Assert.Equal(False, none.Parameters(0).IsParamArray) Else ' No attribute because paramarray is a language construct not a custom attribute Assert.Equal(0, attrsLang.Count) Assert.Equal(1, attrsBoth.Count) Assert.Equal(1, attrsCustom.Count) Assert.Equal(0, attrsNone.Count) Assert.Equal(True, lang.Parameters(0).IsParamArray) Assert.Equal(True, both.Parameters(0).IsParamArray) Assert.Equal(True, custom.Parameters(0).IsParamArray) Assert.Equal(False, none.Parameters(0).IsParamArray) End If End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub #End Region #Region "SpecialNameAttribute" <Fact> Public Sub SpecialName_AllTargets() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Runtime.CompilerServices <SpecialName> Class Z <SpecialName> Sub m() End Sub <SpecialName> Dim f As Integer <SpecialName> Property p1 As Integer <SpecialName> ReadOnly Property p2 As Integer Get Return 1 End Get End Property <SpecialName> Property p3 As Integer <SpecialName()> Get Return 1 End Get <SpecialName> Set(value As Integer) End Set End Property <SpecialName> Event e As Action End Class <SpecialName> Module M <SpecialName> Public WithEvents we As New Z <SpecialName> Sub WEHandler() Handles we.e End Sub End Module Enum En <SpecialName> A = 1 <SpecialName> B End Enum <SpecialName> Structure S End Structure ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim peFileReader = assembly.GetMetadataReader() For Each ca In peFileReader.CustomAttributes Dim name = GetAttributeName(peFileReader, ca) Assert.NotEqual("SpecialNameAttribute", name) Next For Each typeDef In peFileReader.TypeDefinitions Dim row = peFileReader.GetTypeDefinition(typeDef) Dim name = peFileReader.GetString(row.Name) Select Case name Case "S", "Z", "M" Assert.Equal(TypeAttributes.SpecialName, row.Attributes And TypeAttributes.SpecialName) Case "<Module>", "En" Assert.Equal(0, row.Attributes And TypeAttributes.SpecialName) Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next For Each methodDef In peFileReader.MethodDefinitions Dim flags = peFileReader.GetMethod(methodDef).Attributes Assert.Equal(MethodAttributes.SpecialName, flags And MethodAttributes.SpecialName) Next For Each fieldDef In peFileReader.FieldDefinitions Dim field = peFileReader.GetField(fieldDef) Dim name = peFileReader.GetString(field.Name) Dim flags = field.Attributes Select Case name Case "En", "value__", "_we", "f", "A", "B" Assert.Equal(FieldAttributes.SpecialName, flags And FieldAttributes.SpecialName) Case "_p1", "eEvent" Assert.Equal(0, flags And FieldAttributes.SpecialName) Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next For Each propertyDef In peFileReader.PropertyDefinitions Dim prop = peFileReader.GetProperty(propertyDef) Dim name = peFileReader.GetString(prop.Name) Dim flags = prop.Attributes Select Case name Case "p1", "p2", "p3" Assert.Equal(PropertyAttributes.SpecialName, flags And PropertyAttributes.SpecialName) Case "we" Assert.Equal(0, flags And PropertyAttributes.SpecialName) Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next For Each eventDef In peFileReader.EventDefinitions Dim flags = peFileReader.GetEvent(eventDef).Attributes Assert.Equal(EventAttributes.SpecialName, flags And EventAttributes.SpecialName) Next End Sub) End Sub #End Region #Region "SerializableAttribute, NonSerializedAttribute" <Fact> Public Sub Serializable_NonSerialized_AllTargets() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Runtime.CompilerServices <Serializable> Class A <NonSerialized> Event e1 As Action <NonSerialized> Event e3(a As Integer) End Class <Serializable> Module M <NonSerialized> Public WithEvents we As New EventClass Sub WEHandler() Handles we.e2 End Sub End Module <Serializable> Structure B <NonSerialized> Dim x As Integer End Structure <Serializable> Enum E <NonSerialized> A = 1 End Enum <Serializable> Delegate Sub D() <Serializable> Class EventClass <NonSerialized> Public Event e2() Sub RaiseEvents() RaiseEvent e2() End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(assembly, _omitted) Dim peFileReader = assembly.GetMetadataReader() For Each ca In peFileReader.CustomAttributes Dim name = GetAttributeName(peFileReader, ca) Assert.NotEqual("SerializableAttribute", name) Assert.NotEqual("NonSerializedAttribute", name) Next For Each typeDef In peFileReader.TypeDefinitions Dim row = peFileReader.GetTypeDefinition(typeDef) Dim name = peFileReader.GetString(row.Name) Select Case name Case "A", "B", "D", "E", "EventClass", "M" Assert.Equal(TypeAttributes.Serializable, row.Attributes And TypeAttributes.Serializable) Case "<Module>", "StandardModuleAttribute", "e2EventHandler", "e3EventHandler" Assert.Equal(0, row.Attributes And TypeAttributes.Serializable) Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next For Each fieldDef In peFileReader.FieldDefinitions Dim field = peFileReader.GetField(fieldDef) Dim name = peFileReader.GetString(field.Name) Dim flags = field.Attributes Select Case name Case "e1Event", "x", "A", "e2Event", "_we", "e3Event" Assert.Equal(FieldAttributes.NotSerialized, flags And FieldAttributes.NotSerialized) Case "value__" Assert.Equal(0, flags And FieldAttributes.NotSerialized) End Select Next End Sub) End Sub <WorkItem(545199, "DevDiv")> <Fact> Sub Serializable_NonSerialized_CustomEvents() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I <NonSerialized> Event e1 As Action End Interface MustInherit Class C <NonSerialized> Custom Event e2 As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class ]]> </file> </compilation> CompilationUtils.AssertTheseDiagnostics(CreateCompilationWithMscorlib(source), <expected><![CDATA[ BC30662: Attribute 'NonSerializedAttribute' cannot be applied to 'e1' because the attribute is not valid on this declaration type. <NonSerialized> ~~~~~~~~~~~~~ BC30662: Attribute 'NonSerializedAttribute' cannot be applied to 'e2' because the attribute is not valid on this declaration type. <NonSerialized> ~~~~~~~~~~~~~ ]]></expected>) End Sub #End Region #Region "AttributeUsageAttribute" <WorkItem(541733, "DevDiv")> <Fact()> Public Sub TestSourceOverrideWellKnownAttribute_01() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Namespace System <AttributeUsage(AttributeTargets.Class)> <AttributeUsage(AttributeTargets.Class)> Class AttributeUsageAttribute Inherits Attribute Public Sub New(x As AttributeTargets) End Sub End Class End Namespace ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) ' BC30663: Attribute 'AttributeUsageAttribute' cannot be applied multiple times. compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "AttributeUsage(AttributeTargets.Class)").WithArguments("AttributeUsageAttribute")) End Sub <WorkItem(541733, "DevDiv")> <Fact()> Public Sub TestSourceOverrideWellKnownAttribute_02() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Namespace System <AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)> <AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)> Class AttributeUsageAttribute Inherits Attribute Public Sub New(x As AttributeTargets) End Sub Public Property AllowMultiple As Boolean Get Return False End Get Set End Set End Property End Class End Namespace ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary) Dim attributeValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("System"), NamespaceSymbol) Dim attrType = ns.GetTypeMember("AttributeUsageAttribute") Dim attrs = attrType.GetAttributes(attrType) Assert.Equal(2, attrs.Count) ' Verify attributes Dim attrSym = attrs(0) Assert.Equal(1, attrSym.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Enum, attrSym.CommonConstructorArguments(0).Kind) Assert.Equal(AttributeTargets.Class, DirectCast(attrSym.CommonConstructorArguments(0).Value, AttributeTargets)) Assert.Equal(1, attrSym.CommonNamedArguments.Length) Assert.Equal("Boolean", attrSym.CommonNamedArguments(0).Value.Type.ToDisplayString) Assert.Equal("AllowMultiple", attrSym.CommonNamedArguments(0).Key) Assert.Equal(True, attrSym.CommonNamedArguments(0).Value.Value) attrSym = attrs(1) Assert.Equal(1, attrSym.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Enum, attrSym.CommonConstructorArguments(0).Kind) Assert.Equal(AttributeTargets.Class, DirectCast(attrSym.CommonConstructorArguments(0).Value, AttributeTargets)) Assert.Equal(1, attrSym.CommonNamedArguments.Length) Assert.Equal("Boolean", attrSym.CommonNamedArguments(0).Value.Type.ToDisplayString) Assert.Equal("AllowMultiple", attrSym.CommonNamedArguments(0).Key) Assert.Equal(True, attrSym.CommonNamedArguments(0).Value.Value) ' Verify AttributeUsage Dim attributeUage = attrType.GetAttributeUsageInfo() Assert.Equal(AttributeTargets.Class, attributeUage.ValidTargets) Assert.Equal(True, attributeUage.AllowMultiple) Assert.Equal(True, attributeUage.Inherited) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact()> Public Sub TestSourceOverrideWellKnownAttribute_03() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Namespace System <AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)> ' First AttributeUsageAttribute is used for determining AttributeUsage. <AttributeUsage(AttributeTargets.Class, AllowMultiple:= False)> Class AttributeUsageAttribute Inherits Attribute Public Sub New(x As AttributeTargets) End Sub Public Property AllowMultiple As Boolean Get Return False End Get Set End Set End Property End Class End Namespace ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub TestSourceOverrideWellKnownAttribute_03_DifferentOrder() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Namespace System <AttributeUsage(AttributeTargets.Class, AllowMultiple:= False)> ' First AttributeUsageAttribute is used for determining AttributeUsage. <AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)> Class AttributeUsageAttribute Inherits Attribute Public Sub New(x As AttributeTargets) End Sub Public Property AllowMultiple As Boolean Get Return False End Get Set End Set End Property End Class End Namespace ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "AttributeUsage(AttributeTargets.Class, AllowMultiple:= True)").WithArguments("AttributeUsageAttribute")) End Sub <Fact()> Public Sub TestAttributeUsageInvalidTargets_01() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Namespace System <AttributeUsage(0)> ' No error here Class X Inherits Attribute End Class <AttributeUsage(-1)> ' No error here Class Y Inherits Attribute End Class End Namespace ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub TestAttributeUsageInvalidTargets_02() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Namespace System <AttributeUsage(0)> ' No error here Class X Inherits Attribute End Class <AttributeUsage(-1)> ' No error here Class Y Inherits Attribute End Class <X> ' Error here <Y> ' No Error here Class Z End Class End Namespace ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30662: Attribute 'X' cannot be applied to 'Z' because the attribute is not valid on this declaration type. <X> ' Error here ~ ]]></expected>) End Sub #End Region #Region "Security Attributes" <Fact> Public Sub TestHostProtectionAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ <System.Security.Permissions.HostProtection(MayLeakOnAbort := true)> public structure EventDescriptor end structure ]]> </file> </compilation> Dim attributeValidator As Action(Of ModuleSymbol) = Sub([module] As ModuleSymbol) Dim assembly = [module].ContainingAssembly Dim sourceAssembly = DirectCast(assembly, SourceAssemblySymbol) Dim compilation = sourceAssembly.DeclaringCompilation ' Get System.Security.Permissions.HostProtection Dim emittedName = MetadataTypeName.FromNamespaceAndTypeName("System.Security.Permissions", "HostProtectionAttribute") Dim hostProtectionAttr As NamedTypeSymbol = sourceAssembly.CorLibrary.LookupTopLevelMetadataType(emittedName, True) Assert.NotNull(hostProtectionAttr) ' Verify type security attributes Dim type = DirectCast([module].GlobalNamespace.GetMember("EventDescriptor"), Microsoft.Cci.ITypeDefinition) Debug.Assert(type.HasDeclarativeSecurity) Dim typeSecurityAttributes As IEnumerable(Of Microsoft.Cci.SecurityAttribute) = type.SecurityAttributes Assert.Equal(1, typeSecurityAttributes.Count()) ' Verify <System.Security.Permissions.HostProtection(MayLeakOnAbort := true)> Dim securityAttribute = typeSecurityAttributes.First() Assert.Equal(Cci.SecurityAction.LinkDemand, securityAttribute.Action) Dim typeAttribute = DirectCast(securityAttribute.Attribute, VisualBasicAttributeData) Assert.Equal(hostProtectionAttr, typeAttribute.AttributeClass) Assert.Equal(0, typeAttribute.CommonConstructorArguments.Length) typeAttribute.VerifyNamedArgumentValue(0, "MayLeakOnAbort", TypedConstantKind.Primitive, True) End Sub CompileAndVerify(source, emitOptions:=EmitOptions.RefEmitBug, sourceSymbolValidator:=attributeValidator) End Sub <Fact()> Public Sub TestValidSecurityAction() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Security.Permissions Imports System.Security.Principal <PrincipalPermission(DirectCast(1, SecurityAction))> <PrincipalPermission(SecurityAction.Assert)> <PrincipalPermission(SecurityAction.Demand)> <PrincipalPermission(SecurityAction.Deny)> <PrincipalPermission(SecurityAction.PermitOnly)> Class A End Class Module Module1 Sub Main() End Sub End Module]]> </file> </compilation> CompileAndVerify(source) End Sub <Fact()> Public Sub TestValidSecurityActionForTypeOrMethod() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Security.Permissions Imports System.Security <MySecurityAttribute(Directcast(1,SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly. <MySecurityAttribute(SecurityAction.Assert)> <MySecurityAttribute(SecurityAction.Demand)> <MySecurityAttribute(SecurityAction.Deny)> <MySecurityAttribute(SecurityAction.InheritanceDemand)> <MySecurityAttribute(SecurityAction.LinkDemand)> <MySecurityAttribute(SecurityAction.PermitOnly)> <MyCodeAccessSecurityAttribute(Directcast(1,SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly. <MyCodeAccessSecurityAttribute(SecurityAction.Assert)> <MyCodeAccessSecurityAttribute(SecurityAction.Demand)> <MyCodeAccessSecurityAttribute(SecurityAction.Deny)> <MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)> <MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)> <MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)> class Test <MySecurityAttribute(directcast(1, SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly. <MySecurityAttribute(SecurityAction.Assert)> <MySecurityAttribute(SecurityAction.Demand)> <MySecurityAttribute(SecurityAction.Deny)> <MySecurityAttribute(SecurityAction.InheritanceDemand)> <MySecurityAttribute(SecurityAction.LinkDemand)> <MySecurityAttribute(SecurityAction.PermitOnly)> <MyCodeAccessSecurityAttribute(Directcast(1,SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly. <MyCodeAccessSecurityAttribute(SecurityAction.Assert)> <MyCodeAccessSecurityAttribute(SecurityAction.Demand)> <MyCodeAccessSecurityAttribute(SecurityAction.Deny)> <MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)> <MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)> <MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)> public shared sub Main() End Sub end class class MySecurityAttribute inherits SecurityAttribute public sub new (a as SecurityAction) mybase.new(a) end sub public overrides function CreatePermission() as IPermission return nothing end function end class class MyCodeAccessSecurityAttribute inherits CodeAccessSecurityAttribute public sub new (a as SecurityAction) mybase.new(a) end sub public overrides function CreatePermission() as IPermission return nothing end function public shared sub Main() end sub end class ]]> </file> </compilation> CompileAndVerify(source) End Sub <Fact()> Public Sub TestValidSecurityActionsForAssembly() Dim source = <compilation> <file name="a.vb"> <![CDATA[ imports System imports System.Security imports System.Security.Permissions <assembly: MySecurityAttribute(SecurityAction.RequestMinimum)> <assembly: MySecurityAttribute(SecurityAction.RequestOptional)> <assembly: MySecurityAttribute(SecurityAction.RequestRefuse)> <assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)> <assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)> <assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)> class MySecurityAttribute inherits SecurityAttribute public sub new (a as SecurityAction) mybase.new(a) end sub public overrides function CreatePermission() as IPermission return nothing end function end class class MyCodeAccessSecurityAttribute inherits CodeAccessSecurityAttribute public sub new (a as SecurityAction) mybase.new(a) end sub public overrides function CreatePermission() as IPermission return nothing end function public shared sub Main() end sub end class ]]> </file> </compilation> CompileAndVerify(source) End Sub <Fact()> Public Sub TestInvalidSecurityActionErrors() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Security.Permissions Public Class MySecurityAttribute Inherits SecurityAttribute Public Sub New(action As SecurityAction) MyBase.New(action) End Sub Public Overrides Function CreatePermission() As System.Security.IPermission Return Nothing End Function End Class <MySecurityAttribute(DirectCast(0, SecurityAction))> <MySecurityAttribute(DirectCast(11, SecurityAction))> <MySecurityAttribute(DirectCast(-1, SecurityAction))> <FileIOPermission(DirectCast(0, SecurityAction))> <FileIOPermission(DirectCast(11, SecurityAction))> <FileIOPermission(DirectCast(-1, SecurityAction))> <FileIOPermission()> Class A <FileIOPermission(SecurityAction.Demand)> Public Field as Integer End Class Module Module1 Sub Main() End Sub End Module]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OmittedArgument2, "FileIOPermission").WithArguments("action", "Public Overloads Sub New(action As System.Security.Permissions.SecurityAction)"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(0, SecurityAction)").WithArguments("MySecurityAttribute", "DirectCast(0, SecurityAction)"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(11, SecurityAction)").WithArguments("MySecurityAttribute", "DirectCast(11, SecurityAction)"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(-1, SecurityAction)").WithArguments("MySecurityAttribute", "DirectCast(-1, SecurityAction)"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(0, SecurityAction)").WithArguments("FileIOPermission", "DirectCast(0, SecurityAction)"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(11, SecurityAction)").WithArguments("FileIOPermission", "DirectCast(11, SecurityAction)"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "DirectCast(-1, SecurityAction)").WithArguments("FileIOPermission", "DirectCast(-1, SecurityAction)"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "FileIOPermission").WithArguments("FileIOPermissionAttribute", "Field")) End Sub <Fact()> Public Sub TestMissingSecurityActionErrors() Dim source = <compilation> <file name="a.vb"> <![CDATA[ imports System.Security imports System.Security.Permissions Public Class MySecurityAttribute Inherits CodeAccessSecurityAttribute Public Field As Boolean Public Property Prop As Boolean Public Overrides Function CreatePermission() As IPermission Return Nothing End Function Public Sub New() MyBase.New(SecurityAction.Assert) End Sub Public Sub New(x As Integer, a1 As SecurityAction) MyBase.New(a1) End Sub End Class <MySecurityAttribute()> <MySecurityAttribute(Field := true)> <MySecurityAttribute(Field := true, Prop := true)> <MySecurityAttribute(Prop := true)> <MySecurityAttribute(Prop := true, Field := true)> <MySecurityAttribute(0, SecurityAction.Assert)> public class C end class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"), Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"), Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"), Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"), Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute"), Diagnostic(ERRID.ERR_SecurityAttributeMissingAction, "MySecurityAttribute").WithArguments("MySecurityAttribute") ) End Sub <Fact()> Public Sub TestInvalidSecurityActionsForAssemblyErrors() Dim source = <compilation> <file name="a.vb"> <![CDATA[ imports System.Security imports System.Security.Permissions <assembly: MySecurityAttribute(DirectCast(1, SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly. <assembly: MySecurityAttribute(SecurityAction.Assert)> <assembly: MySecurityAttribute(SecurityAction.Demand)> <assembly: MySecurityAttribute(SecurityAction.Deny)> <assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)> <assembly: MySecurityAttribute(SecurityAction.LinkDemand)> <assembly: MySecurityAttribute(SecurityAction.PermitOnly)> <assembly: MyCodeAccessSecurityAttribute(DirectCast(1, SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly. <assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)> <assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)> <assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)> <assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)> <assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)> <assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)> class MySecurityAttribute inherits SecurityAttribute public sub new (a as SecurityAction) mybase.new(a) end sub public overrides function CreatePermission() as IPermission return nothing end function end class class MyCodeAccessSecurityAttribute inherits CodeAccessSecurityAttribute public sub new (a as SecurityAction) mybase.new(a) end sub public overrides function CreatePermission() as IPermission return nothing end function public shared sub Main() end sub end class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) VerifyDiagnostics(compilation, Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.Deny").WithArguments("Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.Deny").WithArguments("Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "DirectCast(1, SecurityAction)").WithArguments("DirectCast(1, SecurityAction)"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "DirectCast(1, SecurityAction)").WithArguments("DirectCast(1, SecurityAction)"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly")) End Sub <Fact()> Public Sub TestInvalidSecurityActionForTypeOrMethod() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Security.Permissions Imports System.Security <MySecurityAttribute(SecurityAction.RequestMinimum)> <MySecurityAttribute(SecurityAction.RequestOptional)> <MySecurityAttribute(SecurityAction.RequestRefuse)> <MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)> <MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)> <MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)> class Test <MySecurityAttribute(SecurityAction.RequestMinimum)> <MySecurityAttribute(SecurityAction.RequestOptional)> <MySecurityAttribute(SecurityAction.RequestRefuse)> <MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)> <MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)> <MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)> public shared sub Main() End Sub end class class MySecurityAttribute inherits SecurityAttribute public sub new (a as SecurityAction) mybase.new(a) end sub public overrides function CreatePermission() as IPermission return nothing end function end class class MyCodeAccessSecurityAttribute inherits CodeAccessSecurityAttribute public sub new (a as SecurityAction) mybase.new(a) end sub public overrides function CreatePermission() as IPermission return nothing end function public shared sub Main() end sub end class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) VerifyDiagnostics(compilation, Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestMinimum").WithArguments("RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestOptional").WithArguments("RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestRefuse").WithArguments("RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestMinimum").WithArguments("RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestOptional").WithArguments("RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestRefuse").WithArguments("RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestMinimum").WithArguments("RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestOptional").WithArguments("RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestRefuse").WithArguments("RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestMinimum").WithArguments("RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestOptional").WithArguments("RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.RequestRefuse").WithArguments("RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), Diagnostic(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse")) End Sub <WorkItem(546623, "DevDiv")> <Fact> Public Sub TestSecurityAttributeInvalidTarget() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Security Imports System.Security.Permissions Class Program <MyPermission(SecurityAction.Demand)> _ Private x As Integer End Class <AttributeUsage(AttributeTargets.All)> _ Class MyPermissionAttribute Inherits CodeAccessSecurityAttribute Public Sub New(action As SecurityAction) MyBase.New(action) End Sub Public Overrides Function CreatePermission() As IPermission Return Nothing End Function End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_SecurityAttributeInvalidTarget, "MyPermission").WithArguments("MyPermissionAttribute")) End Sub <WorkItem(544929, "DevDiv")> <Fact> Public Sub PrincipalPermissionAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ imports System.Security.Permissions Class Program <PrincipalPermission(DirectCast(1,SecurityAction))> ' Native compiler allows this security action value for type/method security attributes, but not for assembly. <PrincipalPermission(SecurityAction.Assert)> <PrincipalPermission(SecurityAction.Demand)> <PrincipalPermission(SecurityAction.Deny)> <PrincipalPermission(SecurityAction.InheritanceDemand)> ' BC31209 <PrincipalPermission(SecurityAction.LinkDemand)> ' BC31209 <PrincipalPermission(SecurityAction.PermitOnly)> public shared sub Main() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics(Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "SecurityAction.Deny").WithArguments("Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), Diagnostic(ERRID.ERR_PrincipalPermissionInvalidAction, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), Diagnostic(ERRID.ERR_PrincipalPermissionInvalidAction, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand")) End Sub <WorkItem(544956, "DevDiv")> <Fact> Public Sub SuppressUnmanagedCodeSecurityAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ imports System <System.Security.SuppressUnmanagedCodeSecurityAttribute> Class Program <System.Security.SuppressUnmanagedCodeSecurityAttribute> public shared sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub #End Region #Region "ComImportAttribute" <Fact> Public Sub TestCompImport() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <ComImport()> Public Interface I Property PI As Object Event EI As Action Sub MI() End Interface <ComImport> Public Class C Dim WithEvents WEC As New EventClass Property PC As Object Property QC As Object Get Return Nothing End Get Set(value AS Object) End Set End Property Custom Event CEC As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Event EC As Action Sub MC End Sub End Class <ComImport> Class EventClass Public Event XEvent() End Class ]]> </file> </compilation> CompileAndVerify(source, validator:= Sub(m, _omitted) Dim reader = m.GetMetadataReader() For Each methodDef In reader.MethodDefinitions Dim row = reader.GetMethod(methodDef) Dim name = reader.GetString(row.Name) Dim actual = row.ImplAttributes Dim expected As MethodImplAttributes Select Case name Case ".ctor" Continue For Case "get_WEC", "get_PC", "set_PC", "get_QC", "set_QC", "add_CEC", "remove_CEC", "raise_CEC", "MC" ' runtime managed internalcall expected = MethodImplAttributes.InternalCall Or MethodImplAttributes.Runtime Case "set_WEC" ' runtime managed internalcall synchronized expected = MethodImplAttributes.InternalCall Or MethodImplAttributes.Runtime Or MethodImplAttributes.Synchronized Case "BeginInvoke", "EndInvoke", "Invoke" ' runtime managed expected = MethodImplAttributes.Runtime Case "get_PI", "set_PI", "add_EI", "remove_EI", "MI" ' cil managed expected = MethodImplAttributes.IL Case "add_XEvent", "remove_XEvent", "add_EC", "remove_EC" ' Dev11: runtime managed internalcall synchronized ' Roslyn: runtime managed internalcall expected = MethodImplAttributes.InternalCall Or MethodImplAttributes.Runtime End Select Assert.Equal(expected, actual) Next End Sub) End Sub #End Region #Region "ClassInterfaceAttribute" <Fact> Public Sub TestClassInterfaceAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices ' Valid cases <Assembly: ClassInterface(ClassInterfaceType.None)> <ClassInterface(ClassInterfaceType.AutoDispatch)> Public Class Class1 End Class <ClassInterface(ClassInterfaceType.AutoDual)> Public Class Class2 End Class <ClassInterface(CShort(0))> Public Class Class4 End Class <ClassInterface(CShort(1))> Public Class Class5 End Class <ClassInterface(CShort(2))> Public Class Class6 End Class ' Invalid cases <ClassInterface(DirectCast(-1, ClassInterfaceType))> Public Class InvalidClass1 End Class <ClassInterface(DirectCast(3, ClassInterfaceType))> Public Class InvalidClass2 End Class <ClassInterface(CShort(-1))> Public Class InvalidClass3 End Class <ClassInterface(CShort(3))> Public Class InvalidClass4 End Class <ClassInterface(3)> Public Class InvalidClass5 End Class <ClassInterface(ClassInterfaceType.None)> Public Interface InvalidTarget End Interface ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30127: Attribute 'System.Runtime.InteropServices.ClassInterfaceAttribute' is not valid: Incorrect argument value. <ClassInterface(DirectCast(-1, ClassInterfaceType))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30127: Attribute 'System.Runtime.InteropServices.ClassInterfaceAttribute' is not valid: Incorrect argument value. <ClassInterface(DirectCast(3, ClassInterfaceType))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30127: Attribute 'System.Runtime.InteropServices.ClassInterfaceAttribute' is not valid: Incorrect argument value. <ClassInterface(CShort(-1))> ~~~~~~~~~~ BC30127: Attribute 'System.Runtime.InteropServices.ClassInterfaceAttribute' is not valid: Incorrect argument value. <ClassInterface(CShort(3))> ~~~~~~~~~ BC30519: Overload resolution failed because no accessible 'New' can be called without a narrowing conversion: 'Public Overloads Sub New(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)': Argument matching parameter 'classInterfaceType' narrows from 'Integer' to 'System.Runtime.InteropServices.ClassInterfaceType'. 'Public Overloads Sub New(classInterfaceType As Short)': Argument matching parameter 'classInterfaceType' narrows from 'Integer' to 'Short'. <ClassInterface(3)> ~~~~~~~~~~~~~~ BC30662: Attribute 'ClassInterfaceAttribute' cannot be applied to 'InvalidTarget' because the attribute is not valid on this declaration type. <ClassInterface(ClassInterfaceType.None)> ~~~~~~~~~~~~~~ ]]></expected>) End Sub #End Region #Region "InterfaceTypeAttribute, TypeLibTypeAttribute" <Fact> Public Sub TestInterfaceTypeAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices ' Valid cases <InterfaceType(ComInterfaceType.InterfaceIsDual)> Public Interface Interface1 End Interface <InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> Public Interface Interface2 End Interface <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface Interface4 End Interface ' ComInterfaceType.InterfaceIsIInspectable seems to be undefined in version of mscorlib used by the test framework. <InterfaceType(DirectCast(3, ComInterfaceType))> Public Interface Interface3 End Interface <InterfaceType(CShort(0))> Public Interface Interface5 End Interface <InterfaceType(CShort(1))> Public Interface Interface6 End Interface <InterfaceType(CShort(2))> Public Interface Interface7 End Interface <InterfaceType(CShort(3))> Public Interface Interface8 End Interface ' Invalid cases <InterfaceType(DirectCast(-1, ComInterfaceType))> Public Interface InvalidInterface1 End Interface <InterfaceType(DirectCast(4, ComInterfaceType))> Public Interface InvalidInterface2 End Interface <InterfaceType(CShort(-1))> Public Interface InvalidInterface3 End Interface <InterfaceType(CShort(4))> Public Interface InvalidInterface4 End Interface <InterfaceType(4)> Public Interface InvalidInterface5 End Interface <InterfaceType(ComInterfaceType.InterfaceIsDual)> Public Class InvalidTarget End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30127: Attribute 'System.Runtime.InteropServices.InterfaceTypeAttribute' is not valid: Incorrect argument value. <InterfaceType(DirectCast(-1, ComInterfaceType))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30127: Attribute 'System.Runtime.InteropServices.InterfaceTypeAttribute' is not valid: Incorrect argument value. <InterfaceType(DirectCast(4, ComInterfaceType))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30127: Attribute 'System.Runtime.InteropServices.InterfaceTypeAttribute' is not valid: Incorrect argument value. <InterfaceType(CShort(-1))> ~~~~~~~~~~ BC30127: Attribute 'System.Runtime.InteropServices.InterfaceTypeAttribute' is not valid: Incorrect argument value. <InterfaceType(CShort(4))> ~~~~~~~~~ BC30519: Overload resolution failed because no accessible 'New' can be called without a narrowing conversion: 'Public Overloads Sub New(interfaceType As System.Runtime.InteropServices.ComInterfaceType)': Argument matching parameter 'interfaceType' narrows from 'Integer' to 'System.Runtime.InteropServices.ComInterfaceType'. 'Public Overloads Sub New(interfaceType As Short)': Argument matching parameter 'interfaceType' narrows from 'Integer' to 'Short'. <InterfaceType(4)> ~~~~~~~~~~~~~ BC30662: Attribute 'InterfaceTypeAttribute' cannot be applied to 'InvalidTarget' because the attribute is not valid on this declaration type. <InterfaceType(ComInterfaceType.InterfaceIsDual)> ~~~~~~~~~~~~~ ]]></expected>) End Sub <WorkItem(546664, "DevDiv")> <Fact()> Public Sub TestIsExtensibleInterface() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Option Strict Off Imports System Imports Microsoft.VisualBasic Imports System.Runtime.InteropServices ' InterfaceTypeAttribute ' Extensible interface <InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> Public Interface ExtensibleInterface1 End Interface ' Not Extensible interface <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface NotExtensibleInterface1 End Interface ' Extensible interface via inheritance Public Interface ExtensibleInterface2 Inherits ExtensibleInterface1 End Interface ' TypeLibTypeAttribute ' Extensible interface <TypeLibTypeAttribute(CType(TypeLibTypeFlags.FAppObject, Int16))> Public Interface ExtensibleInterface3 End Interface ' Extensible interface <TypeLibTypeAttribute(TypeLibTypeFlags.FAppObject)> Public Interface ExtensibleInterface4 End Interface ' Extensible interface <TypeLibTypeAttribute(0)> Public Interface ExtensibleInterface5 End Interface ' Extensible interface via inheritance Public Interface ExtensibleInterface6 Inherits ExtensibleInterface3 End Interface ' Not Extensible interface <TypeLibTypeAttribute(TypeLibTypeFlags.FNonExtensible)> Public Interface NotExtensibleInterface2 End Interface ' Not Extensible interface <TypeLibTypeAttribute(CType(TypeLibTypeFlags.FNonExtensible Or TypeLibTypeFlags.FAppObject, Int16))> Public Interface NotExtensibleInterface3 End Interface ]]> </file> </compilation>, options:=TestOptions.ReleaseDll) Dim validator = Sub(m As ModuleSymbol) Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface1").IsExtensibleInterfaceNoUseSiteDiagnostics()) Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface2").IsExtensibleInterfaceNoUseSiteDiagnostics()) Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface3").IsExtensibleInterfaceNoUseSiteDiagnostics()) Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface4").IsExtensibleInterfaceNoUseSiteDiagnostics()) Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface5").IsExtensibleInterfaceNoUseSiteDiagnostics()) Assert.True(m.GlobalNamespace.GetTypeMember("ExtensibleInterface6").IsExtensibleInterfaceNoUseSiteDiagnostics()) Assert.False(m.GlobalNamespace.GetTypeMember("NotExtensibleInterface1").IsExtensibleInterfaceNoUseSiteDiagnostics()) Assert.False(m.GlobalNamespace.GetTypeMember("NotExtensibleInterface2").IsExtensibleInterfaceNoUseSiteDiagnostics()) Assert.False(m.GlobalNamespace.GetTypeMember("NotExtensibleInterface3").IsExtensibleInterfaceNoUseSiteDiagnostics()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=validator, symbolValidator:=validator) End Sub <WorkItem(546664, "DevDiv")> <Fact()> Public Sub TestIsExtensibleInterface_LateBinding() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Option Strict Off Imports System Imports Microsoft.VisualBasic Imports System.Runtime.InteropServices ' InterfaceTypeAttribute ' Extensible interface <InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> Public Interface ExtensibleInterface1 End Interface ' Not Extensible interface <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface NotExtensibleInterface1 End Interface ' Extensible interface via inheritance Public Interface ExtensibleInterface2 Inherits ExtensibleInterface1 End Interface ' TypeLibTypeAttribute ' Extensible interface <TypeLibTypeAttribute(CType(TypeLibTypeFlags.FAppObject, Int16))> Public Interface ExtensibleInterface3 End Interface ' Extensible interface <TypeLibTypeAttribute(TypeLibTypeFlags.FAppObject)> Public Interface ExtensibleInterface4 End Interface ' Extensible interface <TypeLibTypeAttribute(0)> Public Interface ExtensibleInterface5 End Interface ' Extensible interface via inheritance Public Interface ExtensibleInterface6 Inherits ExtensibleInterface3 End Interface ' Not Extensible interface <TypeLibTypeAttribute(TypeLibTypeFlags.FNonExtensible)> Public Interface NotExtensibleInterface2 End Interface ' Not Extensible interface <TypeLibTypeAttribute(CType(TypeLibTypeFlags.FNonExtensible Or TypeLibTypeFlags.FAppObject, Int16))> Public Interface NotExtensibleInterface3 End Interface Public Class C Dim fExtensible1 As ExtensibleInterface1 Dim fExtensible2 As ExtensibleInterface2 Dim fExtensible3 As ExtensibleInterface3 Dim fExtensible4 As ExtensibleInterface4 Dim fExtensible5 As ExtensibleInterface5 Dim fExtensible6 As ExtensibleInterface6 Dim fNotExtensible1 As NotExtensibleInterface1 Dim fNotExtensible2 As NotExtensibleInterface2 Dim fNotExtensible3 As NotExtensibleInterface3 Public Sub Foo() fExtensible1.LateBound() fExtensible2.LateBound() fExtensible3.LateBound() fExtensible4.LateBound() fExtensible5.LateBound() fExtensible6.LateBound() fNotExtensible1.LateBound() fNotExtensible2.LateBound() fNotExtensible3.LateBound() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll) Dim expectedErrors = <errors><![CDATA[ BC30456: 'LateBound' is not a member of 'NotExtensibleInterface1'. fNotExtensible1.LateBound() ~~~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'LateBound' is not a member of 'NotExtensibleInterface2'. fNotExtensible2.LateBound() ~~~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'LateBound' is not a member of 'NotExtensibleInterface3'. fNotExtensible3.LateBound() ~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <WorkItem(546664, "DevDiv")> <Fact()> Public Sub Bug16489_StackOverflow() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Option Strict Off Imports System Imports Microsoft.VisualBasic Imports System.Runtime.InteropServices Module Module1 Class XAttribute Inherits Attribute Public Sub New(x As Object) End Sub End Class Sub Main() End Sub <InterfaceType(CType(3, ComInterfaceType))> <X(DirectCast(New Object(), II1).GoHome())> Interface II1 End Interface Property I1 As II2 <InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> <X(DirectCast(New Object(), II2).GoHome())> Interface II2 End Interface Property I2 As II2 <TypeLibTypeAttribute(CType(TypeLibTypeFlags.FAppObject, Int16))> <X(DirectCast(New Object(), II3).GoHome())> Interface II3 End Interface Property I3 As II3 <TypeLibTypeAttribute(TypeLibTypeFlags.FAppObject)> <X(DirectCast(New Object(), II4).GoHome())> Interface II4 End Interface Property I4 As II4 End Module ]]> </file> </compilation>) Dim expectedErrors = <errors><![CDATA[ BC30059: Constant expression is required. <X(DirectCast(New Object(), II1).GoHome())> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. <X(DirectCast(New Object(), II2).GoHome())> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. <X(DirectCast(New Object(), II3).GoHome())> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. <X(DirectCast(New Object(), II4).GoHome())> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub #End Region #Region "TypeLibVersionAttribute" <Fact> Public Sub TestTypeLibVersionAttribute_Valid() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices <Assembly: TypeLibVersionAttribute(0, Integer.MaxValue)> Class C End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics() End Sub <Fact> Public Sub TestTypeLibVersionAttribute_Valid2() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices <Assembly: TypeLibVersionAttribute(2147483647, CInt(C.CS * C.CS))> Public Class C Public Const CS As Integer = Short.MaxValue End Class ]]> </file> </compilation> CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics() End Sub <Fact> Public Sub TestTypeLibVersionAttribute_Invalid() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices <Assembly: TypeLibVersionAttribute(-1, Integer.MinValue)> ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30127: Attribute 'System.Runtime.InteropServices.TypeLibVersionAttribute' is not valid: Incorrect argument value. <Assembly: TypeLibVersionAttribute(-1, Integer.MinValue)> ~~ BC30127: Attribute 'System.Runtime.InteropServices.TypeLibVersionAttribute' is not valid: Incorrect argument value. <Assembly: TypeLibVersionAttribute(-1, Integer.MinValue)> ~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub TestTypeLibVersionAttribute_Invalid_02() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices <Assembly: TypeLibVersionAttribute("str", 0)> ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30934: Conversion from 'String' to 'Integer' cannot occur in a constant expression used as an argument to an attribute. <Assembly: TypeLibVersionAttribute("str", 0)> ~~~~~ ]]></expected>) End Sub #End Region #Region "ComCompatibleVersionAttribute" <Fact> Public Sub TestComCompatibleVersionAttribute_Valid() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices <Assembly: ComCompatibleVersionAttribute(0, 0, 0, 0)> ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertNoErrors(comp) End Sub <Fact> Public Sub TestComCompatibleVersionAttribute_Invalid() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices <Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)> ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30127: Attribute 'System.Runtime.InteropServices.ComCompatibleVersionAttribute' is not valid: Incorrect argument value. <Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)> ~~ BC30127: Attribute 'System.Runtime.InteropServices.ComCompatibleVersionAttribute' is not valid: Incorrect argument value. <Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)> ~~ BC30127: Attribute 'System.Runtime.InteropServices.ComCompatibleVersionAttribute' is not valid: Incorrect argument value. <Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)> ~~ BC30127: Attribute 'System.Runtime.InteropServices.ComCompatibleVersionAttribute' is not valid: Incorrect argument value. <Assembly: ComCompatibleVersionAttribute(-1, -1, -1, -1)> ~~ ]]></expected>) End Sub <Fact> Public Sub TestComCompatibleVersionAttribute_Invalid_02() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices <Assembly: ComCompatibleVersionAttribute("str", 0, 0, 0)> ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30934: Conversion from 'String' to 'Integer' cannot occur in a constant expression used as an argument to an attribute. <Assembly: ComCompatibleVersionAttribute("str", 0, 0, 0)> ~~~~~ ]]></expected>) End Sub #End Region #Region "GuidAttribute" <Fact> Public Sub TestInvalidGuidAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices <ComImport> <Guid("69D3E2A0-BB0F-4FE3-9860-ED714C510756")> ' valid (36 chars) Class A End Class <Guid("69D3E2A0-BB0F-4FE3-9860-ED714C51075")> ' incorrect length (35 chars) Class B End Class <Guid("69D3E2A0BB0F--4FE3-9860-ED714C510756")> ' invalid format Class C End Class <Guid("")> ' empty string Class D End Class <Guid(Nothing)> ' Nothing Class E End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID '69D3E2A0-BB0F-4FE3-9860-ED714C51075' is not correct. <Guid("69D3E2A0-BB0F-4FE3-9860-ED714C51075")> ' incorrect length (35 chars) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID '69D3E2A0BB0F--4FE3-9860-ED714C510756' is not correct. <Guid("69D3E2A0BB0F--4FE3-9860-ED714C510756")> ' invalid format ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID '' is not correct. <Guid("")> ' empty string ~~ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID 'Nothing' is not correct. <Guid(Nothing)> ' Nothing ~~~~~~~ ]]></expected>) End Sub <WorkItem(545490, "DevDiv")> <Fact> Public Sub TestInvalidGuidAttribute_02() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices ' Following are alternate valid Guid formats, but disallowed by the native compiler. Ensure we disallow them. ' 32 digits, no hyphens <Guid("69D3E2A0BB0F4FE39860ED714C510756")> Class A End Class ' 32 digits separated by hyphens, enclosed in braces <Guid("{69D3E2A0-BB0F-4FE3-9860-ED714C510756}")> Class B End Class ' 32 digits separated by hyphens, enclosed in parentheses <Guid("(69D3E2A0-BB0F-4FE3-9860-ED714C510756)")> Class C End Class ' Four hexadecimal values enclosed in braces, where the fourth value is a subset of eight hexadecimal values that is also enclosed in braces <Guid("{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}")> Class D End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID '69D3E2A0BB0F4FE39860ED714C510756' is not correct. <Guid("69D3E2A0BB0F4FE39860ED714C510756")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID '{69D3E2A0-BB0F-4FE3-9860-ED714C510756}' is not correct. <Guid("{69D3E2A0-BB0F-4FE3-9860-ED714C510756}")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID '(69D3E2A0-BB0F-4FE3-9860-ED714C510756)' is not correct. <Guid("(69D3E2A0-BB0F-4FE3-9860-ED714C510756)")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID '{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}' is not correct. <Guid("{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub TestInvalidGuidAttribute_Assembly() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.InteropServices ' invalid format <Assembly: Guid("69D3E2A0BB0F--4FE3-9860-ED714C510756")> ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC32500: 'System.Runtime.InteropServices.GuidAttribute' cannot be applied because the format of the GUID '69D3E2A0BB0F--4FE3-9860-ED714C510756' is not correct. <Assembly: Guid("69D3E2A0BB0F--4FE3-9860-ED714C510756")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub #End Region #Region "WindowsRuntimeImportAttribute" <Fact> <WorkItem(531295, "DevDiv")> Public Sub TestWindowsRuntimeImportAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Runtime.InteropServices Namespace System.Runtime.InteropServices.WindowsRuntime <AttributeUsage(AttributeTargets.[Class] Or AttributeTargets.[Interface] Or AttributeTargets.[Enum] Or AttributeTargets.Struct Or AttributeTargets.[Delegate], Inherited := False)> Friend NotInheritable Class WindowsRuntimeImportAttribute Inherits Attribute Public Sub New() End Sub End Class End Namespace <System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImport> Class A Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim sourceValidator = Sub(m As ModuleSymbol) Dim assembly = m.ContainingSymbol Dim sysNS = DirectCast(m.DeclaringCompilation.GlobalNamespace.GetMember("System"), NamespaceSymbol) Dim runtimeNS = sysNS.GetNamespace("Runtime") Dim interopNS = runtimeNS.GetNamespace("InteropServices") Dim windowsRuntimeNS = interopNS.GetNamespace("WindowsRuntime") Dim windowsRuntimeImportAttrType = windowsRuntimeNS.GetTypeMembers("WindowsRuntimeImportAttribute").First() Dim typeA = m.GlobalNamespace.GetTypeMember("A") Assert.Equal(1, typeA.GetAttributes(windowsRuntimeImportAttrType).Count) Assert.True(typeA.IsWindowsRuntimeImport, "Metadata flag not set for IsWindowsRuntimeImport") End Sub Dim metadataValidator = Sub(m As ModuleSymbol) Dim typeA = m.GlobalNamespace.GetTypeMember("A") Assert.Equal(0, typeA.GetAttributes().Length) Assert.True(typeA.IsWindowsRuntimeImport, "Metadata flag not set for IsWindowsRuntimeImport") End Sub ' Verify that PEVerify will fail despite the fact that compiler produces no errors ' This is consistent with Dev10 behavior ' ' Dev10 PEVerify failure: ' [token 0x02000003] Type load failed. ' ' Dev10 Runtime Exception: ' Unhandled Exception: System.TypeLoadException: Windows Runtime types can only be declared in Windows Runtime assemblies. Dim validator = CompileAndVerify(source, emitOptions:=EmitOptions.CCI, sourceSymbolValidator:=sourceValidator, symbolValidator:=metadataValidator, verify:=False) validator.EmitAndVerify("Type load failed.") End Sub #End Region #Region "STAThreadAttribute, MTAThreadAttribute" Private Sub VerifySynthesizedSTAThreadAttribute(sourceMethod As SourceMethodSymbol, expected As Boolean) Dim synthesizedAttributes = sourceMethod.GetSynthesizedAttributes() If expected Then Assert.Equal(1, synthesizedAttributes.Length) Dim attribute = synthesizedAttributes(0) Dim compilation = sourceMethod.DeclaringCompilation Dim sysNS = DirectCast(compilation.GlobalNamespace.GetMember("System"), NamespaceSymbol) Dim attributeType As NamedTypeSymbol = sysNS.GetTypeMember("STAThreadAttribute") Dim attributeTypeCtor = DirectCast(compilation.GetWellKnownTypeMember(WellKnownMember.System_STAThreadAttribute__ctor), MethodSymbol) Assert.Equal(attributeType, attribute.AttributeClass) Assert.Equal(attributeTypeCtor, attribute.AttributeConstructor) Assert.Equal(0, attribute.ConstructorArguments.Count) Assert.Equal(0, attribute.NamedArguments.Count) Else Assert.Equal(0, synthesizedAttributes.Length) End If End Sub <Fact> Public Sub TestSynthesizedSTAThread() Dim source = <compilation> <file name="a.vb"> Imports System Module Module1 Sub foo() End Sub Sub Main() End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) compilation.AssertNoErrors() Dim sourceValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("Module1"), SourceNamedTypeSymbol) Dim fooMethod = DirectCast(type.GetMember("foo"), SourceMethodSymbol) VerifySynthesizedSTAThreadAttribute(fooMethod, expected:=False) Dim mainMethod = DirectCast(type.GetMember("Main"), SourceMethodSymbol) VerifySynthesizedSTAThreadAttribute(mainMethod, expected:=True) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator, expectedOutput:="") End Sub <Fact> Public Sub TestNoSynthesizedSTAThread_01() Dim source = <compilation> <file name="a.vb"> Imports System Module Module1 Sub foo() End Sub Sub Main() End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseDll) compilation.AssertNoErrors() Dim sourceValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("Module1"), SourceNamedTypeSymbol) Dim fooMethod = DirectCast(type.GetMember("foo"), SourceMethodSymbol) VerifySynthesizedSTAThreadAttribute(fooMethod, expected:=False) Dim mainMethod = DirectCast(type.GetMember("Main"), SourceMethodSymbol) VerifySynthesizedSTAThreadAttribute(mainMethod, expected:=False) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator) End Sub <Fact> Public Sub TestNoSynthesizedSTAThread_02() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub foo() End Sub <STAThread()> Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) compilation.AssertNoErrors() Dim sourceValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("Module1"), SourceNamedTypeSymbol) Dim fooMethod = DirectCast(type.GetMember("foo"), SourceMethodSymbol) VerifySynthesizedSTAThreadAttribute(fooMethod, expected:=False) Dim mainMethod = DirectCast(type.GetMember("Main"), SourceMethodSymbol) VerifySynthesizedSTAThreadAttribute(mainMethod, expected:=False) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator) End Sub <Fact> Public Sub TestNoSynthesizedSTAThread_03() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub foo() End Sub <MTAThread()> Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) compilation.AssertNoErrors() Dim sourceValidator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("Module1"), SourceNamedTypeSymbol) Dim fooMethod = DirectCast(type.GetMember("foo"), SourceMethodSymbol) VerifySynthesizedSTAThreadAttribute(fooMethod, expected:=False) Dim mainMethod = DirectCast(type.GetMember("Main"), SourceMethodSymbol) VerifySynthesizedSTAThreadAttribute(mainMethod, expected:=False) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator) End Sub #End Region #Region "RequiredAttributeAttribute" <Fact, WorkItem(81)> Public Sub DisallowRequiredAttributeInSource() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Namespace VBClassLibrary <System.Runtime.CompilerServices.RequiredAttribute(GetType(RS))> Public Structure RS Public F1 As Integer Public Sub New(ByVal p1 As Integer) F1 = p1 End Sub End Structure <System.Runtime.CompilerServices.RequiredAttribute(GetType(RI))> Public Interface RI Function F() As Integer End Interface Public Class CRI Implements RI Public Function F() As Integer Implements RI.F F = 0 End Function Public Shared Frs As RS = New RS(0) End Class End Namespace ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC37235: The RequiredAttribute attribute is not permitted on Visual Basic types. <System.Runtime.CompilerServices.RequiredAttribute(GetType(RS))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37235: The RequiredAttribute attribute is not permitted on Visual Basic types. <System.Runtime.CompilerServices.RequiredAttribute(GetType(RI))> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(81)> Public Sub DisallowRequiredAttributeFromMetadata01() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit RequiredAttrClass extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 59 53 79 73 74 65 6D 2E 49 6E 74 33 32 2C // ..YSystem.Int32, 20 6D 73 63 6F 72 6C 69 62 2C 20 56 65 72 73 69 // mscorlib, Versi 6F 6E 3D 34 2E 30 2E 30 2E 30 2C 20 43 75 6C 74 // on=4.0.0.0, Cult 75 72 65 3D 6E 65 75 74 72 61 6C 2C 20 50 75 62 // ure=neutral, Pub 6C 69 63 4B 65 79 54 6F 6B 65 6E 3D 62 37 37 61 // licKeyToken=b77a 35 63 35 36 31 39 33 34 65 30 38 39 00 00 ) // 5c561934e089.. .field public int32 intVar .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method RequiredAttrClass::.ctor } // end of class RequiredAttrClass ]]> Dim source = <compilation> <file name="a.vb"> <![CDATA[ Module M Sub Main() Dim r = New RequiredAttrClass() System.Console.WriteLine(r) End Sub End Module ]]> </file> </compilation> Dim ilReference = CompileIL(ilSource.Value) Dim comp = CreateCompilationWithMscorlibAndReferences(source, references:={MsvbRef, ilReference}) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30649: 'RequiredAttrClass' is an unsupported type. Dim r = New RequiredAttrClass() ~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(81)> Public Sub DisallowRequiredAttributeFromMetadata02() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit RequiredAttr.Scenario1 extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 59 53 79 73 74 65 6D 2E 49 6E 74 33 32 2C // ..YSystem.Int32, 20 6D 73 63 6F 72 6C 69 62 2C 20 56 65 72 73 69 // mscorlib, Versi 6F 6E 3D 34 2E 30 2E 30 2E 30 2C 20 43 75 6C 74 // on=4.0.0.0, Cult 75 72 65 3D 6E 65 75 74 72 61 6C 2C 20 50 75 62 // ure=neutral, Pub 6C 69 63 4B 65 79 54 6F 6B 65 6E 3D 62 37 37 61 // licKeyToken=b77a 35 63 35 36 31 39 33 34 65 30 38 39 00 00 ) // 5c561934e089.. .field public int32 intVar .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Scenario1::.ctor } // end of class RequiredAttr.Scenario1 .class public auto ansi beforefieldinit RequiredAttr.ReqAttrUsage extends [mscorlib]System.Object { .field public class RequiredAttr.Scenario1 sc1_field .method public hidebysig newslot specialname virtual instance class RequiredAttr.Scenario1 get_sc1_prop() cil managed { // Code size 9 (0x9) .maxstack 1 .locals (class RequiredAttr.Scenario1 V_0) IL_0000: ldarg.0 IL_0001: ldfld class RequiredAttr.Scenario1 RequiredAttr.ReqAttrUsage::sc1_field IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ret } // end of method ReqAttrUsage::get_sc1_prop .method public hidebysig instance class RequiredAttr.Scenario1 sc1_method() cil managed { // Code size 9 (0x9) .maxstack 1 .locals (class RequiredAttr.Scenario1 V_0) IL_0000: ldarg.0 IL_0001: ldfld class RequiredAttr.Scenario1 RequiredAttr.ReqAttrUsage::sc1_field IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ret } // end of method ReqAttrUsage::sc1_method .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method ReqAttrUsage::.ctor .property instance class RequiredAttr.Scenario1 sc1_prop() { .get instance class RequiredAttr.Scenario1 RequiredAttr.ReqAttrUsage::get_sc1_prop() } // end of property ReqAttrUsage::sc1_prop } // end of class RequiredAttr.ReqAttrUsage ]]> Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports RequiredAttr Public Class C Public Shared Function Main() As Integer Dim r = New ReqAttrUsage() r.sc1_field = Nothing Dim o As Object = r.sc1_prop r.sc1_method() Return 1 End Function End Class ]]> </file> </compilation> Dim ilReference = CompileIL(ilSource.Value) Dim comp = CreateCompilationWithMscorlib(source, references:={ilReference}) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30656: Field 'sc1_field' is of an unsupported type. r.sc1_field = Nothing ~~~~~~~~~~~ BC30643: Property 'sc1_prop' is of an unsupported type. Dim o As Object = r.sc1_prop ~~~~~~~~ BC30657: 'sc1_method' has a return type that is not supported or parameter types that are not supported. r.sc1_method() ~~~~~~~~~~ ]]></expected>) End Sub #End Region End Class End Namespace
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicCastReducer Private Class Rewriter Inherits AbstractExpressionRewriter Public Sub New(optionSet As OptionSet, cancellationToken As CancellationToken) MyBase.New(optionSet, cancellationToken) End Sub Public Overrides Function VisitCTypeExpression(node As CTypeExpressionSyntax) As SyntaxNode Return SimplifyExpression( node, newNode:=MyBase.VisitCTypeExpression(node), simplifier:=AddressOf SimplifyCast) End Function Public Overrides Function VisitDirectCastExpression(node As DirectCastExpressionSyntax) As SyntaxNode Return SimplifyExpression( node, newNode:=MyBase.VisitDirectCastExpression(node), simplifier:=AddressOf SimplifyCast) End Function Public Overrides Function VisitTryCastExpression(node As TryCastExpressionSyntax) As SyntaxNode Return SimplifyExpression( node, newNode:=MyBase.VisitTryCastExpression(node), simplifier:=AddressOf SimplifyCast) End Function Public Overrides Function VisitPredefinedCastExpression(node As PredefinedCastExpressionSyntax) As SyntaxNode Return SimplifyExpression( node, newNode:=MyBase.VisitPredefinedCastExpression(node), simplifier:=AddressOf SimplifyCast) End Function End Class End Class End Namespace
' 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.ExpressionEvaluator Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Public Class VisualBasicResultProviderTestBase : Inherits ResultProviderTestBase Private Shared ReadOnly s_resultProvider As ResultProvider = New VisualBasicResultProvider() Private Shared ReadOnly s_inspectionContext As DkmInspectionContext = CreateDkmInspectionContext(s_resultProvider.Formatter, DkmEvaluationFlags.None, radix:=10) Public Sub New() MyBase.New(s_resultProvider, s_inspectionContext) End Sub Protected Shared Function GetAssembly(source As String) As Assembly Dim comp = CompilationUtils.CreateCompilationWithMscorlib({source}, compOptions:=TestOptions.ReleaseDll) Return ReflectionUtilities.Load(comp.EmitToArray()) End Function Protected Shared Function GetAssemblyFromIL(ilSource As String) As Assembly Dim ilImage As ImmutableArray(Of Byte) = Nothing Dim comp = CompilationUtils.CreateCompilationWithCustomILSource(sources:=<compilation/>, ilSource:=ilSource, options:=TestOptions.ReleaseDll, ilImage:=ilImage) Return ReflectionUtilities.Load(ilImage) End Function Protected Shared Function PointerToString(pointer As IntPtr) As String If Environment.Is64BitProcess Then Return String.Format("&H{0:X16}", pointer.ToInt64()) Else Return String.Format("&H{0:X8}", pointer.ToInt32()) End If End Function End Class End Namespace
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:2.0.50727.5466 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '<summary> ' A strongly-typed resource class, for looking up localized strings, etc. '</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '<summary> ' Returns the cached ResourceManager instance used by this class. '</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("VBLib.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
Imports System.IO 'Files Imports System.Text 'Binary Formatter Partial Class GeneralTools 'This is included to disable Visual Studio thinking that this file should be a form. End Class Partial Class MainForm Public CreatedImages As List(Of String) Sub FillPictureView(SelectedData As TreeNode) Dim PictureBytes As Byte() = FilePartHandlers.GetFilePartBytes(SelectedData.Tag) Dim ImageStream As MemoryStream = New MemoryStream(PictureBytes) Dim TempName As String = Path.GetTempFileName FileSystem.Rename(TempName, TempName + ".dds") TempName += ".dds" File.WriteAllBytes(TempName, PictureBytes) Process.Start(My.Settings.TexConvPath, " -ft bmp " & TempName).WaitForExit() Dim TempBMP As String = Path.GetDirectoryName(My.Settings.TexConvPath) & Path.DirectorySeparatorChar & Path.GetFileNameWithoutExtension(TempName) & ".BMP" Dim TempBMPLocal As String = Application.StartupPath & Path.DirectorySeparatorChar & Path.GetFileNameWithoutExtension(TempName) & ".BMP" If Not TempBMP.ToLower = TempBMPLocal.ToLower Then If File.Exists(TempBMPLocal) Then If File_FolderHandlers.WaitForFile(TempBMPLocal) Then File.Copy(TempBMPLocal, TempBMP, True) File.Delete(TempBMPLocal) End If End If End If If File.Exists(TempBMP) Then Dim tempimage As Image Using TempObject = New Bitmap(TempBMP) tempimage = New Bitmap(TempObject) End Using PictureBox2.Image = tempimage Else MessageBox.Show("Error creating bitmap image.") End If CreatedImages.Add(TempBMP) File.Delete(TempName) End Sub Sub DeleteTempImages() PictureBox2.Image = Nothing For Each CurrentImage As String In CreatedImages Try If File.Exists(CurrentImage) Then File.Delete(CurrentImage) End If Catch ex As Exception MessageBox.Show(ex.Message) End Try Next CreatedImages.Clear() End Sub End Class
' 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 Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class NameOfTests Inherits BasicTestBase <Fact> Public Sub TestParsing_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Integer.MaxValue) Dim y = NameOf(Integer) Dim z = NameOf(Variant) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC37244: This expression does not have a name. Dim y = NameOf(Integer) ~~~~~~~ BC30804: 'Variant' is no longer a supported type; use the 'Object' type instead. Dim z = NameOf(Variant) ~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().ToArray() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) If True Then Dim node1 = nodes(0) Assert.Equal("NameOf(Integer.MaxValue)", node1.ToString()) Assert.Equal("MaxValue", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("System.Int32.MaxValue As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.True(group.IsEmpty) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End If If True Then Dim node2 = nodes(1) Assert.Equal("NameOf(Integer)", node2.ToString()) Assert.Null(model.GetConstantValue(node2).Value) typeInfo = model.GetTypeInfo(node2) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node2) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node2) Assert.True(group.IsEmpty) Dim argument = node2.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.True(group.IsEmpty) End If If True Then Dim node3 = nodes(2) Assert.Equal("NameOf(Variant)", node3.ToString()) Assert.Equal("Variant", model.GetConstantValue(node3).Value) typeInfo = model.GetTypeInfo(node3) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node3) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node3) Assert.True(group.IsEmpty) Dim argument = node3.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.True(group.IsEmpty) End If End Sub <Fact> Public Sub TestParsing_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of )) Dim y = NameOf(C2(Of ).C3(Of Integer)) Dim z = NameOf(C2(Of Integer).C3(Of Integer)) End Sub End Module Class C2(Of T) Class C3(Of S) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30182: Type expected. Dim x = NameOf(C2(Of Integer).C3(Of )) ~ BC30182: Type expected. Dim y = NameOf(C2(Of ).C3(Of Integer)) ~ </expected>) End Sub <Fact> Public Sub TestParsing_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of ).M1) Dim y = NameOf(C2(Of ).C3(Of Integer).M1) Dim z = NameOf(C2(Of Integer).C3(Of Integer).M1) End Sub End Module Class C2(Of T) Class C3(Of S) Sub M1() End Sub End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30182: Type expected. Dim x = NameOf(C2(Of Integer).C3(Of ).M1) ~ BC30182: Type expected. Dim y = NameOf(C2(Of ).C3(Of Integer).M1) ~ </expected>) End Sub <Fact> Public Sub TestParsing_04() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Global) Dim y = NameOf(Global.System) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC36000: 'Global' must be followed by '.' and an identifier. Dim x = NameOf(Global) ~~~~~~ BC37244: This expression does not have a name. Dim x = NameOf(Global) ~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_05() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module Class CTest Sub Test1() Dim x = NameOf(MyClass) Dim y = NameOf(MyClass.Test1) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC32028: 'MyClass' must be followed by '.' and an identifier. Dim x = NameOf(MyClass) ~~~~~~~ BC37244: This expression does not have a name. Dim x = NameOf(MyClass) ~~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_06() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module Class CTest Sub Test1() Dim x = NameOf(MyBase) Dim y = NameOf(MyBase.GetHashCode) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC32027: 'MyBase' must be followed by '.' and an identifier. Dim x = NameOf(MyBase) ~~~~~~ BC37244: This expression does not have a name. Dim x = NameOf(MyBase) ~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_07() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module Class CTest Sub Test1() Dim x = NameOf(Me) Dim y = NameOf(Me.GetHashCode) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC37244: This expression does not have a name. Dim x = NameOf(Me) ~~ </expected>) End Sub <Fact> Public Sub TestParsing_08() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Integer?) Dim y = NameOf(Integer?.GetValueOrDefault) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC37244: This expression does not have a name. Dim x = NameOf(Integer?) ~~~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_09() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As Integer? = Nothing Dim y = NameOf(x.GetValueOrDefault) Dim z = NameOf((x).GetValueOrDefault) Dim u = NameOf(New Integer?().GetValueOrDefault) Dim v = NameOf(GetVal().GetValueOrDefault) Dim w = NameOf(GetVal.GetValueOrDefault) End Sub Function GetVal() As Integer? Return Nothing End Function End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC37245: This sub-expression cannot be used inside NameOf argument. Dim z = NameOf((x).GetValueOrDefault) ~~~ BC37245: This sub-expression cannot be used inside NameOf argument. Dim u = NameOf(New Integer?().GetValueOrDefault) ~~~~~~~~~~~~~~ BC37245: This sub-expression cannot be used inside NameOf argument. Dim v = NameOf(GetVal().GetValueOrDefault) ~~~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_10() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As Integer? = Nothing NameOf(x.GetValueOrDefault) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30035: Syntax error. NameOf(x.GetValueOrDefault) ~~~~~~ </expected>) End Sub <Fact> Public Sub Namespace_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(Global.System)) System.Console.WriteLine(NameOf(Global.system)) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ System system ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(Global.System)", node1.ToString()) Assert.Equal("System", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("System", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("Global", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Method_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2(Of Integer).C3(Of Short).M1)) System.Console.WriteLine(NameOf(C2(Of Integer).C3(Of Short).m1)) End Sub End Module Class C2(Of T) Class C3(Of S) Sub M1() End Sub End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 m1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Sub C2(Of System.Int32).C3(Of System.Int16).M1()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(1, group.Length) Assert.Equal("Sub C2(Of System.Int32).C3(Of System.Int16).M1()", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Method_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1)) System.Console.WriteLine(NameOf(C1.m1)) End Sub End Module Class C1 Sub M1(Of T)() End Sub Sub M1(x as Integer) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 m1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1)", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub C1.M1(Of T)()", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal("Sub C1.M1(x As System.Int32)", symbolInfo.CandidateSymbols(1).ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(2, group.Length) Assert.Equal("Sub C1.M1(Of T)()", group(0).ToTestDisplayString()) Assert.Equal("Sub C1.M1(x As System.Int32)", group(1).ToTestDisplayString()) End Sub <Fact> Public Sub Method_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1)) End Sub End Module Class C1 Sub M1(Of T)() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1)", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Sub C1.M1(Of T)()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Sub C1.M1(Of T)()", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Method_04() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1(Of Integer))) End Sub End Module Class C1 Sub M1(Of T)() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC37246: Method type arguments unexpected. System.Console.WriteLine(NameOf(C1.M1(Of Integer))) ~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1(Of Integer))", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Sub C1.M1(Of System.Int32)()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Sub C1.M1(Of System.Int32)()", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Method_05() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1(Of Integer))) End Sub End Module Class C1 Sub M1(Of T)() End Sub Sub M1(x as Integer) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC37246: Method type arguments unexpected. System.Console.WriteLine(NameOf(C1.M1(Of Integer))) ~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1(Of Integer))", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Sub C1.M1(Of System.Int32)()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Sub C1.M1(Of System.Int32)()", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Method_06() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1(Of Integer))) End Sub End Module Class C1 Sub M1(x as Integer) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC37246: Method type arguments unexpected. System.Console.WriteLine(NameOf(C1.M1(Of Integer))) ~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1(Of Integer))", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub GenericType_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2(Of Integer).C3(Of Short))) System.Console.WriteLine(NameOf(C2(Of Integer).c3(Of Short))) End Sub End Module Class C2(Of T) Class C3(Of S) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ C3 c3 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short))", node1.ToString()) Assert.Equal("C3", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub AmbiguousType_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2(Of Integer).CC3)) System.Console.WriteLine(NameOf(C2(Of Integer).cc3)) End Sub End Module Class C2(Of T) Class Cc3(Of S) End Class Class cC3(Of U, V) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC32042: Too few type arguments to 'C2(Of Integer).Cc3(Of S)'. System.Console.WriteLine(NameOf(C2(Of Integer).CC3)) ~~~~~~~~~~~~~~~~~~ BC32042: Too few type arguments to 'C2(Of Integer).Cc3(Of S)'. System.Console.WriteLine(NameOf(C2(Of Integer).cc3)) ~~~~~~~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).CC3)", node1.ToString()) Assert.Equal("CC3", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("C2(Of System.Int32).Cc3(Of S)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.WrongArity, symbolInfo.CandidateReason) Assert.Equal("C2(Of System.Int32).Cc3(Of S)", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub AmbiguousType_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.CC3)) System.Console.WriteLine(NameOf(C2.cc3)) End Sub End Module Class C1 Class Cc3(Of S) End Class End Class Class C2 Inherits C1 Class cC3(Of U, V) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC32042: Too few type arguments to 'C2.cC3(Of U, V)'. System.Console.WriteLine(NameOf(C2.CC3)) ~~~~~~ BC32042: Too few type arguments to 'C2.cC3(Of U, V)'. System.Console.WriteLine(NameOf(C2.cc3)) ~~~~~~ </expected>) End Sub <Fact> Public Sub InaccessibleNonGenericType_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.CC3)) End Sub End Module Class C2 protected Class Cc3 End Class Class cC3(Of U, V) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30389: 'C2.Cc3' is not accessible in this context because it is 'Protected'. System.Console.WriteLine(NameOf(C2.CC3)) ~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.CC3)", node1.ToString()) Assert.Equal("CC3", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("C2.Cc3", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("C2.Cc3", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Alias_01() Dim compilationDef = <compilation> <file name="a.vb"> Imports [alias] = System Module Module1 Sub Main() System.Console.WriteLine(NameOf([alias])) System.Console.WriteLine(NameOf([ALIAS])) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ alias ALIAS ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf([alias])", node1.ToString()) Assert.Equal("alias", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("System", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Assert.Equal("[alias]=System", model.GetAliasInfo(argument).ToTestDisplayString()) End Sub <Fact> Public Sub InaccessibleMethod_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).M1) End Sub End Module Class C2(Of T) Class C3(Of S) Protected Sub M1() End Sub End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30390: 'C3.Protected Sub M1()' is not accessible in this context because it is 'Protected'. Dim x = NameOf(C2(Of Integer).C3(Of Short).M1) ~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("Sub C2(Of System.Int32).C3(Of System.Int16).M1()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(1, group.Length) Assert.Equal("Sub C2(Of System.Int32).C3(Of System.Int16).M1()", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InaccessibleProperty_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).P1) End Sub End Module Class C2(Of T) Class C3(Of S) Protected Property P1 As Integer End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30389: 'C2(Of Integer).C3(Of Short).P1' is not accessible in this context because it is 'Protected'. Dim x = NameOf(C2(Of Integer).C3(Of Short).P1) ~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).P1)", node1.ToString()) Assert.Equal("P1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("Property C2(Of System.Int32).C3(Of System.Int16).P1 As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(1, group.Length) Assert.Equal("Property C2(Of System.Int32).C3(Of System.Int16).P1 As System.Int32", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InaccessibleField_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).F1) End Sub End Module Class C2(Of T) Class C3(Of S) Protected F1 As Integer End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30389: 'C2(Of Integer).C3(Of Short).F1' is not accessible in this context because it is 'Protected'. Dim x = NameOf(C2(Of Integer).C3(Of Short).F1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).F1)", node1.ToString()) Assert.Equal("F1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16).F1 As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InaccessibleEvent_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).E1) End Sub End Module Class C2(Of T) Class C3(Of S) Protected Event E1 As System.Action End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30389: 'C2(Of Integer).C3(Of Short).E1' is not accessible in this context because it is 'Protected'. Dim x = NameOf(C2(Of Integer).C3(Of Short).E1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).E1)", node1.ToString()) Assert.Equal("E1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("Event C2(Of System.Int32).C3(Of System.Int16).E1 As System.Action", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Missing_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).Missing) End Sub End Module Class C2(Of T) Class C3(Of S) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30456: 'Missing' is not a member of 'C2(Of Integer).C3(Of Short)'. Dim x = NameOf(C2(Of Integer).C3(Of Short).Missing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).Missing)", node1.ToString()) Assert.Equal("Missing", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Missing_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Missing.M1) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30451: 'Missing' is not declared. It may be inaccessible due to its protection level. Dim x = NameOf(Missing.M1) ~~~~~~~ </expected>) End Sub <Fact> Public Sub Missing_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Missing) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30451: 'Missing' is not declared. It may be inaccessible due to its protection level. Dim x = NameOf(Missing) ~~~~~~~ </expected>) End Sub <Fact> Public Sub AmbiguousMethod_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(Ambiguous)) End Sub End Module Module Module2 Sub Ambiguous() End Sub End Module Module Module3 Sub Ambiguous() End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30562: 'Ambiguous' is ambiguous between declarations in Modules 'Module2, Module3'. System.Console.WriteLine(NameOf(Ambiguous)) ~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(Ambiguous)", node1.ToString()) Assert.Equal("Ambiguous", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub Module2.Ambiguous()", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal("Sub Module3.Ambiguous()", symbolInfo.CandidateSymbols(1).ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub AmbiguousMethod_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(I3.Ambiguous)) End Sub End Module Interface I1 Sub Ambiguous() End Interface Interface I2 Sub Ambiguous(x as Integer) End Interface Interface I3 Inherits I1, I2 End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ Ambiguous ]]>) End Sub <Fact> Public Sub Local_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim local As Integer = 0 System.Console.WriteLine(NameOf(LOCAL)) System.Console.WriteLine(NameOf(loCal)) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ LOCAL loCal ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(LOCAL)", node1.ToString()) Assert.Equal("LOCAL", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("local As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Local_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(LOCAL)) Dim local As Integer = 0 End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC32000: Local variable 'local' cannot be referred to before it is declared. System.Console.WriteLine(NameOf(LOCAL)) ~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(LOCAL)", node1.ToString()) Assert.Equal("LOCAL", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("local As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Local_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim local = NameOf(LOCAL) System.Console.WriteLine(local) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30980: Type of 'local' cannot be inferred from an expression containing 'local'. Dim local = NameOf(LOCAL) ~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(LOCAL)", node1.ToString()) Assert.Equal("LOCAL", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("local As System.String", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Local_04() Dim compilationDef = <compilation> <file name="a.vb"> Option Explicit Off Module Module1 Sub Main() System.Console.WriteLine(NameOf(LOCAL)) local = 0 End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ LOCAL ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(LOCAL)", node1.ToString()) Assert.Equal("LOCAL", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Object", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("LOCAL As System.Object", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Local_05() Dim compilationDef = <compilation> <file name="a.vb"> Option Explicit Off Module Module1 Sub Main() local = 3 System.Console.WriteLine(NameOf(LOCAL)) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ LOCAL ]]>) End Sub <Fact> Public Sub Local_06() Dim compilationDef = <compilation> <file name="a.vb"> Option Explicit Off Module Module1 Sub Main() local = NameOf(LOCAL) System.Console.WriteLine(local) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ LOCAL ]]>) End Sub <Fact> Public Sub TypeParameterAsQualifier_01() Dim compilationDef = <compilation> <file name="a.vb"> Option Explicit Off Module Module1 Sub Main() C3(Of C2).Test() End Sub End Module Class C2 Sub M1() End Sub End Class Class C3(Of T As C2) Shared Sub Test() System.Console.WriteLine(NameOf(T.M1)) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC32098: Type parameters cannot be used as qualifiers. System.Console.WriteLine(NameOf(T.M1)) ~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.F1)) End Sub End Module Class C2 Public F1 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.F1)", node1.ToString()) Assert.Equal("F1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("C2.F1 As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.F1.F2)) End Sub End Module Class C2 Public F1 As C3 End Class Class C3 Public F2 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.F1.F2)) ~~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.P1)) End Sub End Module Class C2 Public Property P1 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ P1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.P1)", node1.ToString()) Assert.Equal("P1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Property C2.P1 As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Property C2.P1 As System.Int32", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_04() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.P1.P2)) End Sub End Module Class C2 Public Property P1 As C3 End Class Class C3 Public Property P2 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.P1.P2)) ~~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_05() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1)) End Sub End Module Class C2 Public Function M1() As Integer Return Nothing End Function End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function C2.M1() As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function C2.M1() As System.Int32", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_06() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1.M2)) End Sub End Module Class C2 Public Function M1() As C3 Return Nothing End Function End Class Class C3 Public Sub M2() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.M1.M2)) ~~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_07() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1)) End Sub <System.Runtime.CompilerServices.Extension> Public Function M1(this As C2) As Integer Return Nothing End Function End Module Class C2 End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function C2.M1() As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function C2.M1() As System.Int32", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_08() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1.M2)) End Sub <System.Runtime.CompilerServices.Extension> Public Function M1(this As C2) As C3 Return Nothing End Function End Module Class C2 End Class Class C3 Public Sub M2() End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.M1.M2)) ~~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_09() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.E1)) End Sub End Module Class C2 Public Event E1 As System.Action End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ E1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.E1)", node1.ToString()) Assert.Equal("E1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Event C2.E1 As System.Action", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_10() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.E1.Invoke)) End Sub End Module Class C2 Public Event E1 As System.Action End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.E1.Invoke)) ~~~~~ </expected>) End Sub <Fact> Public Sub SharedOfValue_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.F1)) System.Console.WriteLine(NameOf(x.F1.F2)) End Sub End Module Class C2 Shared Public F1 As C3 End Class Class C3 Shared Public F2 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.F1)) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.F1.F2)) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.F1.F2)) ~~~~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 F2 ]]>) End Sub <Fact> Public Sub SharedOfValue_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.P1)) System.Console.WriteLine(NameOf(x.P1.P2)) End Sub End Module Class C2 Shared Public Property P1 As C3 End Class Class C3 Shared Public Property P2 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.P1.P2)) ~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ P1 P2 ]]>) End Sub <Fact> Public Sub SharedOfValue_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.M1)) System.Console.WriteLine(NameOf(x.M1.M2)) End Sub End Module Class C2 Shared Public Function M1() As C3 Return Nothing End Function End Class Class C3 Shared Public Sub M2() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.M1.M2)) ~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 M2 ]]>) End Sub <Fact> Public Sub SharedOfValue_04() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.E1)) End Sub End Module Class C2 Shared Public Event E1 As System.Action End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.E1)) ~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ E1 ]]>) End Sub <Fact> Public Sub SharedOfValue_05() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.T1)) System.Console.WriteLine(NameOf(x.P1.T2)) End Sub End Module Class C2 Shared Public Property P1 As C3 Public Class T1 End Class End Class Class C3 Public Class T2 End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.T1)) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.P1.T2)) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.P1.T2)) ~~~~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ T1 T2 ]]>) End Sub <Fact> Public Sub DataFlow_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As C2 System.Console.WriteLine(NameOf(x.F1)) Dim y As C2 Return System.Console.WriteLine(y.F1) End Sub End Module Class C2 Public F1 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 ]]>).VerifyDiagnostics() End Sub <Fact> Public Sub Attribute_01() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <System.Diagnostics.DebuggerDisplay("={" + NameOf(Test.MTest) + "()}")> Class Test Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub Function MTest() As String Return "" End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(Test.MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function Test.MTest() As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function Test.MTest() As System.String", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("Test", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("Test", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Attribute_02() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub Function MTest() As String Return "" End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30059: Constant expression is required. <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30451: 'MTest' is not declared. It may be inaccessible due to its protection level. <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> ~~~~~ ]]></expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Attribute_03() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <System.Diagnostics.DebuggerDisplay("={" + NameOf(.MTest) + "()}")> Class Test Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub Function MTest() As String Return "" End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30059: Constant expression is required. <System.Diagnostics.DebuggerDisplay("={" + NameOf(.MTest) + "()}")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. <System.Diagnostics.DebuggerDisplay("={" + NameOf(.MTest) + "()}")> ~~~~~~ ]]></expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(.MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Attribute_04() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test End Class Function MTest() As String Return "" End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function Module1.MTest() As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function Module1.MTest() As System.String", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Attribute_05() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test End Class Property MTest As String End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Property Module1.MTest As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Property Module1.MTest As System.String", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Attribute_06() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test End Class Dim MTest As String End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Module1.MTest As System.String", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Attribute_07() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test End Class Event MTest As System.Action End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Event Module1.MTest As System.Action", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub InstanceAndExtension() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1)) End Sub <System.Runtime.CompilerServices.Extension> Public Function M1(this As C2) As Integer Return Nothing End Function End Module Class C2 Sub M1(x as Integer) End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub C2.M1(x As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal("Function C2.M1() As System.Int32", symbolInfo.CandidateSymbols(1).ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(2, group.Length) Assert.Equal("Sub C2.M1(x As System.Int32)", group(0).ToTestDisplayString()) Assert.Equal("Function C2.M1() As System.Int32", group(1).ToTestDisplayString()) End Sub <Fact> Public Sub InstanceInShared_01() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Shared Sub Main() System.Console.WriteLine(NameOf(F1)) End Sub Public F1 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(F1)", node1.ToString()) Assert.Equal("F1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Module1.F1 As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub InstanceInShared_02() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Shared Sub Main() System.Console.WriteLine(NameOf(F1)) End Sub Event F1 As System.Action End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(F1)", node1.ToString()) Assert.Equal("F1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Event Module1.F1 As System.Action", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub InstanceInShared_03() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Shared Sub Main() System.Console.WriteLine(NameOf(MTest)) End Sub Function MTest() As String Return "" End Function End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ MTest ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function Module1.MTest() As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function Module1.MTest() As System.String", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub InstanceInShared_04() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Shared Sub Main() System.Console.WriteLine(NameOf(MTest)) End Sub Property MTest As String End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ MTest ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Property Module1.MTest As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Property Module1.MTest As System.String", group.Single.ToTestDisplayString()) End Sub <Fact, WorkItem(543, "https://github.com/dotnet/roslyn")> Public Sub NameOfConstantInInitializer() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Const N1 As String = NameOf(N1) Shared Sub Main() Const N2 As String = NameOf(N2) System.Console.WriteLine(N1 &amp; N2) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ N1N2 ]]>).VerifyDiagnostics() End Sub <Fact, WorkItem(564, "https://github.com/dotnet/roslyn/issues/564")> Public Sub NameOfTypeParameterInDefaultValue() Dim compilationDef = <compilation> <file name="a.vb"> Module Program Sub M(Of TP)(Optional name As String = NameOf(TP)) System.Console.WriteLine(name) End Sub Sub Main() M(Of String)() End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ TP ]]>).VerifyDiagnostics() End Sub <Fact, WorkItem(10839, "https://github.com/dotnet/roslyn/issues/10839")> Public Sub NameOfByRefInLambda() Dim compilationDef = <compilation> <file name="a.vb"> Module Program Sub DoSomething(ByRef x As Integer) Dim f = Function() Return NameOf(x) End Function System.Console.WriteLine(f()) End Sub Sub Main() Dim x = 5 DoSomething(x) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:="x").VerifyDiagnostics() End Sub <Fact, WorkItem(10839, "https://github.com/dotnet/roslyn/issues/10839")> Public Sub NameOfByRefInQuery() Dim compilationDef = <compilation> <file name="a.vb"> Imports System.Linq Module Program Sub DoSomething(ByRef x As Integer) Dim f = from y in {1, 2, 3} select nameof(x) System.Console.WriteLine(f.Aggregate("", Function(a, b) a + b)) End Sub Sub Main() Dim x = 5 DoSomething(x) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(compilationDef, options:=TestOptions.DebugExe, additionalRefs:={LinqAssemblyRef}) CompileAndVerify(comp, expectedOutput:="xxx").VerifyDiagnostics() End Sub End Class End Namespace
Public Class SelectManagerForm Public SelectedManager As String = "" Private Sub OkayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OkayButton.Click SelectedManager = ComboBox1.SelectedItem DialogResult = DialogResult.OK End Sub Private Sub CancelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CancelButton.Click Me.Close() End Sub Private Sub SelectManagerForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ComboBox1.SelectedItem = "PAUL" OkayButton.Select() End Sub Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged OkayButton.Select() End Sub End Class
'//////////////////////////////////////////////////////////////////////// ' Copyright 2001-2015 Aspose Pty Ltd. All Rights Reserved. ' ' This file is part of Aspose.Imaging. 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 Aspose.Cloud Imports System Namespace Aspose.Imaging.Cloud.Examples.TiffFrames Friend Class ResizeFrame Shared Sub Main() Dim dataDir As String = Common.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) Dim input As String = "sample1.tiff" Dim output As String = "output.tiff" Dim outPath As String = "Imaging/" & input Dim frameId As Integer = 0 Dim newWidth As Integer = 200 Dim newHeight As Integer = 200 Dim x As Integer = 20 Dim y As Integer = 20 Dim rectWidth As Integer = 100 Dim rectHeight As Integer = 100 Common.StorageService.File.UploadFile(dataDir & input, input, storage:= Common.STORAGE) Common.GetImagingSdk().Frame.UpdatePropertiesOfFrameInExistingTiffImage(input, frameId, newWidth, newHeight, x, y, rectWidth, rectHeight, True, outPath, Common.FOLDER, storage:= Common.STORAGE) Common.StorageService.File.DownloadFile(outPath, dataDir & output, storage:= Common.STORAGE) End Sub End Class End Namespace
Imports System.Data Partial Class fRequisiciones_Internas_Ingles 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 Requisiciones.Cod_Pro As Cod_Cli, ") loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro As Nom_Cli, ") loComandoSeleccionar.AppendLine(" Proveedores.Rif, ") loComandoSeleccionar.AppendLine(" Proveedores.Nit, ") loComandoSeleccionar.AppendLine(" Proveedores.Dir_Fis, ") loComandoSeleccionar.AppendLine(" Proveedores.Telefonos, ") loComandoSeleccionar.AppendLine(" Proveedores.Fax, ") loComandoSeleccionar.AppendLine(" Requisiciones.Nom_Pro As Nom_Gen, ") loComandoSeleccionar.AppendLine(" Requisiciones.Rif As Rif_Gen, ") loComandoSeleccionar.AppendLine(" Requisiciones.Nit As Nit_Gen, ") loComandoSeleccionar.AppendLine(" SPACE(1) As Dir_Gen, ") loComandoSeleccionar.AppendLine(" SPACE(1) As Tel_Gen, ") loComandoSeleccionar.AppendLine(" Requisiciones.Documento, ") loComandoSeleccionar.AppendLine(" Requisiciones.Fec_Ini, ") loComandoSeleccionar.AppendLine(" Requisiciones.Fec_Fin, ") loComandoSeleccionar.AppendLine(" Requisiciones.Mon_Bru, ") loComandoSeleccionar.AppendLine(" Requisiciones.Mon_Imp1, ") loComandoSeleccionar.AppendLine(" Requisiciones.Por_Des1, ") loComandoSeleccionar.AppendLine(" Requisiciones.Por_Rec1, ") loComandoSeleccionar.AppendLine(" Requisiciones.Mon_Des1, ") loComandoSeleccionar.AppendLine(" Requisiciones.Mon_Rec1, ") loComandoSeleccionar.AppendLine(" Requisiciones.Dis_Imp, ") loComandoSeleccionar.AppendLine(" Requisiciones.Mon_Net, ") loComandoSeleccionar.AppendLine(" Requisiciones.Cod_For, ") loComandoSeleccionar.AppendLine(" SUBSTRING(Formas_Pagos.Nom_For,1,24) AS Nom_For, ") loComandoSeleccionar.AppendLine(" Requisiciones.Cod_Ven, ") loComandoSeleccionar.AppendLine(" Requisiciones.Comentario, ") loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Cod_Art, ") loComandoSeleccionar.AppendLine(" Articulos.Nom_Art, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Renglon, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Can_Art1, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Cod_Uni, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Precio1, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Mon_Net As Neto, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Por_Imp1 As Por_Imp, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Cod_Imp, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Mon_Imp1 As Impuesto, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Por_Des As Por_Des, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Mon_Des As Descuento ") loComandoSeleccionar.AppendLine(" FROM Requisiciones, ") loComandoSeleccionar.AppendLine(" Renglones_Requisiciones, ") loComandoSeleccionar.AppendLine(" Proveedores, ") loComandoSeleccionar.AppendLine(" Formas_Pagos, ") loComandoSeleccionar.AppendLine(" Vendedores, ") loComandoSeleccionar.AppendLine(" Articulos ") loComandoSeleccionar.AppendLine(" WHERE Requisiciones.Documento = Renglones_Requisiciones.Documento AND ") loComandoSeleccionar.AppendLine(" Requisiciones.Cod_Pro = Proveedores.Cod_Pro AND ") loComandoSeleccionar.AppendLine(" Requisiciones.Cod_For = Formas_Pagos.Cod_For AND ") loComandoSeleccionar.AppendLine(" Requisiciones.Cod_Ven = Vendedores.Cod_Ven AND ") loComandoSeleccionar.AppendLine(" Articulos.Cod_Art = Renglones_Requisiciones.Cod_Art AND " & cusAplicacion.goFormatos.pcCondicionPrincipal) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") Dim lcXml As String = "<impuesto></impuesto>" Dim lcPorcentajesImpueto As String Dim loImpuestos As New System.Xml.XmlDocument() lcPorcentajesImpueto = "(" 'Recorre cada renglon de la tabla For lnNumeroFila As Integer = 0 To laDatosReporte.Tables(0).Rows.Count - 1 lcXml = laDatosReporte.Tables(0).Rows(lnNumeroFila).Item("dis_imp") If String.IsNullOrEmpty(lcXml.Trim()) Then Continue For End If loImpuestos.LoadXml(lcXml) 'En cada renglón lee el contenido de la distribució de impuestos For Each loImpuesto As System.Xml.XmlNode In loImpuestos.SelectNodes("impuestos/impuesto") If lnNumeroFila = laDatosReporte.Tables(0).Rows.Count - 1 Then lcPorcentajesImpueto = lcPorcentajesImpueto & ", " & goServicios.mObtenerFormatoCadena(CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText)) & "%" End If Next loImpuesto Next lnNumeroFila lcPorcentajesImpueto = lcPorcentajesImpueto & ")" lcPorcentajesImpueto = lcPorcentajesImpueto.Replace("(, ", "(") '--------------------------------------------------' ' 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("fRequisiciones_Internas_Ingles", laDatosReporte) CType(loObjetoReporte.ReportDefinition.ReportObjects("Text29"), CrystalDecisions.CrystalReports.Engine.TextObject).Text = lcPorcentajesImpueto.ToString Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvfRequisiciones_Internas_Ingles.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 '-------------------------------------------------------------------------------------------' ' Douglas Cortez: 10/05/2010: Codigo inicial '-------------------------------------------------------------------------------------------' ' RAC: 23/03/2011: Se hicieron los ajustes para Impresion. '-------------------------------------------------------------------------------------------' ' 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 '-------------------------------------------------------------------------------------------'
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "rTCotdArtVC" '-------------------------------------------------------------------------------------------' Partial Class rTCotdArtVC Inherits vis2Formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0)) Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0)) Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia) Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia) Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2)) Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2)) Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3)) Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3)) Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4)) Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4)) Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5)) Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5)) Dim lcParametro6Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6)) Dim lcParametro7Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7)) Dim lcParametro7Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(7)) Dim lcParametro8Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8)) Dim lcParametro8Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(8)) Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden Dim loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine(" SELECT Renglones_Cotizaciones.Cod_Art, ") loComandoSeleccionar.AppendLine(" Articulos.Nom_art, ") loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_Cli, ") loComandoSeleccionar.AppendLine(" Clientes.Nom_Cli, ") loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_Ven, ") loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven, ") loComandoSeleccionar.AppendLine(" sum (Renglones_Cotizaciones.Can_Art1) as can_art1,") loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Cod_Uni, ") loComandoSeleccionar.AppendLine(" sum (Renglones_Cotizaciones.Mon_Net) as mon_net ") loComandoSeleccionar.AppendLine(" FROM Articulos, ") loComandoSeleccionar.AppendLine(" Cotizaciones, ") loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones, ") loComandoSeleccionar.AppendLine(" Clientes, ") loComandoSeleccionar.AppendLine(" Vendedores, ") loComandoSeleccionar.AppendLine(" Monedas, ") loComandoSeleccionar.AppendLine(" Transportes, ") loComandoSeleccionar.AppendLine(" Almacenes, ") loComandoSeleccionar.AppendLine(" Departamentos, ") loComandoSeleccionar.AppendLine(" Clases_Articulos ") loComandoSeleccionar.AppendLine(" WHERE Articulos.Cod_Art = Renglones_Cotizaciones.Cod_Art ") loComandoSeleccionar.AppendLine(" AND Renglones_Cotizaciones.Documento = Cotizaciones.Documento ") loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Cli = Clientes.Cod_Cli ") loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Ven = Vendedores.Cod_Ven") loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Mon = Monedas.Cod_Mon") loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Tra = Transportes.Cod_Tra") loComandoSeleccionar.AppendLine(" AND Renglones_Cotizaciones.Cod_Alm = Almacenes.Cod_Alm") loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep = Departamentos.Cod_Dep ") loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla = Clases_Articulos.Cod_Cla ") 'loComandoSeleccionar.AppendLine(" AND SUBSTRING(Articulos.Cod_Art,1,4) <> 'VIA-' ") 'loComandoSeleccionar.AppendLine(" AND SUBSTRING(Articulos.Cod_Art,1,4) <> 'GEN-' ") 'loComandoSeleccionar.AppendLine(" AND SUBSTRING(Articulos.Cod_Art,1,5) <> 'NOTAS' ") 'loComandoSeleccionar.AppendLine(" AND SUBSTRING(Articulos.Cod_Art,1,7) <> 'SES-CAN' ") 'loComandoSeleccionar.AppendLine(" AND SUBSTRING(Articulos.Cod_Art,1,7) <> 'INC-CAN' ") 'loComandoSeleccionar.AppendLine(" AND SUBSTRING(Articulos.Cod_Art,1,7) <> 'INC-PER' ") 'loComandoSeleccionar.AppendLine(" AND SUBSTRING(Articulos.Cod_Art,1,4) <> 'REQ-' ") loComandoSeleccionar.AppendLine(" AND Renglones_Cotizaciones.Cod_Art between " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Fec_Ini between " & lcParametro1Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Cli between " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Ven between " & lcParametro3Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta) loComandoSeleccionar.AppendLine(" AND Departamentos.Cod_Dep between" & lcParametro4Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta) loComandoSeleccionar.AppendLine(" AND Clases_Articulos.Cod_Cla between" & lcParametro5Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Status IN (" & lcParametro6Desde & ")") loComandoSeleccionar.AppendLine(" AND Almacenes.Cod_Alm between " & lcParametro7Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Mon between " & lcParametro8Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta) loComandoSeleccionar.AppendLine(" GROUP BY Cotizaciones.Cod_Ven, Cotizaciones.Cod_Cli, Renglones_Cotizaciones.Cod_Art, Articulos.Nom_Art, ") loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Cod_Uni, Vendedores.Nom_Ven, Clientes.Nom_Cli ") 'loComandoSeleccionar.AppendLine(" ORDER BY Cotizaciones.Cod_Ven, Cotizaciones.Cod_Cli, Renglones_Cotizaciones.Cod_Art ") loComandoSeleccionar.AppendLine("ORDER BY Cotizaciones.Cod_Ven, Cotizaciones.Cod_Cli, " & lcOrdenamiento) 'me.mEscribirConsulta(loComandoSeleccionar.ToString) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rTCotdArtVC", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrTCotdArtVC.ReportSource = loObjetoReporte Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload Try loObjetoReporte.Close() Catch loExcepcion As Exception End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo '-------------------------------------------------------------------------------------------' ' CMS: 12/08/08: Codigo inicial '-------------------------------------------------------------------------------------------'
Namespace My ''' <summary> Provides assembly information for the class library. </summary> Public NotInheritable Class MyLibrary ''' <summary> Constructor that prevents a default instance of this class from being created. </summary> Private Sub New() MyBase.New() End Sub ''' <summary> Gets the identifier of the trace source. </summary> Public Const TraceEventId As Integer = VI.Pith.My.ProjectTraceEventId.K2000 Public Const AssemblyTitle As String = "VI K2000 Meter Library" Public Const AssemblyDescription As String = "K2000 Meter Virtual Instrument Library" Public Const AssemblyProduct As String = "VI.K2000.Meter.2018" End Class End Namespace
Public Class FlagSelecterMini Private DatFile As SCDatFiles.DatFiles Private ObjectID As Integer Private Parameter As String Private DatCommand As DatCommand Public Sub Init(_DatFile As SCDatFiles.DatFiles, _ObjectID As Integer, _Parameter As String, ItemWidth As Integer) DatFile = _DatFile ObjectID = _ObjectID Parameter = _Parameter Field.Init(DatFile, ObjectID, Parameter, InputField.SFlag.FLAG) Dim DB As DatBinding = pjData.BindingManager.DatBinding(DatFile, Parameter, ObjectID) DataContext = DB If True Then Dim tbind As New Binding tbind.Path = New PropertyPath("ToolTipText") CheckboxList.SetBinding(CheckBox.ToolTipProperty, tbind) 'ValueText.ToolTip = pjData.BindingManager.DatBinding(DatFile, Parameter, ObjectID).GetToolTip End If CheckboxList.Children.Clear() Dim RelaWidth As Integer = ItemWidth Dim itmes As String() = DB.ComboxItems For i = 0 To itmes.Count - 1 Dim tBorder As New Border Dim tcheckBox As New CheckBox tcheckBox.Content = itmes(i) tcheckBox.Width = RelaWidth tcheckBox.Foreground = Application.Current.Resources("MaterialDesignBody") tBorder.DataContext = DB.GetFlagBinding(i) Dim Binding As New Binding Binding.Path = New PropertyPath("MiniFlag") tcheckBox.SetBinding(CheckBox.IsCheckedProperty, Binding) tBorder.Child = tcheckBox Dim Binding2 As New Binding Binding2.Path = New PropertyPath("MiniBackColor") tBorder.SetBinding(Border.BackgroundProperty, Binding2) CheckboxList.Children.Add(tBorder) Next DatCommand = New DatCommand(DatFile, Parameter, ObjectID) CopyItem.Command = DatCommand CopyItem.CommandParameter = DatCommand.CommandType.Copy PasteItem.Command = DatCommand PasteItem.CommandParameter = DatCommand.CommandType.Paste ResetItem.Command = DatCommand ResetItem.CommandParameter = DatCommand.CommandType.Reset End Sub Public Sub ReLoad(_DatFile As SCDatFiles.DatFiles, _ObjectID As Integer, _Parameter As String) DatFile = _DatFile ObjectID = _ObjectID Parameter = _Parameter Field.ReLoad(DatFile, ObjectID, Parameter, InputField.SFlag.FLAG) Dim DB As DatBinding = pjData.BindingManager.DatBinding(DatFile, Parameter, ObjectID) DataContext = DB If True Then Dim tbind As New Binding tbind.Path = New PropertyPath("ToolTipText") CheckboxList.SetBinding(CheckBox.ToolTipProperty, tbind) 'ValueText.ToolTip = pjData.BindingManager.DatBinding(DatFile, Parameter, ObjectID).GetToolTip End If Dim itmes As String() = DB.ComboxItems For i = 0 To itmes.Count - 1 Dim tBorder As Border = CheckboxList.Children.Item(i) Dim tcheckBox As CheckBox = tBorder.Child tBorder.DataContext = DB.GetFlagBinding(i) Dim Binding As New Binding Binding.Path = New PropertyPath("MiniFlag") tcheckBox.SetBinding(CheckBox.IsCheckedProperty, Binding) Dim Binding2 As New Binding Binding2.Path = New PropertyPath("MiniBackColor") tBorder.SetBinding(Border.BackgroundProperty, Binding2) Next DatCommand.ReLoad(DatFile, Parameter, ObjectID) End Sub Private Sub OpneMenu(sender As Object, e As ContextMenuEventArgs) Handles CheckboxList.ContextMenuOpening CopyItem.IsEnabled = DatCommand.IsEnabled(CopyItem.CommandParameter) PasteItem.IsEnabled = DatCommand.IsEnabled(PasteItem.CommandParameter) ResetItem.IsEnabled = DatCommand.IsEnabled(ResetItem.CommandParameter) End Sub End Class
#Region "Microsoft.VisualBasic::adcefd6711a8b39639f9284614ace80a, mzkit\src\metadb\Chemoinformatics\SDF\SDFParser.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: ' Code Statistics: ' Total Lines: 197 ' Code Lines: 135 ' Comment Lines: 34 ' Blank Lines: 28 ' File Size: 7.42 KB ' Module SDFParser ' ' Function: IterateParser, MoleculePopulator, parseSingle, ScanKeys, solveOffset ' SplitMolData, StreamParser ' ' ' /********************************************************************************/ #End Region Imports System.Runtime.CompilerServices Imports System.Text.RegularExpressions Imports BioNovoGene.BioDeep.Chemoinformatics.SDF.Models Imports Microsoft.VisualBasic.ComponentModel.Collection Imports Microsoft.VisualBasic.Language.UnixBash Namespace SDF ''' <summary> ''' An internal file parser module ''' </summary> Public Module SDFParser ''' <summary> ''' 解析单个的SDF文件 ''' </summary> ''' <param name="path$"></param> ''' <returns></returns> Public Function IterateParser(path$, Optional parseStruct As Boolean = True, Optional parallel As Boolean = False) As IEnumerable(Of SDF) If parallel Then Return path _ .IterateAllLines _ .Split(Function(s) s = "$$$$", includes:=False) _ .AsParallel _ .Select(Function(block) Return parseSingle(block, parseStruct) End Function) Else Return Iterator Function() As IEnumerable(Of SDF) For Each block As String() In path _ .IterateAllLines _ .Split(Function(s) s = "$$$$", includes:=False) Yield parseSingle(block, parseStruct) Next End Function() End If End Function Private Function parseSingle(block As String(), parseStruct As Boolean) As SDF Dim offset = block.solveOffset() If offset > 0 Then block = block _ .Skip(offset) _ .ToArray End If Return SDFParser.StreamParser(block, parseStruct) End Function Const MolEndMarks$ = "M END" <Extension> Private Iterator Function SplitMolData(block As String()) As IEnumerable(Of String()) For i As Integer = 3 To block.Length - 1 If block(i) = MolEndMarks OrElse (InStr(block(i), ">") = 1) Then Dim addCurrent As Integer = If(block(i) = MolEndMarks, 1, 0) Dim mol$() = block.Skip(3).Take(i - 3 + addCurrent).ToArray ' 抛出分子结构数据部分的文本数据行 If block(i) <> MolEndMarks Then Yield mol.Join(MolEndMarks).ToArray Else Yield mol End If ' 抛出分子物质注释信息部分的文本行数据 Yield block.Skip(i + addCurrent).ToArray Exit For ElseIf block(i) = "No Structure" Then ' no structure, yield nothing Yield {} Yield block.Skip(i + 1).ToArray End If Next End Function Const MolStartFlag$ = "((\d+)|(\s+))+V2000\s*" ''' <summary> ''' 假设Program名称的行总是不是空的 ''' </summary> ''' <param name="block"></param> ''' <returns></returns> <Extension> Private Function solveOffset(block As String()) As Integer For i As Integer = 0 To block.Length - 1 If block(i).IsPattern(MolStartFlag, RegexOptions.Singleline) Then Return i - 3 ElseIf block(i) = "No Structure" Then Return i - 3 End If Next Throw New BadImageFormatException End Function Public Function StreamParser(block$(), parseStruct As Boolean) As SDF Dim ID$ = block(0), program$ = block(1) Dim comment$ = block(2) Dim metas$() Dim mol$() ' 使用iterator必须要注意 ' 调用一次linq函数会调用一次迭代器函数 ' 所以没有ToArray的时候下面的两个linq拓展函数会重新调用两次迭代器函数,浪费计算性能 ' 所以下面的代码必须要加上ToArray With block.SplitMolData.ToArray mol = .First metas = .Last End With Dim struct As [Structure] = Nothing Dim metaData As Dictionary(Of String, String()) = metas _ .Split(Function(s) s.StringEmpty, includes:=False) _ .Where(Function(t) Not t.IsNullOrEmpty) _ .ToDictionary(Function(t) Dim title As String = t(Scan0).GetStackValue("<", ">") Return title End Function, Function(t) Return t.Skip(1).ToArray End Function) If parseStruct Then struct = [Structure].ParseStream(mol) End If If ID.StringEmpty Then ' 20201213 unsure for missing ID ' use inchikey instead If metaData.ContainsKey("ID") Then ID = (metaData!ID)(Scan0) Else ID = (metaData!INCHI_KEY)(Scan0) End If End If Return New SDF With { .ID = ID.Trim, .[Structure] = struct, .Software = program.Trim, .Comment = comment.Trim, .MetaData = metaData } End Function ''' <summary> ''' 这个函数可能在构建csv文件进行数据存储的时候回有用 ''' </summary> ''' <param name="directory"></param> ''' <returns></returns> Public Function ScanKeys(directory As String) As String() Dim keys As New Index(Of String) For Each model As SDF In MoleculePopulator(directory, takes:=20) For Each key As String In model.MetaData.Keys If keys.IndexOf(key) = -1 Then Call keys.Add(key) End If Next Next Return keys.Objects End Function ''' <summary> ''' Scan and parsing all of the ``*.sdf`` model file in the target <paramref name="directory"/> ''' </summary> ''' <param name="directory$"></param> ''' <param name="takes%"></param> ''' <param name="echo"></param> ''' <returns></returns> Public Iterator Function MoleculePopulator(directory$, Optional takes% = -1, Optional echo As Boolean = True, Optional parseStruct As Boolean = True) As IEnumerable(Of SDF) Dim list = ls - l - r - "*.sdf" <= directory If takes > 0 Then list = list.Take(takes) End If For Each path As String In list If echo Then Call path.__INFO_ECHO End If For Each model As SDF In SDFParser.IterateParser(path, parseStruct) Yield model Next Next End Function End Module End Namespace
#Region "Copyright (c) 1998-2007 Gravitybox LLC, All Rights Reserved" '--------------------------------------------------------------------- * ' Gravitybox LLC * ' Copyright (c) 1998-2007 All Rights reserved * ' * ' * 'This file and its contents are protected by United States and * 'International copyright laws. Unauthorized reproduction and/or * 'distribution of all or any portion of the code contained herein * 'is strictly prohibited and will result in severe civil and criminal * 'penalties. Any violations of this copyright will be prosecuted * 'to the fullest extent possible under law. * ' * 'THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED * 'TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND * 'TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE * 'CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY * 'THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF Gravitybox LLC * ' * 'UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN * 'PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR * 'SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY GRAVITYBOX PRODUCT. * ' * 'THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE * 'CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF GRAVITYBOX, * 'INC. THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO * 'INSURE ITS CONFIDENTIALITY. * ' * 'THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT * 'PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN * 'EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING * 'THE PRODUCT. IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE * 'SOURCE CODE CONTAINED HEREIN. * ' * 'THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. * '--------------------------------------------------------------------- * #End Region Option Strict On Option Explicit On Imports System.ComponentModel Namespace Gravitybox.Objects Public Class ProviderDialogSettings Inherits DialogSettingsBase #Region "Class Members" 'Private Constants Protected Shadows ReadOnly m_def_WindowText As String = "Select Providers" Protected Shadows ReadOnly m_def_FormBorderStyle As System.Windows.Forms.FormBorderStyle = FormBorderStyle.Sizable Protected Shadows ReadOnly m_def_StartPosition As System.Windows.Forms.FormStartPosition = FormStartPosition.Manual 'Property Variables 'Constructor Public Sub New() MyBase.New() MyBase.WindowText = m_def_WindowText MyBase.FormBorderStyle = m_def_FormBorderStyle MyBase.StartPosition = m_def_StartPosition End Sub #End Region #Region "Property Implementations" #End Region End Class End Namespace
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeNamespaceTests Inherits AbstractCodeNamespaceTests #Region "GetStartPoint() tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint1() Dim code = <Code> Namespace $$N : End Namespace </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=13, absoluteOffset:=13, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=1, lineOffset:=13, absoluteOffset:=13, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=27))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint2() Dim code = <Code> Namespace $$N : End Namespace </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=13, absoluteOffset:=13, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=1, lineOffset:=13, absoluteOffset:=13, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=13))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint3() Dim code = <Code> Namespace $$N ' N End Namespace </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=17, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=17, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=15)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=15)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=15)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=17, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=15)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=15))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint4() Dim code = <Code> Namespace $$N End Namespace </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint5() Dim code = <Code> Namespace $$N End Namespace </Code> ' Note: TextPoint.AbsoluteCharOffset throws in VS 2012 for vsCMPartNavigate TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint6() Dim code = <Code> Namespace $$N Class C End Class End Namespace </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=17, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint7() Dim code = <Code> Namespace $$N Class C End Class End Namespace </Code> ' Note: TextPoint.AbsoluteCharOffset throws in VS 2012 for vsCMPartNavigate TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11))) End Sub #End Region #Region "GetEndPoint() tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint1() Dim code = <Code> Namespace $$N : End Namespace </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=15, absoluteOffset:=15, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=1, lineOffset:=15, absoluteOffset:=15, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=15, absoluteOffset:=15, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=1, lineOffset:=28, absoluteOffset:=28, lineLength:=27)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=28, absoluteOffset:=28, lineLength:=27))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint2() Dim code = <Code> Namespace $$N End Namespace </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=13, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=14, absoluteOffset:=26, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=14, absoluteOffset:=26, lineLength:=13))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint3() Dim code = <Code> Namespace $$N End Namespace </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=14, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=14, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=14, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=14, absoluteOffset:=27, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=14, absoluteOffset:=27, lineLength:=13))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint4() Dim code = <Code> Namespace $$N Class C End Class End Namespace </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=39, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=39, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=39, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=4, lineOffset:=14, absoluteOffset:=52, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=4, lineOffset:=14, absoluteOffset:=52, lineLength:=13))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint5() Dim code = <Code> Namespace $$N Class C End Class End Namespace </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=41, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=41, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=41, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=6, lineOffset:=14, absoluteOffset:=54, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=6, lineOffset:=14, absoluteOffset:=54, lineLength:=13))) End Sub #End Region #Region "Comment tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment1() Dim code = <Code> ' Goo Namespace $$N End Namespace </Code> Dim result = " Goo" TestComment(code, result) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment2() Dim code = <Code> ' Goo ' Bar Namespace $$N End Namespace </Code> Dim result = " Goo" & vbCrLf & " Bar" TestComment(code, result) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment3() Dim code = <Code> ' Goo ' Bar Namespace $$N End Namespace </Code> Dim result = " Bar" TestComment(code, result) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment4() Dim code = <Code> Namespace N1 End Namespace ' Goo ' Bar Namespace $$N2 End Namespace </Code> Dim result = " Bar" TestComment(code, result) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment5() Dim code = <Code> ' Goo ''' &lt;summary&gt;Bar&lt;/summary&gt; Namespace $$N End Namespace </Code> Dim result = "" TestComment(code, result) End Sub #End Region #Region "DocComment tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment1() Dim code = <Code> ''' &lt;summary&gt; ''' Goo ''' &lt;/summary&gt; ''' &lt;remarks&gt;&lt;/remarks&gt; Namespace $$N End Namespace </Code> Dim result = " <summary>" & vbCrLf & " Goo" & vbCrLf & " </summary>" & vbCrLf & " <remarks></remarks>" TestDocComment(code, result) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment2() Dim code = <Code> ''' &lt;summary&gt; ''' Hello World ''' &lt;/summary&gt; Namespace $$N End Namespace </Code> Dim result = " <summary>" & vbCrLf & " Hello World" & vbCrLf & " </summary>" TestDocComment(code, result) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment3() Dim code = <Code> ''' &lt;summary&gt; ''' Goo ''' &lt;/summary&gt; ' Bar ''' &lt;remarks&gt;&lt;/remarks&gt; Namespace $$N End Namespace </Code> Dim result = " <remarks></remarks>" TestDocComment(code, result) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment4() Dim code = <Code> Namespace N1 ''' &lt;summary&gt; ''' Goo ''' &lt;/summary&gt; ''' &lt;remarks&gt;&lt;/remarks&gt; Namespace $$N2 End Namespace End Namespace </Code> Dim result = " <summary>" & vbCrLf & " Goo" & vbCrLf & " </summary>" & vbCrLf & " <remarks></remarks>" TestDocComment(code, result) End Sub #End Region #Region "Set Comment tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment1() As Task Dim code = <Code> ' Goo ' Bar Namespace $$N End Namespace </Code> Dim expected = <Code> ' Goo Namespace N End Namespace </Code> Await TestSetComment(code, expected, Nothing) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment2() As Task Dim code = <Code> ' Goo ''' &lt;summary&gt;Bar&lt;/summary&gt; Namespace $$N End Namespace </Code> Dim expected = <Code> ' Goo ''' &lt;summary&gt;Bar&lt;/summary&gt; ' Bar Namespace N End Namespace </Code> Await TestSetComment(code, expected, "Bar") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment3() As Task Dim code = <Code> ' Goo ' Bar Namespace $$N End Namespace </Code> Dim expected = <Code> ' Goo ' Blah Namespace N End Namespace </Code> Await TestSetComment(code, expected, "Blah") End Function #End Region #Region "Set DocComment tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_Nothing1() As Task Dim code = <Code> Namespace $$N End Namespace </Code> Dim expected = <Code> Namespace N End Namespace </Code> Await TestSetDocComment(code, expected, Nothing) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_Nothing2() As Task Dim code = <Code> ''' &lt;summary&gt; ''' Goo ''' &lt;/summary&gt; Namespace $$N End Namespace </Code> Dim expected = <Code> Namespace N End Namespace </Code> Await TestSetDocComment(code, expected, Nothing) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml1() As Task Dim code = <Code> Namespace $$N End Namespace </Code> Dim expected = <Code> ''' &lt;doc&gt;&lt;summary&gt;Blah&lt;/doc&gt; Namespace N End Namespace </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</doc>") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml2() As Task Dim code = <Code> Namespace $$N End Namespace </Code> Dim expected = <Code> ''' &lt;doc___&gt;&lt;summary&gt;Blah&lt;/summary&gt;&lt;/doc___&gt; Namespace N End Namespace </Code> Await TestSetDocComment(code, expected, "<doc___><summary>Blah</summary></doc___>") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment1() As Task Dim code = <Code> Namespace $$N End Namespace </Code> Dim expected = <Code> ''' &lt;summary&gt;Hello World&lt;/summary&gt; Namespace N End Namespace </Code> Await TestSetDocComment(code, expected, "<summary>Hello World</summary>") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment2() As Task Dim code = <Code> ''' &lt;summary&gt;Hello World&lt;/summary&gt; Namespace $$N End Namespace </Code> Dim expected = <Code> ''' &lt;summary&gt;Blah&lt;/summary&gt; Namespace N End Namespace </Code> Await TestSetDocComment(code, expected, "<summary>Blah</summary>") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment3() As Task Dim code = <Code> ' Goo Namespace $$N End Namespace </Code> Dim expected = <Code> ' Goo ''' &lt;summary&gt;Blah&lt;/summary&gt; Namespace N End Namespace </Code> Await TestSetDocComment(code, expected, "<summary>Blah</summary>") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment4() As Task Dim code = <Code> ''' &lt;summary&gt;FogBar&lt;/summary&gt; ' Goo Namespace $$N End Namespace </Code> Dim expected = <Code> ''' &lt;summary&gt;Blah&lt;/summary&gt; ' Goo Namespace N End Namespace </Code> Await TestSetDocComment(code, expected, "<summary>Blah</summary>") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment5() As Task Dim code = <Code> Namespace N1 Namespace $$N2 End Namespace End Namespace </Code> Dim expected = <Code> Namespace N1 ''' &lt;summary&gt;Hello World&lt;/summary&gt; Namespace N2 End Namespace End Namespace </Code> Await TestSetDocComment(code, expected, "<summary>Hello World</summary>") End Function #End Region #Region "Remove tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove1() As Task Dim code = <Code> Namespace $$Goo Class C End Class End Namespace </Code> Dim expected = <Code> Namespace Goo End Namespace </Code> Await TestRemoveChild(code, expected, "C") End Function #End Region <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren1() Dim code = <Code> Namespace N$$ Class C1 End Class Class C2 End Class Class C3 End Class End Namespace </Code> TestChildren(code, IsElement("C1", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C2", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C3", EnvDTE.vsCMElement.vsCMElementClass)) End Sub <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub NoChildrenForInvalidMembers() Dim code = <Code> Namespace N$$ Sub M() End Sub Function M() As Integer End Function Property P As Integer Event E() End Sub </Code> TestChildren(code, NoElements) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
' 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 Friend Partial Class BoundRangeVariable Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Me.RangeVariable End Get End Property End Class End Namespace
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.239 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "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( sender As Global.System.Object, e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class 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.Fusion.RayTracer.Windows.MySettings Get Return Global.Fusion.RayTracer.Windows.MySettings.Default End Get End Property End Module End Namespace
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.34014 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On 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.AfterAllFormsClose End Sub <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Protected Overrides Sub OnCreateMainForm() Me.MainForm = Global.ics.login End Sub End Class End Namespace
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.0.1.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.SkyEditor.ROMEditor.My.MySettings Get Return Global.SkyEditor.ROMEditor.My.MySettings.Default End Get End Property End Module End Namespace
Imports System.IO Imports Microsoft.Win32 Imports SolidWorks.Interop.swconst Public Class PFiles Public Const Extension_Part As String = ".sldprt" Public Const Extension_Assembly As String = ".sldasm" Public Const Extension_Drawing As String = ".slddrw" ''' <summary> ''' Bitmask. ''' </summary> <Flags> Public Enum CTDocTypes Part = 1 Assembly = 2 Drawing = 4 All = 7 End Enum ''' <summary> ''' Attempts to create a folder. Returns false and an exception if creation fails. ''' </summary> Public Shared Function CreateFolder(path As String, ByRef ex As Exception) As Boolean Try Directory.CreateDirectory(path) Return True Catch except As Exception ex = except Return False End Try End Function Public Shared Function CopyFolder(sourceDir As String, destinationDir As String, ByRef ex As Exception) As Boolean Try For Each dirPath As String In Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories) Dim newDir As String = dirPath.Replace(sourceDir, destinationDir) If Directory.Exists(newDir) = False Then Directory.CreateDirectory(newDir) End If Next For Each filePath As String In Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories) Dim newPath As String = filePath.Replace(sourceDir, destinationDir) File.Copy(filePath, newPath, True) Next ex = Nothing Return True Catch except As Exception ex = except Return False End Try End Function Public Shared Function DeleteFile(path As String, ByRef ex As Exception) As Boolean Try If File.Exists(path) = False Then Return False File.Delete(path) Return True Catch except As Exception ex = except Return False End Try End Function Public Shared Function DeleteFolder(path As String, ByRef ex As Exception) As Boolean Try Directory.Delete(path, True) Return True Catch except As Exception ex = except Return False End Try End Function Public Shared Function RenameFile(oldFilePath As String, newFileName As String, ByRef ex As Exception) As Boolean Const tempFileNamePrefix = "_TEMP_" Try Dim dirName As String = Path.GetDirectoryName(oldFilePath) Dim tempFilePath As String = Path.Combine(dirName, tempFileNamePrefix + Path.GetFileName(oldFilePath)) Dim newFilePath As String = Path.Combine(dirName, newFileName) File.Move(oldFilePath, tempFilePath) File.Move(tempFilePath, newFilePath) Return True Catch except As Exception ex = except Return False End Try End Function Public Shared Function IsFileReadOnly(file As String) As Boolean Dim myFileInfo As FileInfo = New FileInfo(file) Return myFileInfo.IsReadOnly End Function ''' <summary> ''' Verifies that a file has a specified extension. ''' </summary> ''' <param name="filePath"></param> ''' <param name="extension"></param> ''' <returns></returns> Public Shared Function VerifyExtension(filePath As String, extension As String) As Boolean If Path.GetExtension(filePath).ToUpper() = extension.ToUpper() Then Return True Else Return False End If End Function Public Shared Function IsValidFileName(text As String) As Boolean For Each c As Char In Path.GetInvalidFileNameChars() If text.Contains(c.ToString()) Then Return False End If Next Return True End Function Public Shared Function ReplaceIllegalChars(text As String, replaceChar As String) As String Dim illegalChars As String() = {Chr(34), "<", ">", "/", "\", ":", "*", "?", "|", ControlChars.Quote} For Each illegalChar As String In illegalChars If text.Contains(illegalChar) Then text = text.Replace(illegalChar, replaceChar) Next Return text End Function Public Shared Function ReadTextFile(textFilePath As String) As List(Of String) Try Dim myList As New List(Of String) Using reader As New StreamReader(textFilePath) Do While reader.Peek <> -1 myList.Add(reader.ReadLine) Loop reader.Close() End Using Return myList Catch ex As Exception Return Nothing End Try End Function ''' <summary> ''' Returns a list of file paths of SolidWorks files in a directory, not including temporary files. ''' </summary> ''' <param name="folderPath"></param> ''' <param name="docTypes">Bitmask.</param> ''' <param name="includeSubFolders"></param> ''' <returns></returns> Public Shared Function GetSolidWorksFilePaths(folderPath As String, Optional docTypes As CTDocTypes = CTDocTypes.All, Optional includeSubFolders As Boolean = False) As List(Of String) Dim searchOption As SearchOption If includeSubFolders Then searchOption = SearchOption.AllDirectories Else searchOption = SearchOption.TopDirectoryOnly End If Dim fileList As New List(Of String) If docTypes And CTDocTypes.Part Then fileList.AddRange(Directory.GetFiles(folderPath, "*" + Extension_Part, searchOption)) If docTypes And CTDocTypes.Assembly Then fileList.AddRange(Directory.GetFiles(folderPath, "*" + Extension_Assembly, searchOption)) If docTypes And CTDocTypes.Drawing Then fileList.AddRange(Directory.GetFiles(folderPath, "*" + Extension_Drawing, searchOption)) For i As Integer = fileList.Count - 1 To 0 Step -1 If fileList(i).IndexOf("~$") <> -1 Then fileList.RemoveAt(i) Next Return fileList End Function ''' <summary> ''' Examines the extension of a file path to determine if the file is a SolidWorks part, assembly, or drawing. Returns -1 if file is not a SolidWorks model. ''' </summary> ''' <param name="filePath"></param> ''' <returns></returns> Public Shared Function GetSolidWorksDocType(filePath As String) As swDocumentTypes_e If filePath Is Nothing Then Return -1 Select Case Path.GetExtension(filePath).ToLower() Case Extension_Part Return swDocumentTypes_e.swDocPART Case Extension_Assembly Return swDocumentTypes_e.swDocASSEMBLY Case Extension_Drawing Return swDocumentTypes_e.swDocDRAWING Case Else Return -1 End Select End Function ''' <param name="version">Major version of SolidWorks, or -1 for the newest version.</param> ''' <returns></returns> Public Shared Function GetSolidWorksExecutablePath(version As Integer) As String Using hklm As RegistryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) If version = -1 Then Using swKeys As RegistryKey = hklm.OpenSubKey("SOFTWARE\SolidWorks") Dim keys As String() = swKeys.GetSubKeyNames() For Each key As String In keys If key.IndexOf("SOLIDWORKS ") <> -1 Then Dim split As String() = key.Split(" ") Dim retVal As Integer If Integer.TryParse(split(1), retVal) Then version = PSolidWorks.ConvertYearToMajorVersion(retVal) End If Next End Using End If Using key As RegistryKey = hklm.OpenSubKey("SOFTWARE\SolidWorks\SOLIDWORKS " + PSolidWorks.ConvertMajorVersionToYear(version).ToString() + "\Setup") If key Is Nothing Then Return Nothing Else Return key.GetValue("SolidWorks Folder") + "SLDWORKS.EXE" End If End Using End Using End Function End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmSetting_File Inherits System.Windows.Forms.Form 'Form remplace la méthode Dispose pour nettoyer la liste des composants. <System.Diagnostics.DebuggerNonUserCode()> Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Requise par le Concepteur Windows Form Private components As System.ComponentModel.IContainer 'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form 'Elle peut être modifiée à l'aide du Concepteur Windows Form. 'Ne la modifiez pas à l'aide de l'éditeur de code. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmSetting_File)) Me.ElipBorder = New Bunifu.Framework.UI.BunifuElipse(Me.components) Me.txtFileNameFSF = New Bunifu.Framework.UI.BunifuMaterialTextbox() Me.grpFileSettingsFSF = New System.Windows.Forms.GroupBox() Me.switch_Nothimg2FSL = New Bunifu.Framework.UI.BunifuiOSSwitch() Me.switch_NothimgFSL = New Bunifu.Framework.UI.BunifuiOSSwitch() Me.switchOriginal_YoutubeTileFSF = New Bunifu.Framework.UI.BunifuiOSSwitch() Me.lblTextFSF1 = New System.Windows.Forms.Label() Me.lblCkbTextFSA3 = New System.Windows.Forms.Label() Me.lblCkbTextFSA2 = New System.Windows.Forms.Label() Me.btnNameInfoFSL = New Bunifu.Framework.UI.BunifuImageButton() Me.lblInfos_FileNameFSL = New System.Windows.Forms.Label() Me.lblFileNameFLF = New System.Windows.Forms.Label() Me.btnMainInfoFSL = New Bunifu.Framework.UI.BunifuImageButton() Me.btnSaveFSL = New Bunifu.Framework.UI.BunifuImageButton() Me.grpFileSettingsFSF.SuspendLayout() CType(Me.btnNameInfoFSL, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.btnMainInfoFSL, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.btnSaveFSL, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'ElipBorder ' Me.ElipBorder.ElipseRadius = 5 Me.ElipBorder.TargetControl = Me ' 'txtFileNameFSF ' Me.txtFileNameFSF.Cursor = System.Windows.Forms.Cursors.IBeam Me.txtFileNameFSF.Font = New System.Drawing.Font("Century Gothic", 9.75!) Me.txtFileNameFSF.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer)) Me.txtFileNameFSF.HintForeColor = System.Drawing.Color.Empty Me.txtFileNameFSF.HintText = "" Me.txtFileNameFSF.isPassword = False Me.txtFileNameFSF.LineFocusedColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(187, Byte), Integer), CType(CType(125, Byte), Integer)) Me.txtFileNameFSF.LineIdleColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(187, Byte), Integer), CType(CType(125, Byte), Integer)) Me.txtFileNameFSF.LineMouseHoverColor = System.Drawing.Color.FromArgb(CType(CType(19, Byte), Integer), CType(CType(65, Byte), Integer), CType(CType(135, Byte), Integer)) Me.txtFileNameFSF.LineThickness = 3 Me.txtFileNameFSF.Location = New System.Drawing.Point(101, 54) Me.txtFileNameFSF.Margin = New System.Windows.Forms.Padding(5) Me.txtFileNameFSF.Name = "txtFileNameFSF" Me.txtFileNameFSF.Size = New System.Drawing.Size(291, 43) Me.txtFileNameFSF.TabIndex = 2 Me.txtFileNameFSF.TextAlign = System.Windows.Forms.HorizontalAlignment.Left ' 'grpFileSettingsFSF ' Me.grpFileSettingsFSF.Controls.Add(Me.switch_Nothimg2FSL) Me.grpFileSettingsFSF.Controls.Add(Me.switch_NothimgFSL) Me.grpFileSettingsFSF.Controls.Add(Me.switchOriginal_YoutubeTileFSF) Me.grpFileSettingsFSF.Controls.Add(Me.lblTextFSF1) Me.grpFileSettingsFSF.Controls.Add(Me.lblCkbTextFSA3) Me.grpFileSettingsFSF.Controls.Add(Me.lblCkbTextFSA2) Me.grpFileSettingsFSF.Controls.Add(Me.btnNameInfoFSL) Me.grpFileSettingsFSF.Controls.Add(Me.lblInfos_FileNameFSL) Me.grpFileSettingsFSF.Controls.Add(Me.txtFileNameFSF) Me.grpFileSettingsFSF.Controls.Add(Me.lblFileNameFLF) Me.grpFileSettingsFSF.Location = New System.Drawing.Point(12, 33) Me.grpFileSettingsFSF.Margin = New System.Windows.Forms.Padding(4) Me.grpFileSettingsFSF.Name = "grpFileSettingsFSF" Me.grpFileSettingsFSF.Padding = New System.Windows.Forms.Padding(4) Me.grpFileSettingsFSF.Size = New System.Drawing.Size(420, 274) Me.grpFileSettingsFSF.TabIndex = 3 Me.grpFileSettingsFSF.TabStop = False Me.grpFileSettingsFSF.Text = "File Settings" ' 'switch_Nothimg2FSL ' Me.switch_Nothimg2FSL.BackColor = System.Drawing.Color.Transparent Me.switch_Nothimg2FSL.BackgroundImage = CType(resources.GetObject("switch_Nothimg2FSL.BackgroundImage"), System.Drawing.Image) Me.switch_Nothimg2FSL.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.switch_Nothimg2FSL.Cursor = System.Windows.Forms.Cursors.Hand Me.switch_Nothimg2FSL.Enabled = False Me.switch_Nothimg2FSL.Location = New System.Drawing.Point(81, 243) Me.switch_Nothimg2FSL.Margin = New System.Windows.Forms.Padding(12, 16, 12, 16) Me.switch_Nothimg2FSL.Name = "switch_Nothimg2FSL" Me.switch_Nothimg2FSL.OffColor = System.Drawing.Color.Tomato Me.switch_Nothimg2FSL.OnColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(187, Byte), Integer), CType(CType(125, Byte), Integer)) Me.switch_Nothimg2FSL.Size = New System.Drawing.Size(35, 20) Me.switch_Nothimg2FSL.TabIndex = 16 Me.switch_Nothimg2FSL.Value = False ' 'switch_NothimgFSL ' Me.switch_NothimgFSL.BackColor = System.Drawing.Color.Transparent Me.switch_NothimgFSL.BackgroundImage = CType(resources.GetObject("switch_NothimgFSL.BackgroundImage"), System.Drawing.Image) Me.switch_NothimgFSL.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.switch_NothimgFSL.Cursor = System.Windows.Forms.Cursors.Hand Me.switch_NothimgFSL.Enabled = False Me.switch_NothimgFSL.Location = New System.Drawing.Point(81, 205) Me.switch_NothimgFSL.Margin = New System.Windows.Forms.Padding(9, 12, 9, 12) Me.switch_NothimgFSL.Name = "switch_NothimgFSL" Me.switch_NothimgFSL.OffColor = System.Drawing.Color.Tomato Me.switch_NothimgFSL.OnColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(187, Byte), Integer), CType(CType(125, Byte), Integer)) Me.switch_NothimgFSL.Size = New System.Drawing.Size(35, 20) Me.switch_NothimgFSL.TabIndex = 17 Me.switch_NothimgFSL.Value = False ' 'switchOriginal_YoutubeTileFSF ' Me.switchOriginal_YoutubeTileFSF.BackColor = System.Drawing.Color.Transparent Me.switchOriginal_YoutubeTileFSF.BackgroundImage = CType(resources.GetObject("switchOriginal_YoutubeTileFSF.BackgroundImage"), System.Drawing.Image) Me.switchOriginal_YoutubeTileFSF.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.switchOriginal_YoutubeTileFSF.Cursor = System.Windows.Forms.Cursors.Hand Me.switchOriginal_YoutubeTileFSF.Location = New System.Drawing.Point(81, 160) Me.switchOriginal_YoutubeTileFSF.Margin = New System.Windows.Forms.Padding(7, 9, 7, 9) Me.switchOriginal_YoutubeTileFSF.Name = "switchOriginal_YoutubeTileFSF" Me.switchOriginal_YoutubeTileFSF.OffColor = System.Drawing.Color.Tomato Me.switchOriginal_YoutubeTileFSF.OnColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(187, Byte), Integer), CType(CType(125, Byte), Integer)) Me.switchOriginal_YoutubeTileFSF.Size = New System.Drawing.Size(35, 20) Me.switchOriginal_YoutubeTileFSF.TabIndex = 18 Me.switchOriginal_YoutubeTileFSF.Value = True ' 'lblTextFSF1 ' Me.lblTextFSF1.AutoSize = True Me.lblTextFSF1.ForeColor = System.Drawing.Color.Black Me.lblTextFSF1.Location = New System.Drawing.Point(127, 163) Me.lblTextFSF1.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.lblTextFSF1.Name = "lblTextFSF1" Me.lblTextFSF1.Size = New System.Drawing.Size(144, 17) Me.lblTextFSF1.TabIndex = 13 Me.lblTextFSF1.Text = "Original YouTube Title" ' 'lblCkbTextFSA3 ' Me.lblCkbTextFSA3.AutoSize = True Me.lblCkbTextFSA3.ForeColor = System.Drawing.Color.Tomato Me.lblCkbTextFSA3.Location = New System.Drawing.Point(134, 246) Me.lblCkbTextFSA3.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.lblCkbTextFSA3.Name = "lblCkbTextFSA3" Me.lblCkbTextFSA3.Size = New System.Drawing.Size(137, 17) Me.lblCkbTextFSA3.TabIndex = 14 Me.lblCkbTextFSA3.Text = "Resolution Standard" ' 'lblCkbTextFSA2 ' Me.lblCkbTextFSA2.AutoSize = True Me.lblCkbTextFSA2.ForeColor = System.Drawing.Color.Tomato Me.lblCkbTextFSA2.Location = New System.Drawing.Point(129, 205) Me.lblCkbTextFSA2.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.lblCkbTextFSA2.Name = "lblCkbTextFSA2" Me.lblCkbTextFSA2.Size = New System.Drawing.Size(202, 17) Me.lblCkbTextFSA2.TabIndex = 15 Me.lblCkbTextFSA2.Text = "Always Convert audio to mp3" ' 'btnNameInfoFSL ' Me.btnNameInfoFSL.BackColor = System.Drawing.Color.White Me.btnNameInfoFSL.Image = Global.MySoft_YouTube_Downloader.My.Resources.Resources.icons8_Info_48 Me.btnNameInfoFSL.ImageActive = Nothing Me.btnNameInfoFSL.Location = New System.Drawing.Point(382, 106) Me.btnNameInfoFSL.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.btnNameInfoFSL.Name = "btnNameInfoFSL" Me.btnNameInfoFSL.Size = New System.Drawing.Size(12, 16) Me.btnNameInfoFSL.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom Me.btnNameInfoFSL.TabIndex = 12 Me.btnNameInfoFSL.TabStop = False Me.btnNameInfoFSL.Zoom = 10 ' 'lblInfos_FileNameFSL ' Me.lblInfos_FileNameFSL.AutoSize = True Me.lblInfos_FileNameFSL.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblInfos_FileNameFSL.Location = New System.Drawing.Point(98, 102) Me.lblInfos_FileNameFSL.Name = "lblInfos_FileNameFSL" Me.lblInfos_FileNameFSL.Size = New System.Drawing.Size(278, 15) Me.lblInfos_FileNameFSL.TabIndex = 11 Me.lblInfos_FileNameFSL.Text = "Sensitive case please no special charactar allow" ' 'lblFileNameFLF ' Me.lblFileNameFLF.AutoSize = True Me.lblFileNameFLF.Location = New System.Drawing.Point(8, 67) Me.lblFileNameFLF.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.lblFileNameFLF.Name = "lblFileNameFLF" Me.lblFileNameFLF.Size = New System.Drawing.Size(84, 17) Me.lblFileNameFLF.TabIndex = 1 Me.lblFileNameFLF.Text = "File Name : " ' 'btnMainInfoFSL ' Me.btnMainInfoFSL.BackColor = System.Drawing.Color.White Me.btnMainInfoFSL.Image = Global.MySoft_YouTube_Downloader.My.Resources.Resources.icons8_Info_48 Me.btnMainInfoFSL.ImageActive = Nothing Me.btnMainInfoFSL.Location = New System.Drawing.Point(12, 355) Me.btnMainInfoFSL.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.btnMainInfoFSL.Name = "btnMainInfoFSL" Me.btnMainInfoFSL.Size = New System.Drawing.Size(31, 33) Me.btnMainInfoFSL.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom Me.btnMainInfoFSL.TabIndex = 9 Me.btnMainInfoFSL.TabStop = False Me.btnMainInfoFSL.Zoom = 10 ' 'btnSaveFSL ' Me.btnSaveFSL.BackColor = System.Drawing.Color.White Me.btnSaveFSL.Image = Global.MySoft_YouTube_Downloader.My.Resources.Resources.icons8_Save_64 Me.btnSaveFSL.ImageActive = Nothing Me.btnSaveFSL.Location = New System.Drawing.Point(378, 351) Me.btnSaveFSL.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.btnSaveFSL.Name = "btnSaveFSL" Me.btnSaveFSL.Size = New System.Drawing.Size(64, 35) Me.btnSaveFSL.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom Me.btnSaveFSL.TabIndex = 9 Me.btnSaveFSL.TabStop = False Me.btnSaveFSL.Zoom = 10 ' 'frmSetting_File ' Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 17.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.White Me.ClientSize = New System.Drawing.Size(446, 399) Me.Controls.Add(Me.btnMainInfoFSL) Me.Controls.Add(Me.btnSaveFSL) Me.Controls.Add(Me.grpFileSettingsFSF) Me.Font = New System.Drawing.Font("Century Gothic", 9.75!) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.Margin = New System.Windows.Forms.Padding(4) Me.Name = "frmSetting_File" Me.Text = "frmSetting_File" Me.grpFileSettingsFSF.ResumeLayout(False) Me.grpFileSettingsFSF.PerformLayout() CType(Me.btnNameInfoFSL, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.btnMainInfoFSL, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.btnSaveFSL, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents ElipBorder As Bunifu.Framework.UI.BunifuElipse Friend WithEvents grpFileSettingsFSF As GroupBox Friend WithEvents txtFileNameFSF As Bunifu.Framework.UI.BunifuMaterialTextbox Friend WithEvents lblFileNameFLF As Label Friend WithEvents btnSaveFSL As Bunifu.Framework.UI.BunifuImageButton Friend WithEvents btnMainInfoFSL As Bunifu.Framework.UI.BunifuImageButton Friend WithEvents lblInfos_FileNameFSL As Label Friend WithEvents btnNameInfoFSL As Bunifu.Framework.UI.BunifuImageButton Friend WithEvents switch_Nothimg2FSL As Bunifu.Framework.UI.BunifuiOSSwitch Friend WithEvents switch_NothimgFSL As Bunifu.Framework.UI.BunifuiOSSwitch Friend WithEvents switchOriginal_YoutubeTileFSF As Bunifu.Framework.UI.BunifuiOSSwitch Friend WithEvents lblTextFSF1 As Label Friend WithEvents lblCkbTextFSA3 As Label Friend WithEvents lblCkbTextFSA2 As Label End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class NoPizza_update_ 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() components = New System.ComponentModel.Container Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(800, 450) Me.Text = "NoPizza_update_" End Sub End Class
'Author: Ritvik Mayank <mritvik@novell.com> 'Copyright (C) 2005 Novell, Inc (http://www.novell.com) Option Strict Off Imports System Module ConversionXorOperator Function _Main() As Integer Dim A As Integer = 0 Dim B As Integer = 2 Dim R As Boolean R = A Xor B '00 XOr 10 If R = False Then System.Console.WriteLine("#Error With Xor Operator") : Return 1 End If End Function Sub Main() _Main() System.Console.WriteLine("<%END%>") End Sub End Module
Module Users Public Function IsRegistered(n As String) As Boolean Dim t As Boolean = False For Each i In My.Settings.UDB t = i.StartsWith(String.Format("{0};", n)) Next IsRegistered = t End Function Public Function Authorize(a As String, b As String) As Boolean Dim t As Boolean = False For Each i In My.Settings.UDB t = i.StartsWith(String.Format("{0};{1};", a, b)) Next Authorize = t End Function End Module
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.IO Imports System.Text Imports System.Text.RegularExpressions Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenVBCore Inherits BasicTestBase ' The Embedded attribute should only be available ' if other embedded code is included. <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On <Microsoft.VisualBasic.Embedded()> Class C End Class ]]></file> </compilation> ' With InternalXmlHelper. Dim compilation = CreateCompilationWithMscorlibAndReferences(sources, references:=NoVbRuntimeReferences.Concat(XmlReferences), options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() ' With VBCore. compilation = CreateCompilationWithMscorlibAndReferences(sources, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() ' No embedded code. compilation = CreateCompilationWithMscorlibAndReferences(sources, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. <Microsoft.VisualBasic.Embedded()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub ' The Embedded attribute should only be available for ' user-define code if vb runtime is included. <WorkItem(546059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546059")> <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode2() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On <Microsoft.VisualBasic.Embedded()> Class C End Class ]]></file> </compilation> ' No embedded code. Dim compilation = CreateCompilationWithMscorlibAndReferences(sources, references:=NoVbRuntimeReferences.Concat({MsvbRef, SystemXmlRef, SystemXmlLinqRef}), options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. <Microsoft.VisualBasic.Embedded()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub ' The Embedded attribute should only be available for ' user-define code if vb runtime is included. <WorkItem(546059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546059")> <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode3() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C Public x As Microsoft.VisualBasic.Embedded End Class ]]></file> </compilation> ' No embedded code. Dim compilation = CreateCompilationWithMscorlibAndReferences(sources, references:=NoVbRuntimeReferences.Concat({MsvbRef, SystemXmlRef, SystemXmlLinqRef}), options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. Public x As Microsoft.VisualBasic.Embedded ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub InternalXmlHelper_NoReferences() Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences, sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class C > Sub C..ctor() End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_NoSymbols() Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class C > Sub C..ctor() End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_CreateNamespaceAttribute_NoDebug() Dim symbols = <expected> Namespace Global Class C > C.F As System.Object > Sub C..ctor() End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class End Namespace End Namespace Namespace My [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class My.InternalXmlHelper [System.ComponentModel.EditorBrowsableAttribute] > Function My.InternalXmlHelper.CreateNamespaceAttribute(name As System.Xml.Linq.XName, ns As System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute End Class End Namespace End Namespace </expected>.Value Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Class C Public Shared F As Object = <p:x/> End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], symbols), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <WorkItem(545438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545438"), WorkItem(546887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546887")> <Fact()> Public Sub InternalXmlHelper_ValueProperty() Dim symbols = <expected> Namespace Global Class C > Sub C..ctor() > Sub C.M(x As System.Xml.Linq.XElement) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class End Namespace End Namespace Namespace My [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class My.InternalXmlHelper > Function My.InternalXmlHelper.get_AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName) As System.String > Function My.InternalXmlHelper.get_Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As System.String > Property My.InternalXmlHelper.AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName) As System.String > Property My.InternalXmlHelper.Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As System.String > Sub My.InternalXmlHelper.set_AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName, value As System.String) > Sub My.InternalXmlHelper.set_Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), value As System.String) End Class End Namespace End Namespace </expected>.Value Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C Shared Sub M(x As System.Xml.Linq.XElement) x.@a = x.<y>.Value End Sub End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), symbolValidator:=Sub([module]) ValidateSymbols([module], symbols), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_Locations() Dim compilation = CreateCompilationWithMscorlibAndReferences( <compilation> <file name="c.vb"><![CDATA[ Class C Public Shared F As Object = <x xmlns:p="http://roslyn"/> End Class ]]></file> </compilation>, references:=NoVbRuntimeReferences.Concat(XmlReferences), options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() Dim globalNamespace = compilation.SourceModule.GlobalNamespace Assert.Equal(globalNamespace.Locations.Length, 4) Dim [namespace] = globalNamespace.GetMember(Of NamespaceSymbol)("My") Assert.Equal([namespace].Locations.Length, 1) Dim type = [namespace].GetMember(Of NamedTypeSymbol)("InternalXmlHelper") Assert.Equal(type.Locations.Length, 1) End Sub <Fact()> Public Sub VbCore_NoSymbols() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_SymbolInGetType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports System.Collections.Generic Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Console.Write(GetType(List(Of List(Of StandardModuleAttribute))).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="System.Collections.Generic.List`1[System.Collections.Generic.List`1[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]]", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(Constants).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.Constants", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Constants End Module [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants_WithVbRuntime() MyBase.CompileAndVerify(source:= <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(Constants).ToString()) End Sub End Class </file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(MsvbRef), expectedOutput:="Microsoft.VisualBasic.Constants", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Constants End Module [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub, options:=TestOptions.DebugExe.WithEmbedVbCoreRuntime(True).WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants_All() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim s = String.Format("|{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|", vbCrLf, vbNewLine, vbCr, vbLf, vbBack, vbFormFeed, vbTab, vbVerticalTab, vbNullChar, vbNullString) s = s.Replace(vbCr, "vbCr") s = s.Replace(vbLf, "vbLf") s = s.Replace(vbBack, "vbBack") s = s.Replace(vbFormFeed, "vbFormFeed") s = s.Replace(vbTab, "vbTab") s = s.Replace(vbVerticalTab, "vbVerticalTab") s = s.Replace(vbNullChar, "vbNullChar") Console.Write(s) End Sub End Class </file> </compilation>, expectedOutput:="|vbCrvbLf|vbCrvbLf|vbCr|vbLf|vbBack|vbFormFeed|vbTab|vbVerticalTab|vbNullChar||", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.EmbeddedOperators).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.EmbeddedOperators", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators_CompareString() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.EmbeddedOperators.CompareString("a", "A", True)) End Sub End Class </file> </compilation>, expectedOutput:="0", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators > Function Microsoft.VisualBasic.CompilerServices.EmbeddedOperators.CompareString(Left As System.String, Right As System.String, TextCompare As System.Boolean) As System.Int32 End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators_CompareString2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim x As String = "Foo" Console.WriteLine(If(x = "Foo", "y", x)) End Sub End Class </file> </compilation>, expectedOutput:="y", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators > Function Microsoft.VisualBasic.CompilerServices.EmbeddedOperators.CompareString(Left As System.String, Right As System.String, TextCompare As System.Boolean) As System.Int32 End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.Conversions).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.Conversions", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToBoolean_String() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToBoolean("True").ToString()) End Sub End Class </file> </compilation>, expectedOutput:="True", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.String) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToBoolean_Object() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToBoolean(directcast("True".ToString(), Object)).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="True", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.Object) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.String) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToSByte_String() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToSByte("77").ToString()) End Sub End Class </file> </compilation>, expectedOutput:="77", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.String) As System.SByte End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToSByte_Object() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToSByte(directcast("77", Object)).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="77", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.Object) As System.SByte [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.String) As System.SByte End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Utils_CopyArray() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim a(10) As String Redim Preserve a(12) Console.Write(a.Length.ToString) End Sub End Class </file> </compilation>, expectedOutput:="13", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Utils > Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(arySrc As System.Array, aryDest As System.Array) As System.Array End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.ObjectFlowControl).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.ObjectFlowControl", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl_ForLoopControl() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.ObjectFlowControl.ForLoopControl).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl..ctor() End Class End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl_ForLoopControl_ForNextCheckR8() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckR8(CDbl(100), 1, 1)) End Sub End Class </file> </compilation>, expectedOutput:="False", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl > Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckR8(count As System.Double, limit As System.Double, StepValue As System.Double) As System.Boolean > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl..ctor() End Class End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StaticLocalInitFlag() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.StaticLocalInitFlag).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag > Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As System.Int16 > Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StaticLocalInitFlag_State() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim v As New CompilerServices.StaticLocalInitFlag v.State = 1 Console.Write(v.State.ToString()) End Sub End Class </file> </compilation>, expectedOutput:="1", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag > Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As System.Int16 > Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_IncompleteInitialization() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.IncompleteInitialization).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.IncompleteInitialization", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.IncompleteInitialization > Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_IncompleteInitialization_Throw() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Try Throw New CompilerServices.IncompleteInitialization() Catch ex As Exception Console.Write(ex.GetType().ToString()) End Try End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.IncompleteInitialization", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.IncompleteInitialization > Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StandardModuleAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;StandardModuleAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Module Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_DesignerGeneratedAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;DesignerGeneratedAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute > Sub Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_OptionCompareAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(&lt;OptionCompareAttribute()&gt;args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute > Sub Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_OptionTextAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;OptionTextAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.CompilerServices.OptionTextAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.OptionTextAttribute > Sub Microsoft.VisualBasic.CompilerServices.OptionTextAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_HideModuleNameAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;HideModuleNameAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.HideModuleNameAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.HideModuleNameAttribute > Sub Microsoft.VisualBasic.HideModuleNameAttribute..ctor() End Class End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> <WorkItem(544511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544511")> Public Sub VbCore_SingleSymbol_Strings_AscW_Char() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Char = "A"c Console.Write(AscW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="65", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Strings_ChrW_Char() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="A", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings > Function Microsoft.VisualBasic.Strings.ChrW(CharCode As System.Int32) As System.Char End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Strings_ChrW_Char_MultipleEmits() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="A", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings > Function Microsoft.VisualBasic.Strings.ChrW(CharCode As System.Int32) As System.Char End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub).Compilation For i = 0 To 10 Using memory As New MemoryStream() compilation.Emit(memory) End Using Next End Sub <Fact()> Public Sub VbCore_TypesReferencedFromAttributes() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;AttributeUsage(AttributeTargets.All)&gt; Class Attr Inherits Attribute Public Sub New(_type As Type) End Sub Public Type As Type End Class &lt;Attr(GetType(Strings), Type:=GetType(Microsoft.VisualBasic.CompilerServices.Conversions))&gt; Module Program Sub Main(args As String()) End Sub End Module </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [System.AttributeUsageAttribute] Class Attr > Attr.Type As System.Type > Sub Attr..ctor(_type As System.Type) End Class [Attr] Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_TypesReferencedFromAttributes_Array() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;AttributeUsage(AttributeTargets.All)&gt; Class Attr Inherits Attribute Public Types() As Type End Class &lt;Attr(Types:= New Type() {GetType(Conversions), GetType(Strings)})&gt; Module Program Sub Main(args As String()) End Sub End Module </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [System.AttributeUsageAttribute] Class Attr > Attr.Types As System.Type() > Sub Attr..ctor() End Class [Attr] Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EnsurePrivateConstructorsEmitted() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Reflection Imports Microsoft.VisualBasic Module Program Sub Main(args As String()) PrintConstructorInfo(GetType(CompilerServices.EmbeddedOperators)) PrintConstructorInfo(GetType(CompilerServices.Conversions)) PrintConstructorInfo(GetType(CompilerServices.ProjectData)) PrintConstructorInfo(GetType(CompilerServices.Utils)) End Sub Sub PrintConstructorInfo(type As Type) Dim constructor = type.GetConstructors(BindingFlags.Instance Or BindingFlags.NonPublic) Console.Write(type.ToString()) Console.Write(" ") Console.WriteLine(constructor(0).ToString()) End Sub End Module </file> </compilation>, expectedOutput:= <output> Microsoft.VisualBasic.CompilerServices.EmbeddedOperators Void .ctor() Microsoft.VisualBasic.CompilerServices.Conversions Void .ctor() Microsoft.VisualBasic.CompilerServices.ProjectData Void .ctor() Microsoft.VisualBasic.CompilerServices.Utils Void .ctor() </output>.Value.Replace(vbLf, vbNewLine), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) > Sub Program.PrintConstructorInfo(type As System.Type) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Utils End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EmbeddedAttributeOnAssembly_NoReferences() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) For Each attr In GetType(Program).Assembly.GetCustomAttributes(True).ToArray() Dim name = attr.ToString() If name.IndexOf("Embedded") >= 0 Then Console.WriteLine(attr.GetType().ToString()) End If dim x = vbNewLine Next End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EmbeddedAttributeOnAssembly_References_NoDebug() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) For Each attr In GetType(Program).Assembly.GetCustomAttributes(True).ToArray() Dim name = attr.ToString() If name.IndexOf("Embedded") >= 0 Then Console.WriteLine(attr.GetType().ToString()) End If dim x = GetType(Strings) Next End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.Embedded", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo() Dim other As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="HasIVTToCompilationVbCore"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(123)) ' Forces Microsoft.VisualBasic.Strings to be embedded into the assembly End Sub Public Shared U As Utils End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="WantsIVTAccessVbCoreButCantHave"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New() Dim a = GetType(Microsoft.VisualBasic.Strings) End Sub End Class End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) 'compilation should not succeed, and internals should not be imported. c.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(c, <error> BC30002: Type 'Microsoft.VisualBasic.Strings' is not defined. Dim a = GetType(Microsoft.VisualBasic.Strings) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) Dim c2 As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New() Dim a = GetType(Microsoft.VisualBasic.Strings) End Sub End Class End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c2, <error> BC30002: Type 'Microsoft.VisualBasic.Strings' is not defined. Dim a = GetType(Microsoft.VisualBasic.Strings) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo2() Dim other As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo2"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot2")> Friend Class SourceLibrary Shared Sub Main(args As String()) Dim a() As String Redim Preserve a(2) End Sub Public Shared U As Utils End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot2"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) SourceLibrary.U.CopyArray(Nothing, Nothing) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30456: 'CopyArray' is not a member of 'Utils'. SourceLibrary.U.CopyArray(Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo3() Dim other As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(args.Length)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo3_ViaBinary() Dim other As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(args.Length)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim memory As New MemoryStream() other.Emit(memory) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlibAndReferences( (<compilation name="WantsIVTAccessVbCoreAndStillCannot3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>), references:=NoVbRuntimeReferences.Concat({MetadataReference.CreateFromImage(memory.ToImmutable())}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) End Sub <Fact> Public Sub VbCore_EmbeddedVbCoreWithIVToAndRuntime() Dim other As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="VbCore_EmbeddedVbCoreWithIVToAndRuntime"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) MyBase.CompileAndVerify(source:= <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Try Dim s As String = "123" Dim i As Integer = s ' This should use Conversions.ToInteger(String) Catch e As Exception ' This should use ProjectData.SetProjectError()/ClearProjectError() End Try End Sub End Class </file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(MsvbRef).Concat(New VisualBasicCompilationReference(other)), expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub <Fact()> Public Sub VbCore_CompilationOptions() Dim withoutVbCore As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="VbCore_CompilationOptions1"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) CompilationUtils.AssertTheseDiagnostics(withoutVbCore, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) Dim withVbCore As VisualBasicCompilation = withoutVbCore.WithOptions(withoutVbCore.Options.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(withVbCore) Dim withoutVbCore2 As VisualBasicCompilation = withVbCore.WithOptions(withVbCore.Options.WithEmbedVbCoreRuntime(False)) CompilationUtils.AssertTheseDiagnostics(withoutVbCore2, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) Dim withVbCore2 As VisualBasicCompilation = withoutVbCore.WithOptions(withoutVbCore2.Options.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(withVbCore2) End Sub <Fact()> Public Sub NoDebugInfoForVbCoreSymbols() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe.WithEmbedVbCoreRuntime(True)) compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="43, DF, 2, C2, F5, 5F, 6A, CB, 8, D3, 1F, D2, 8E, 4F, FE, A, 8F, C2, 76, D7, "/> </files> <entryPoint declaringType="Program" methodName="Main" parameterNames="args"/> <methods> <method containingType="Program" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="38" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="31" document="1"/> <entry offset="0x4" startLine="7" startColumn="9" endLine="7" endColumn="32" document="1"/> <entry offset="0x10" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x11"> <namespace name="System" importlevel="file"/> <namespace name="Microsoft.VisualBasic" importlevel="file"/> <currentnamespace name=""/> <local name="ch" il_index="0" il_start="0x0" il_end="0x11" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <Fact> Public Sub VbCoreTypeAndUserPartialTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic Partial Friend Class HideModuleNameAttribute Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'HideModuleNameAttribute' conflicts with a Visual Basic Runtime class 'HideModuleNameAttribute'. Partial Friend Class HideModuleNameAttribute ~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic Friend Class HideModuleNameAttribute Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'HideModuleNameAttribute' conflicts with a Visual Basic Runtime class 'HideModuleNameAttribute'. Friend Class HideModuleNameAttribute ~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreNamespaceAndUserTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'VisualBasic' conflicts with a Visual Basic Runtime namespace 'VisualBasic'. Friend Class VisualBasic ~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() Call Console.WriteLine(GetType(Strings).ToString()) End Sub End Module Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30560: 'Strings' is ambiguous in the namespace 'Microsoft.VisualBasic'. Call Console.WriteLine(GetType(Strings).ToString()) ~~~~~~~ BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> <file name="b.vb"> Imports System Namespace Global.Microsoft Namespace VisualBasic Namespace Strings Partial Friend Class Other End Class End Namespace End Namespace End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <Fact> Public Sub VbRuntimeTypeAndUserNamespaceConflictOutsideOfVBCore() ' This verifies the diagnostic BC31210 scenario outsides of using VB Core which ' is triggered by the Embedded Attribute. This occurs on the command line compilers ' when the reference to system.xml.linq is added Dim compilationOptions = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"System", "Microsoft.VisualBasic"})) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="testa.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) Dim x2 = &lt;test/&gt; End Sub End Module Namespace global.Microsoft Public Module VisualBasic End Module End Namespace </file> </compilation>, options:=compilationOptions, additionalRefs:={SystemCoreRef, SystemXmlLinqRef, SystemXmlRef}) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors>BC30560: Error in project-level import 'Microsoft.VisualBasic' at 'Microsoft.VisualBasic' : 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. Imports Microsoft.VisualBasic ~~~~~~~~~~~~~~~~~~~~~ BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) ~~~~~~~~~~~~~~~~~~~~~ BC31210: module 'VisualBasic' conflicts with a Visual Basic Runtime namespace 'VisualBasic'. Public Module VisualBasic ~~~~~~~~~~~ </errors>) ' Remove the reference to System.XML.Linq and verify compilation behavior that the ' diagnostic is not produced. compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="testa.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) End Sub End Module Namespace global.Microsoft Public Module VisualBasic End Module End Namespace </file> </compilation>, options:=compilationOptions) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors>BC30456: 'InStr' is not a member of 'VisualBasic'. Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCore_IsImplicitlyDeclaredSymbols() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) Dim vbCoreType = compilation.GetTypeByMetadataName("Microsoft.VisualBasic.Embedded") Assert.NotNull(vbCoreType) Dim namespacesToCheck As New Queue(Of NamespaceSymbol)() namespacesToCheck.Enqueue(vbCoreType.ContainingNamespace) While namespacesToCheck.Count > 0 Dim ns = namespacesToCheck.Dequeue() For Each member In ns.GetMembers() Select Case member.Kind Case SymbolKind.NamedType AssertTypeAndItsMembersAreImplicitlyDeclared(DirectCast(member, NamedTypeSymbol)) Case SymbolKind.Namespace namespacesToCheck.Enqueue(DirectCast(member, NamespaceSymbol)) End Select Next End While End Sub <Fact()> Public Sub InternalXmlHelper_IsImplicitlyDeclaredSymbols() Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Dim x = <x/>.<y>.Value End Module ]]></file> </compilation>, additionalRefs:=XmlReferences) compilation.AssertNoErrors() Dim type = compilation.GetTypeByMetadataName("My.InternalXmlHelper") AssertTypeAndItsMembersAreImplicitlyDeclared(type) End Sub Private Sub IsImplicitlyDeclaredSymbols([namespace] As NamespaceSymbol) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_UsingEmbedVBCore() 'Static Locals use types contained within VB Runtime so verify with VBCore option to ensure the feature works 'using VBCore which would be the case with platforms such as Phone. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() Foo() Foo() End Sub Sub Foo() Static x as integer = 1 x+=1 End Sub End Module </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_NoRequiredTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime we generate applicable errors about missing types. 'This will include types for Module as well as static locals Dim compilation As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Foo() Foo() End Sub Sub Foo() Static x as integer = 1 x+=1 End Sub End Module </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "Module1").WithArguments("Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_CorrectDefinedTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime but appropriate types specified in Source the static 'local scenarios should work correctly. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Public Class Module1 Public shared Sub Main() Foo() Foo() End Sub shared Sub Foo() Static x as integer = 1 x+=1 End Sub End Class Namespace Global.Microsoft.VisualBasic.CompilerServices Friend Class StaticLocalInitFlag Public State As Short End Class Friend Class IncompleteInitialization Inherits System.Exception Public Sub New() MyBase.New() End Sub End Class End Namespace </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.AssertNoDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_IncorrectDefinedTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime but appropriate types specified in Source the static 'local scenarios should work correctly but if we define the types incorrectly we should generate errors although we 'should not crash. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateCompilationWithReferences( <compilation> <file name="a.vb"> Public Class Module1 Public shared Sub Main() Foo() Foo() End Sub shared Sub Foo() Static x as integer = 1 x+=1 End Sub End Class Namespace Global.Microsoft.VisualBasic.CompilerServices Friend Class StaticLocalInitFlag Public State As Short End Class Friend Structure IncompleteInitialization Inherits System.Exception Public Sub New() MyBase.New() End Sub End Structure End Namespace </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NewInStruct, "New").WithLocation(20, 24), Diagnostic(ERRID.ERR_StructCantInherit, "Inherits System.Exception").WithLocation(19, 13), Diagnostic(ERRID.ERR_UseOfKeywordFromStructure1, "MyBase").WithArguments("MyBase").WithLocation(21, 17) ) End Sub Private Sub AssertTypeAndItsMembersAreImplicitlyDeclared(type As NamedTypeSymbol) Assert.True(type.IsImplicitlyDeclared) Assert.True(type.IsEmbedded) For Each member In type.GetMembers() Assert.True(member.IsEmbedded) Assert.True(member.IsImplicitlyDeclared) Select Case member.Kind Case SymbolKind.Field, SymbolKind.Property Case SymbolKind.Method For Each param In DirectCast(member, MethodSymbol).Parameters Assert.True(param.IsEmbedded) Assert.True(param.IsImplicitlyDeclared) Next For Each typeParam In DirectCast(member, MethodSymbol).TypeParameters Assert.True(typeParam.IsEmbedded) Assert.True(typeParam.IsImplicitlyDeclared) Next Case SymbolKind.NamedType AssertTypeAndItsMembersAreImplicitlyDeclared(DirectCast(member, NamedTypeSymbol)) Case Else Assert.False(True) ' Unexpected member. End Select Next End Sub <Fact, WorkItem(544291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544291")> Public Sub VbCoreSyncLockOnObject() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Private SyncObj As Object = New Object() Sub Main() SyncLock SyncObj End SyncLock End Sub End Module </file> </compilation>).VerifyIL("Module1.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.SyncObj As Object" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact(), WorkItem(545772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545772")> Public Sub VbCoreNoStdLib() Dim source = <compilation> <file name="a.vb"> Module Class1 Public Sub Main() End Sub End Module </file> </compilation> CreateCompilationWithMscorlib( source, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True)). VerifyDiagnostics( Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System")) End Sub #Region "Symbols Validator" Private Shared ReadOnly s_normalizeRegex As New Regex("^(\s*)", RegexOptions.Multiline) Private Sub ValidateSourceSymbols([module] As ModuleSymbol) ValidateSourceSymbol([module].GlobalNamespace) End Sub Private Sub ValidateSourceSymbol(symbol As Symbol) For Each reference In symbol.DeclaringSyntaxReferences Assert.False(reference.SyntaxTree.IsEmbeddedOrMyTemplateTree()) Next Select Case symbol.Kind Case SymbolKind.Namespace Dim [namespace] = DirectCast(symbol, NamespaceSymbol) For Each _type In From x In [namespace].GetTypeMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_type) Next For Each _ns In From x In [namespace].GetNamespaceMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_ns) Next Case SymbolKind.NamedType Dim type = DirectCast(symbol, NamedTypeSymbol) For Each _member In From x In type.GetMembers() Where x.Kind <> SymbolKind.NamedType Select x Order By x.ToTestDisplayString() ValidateSourceSymbol(_member) Next For Each _nested In From x In type.GetTypeMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_nested) Next End Select End Sub Private Sub ValidateSymbols([module] As ModuleSymbol, expected As String) Dim actualBuilder As New StringBuilder CollectAllTypesAndMembers([module].GlobalNamespace, actualBuilder, "") expected = expected.Trim() ' normalize Dim matches = s_normalizeRegex.Matches(expected) Dim captures = matches(matches.Count - 1).Groups(1).Captures Dim indent = captures(captures.Count - 1).Value If indent.Length > 0 Then expected = New Regex("^" + indent, RegexOptions.Multiline).Replace(expected, "") End If Dim actual = actualBuilder.ToString.Trim() If expected.Replace(vbLf, vbNewLine).CompareTo(actual) <> 0 Then Console.WriteLine("Actual:") Console.WriteLine(actual) Console.WriteLine() Console.WriteLine("Diff:") Console.WriteLine(DiffUtil.DiffReport(expected, actual)) Console.WriteLine() Assert.True(False) End If End Sub Private Sub AddSymbolAttributes(symbol As Symbol, builder As StringBuilder, indent As String) For Each attribute In symbol.GetAttributes() builder.AppendLine(indent + "[" + attribute.AttributeClass.ToTestDisplayString() + "]") Next End Sub Private Sub CollectAllTypesAndMembers(symbol As Symbol, builder As StringBuilder, indent As String) Const IndentStep = " " Select Case symbol.Kind Case SymbolKind.Namespace Dim [namespace] = DirectCast(symbol, NamespaceSymbol) builder.AppendLine(indent + "Namespace " + symbol.ToTestDisplayString) For Each _type In From x In [namespace].GetTypeMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_type, builder, indent + IndentStep) Next For Each _ns In From x In [namespace].GetNamespaceMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_ns, builder, indent + IndentStep) Next builder.AppendLine(indent + "End Namespace") Case SymbolKind.NamedType If symbol.Name <> "<Module>" Then AddSymbolAttributes(symbol, builder, indent) Dim type = DirectCast(symbol, NamedTypeSymbol) builder.AppendLine(indent + type.TypeKind.ToString() + " " + symbol.ToTestDisplayString) For Each _member In From x In type.GetMembers() Where x.Kind <> SymbolKind.NamedType Select x Order By x.ToTestDisplayString() AddSymbolAttributes(_member, builder, indent + IndentStep + " ") builder.AppendLine(indent + IndentStep + "> " + _member.ToTestDisplayString()) Next For Each _nested In From x In type.GetTypeMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_nested, builder, indent + IndentStep) Next builder.AppendLine(indent + "End " + type.TypeKind.ToString()) End If End Select End Sub #End Region #Region "Utilities" Protected NoVbRuntimeReferences As MetadataReference() = {MscorlibRef, SystemRef, SystemCoreRef} Friend Shadows Function CompileAndVerify( source As XElement, Optional expectedOutput As String = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing ) As CompilationVerifier Dim options = If(expectedOutput IsNot Nothing, TestOptions.ReleaseExe, TestOptions.ReleaseDll). WithMetadataImportOptions(MetadataImportOptions.Internal). WithEmbedVbCoreRuntime(True) Return MyBase.CompileAndVerify(source:=source, allReferences:=NoVbRuntimeReferences, expectedOutput:=expectedOutput, sourceSymbolValidator:=sourceSymbolValidator, validator:=validator, symbolValidator:=symbolValidator, options:=options) End Function #End Region End Class End Namespace
'Copyright 2016 Esri 'Licensed under the Apache License, Version 2.0 (the "License"); 'you may not use this file except in compliance with the License. 'You may obtain a copy of the License at ' http://www.apache.org/licenses/LICENSE-2.0 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. Option Explicit On Public Interface ITranslateTree Property TranslationFactorX() As Double Property TranslationFactorY() As Double End Interface
Option Explicit On Option Strict On Option Infer On Imports System.Collections.Immutable Imports Basic.CodeAnalysis.Text Namespace Global.Basic.CodeAnalysis.Syntax Friend NotInheritable Class Parser Public ReadOnly Property Diagnostics As DiagnosticBag = New DiagnosticBag Private ReadOnly m_syntaxTree As SyntaxTree Public ReadOnly Property Text As SourceText Private ReadOnly Property Tokens As ImmutableArray(Of SyntaxToken) Private Property Position As Integer Sub New(tree As SyntaxTree) Dim tokens = New List(Of SyntaxToken) Dim badTokens = New List(Of SyntaxToken) Dim lexer = New Lexer(tree) Dim token As SyntaxToken Do token = lexer.Lex If token.Kind = SyntaxKind.BadToken Then badTokens.Add(token) Else If badTokens.Count > 0 Then Dim leadingTrivia = token.LeadingTrivia.ToBuilder Dim index = 0 For Each badToken In badTokens For Each lt In badToken.LeadingTrivia leadingTrivia.Insert(index, lt) : index += 1 Next Dim trivia = New SyntaxTrivia(tree, SyntaxKind.SkippedTextTrivia, badToken.Position, badToken.Text) leadingTrivia.Insert(index, trivia) : index += 1 For Each tt In badToken.TrailingTrivia leadingTrivia.Insert(index, tt) : index += 1 Next Next badTokens.Clear() token = New SyntaxToken(token.SyntaxTree, token.Kind, token.Position, token.Text, token.Value, leadingTrivia.ToImmutable, token.TrailingTrivia) End If tokens.Add(token) End If Loop While token.Kind <> SyntaxKind.EndOfFileToken m_syntaxTree = tree Text = tree.Text Diagnostics.AddRange(lexer.Diagnostics) Me.Tokens = tokens.ToImmutableArray End Sub Private Function Peek(offset As Integer) As SyntaxToken Dim index = Position + offset If index >= Tokens.Length Then Return Tokens(Tokens.Length - 1) End If Return Tokens(index) End Function Private Function Current() As SyntaxToken Return Peek(0) End Function Private Function NextToken() As SyntaxToken Dim current = Me.Current Position += 1 Return current End Function Private Function MatchToken(kind As SyntaxKind) As SyntaxToken If Current.Kind = kind Then Return NextToken() Else Diagnostics.ReportUnexpectedToken(Current.Location, Current.Kind, kind) Return New SyntaxToken(m_syntaxTree, kind, Current.Position, Nothing, Nothing, ImmutableArray(Of SyntaxTrivia).Empty, ImmutableArray(Of SyntaxTrivia).Empty) End If End Function Public Function ParseCompilationUnit() As CompilationUnitSyntax Dim members = ParseMembers Dim endOfFileToken = MatchToken(SyntaxKind.EndOfFileToken) Return New CompilationUnitSyntax(m_syntaxTree, members, endOfFileToken) End Function Private Function ParseMembers() As ImmutableArray(Of MemberSyntax) Dim members = ImmutableArray.CreateBuilder(Of MemberSyntax) While Current.Kind <> SyntaxKind.EndOfFileToken Dim startToken = Current Dim member = ParseMember() members.Add(member) ' If ParseStatement() did not consume any tokens, ' we need to skip the current token and continue ' in order to avoid an infinite loop. ' We don't need to report an error because we'll ' already tried to parse an expression statement ' and reported one. If (Current Is startToken) Then NextToken() End If End While Return members.ToImmutable End Function Private Function ParseMember() As MemberSyntax If Me.Current.Kind = SyntaxKind.FunctionKeyword Then Return ParseFunctionDeclaration End If Return ParseGlobalStatement End Function Private Function ParseFunctionDeclaration() As MemberSyntax Dim functionKeyword = MatchToken(SyntaxKind.FunctionKeyword) Dim identifier = MatchToken(SyntaxKind.IdentifierToken) Dim openParen = MatchToken(SyntaxKind.OpenParenToken) Dim parameters = ParseParameterList Dim closeParen = MatchToken(SyntaxKind.CloseParenToken) Dim type = ParseOptionalTypeClause Dim body = ParseBlockStatement() Return New FunctionDeclarationSyntax(m_syntaxTree, functionKeyword, identifier, openParen, parameters, closeParen, type, body) End Function Private Function ParseParameterList() As SeparatedSyntaxList(Of ParameterSyntax) Dim nodesAndSeparators = ImmutableArray.CreateBuilder(Of SyntaxNode) Dim parseNextParameter = True While parseNextParameter AndAlso Current.Kind <> SyntaxKind.CloseParenToken AndAlso Current.Kind <> SyntaxKind.EndOfFileToken Dim parameter = ParseParameter nodesAndSeparators.Add(parameter) If Me.Current.Kind = SyntaxKind.CommaToken Then Dim comma = MatchToken(SyntaxKind.CommaToken) nodesAndSeparators.Add(comma) Else parseNextParameter = False End If End While Return New SeparatedSyntaxList(Of ParameterSyntax)(nodesAndSeparators.ToImmutable) End Function Private Function ParseParameter() As ParameterSyntax Dim identifier = MatchToken(SyntaxKind.IdentifierToken) Dim type = ParseTypeClause() Return New ParameterSyntax(m_syntaxTree, identifier, type) End Function Private Function ParseGlobalStatement() As MemberSyntax Dim statement = ParseStatement() Return New GlobalStatementSyntax(m_syntaxTree, statement) End Function Private Function ParseStatement() As StatementSyntax Select Case Current.Kind Case SyntaxKind.OpenBraceToken Return ParseBlockStatement Case SyntaxKind.LetKeyword, SyntaxKind.VarKeyword, SyntaxKind.LetKeyword Return ParseVariableDeclaration Case SyntaxKind.IfKeyword Return ParseIfStatement Case SyntaxKind.WhileKeyword Return ParseWhileStatement Case SyntaxKind.DoKeyword Return ParseDoWhileStatement Case SyntaxKind.ForKeyword Return ParseForStatement Case SyntaxKind.BreakKeyword Return ParseBreakStatement Case SyntaxKind.ContinueKeyword Return ParseContinueStatement Case SyntaxKind.ReturnKeyword Return ParseReturnStatement Case Else Return ParseExpressionStatement End Select End Function Private Function ParseBlockStatement() As StatementSyntax Dim statements = ImmutableArray.CreateBuilder(Of StatementSyntax) Dim openBraceToken = MatchToken(SyntaxKind.OpenBraceToken) While Current.Kind <> SyntaxKind.EndOfFileToken AndAlso Current.Kind <> SyntaxKind.CloseBraceToken Dim startToken = Current Dim statement = ParseStatement() statements.Add(statement) ' If ParseStatement() did not consume any tokens, ' we need to skip the current token and continue ' in order to avoid an infinite loop. ' We don't need to report an error because we'll ' already tried to parse an expression statement ' and reported one. If (Current Is startToken) Then NextToken() End If End While Dim closeBraceToken = MatchToken(SyntaxKind.CloseBraceToken) Return New BlockStatementSyntax(m_syntaxTree, openBraceToken, statements.ToImmutable, closeBraceToken) End Function Private Function ParseVariableDeclaration() As StatementSyntax ' The following line is modified from the original in order to ' allow the addition of the DIM keyword (in addition to LET and VAR). 'Dim expected = If(Me.Current.Kind = SyntaxKind.LetKeyword, SyntaxKind.LetKeyword, SyntaxKind.VarKeyword) Dim expected = SyntaxKind.VarKeyword ' If LET or DIM, set... otherwise, default to VAR (whether it's VAR or not). Select Case Current.Kind Case SyntaxKind.LetKeyword : expected = SyntaxKind.LetKeyword Case Else End Select Dim keyword = MatchToken(expected) Dim identifier = MatchToken(SyntaxKind.IdentifierToken) Dim typeClause = ParseOptionalTypeClause() Dim equals = MatchToken(SyntaxKind.EqualsToken) Dim initializer = ParseExpression() Return New VariableDeclarationSyntax(m_syntaxTree, keyword, identifier, typeClause, equals, initializer) End Function Private Function ParseOptionalTypeClause() As TypeClauseSyntax If Current.Kind <> SyntaxKind.ColonToken Then Return Nothing End If Return ParseTypeClause() End Function Private Function ParseTypeClause() As TypeClauseSyntax Dim colonToken = MatchToken(SyntaxKind.ColonToken) Dim identifier = MatchToken(SyntaxKind.IdentifierToken) Return New TypeClauseSyntax(m_syntaxTree, colonToken, identifier) End Function Private Function ParseIfStatement() As StatementSyntax Dim keyword = MatchToken(SyntaxKind.IfKeyword) Dim condition = ParseExpression Dim statement = ParseStatement() Dim elseClause = ParseOptionalElseClause() Return New IfStatementSyntax(m_syntaxTree, keyword, condition, statement, elseClause) End Function Private Function ParseOptionalElseClause() As ElseClauseSyntax If Current.Kind <> SyntaxKind.ElseKeyword Then Return Nothing End If Dim keyword = NextToken() Dim statement = ParseStatement() Return New ElseClauseSyntax(m_syntaxTree, keyword, statement) End Function Private Function ParseWhileStatement() As StatementSyntax Dim keyword = MatchToken(SyntaxKind.WhileKeyword) Dim condition = ParseExpression Dim body = ParseStatement() Return New WhileStatementSyntax(m_syntaxTree, keyword, condition, body) End Function Private Function ParseDoWhileStatement() As StatementSyntax Dim doKeyword = MatchToken(SyntaxKind.DoKeyword) Dim body = ParseStatement Dim whileKeyword = MatchToken(SyntaxKind.WhileKeyword) Dim condition = ParseExpression() Return New DoWhileStatementSyntax(m_syntaxTree, doKeyword, body, whileKeyword, condition) End Function Private Function ParseForStatement() As StatementSyntax Dim keyword = MatchToken(SyntaxKind.ForKeyword) Dim identifier = MatchToken(SyntaxKind.IdentifierToken) Dim equalsToken = MatchToken(SyntaxKind.EqualsToken) Dim lowerBound = ParseExpression Dim toKeyword = MatchToken(SyntaxKind.ToKeyword) Dim upperBound = ParseExpression Dim body = ParseStatement() Return New ForStatementSyntax(m_syntaxTree, keyword, identifier, equalsToken, lowerBound, toKeyword, upperBound, body) End Function Private Function ParseBreakStatement() As StatementSyntax Dim keyword = MatchToken(SyntaxKind.BreakKeyword) Return New BreakStatementSyntax(m_syntaxTree, keyword) End Function Private Function ParseContinueStatement() As StatementSyntax Dim keyword = MatchToken(SyntaxKind.ContinueKeyword) Return New ContinueStatementSyntax(m_syntaxTree, keyword) End Function Private Function ParseReturnStatement() As StatementSyntax Dim keyword = MatchToken(SyntaxKind.ReturnKeyword) Dim keywordLine = Text.GetLineIndex(keyword.Span.Start) Dim currentLine = Text.GetLineIndex(Current.Span.Start) Dim isEof = (Me.Current.Kind = SyntaxKind.EndOfFileToken) Dim sameLine = Not isEof AndAlso keywordLine = currentLine Dim expression = If(sameLine, ParseExpression, Nothing) Return New ReturnStatementSyntax(m_syntaxTree, keyword, expression) End Function Private Function ParseExpressionStatement() As ExpressionStatementSyntax Dim expression = ParseExpression() Return New ExpressionStatementSyntax(m_syntaxTree, expression) End Function Private Function ParseExpression() As ExpressionSyntax Return ParseAssignmentExpression End Function Private Function ParseAssignmentExpression() As ExpressionSyntax If (Me.Peek(0).Kind = SyntaxKind.IdentifierToken AndAlso Me.Peek(1).Kind = SyntaxKind.EqualsToken) Then Dim identifierToken = NextToken Dim operatorToken = NextToken Dim right = Me.ParseAssignmentExpression Return New AssignmentExpressionSyntax(m_syntaxTree, identifierToken, operatorToken, right) End If Return ParseBinaryExpression End Function Private Function ParseBinaryExpression(Optional parentPrecedence As Integer = 0) As ExpressionSyntax Dim left As ExpressionSyntax Dim unaryOperatorPrecedence = Current.Kind.GetUnaryOperatorPrecedence If unaryOperatorPrecedence <> 0 AndAlso unaryOperatorPrecedence >= parentPrecedence Then Dim operatorToken = NextToken() Dim operand = ParseBinaryExpression(unaryOperatorPrecedence) left = New UnaryExpressionSyntax(m_syntaxTree, operatorToken, operand) Else left = ParsePrimaryExpression End If While True Dim precedence = Current.Kind.GetBinaryOperatorPrecedence If precedence = 0 OrElse precedence <= parentPrecedence Then Exit While End If Dim operatorToken = NextToken() Dim right = ParseBinaryExpression(precedence) left = New BinaryExpressionSyntax(m_syntaxTree, left, operatorToken, right) End While Return left End Function Private Function ParsePrimaryExpression() As ExpressionSyntax Select Case Current.Kind Case SyntaxKind.OpenParenToken : Return ParseParenExpression Case SyntaxKind.FalseKeyword : Return ParseBooleanLiteral Case SyntaxKind.TrueKeyword : Return ParseBooleanLiteral Case SyntaxKind.NumberToken : Return ParseNumberLiteral Case SyntaxKind.StringToken : Return ParseStringLiteral Case SyntaxKind.IdentifierToken : Return ParseNameorCallExpression Case Else ' Default to parsing a name expression if we reach this far. Return ParseNameOrCallExpression End Select End Function Private Function ParseParenExpression() As ExpressionSyntax Dim left = MatchToken(SyntaxKind.OpenParenToken) Dim expression = ParseExpression Dim right = MatchToken(SyntaxKind.CloseParenToken) Return New ParenExpressionSyntax(m_syntaxTree, left, expression, right) End Function Private Function ParseBooleanLiteral() As ExpressionSyntax Dim isTrue = (Me.Current.Kind = SyntaxKind.TrueKeyword) Dim keywordToken = MatchToken(If(isTrue, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword)) Return New LiteralExpressionSyntax(m_syntaxTree, keywordToken, isTrue) End Function Private Function ParseNumberLiteral() As ExpressionSyntax Dim numberToken = MatchToken(SyntaxKind.NumberToken) Return New LiteralExpressionSyntax(m_syntaxTree, numberToken) End Function Private Function ParseStringLiteral() As ExpressionSyntax Dim stringToken = MatchToken(SyntaxKind.StringToken) Return New LiteralExpressionSyntax(m_syntaxTree, stringToken) End Function Private Function ParseNameOrCallExpression() As ExpressionSyntax If Me.Peek(0).Kind = SyntaxKind.IdentifierToken AndAlso Me.Peek(1).Kind = SyntaxKind.OpenParenToken Then Return ParseCallExpression Else Return ParseNameExpression End If End Function Private Function ParseCallExpression() As ExpressionSyntax Dim identifier = MatchToken(SyntaxKind.IdentifierToken) Dim openParen = MatchToken(SyntaxKind.OpenParenToken) Dim arguments = ParseArguments Dim closeParen = MatchToken(SyntaxKind.CloseParenToken) Return New CallExpressionSyntax(m_syntaxTree, identifier, openParen, arguments, closeParen) End Function Private Function ParseArguments() As SeparatedSyntaxList(Of ExpressionSyntax) Dim nodesAndSeparators = ImmutableArray.CreateBuilder(Of SyntaxNode) Dim parseNextArgument = True While parseNextArgument AndAlso Current.Kind <> SyntaxKind.CloseParenToken AndAlso Current.Kind <> SyntaxKind.EndOfFileToken Dim expression = ParseExpression nodesAndSeparators.Add(expression) If Me.Current.Kind = SyntaxKind.CommaToken Then Dim comma = MatchToken(SyntaxKind.CommaToken) nodesAndSeparators.Add(comma) Else parseNextArgument = False End If End While Return New SeparatedSyntaxList(Of ExpressionSyntax)(nodesAndSeparators.ToImmutable) End Function Private Function ParseNameExpression() As ExpressionSyntax Dim identifierToken = MatchToken(SyntaxKind.IdentifierToken) Return New NameExpressionSyntax(m_syntaxTree, identifierToken) End Function End Class End Namespace
Imports Autodesk.Revit.DB Imports Autodesk.Revit.UI Imports System.Windows.Forms Imports System.Linq Imports System.Diagnostics Imports [Case].Subs.SharedParameters.Data Public Class form_Main Private _s As clsSettings Private _params As clsSharedParameters Private _eventsEnabled = True ''' <summary> ''' Constructor ''' </summary> ''' <param name="s"></param> ''' <remarks></remarks> Public Sub New(s As clsSettings) InitializeComponent() ' Widen Scope _s = s End Sub #Region "Private Members" ''' <summary> ''' Load the Categories ''' </summary> ''' <remarks></remarks> Private Sub LoadCategories() ' Fresh List Me.TreeViewCategories.Nodes.Clear() ' Parameter Bindable Only For Each c As Category In _s.Doc.Settings.Categories If c.Name.ToLower.Contains("electri") Then Dim m_todo As String = "" End If If c.AllowsBoundParameters = True Then ' Search Active? If Not String.IsNullOrEmpty(TextBoxFilterCategories.Text) Then If Not c.Name.ToLower.Contains(TextBoxFilterCategories.Text.ToLower) Then Continue For End If ' Add the Category Dim m_n As TreeNode = Me.TreeViewCategories.Nodes.Add(c.Name, c.Name) m_n.Tag = c End If Next ' Sort the List Me.TreeViewCategories.Sort() End Sub ''' <summary> ''' Node Check Helper ''' </summary> ''' <param name="n"></param> ''' <param name="v"></param> ''' <remarks></remarks> Private Sub CheckNode(n As TreeNode, v As Boolean) ' No Events _eventsEnabled = False n.Checked = v ' Events _eventsEnabled = True End Sub ''' <summary> ''' Load the Parameter Names ''' </summary> ''' <remarks></remarks> Private Sub LoadSharedParameters() ' Fresh List Me.TreeViewParameters.Nodes.Clear() Try ' Shared Parameters If Me.RadioButtonByGroup.Checked = True Then ' Load by Group For Each x In _params.DefinitionsByGroup Dim m_defs As List(Of Definition) = x.Value ' Each Definition For Each d In m_defs ' Search? If Not String.IsNullOrEmpty(TextBoxFilterParams.Text) Then If Not d.Name.ToLower.Contains(TextBoxFilterParams.Text.ToLower) Then Continue For End If ' Parent Node If Not Me.TreeViewParameters.Nodes.ContainsKey(x.Key.ToString) Then Try ' Add Group Name Me.TreeViewParameters.Nodes.Add(x.Key.ToString, x.Key.ToString) Catch End Try End If Try ' Child Only Dim m_tn As TreeNode = Me.TreeViewParameters.Nodes(x.Key.ToString).Nodes.Add(d.Name, d.Name) m_tn.Tag = d Catch End Try Next Next Else ' Load by Type For Each x In _params.DefinitionsByType Dim m_defs As List(Of Definition) = x.Value ' Each Definition For Each d In m_defs ' Search? If Not String.IsNullOrEmpty(TextBoxFilterParams.Text) Then If Not d.Name.ToLower.Contains(TextBoxFilterParams.Text.ToLower) Then Continue For End If ' Parent Node If Not Me.TreeViewParameters.Nodes.ContainsKey(x.Key.ToString) Then Try ' Add Type Name Me.TreeViewParameters.Nodes.Add(x.Key.ToString, x.Key.ToString) Catch End Try End If Try ' Child Only Dim m_tn As TreeNode = Me.TreeViewParameters.Nodes(x.Key.ToString).Nodes.Add(d.Name, d.Name) m_tn.Tag = d Catch End Try Next Next End If Catch End Try End Sub #End Region #Region "Form Controls & Events" ''' <summary> ''' Startup ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub form_Main_Load(sender As Object, e As EventArgs) Handles Me.Load ' Form Me.Text = "Subscription Super Shared Parameter Loader v" & _s.Version ' Family? If _s.isFamily = True Then ' Check the Family Category Dim m_n As TreeNode = Me.TreeViewCategories.Nodes.Add(_s.FamilyFileCategory.Name, _s.FamilyFileCategory.Name) CheckNode(m_n, True) ' Controls Me.TreeViewCategories.Enabled = False Me.LabelFilterCat.Enabled = False Me.TextBoxFilterCategories.Enabled = False Me.ButtonCatsAll.Enabled = False Me.ButtonCatsNone.Enabled = False Else ' Load Category List LoadCategories() End If ' Parameters _params = New clsSharedParameters(_s.uiApp) Me.LabelParameterFilePath.Text = _params.FileName LoadSharedParameters() ' Parameter Grouping Names Dim m_g As New SortedDictionary(Of String, clsBuiltInParameterGroup) For Each x In [Enum].GetValues(GetType(BuiltInParameterGroup)) Dim m_helper As New clsBuiltInParameterGroup(x) Try m_g.Add(m_helper.DisplayName, m_helper) Catch End Try Next Dim m_groups As List(Of clsBuiltInParameterGroup) = m_g.Values.ToList ' Bind to Control Me.ComboBoxGroup.DataSource = m_groups Me.ComboBoxGroup.DisplayMember = "DisplayName" Me.ComboBoxGroup.SelectedIndex = 0 End Sub ''' <summary> ''' Help ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub ButtonHelp_Click(sender As Object, e As EventArgs) Handles ButtonHelp.Click Process.Start("http://apps.case-inc.com/content/subscription-super-shared-parameter-loader") End Sub ''' <summary> ''' Search for Params ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub TextBoxFilterParams_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBoxFilterParams.TextChanged Try LoadSharedParameters() Catch End Try End Sub ''' <summary> ''' Search for Categories ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub TextBoxFilterCategories_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBoxFilterCategories.TextChanged Try LoadCategories() Catch End Try End Sub ''' <summary> ''' Load All Checked Parameters ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub ButtonLoad_Click(sender As System.Object, e As System.EventArgs) Handles ButtonLoad.Click ' Get all Checked Parameters Dim m_defs As New List(Of Definition) For Each n1 As TreeNode In Me.TreeViewParameters.Nodes For Each n2 As TreeNode In n1.Nodes If n2.Checked = True Then m_defs.Add(n2.Tag) End If Next Next ' Get all Checked Categories Dim m_categories As New List(Of Category) If _s.Doc.IsFamilyDocument = True Then m_categories.Add(_s.FamilyFileCategory) Else For Each x As TreeNode In Me.TreeViewCategories.Nodes If x.Checked = True Then m_categories.Add(x.Tag) End If Next End If Dim m_group As clsBuiltInParameterGroup = Me.ComboBoxGroup.SelectedItem ' Bind the Definitions _params.BindDefinitionsToCategories(m_defs, m_categories, m_group.ParameterGroup, Me.RadioButtonParamInst.Checked) ' Uncheck All LoadSharedParameters() End Sub ''' <summary> ''' Check All Parameters ''' </summary> ''' <param name="sender"></param>, ''' <param name="e"></param> ''' <remarks></remarks> Private Sub ButtonAll_Click(sender As System.Object, e As System.EventArgs) Handles ButtonAll.Click ' Check All For Each x As TreeNode In Me.TreeViewParameters.Nodes ' Uncheck If x.Checked = False Then x.Checked = True ' Children For Each y As TreeNode In x.Nodes If y.Checked = False Then y.Checked = True Next Next End Sub ''' <summary> ''' Uncheck All Parameters ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub ButtonNone_Click(sender As System.Object, e As System.EventArgs) Handles ButtonNone.Click ' Uncheck All For Each x As TreeNode In Me.TreeViewParameters.Nodes ' Uncheck If x.Checked = True Then x.Checked = False ' Children For Each y As TreeNode In x.Nodes If y.Checked = True Then y.Checked = False Next Next End Sub ''' <summary> ''' Check All Categories ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub ButtonCatsAll_Click(sender As System.Object, e As System.EventArgs) Handles ButtonCatsAll.Click ' Uncheck All For Each x As TreeNode In Me.TreeViewCategories.Nodes ' Uncheck If x.Checked = False Then x.Checked = True ' Children For Each y As TreeNode In x.Nodes If y.Checked = False Then y.Checked = True Next Next End Sub ''' <summary> ''' Uncheck All Categories ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub ButtonCatsNone_Click(sender As System.Object, e As System.EventArgs) Handles ButtonCatsNone.Click ' Uncheck All For Each x As TreeNode In Me.TreeViewCategories.Nodes ' Uncheck If x.Checked = True Then x.Checked = False ' Children For Each y As TreeNode In x.Nodes If y.Checked = True Then y.Checked = False Next Next End Sub ''' <summary> ''' Browse for a Shared Parameter File ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub ButtonBrowseShared_Click(sender As System.Object, e As System.EventArgs) Handles ButtonBrowseShared.Click ' Browse for File If Me.OpenFileDialog1.ShowDialog = DialogResult.OK Then If Not String.IsNullOrEmpty(OpenFileDialog1.FileName) Then Me.LabelParameterFilePath.Text = Me.OpenFileDialog1.FileName ' Update the Parameters Listing _params.LoadSharedParameterFile(OpenFileDialog1.FileName) LoadSharedParameters() End If End If End Sub ''' <summary> ''' Filter Parameters List ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub TextBoxFilter_TextChanged(sender As System.Object, e As System.EventArgs) ' Update the Parameters Listing LoadSharedParameters() End Sub ''' <summary> ''' For Parents - Check all or None to Match ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub TreeViewParameters_AfterCheck(sender As Object, e As System.Windows.Forms.TreeViewEventArgs) Handles TreeViewParameters.AfterCheck ' Events Enabled? If _eventsEnabled = False Then Exit Sub ' Is it a parent? If e.Node.Level = 0 Then ' Match Children Checking For Each x As TreeNode In e.Node.Nodes CheckNode(x, e.Node.Checked) Next Else ' Check the Parent, if a child is checked, the parent must be checked If e.Node.Checked = True Then CheckNode(e.Node.Parent, True) Else ' If last child checked, uncheck parent For Each x As TreeNode In e.Node.Parent.Nodes If x.Checked = True Then Exit Sub Next ' Uncheck Parent CheckNode(e.Node.Parent, False) End If End If End Sub ''' <summary> ''' Update Parameter Nodes ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub RadioButtonByGroup_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButtonByGroup.CheckedChanged LoadSharedParameters() End Sub ''' <summary> ''' Update Parameter Nodes ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub RadioButtonByFormat_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButtonByFormat.CheckedChanged LoadSharedParameters() End Sub ''' <summary> ''' Launch CASE Site ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox1.Click ' Launch Site Process.Start("http://www.case-inc.com") End Sub #End Region End Class
Imports System Imports System.Collections.Generic Imports Data = lombok.Data Imports EqualsAndHashCode = lombok.EqualsAndHashCode Imports NoArgsConstructor = lombok.NoArgsConstructor Imports ToString = lombok.ToString Imports Layer = org.deeplearning4j.nn.api.Layer Imports ParamInitializer = org.deeplearning4j.nn.api.ParamInitializer Imports NeuralNetConfiguration = org.deeplearning4j.nn.conf.NeuralNetConfiguration Imports BaseOutputLayer = org.deeplearning4j.nn.conf.layers.BaseOutputLayer Imports OutputLayer = org.deeplearning4j.nn.conf.layers.OutputLayer Imports DefaultParamInitializer = org.deeplearning4j.nn.params.DefaultParamInitializer Imports TrainingListener = org.deeplearning4j.optimize.api.TrainingListener Imports DataType = org.nd4j.linalg.api.buffer.DataType Imports INDArray = org.nd4j.linalg.api.ndarray.INDArray Imports LossFunctions = org.nd4j.linalg.lossfunctions.LossFunctions ' ' * ****************************************************************************** ' * * ' * * ' * * This program and the accompanying materials are made available under the ' * * terms of the Apache License, Version 2.0 which is available at ' * * https://www.apache.org/licenses/LICENSE-2.0. ' * * ' * * See the NOTICE file distributed with this work for additional ' * * information regarding copyright ownership. ' * * 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. ' * * ' * * SPDX-License-Identifier: Apache-2.0 ' * ***************************************************************************** ' Namespace org.deeplearning4j.nn.layers.custom.testclasses 'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: 'ORIGINAL LINE: @Data @NoArgsConstructor @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class CustomOutputLayer extends org.deeplearning4j.nn.conf.layers.BaseOutputLayer <Serializable> Public Class CustomOutputLayer Inherits BaseOutputLayer Protected Friend Sub New(ByVal builder As Builder) MyBase.New(builder) End Sub Public Overrides Function instantiate(ByVal conf As NeuralNetConfiguration, ByVal trainingListeners As ICollection(Of TrainingListener), ByVal layerIndex As Integer, ByVal layerParamsView As INDArray, ByVal initializeParams As Boolean, ByVal networkDataType As DataType) As Layer Dim ret As New CustomOutputLayerImpl(conf, networkDataType) ret.setListeners(trainingListeners) ret.Index = layerIndex ret.ParamsViewArray = layerParamsView Dim paramTable As IDictionary(Of String, INDArray) = initializer().init(conf, layerParamsView, initializeParams) ret.ParamTable = paramTable ret.Conf = conf Return ret End Function Public Overrides Function initializer() As ParamInitializer Return DefaultParamInitializer.Instance End Function 'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: 'ORIGINAL LINE: @NoArgsConstructor public static class Builder extends org.deeplearning4j.nn.conf.layers.BaseOutputLayer.Builder<Builder> Public Class Builder Inherits BaseOutputLayer.Builder(Of Builder) Public Sub New(ByVal lossFunction As LossFunctions.LossFunction) MyBase.lossFunction(lossFunction) End Sub 'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: 'ORIGINAL LINE: @Override @SuppressWarnings("unchecked") public CustomOutputLayer build() Public Overrides Function build() As CustomOutputLayer Return New CustomOutputLayer(Me) End Function End Class End Class End Namespace
Imports System Imports System.Collections.Generic Imports Csla Imports Csla.Security <Serializable()> _ Public Class ReadOnlyChildBindingList Inherits ReadOnlyBindingListBase(Of ReadOnlyChildBindingList, ReadOnlyChild) #Region "Authorization Rules" Private Shared Sub AddObjectAuthorizationRules() ' TODO: add authorization rules 'AuthorizationRules.AllowGet(GetType(ReadOnlyChildList), "Role") End Sub #End Region #Region "Factory Methods" Friend Shared Function GetReadOnlyChildBindingList(ByVal childData As Object) As ReadOnlyChildBindingList Return DataPortal.FetchChild(Of ReadOnlyChildBindingList)(childData) End Function #End Region #Region "Data Access" Private Sub Child_Fetch(ByVal childData As Object) RaiseListChangedEvents = False IsReadOnly = False ' TODO: load values For Each child As Object In DirectCast(childData, List(Of Object)) Add(ReadOnlyChild.GetReadOnlyChild(child)) Next IsReadOnly = True RaiseListChangedEvents = True End Sub #End Region End Class
' Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. Imports System Imports System.Collections.Generic Namespace Another.Place Partial Public Class CustomerMm Public Property CustomerId As Integer Public Property Name As String Public Property ContactInfo As ContactDetailsMm = New ContactDetailsMm Public Property Auditing As AuditInfoMm = New AuditInfoMm Public Overridable Property Orders As ICollection(Of OrderMm) = New HashSet(Of OrderMm) Public Overridable Property Logins As ICollection(Of LoginMm) = New HashSet(Of LoginMm) Public Overridable Property Husband As CustomerMm Public Overridable Property Wife As CustomerMm Public Overridable Property Info As CustomerInfoMm End Class End Namespace
'------------------------------------------------------------------------------ ' <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.circleArea.Form1 End Sub End Class End Namespace
' 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.ComponentModel Namespace Microsoft.VisualBasic.MyServices '''************************************************************************* ''' ;RegistryProxy ''' <summary> ''' An extremely thin wrapper around Microsoft.Win32.Registry to expose the type through My. ''' </summary> <System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)> Public Class RegistryProxy '= FRIEND ============================================================= '''************************************************************************* ''' ;New ''' <summary> ''' Proxy class can only created by internal classes. ''' </summary> Friend Sub New() End Sub End Class End Namespace
Imports System Imports System.Drawing Imports System.Collections Imports System.ComponentModel Imports System.Windows.Forms Imports System.Diagnostics Imports System.IO Imports System.Xml Imports AnimatGuiCtrls.Controls Imports AnimatGUI.Framework Namespace TypeHelpers Public MustInherit Class LinkedBodyPart Inherits AnimatGUI.Framework.DataObject #Region " Attributes " Protected m_doStructure As AnimatGUI.DataObjects.Physical.PhysicalStructure Protected m_bpBodyPart As AnimatGUI.DataObjects.Physical.BodyPart Protected m_tpBodyPartType As System.Type Protected m_doPruner As TreeListPruner #End Region #Region " Properties " <Browsable(False)> _ Public Property PhysicalStructure() As AnimatGUI.DataObjects.Physical.PhysicalStructure Get Return m_doStructure End Get Set(ByVal Value As AnimatGUI.DataObjects.Physical.PhysicalStructure) m_doStructure = Value End Set End Property <Browsable(False)> _ Public Property BodyPart() As AnimatGUI.DataObjects.Physical.BodyPart Get Return m_bpBodyPart End Get Set(ByVal Value As AnimatGUI.DataObjects.Physical.BodyPart) m_bpBodyPart = Value End Set End Property <Browsable(False)> _ Public Property BodyPartType() As System.Type Get Return m_tpBodyPartType End Get Set(ByVal Value As System.Type) m_tpBodyPartType = Value End Set End Property <Browsable(False)> _ Public Overrides Property ViewSubProperties() As Boolean Get Return False End Get Set(ByVal Value As Boolean) End Set End Property <Browsable(False)> _ Public Overridable Property Pruner() As TreeListPruner Get Return m_doPruner End Get Set(ByVal Value As TreeListPruner) m_doPruner = Value End Set End Property #End Region #Region " Methods " Public Sub New(ByVal doParent As AnimatGUI.Framework.DataObject) MyBase.New(doParent) End Sub Public Sub New(ByVal doStructure As AnimatGUI.DataObjects.Physical.PhysicalStructure, _ ByVal bpBodyPart As AnimatGUI.DataObjects.Physical.BodyPart, _ ByVal tpBodyPartType As System.Type, Optional ByVal doPruner As TreeListPruner = Nothing) MyBase.New(doStructure) m_doStructure = doStructure m_bpBodyPart = bpBodyPart m_tpBodyPartType = tpBodyPartType m_doPruner = doPruner End Sub Protected Overrides Sub CloneInternal(ByVal doOriginal As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _ ByVal doRoot As AnimatGUI.Framework.DataObject) MyBase.CloneInternal(doOriginal, bCutData, doRoot) Dim OrigNode As LinkedBodyPart = DirectCast(doOriginal, LinkedBodyPart) Dim thOrig As LinkedBodyPart = DirectCast(OrigNode, LinkedBodyPart) m_doStructure = thOrig.m_doStructure m_bpBodyPart = thOrig.m_bpBodyPart m_tpBodyPartType = thOrig.m_tpBodyPartType m_doPruner = thOrig.m_doPruner End Sub Public Overrides Sub BuildProperties(ByRef propTable As AnimatGuiCtrls.Controls.PropertyTable) End Sub #End Region End Class End Namespace
Public Class MusicPlayerForm Private Sub MusicPlayerForm_Activated(sender As Object, e As EventArgs) Handles Me.Activated FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle ' Enable control to move form, minimize to taskbar and exit Opacity = "1" ' Solid form End Sub Private Sub MusicPlayerForm_Deactivate(sender As Object, e As EventArgs) Handles Me.Deactivate FormBorderStyle = Windows.Forms.FormBorderStyle.None ' Hide the form controls Opacity = "0.8" ' Transparency effect End Sub Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. End Sub Private Sub MusicPlayerForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Load background and Connection string PlayerUserControl1.LoadConfig() ' Load all songs from database to Song List PlayerUserControl1.LoadSongList() End Sub End Class
' 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.Completion Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders <UseExportProvider> Public Class TypeImportCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Private Property ShowImportCompletionItemsOptionValue As Boolean = True Private Property IsExpandedCompletion As Boolean = True Private Property UsePartialSemantic As Boolean = False Protected Overrides Function WithChangedOptions(options As OptionSet) As OptionSet Return options _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.VisualBasic, ShowImportCompletionItemsOptionValue) _ .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, IsExpandedCompletion) _ .WithChangedOption(CompletionServiceOptions.UsePartialSemanticForImportCompletion, UsePartialSemantic) End Function Protected Overrides Function GetComposition() As TestComposition Return MyBase.GetComposition().AddParts(GetType(TestExperimentationService)) End Function Friend Overrides Function GetCompletionProviderType() As Type Return GetType(TypeImportCompletionProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")> Public Async Function AttributeTypeInAttributeNameContext() As Task Dim file1 = <Text> Namespace Foo Public Class MyAttribute Inherits System.Attribute End Class Public Class MyVBClass End Class Public Class MyAttributeWithoutSuffix Inherits System.Attribute End Class End Namespace</Text>.Value Dim file2 = <Text><![CDATA[ Public Class Bar <$$ Sub Main() End Sub End Class]]></Text>.Value Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic) Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttribute", isComplexTextEdit:=True) Await VerifyItemIsAbsentAsync(markup, "MyAttributeWithoutSuffix", inlineDescription:="Foo") ' We intentionally ignore attribute types without proper suffix for perf reason Await VerifyItemIsAbsentAsync(markup, "MyAttribute", inlineDescription:="Foo") Await VerifyItemIsAbsentAsync(markup, "MyVBClass", inlineDescription:="Foo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")> Public Async Function AttributeTypeInNonAttributeNameContext() As Task Dim file1 = <Text> Namespace Foo Public Class MyAttribute Inherits System.Attribute End Class Public Class MyVBClass End Class Public Class MyAttributeWithoutSuffix Inherits System.Attribute End Namespace</Text>.Value Dim file2 = <Text><![CDATA[ Public Class Bar Sub Main() Dim x As $$ End Sub End Class]]></Text>.Value Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic) Await VerifyItemExistsAsync(markup, "MyAttribute", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttribute", isComplexTextEdit:=True) Await VerifyItemExistsAsync(markup, "MyAttributeWithoutSuffix", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttributeWithoutSuffix", isComplexTextEdit:=True) Await VerifyItemExistsAsync(markup, "MyVBClass", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyVBClass", isComplexTextEdit:=True) Await VerifyItemIsAbsentAsync(markup, "My", inlineDescription:="Foo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")> Public Async Function AttributeTypeInAttributeNameContext2() As Task ' attribute suffix isn't capitalized Dim file1 = <Text> Namespace Foo Public Class Myattribute Inherits System.Attribute End Class End Namespace</Text>.Value Dim file2 = <Text><![CDATA[ Public Class Bar <$$ Sub Main() End Sub End Class]]></Text>.Value Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic) Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.Myattribute") Await VerifyItemIsAbsentAsync(markup, "Myattribute", inlineDescription:="Foo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")> Public Async Function CSharpAttributeTypeWithoutSuffixInAttributeNameContext() As Task ' attribute suffix isn't capitalized Dim file1 = <Text> namespace Foo { public class Myattribute : System.Attribute { } }</Text>.Value Dim file2 = <Text><![CDATA[ Public Class Bar <$$ Sub Main() End Sub End Class]]></Text>.Value Dim markup = CreateMarkupForProjectWithProjectReference(file2, file1, LanguageNames.VisualBasic, LanguageNames.CSharp) Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.Myattribute", isComplexTextEdit:=True) Await VerifyItemIsAbsentAsync(markup, "Myattribute", inlineDescription:="Foo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(35124, "https://github.com/dotnet/roslyn/issues/35124")> Public Async Function GenericTypeShouldDisplayProperVBSyntax() As Task Dim file1 = <Text> Namespace Foo Public Class MyGenericClass(Of T) End Class End Namespace</Text>.Value Dim file2 = <Text><![CDATA[ Public Class Bar Sub Main() Dim x As $$ End Sub End Class]]></Text>.Value Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic) Await VerifyItemExistsAsync(markup, "MyGenericClass", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", displayTextSuffix:="(Of ...)", expectedDescriptionOrNull:="Class Foo.MyGenericClass(Of T)", isComplexTextEdit:=True) End Function <InlineData(SourceCodeKind.Regular)> <InlineData(SourceCodeKind.Script)> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")> Public Async Function CommitTypeInImportAliasContextShouldUseFullyQualifiedName(kind As SourceCodeKind) As Task Dim file1 = <Text> Namespace Foo Public Class Bar End Class End Namespace</Text>.Value Dim file2 = "Imports BarAlias = $$" Dim expectedCodeAfterCommit = "Imports BarAlias = Foo.Bar$$" Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic) Await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind:=kind) End Function <InlineData(SourceCodeKind.Regular)> <InlineData(SourceCodeKind.Script)> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")> Public Async Function CommitGenericTypeParameterInImportAliasContextShouldUseFullyQualifiedName(kind As SourceCodeKind) As Task Dim file1 = <Text> Namespace Foo Public Class Bar End Class End Namespace</Text>.Value Dim file2 = "Imports BarAlias = System.Collections.Generic.List(Of $$)" Dim expectedCodeAfterCommit = "Imports BarAlias = System.Collections.Generic.List(Of Foo.Bar$$)" Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic) Await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind:=kind) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionItemWhenAliasExists() As Task Dim file1 = " Imports FFF = Foo1.Foo2.Foo3.Foo4 Imports FFF1 = Foo1.Foo2.Foo3.Foo4.Foo5 Namespace Bar Public Class Bar1 Private Sub EE() F$$ End Sub End Class End Namespace" Dim file2 = " Namespace Foo1 Namespace Foo2 Namespace Foo3 Public Class Foo4 Public Class Foo5 End Class End Class End Namespace End Namespace End Namespace " Dim markup = CreateMarkupForSingleProject(file1, file2, LanguageNames.VisualBasic) Await VerifyItemIsAbsentAsync(markup, "Foo4", inlineDescription:="Foo1.Foo2.Foo3") Await VerifyItemIsAbsentAsync(markup, "Foo5", inlineDescription:="Foo1.Foo2.Foo3") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAliasHasNoEffectOnGenerics() As Task Dim file1 = " Imports FFF = Foo1.Foo2.Foo3.Foo4(Of Int) Namespace Bar Public Class Bar1 Private Sub EE() F$$ End Sub End Class End Namespace" Dim file2 = " Namespace Foo1 Namespace Foo2 Namespace Foo3 Public Class Foo4(Of T) End Class End Namespace End Namespace End Namespace" Dim markup = CreateMarkupForSingleProject(file1, file2, LanguageNames.VisualBasic) Await VerifyItemExistsAsync(markup, "Foo4", glyph:=Glyph.ClassPublic, inlineDescription:="Foo1.Foo2.Foo3", displayTextSuffix:="(Of ...)", isComplexTextEdit:=True) End Function End Class End Namespace
Imports System Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Security ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("CLIENTSIDE_HTML5AudioObject")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Microsoft")> <Assembly: AssemblyProduct("CLIENTSIDE_HTML5AudioObject")> <Assembly: AssemblyCopyright("Copyright © Microsoft 2011")> <Assembly: AssemblyTrademark("")> ' 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("a42027ac-4d8c-42ee-8284-7865baf84dca")> ' 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")>
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Catch" keyword for the statement context ''' </summary> Friend Class CatchKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword) If Not context.IsMultiLineStatementContext Then Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End If ' We'll recommend a catch statement if it's within a Try block or a Catch block, because you could be ' trying to start one in either location If context.IsInStatementBlockOfKind(SyntaxKind.TryBlock, SyntaxKind.CatchBlock) AndAlso Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("Catch", VBFeaturesResources.CatchKeywordToolTip)) End If Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End Function End Class End Namespace
'------------------------------------------------------------------------------ ' <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", "16.8.1.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property <Global.System.Configuration.ApplicationScopedSettingAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Configuration.SpecialSettingAttribute(Global.System.Configuration.SpecialSetting.ConnectionString), _ Global.System.Configuration.DefaultSettingValueAttribute("User Id=postgres;Password=postgres;Host=localhost;Database=Case_SOM_ModelReportin"& _ "g_NY;Persist Security Info=True;Schema=public")> _ Public ReadOnly Property Case_SOM_ModelReporting_NYConnectionString() As String Get Return CType(Me("Case_SOM_ModelReporting_NYConnectionString"),String) 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.[Case].RoomSync.My.MySettings Get Return Global.[Case].RoomSync.My.MySettings.Default End Get End Property End Module End Namespace
' 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration <ExportLanguageService(GetType(SyntaxGenerator), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxGenerator Inherits SyntaxGenerator Public Shared ReadOnly Instance As SyntaxGenerator = New VisualBasicSyntaxGenerator() Friend Overrides ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Friend Overrides ReadOnly Property CarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.CarriageReturnLineFeed Friend Overrides ReadOnly Property RequiresExplicitImplementationForInterfaceMembers As Boolean = True Friend Overrides ReadOnly Property SyntaxFacts As ISyntaxFactsService = VisualBasicSyntaxFactsService.Instance Friend Overrides Function EndOfLine(text As String) As SyntaxTrivia Return SyntaxFactory.EndOfLine(text) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(list As SyntaxNodeOrTokenList) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(Of TElement)(list) End Function #Region "Expressions and Statements" Public Overrides Function AddEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function RemoveEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.RemoveHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function AwaitExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.AwaitExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function NameOfExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NameOfExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function TupleExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsSimpleArgument))) End Function Friend Overrides Function AddParentheses(expression As SyntaxNode) As SyntaxNode Return Parenthesize(expression) End Function Private Function Parenthesize(expression As SyntaxNode) As ParenthesizedExpressionSyntax Return DirectCast(expression, ExpressionSyntax).Parenthesize() End Function Public Overrides Function AddExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overloads Overrides Function Argument(name As String, refKind As RefKind, expression As SyntaxNode) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.SimpleArgument(DirectCast(expression, ExpressionSyntax)) Else Return SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(name.ToIdentifierName()), DirectCast(expression, ExpressionSyntax)) End If End Function Public Overrides Function TryCastExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TryCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)) End Function Public Overrides Function AssignmentStatement(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleAssignmentStatement( DirectCast(left, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.EqualsToken), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function BaseExpression() As SyntaxNode Return SyntaxFactory.MyBaseExpression() End Function Public Overrides Function BitwiseAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function CastExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.DirectCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConvertExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.CTypeExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConditionalExpression(condition As SyntaxNode, whenTrue As SyntaxNode, whenFalse As SyntaxNode) As SyntaxNode Return SyntaxFactory.TernaryConditionalExpression( DirectCast(condition, ExpressionSyntax), DirectCast(whenTrue, ExpressionSyntax), DirectCast(whenFalse, ExpressionSyntax)) End Function Public Overrides Function LiteralExpression(value As Object) As SyntaxNode Return ExpressionGenerator.GenerateNonEnumValueExpression(Nothing, value, canUseFieldReference:=True) End Function Public Overrides Function TypedConstantExpression(value As TypedConstant) As SyntaxNode Return ExpressionGenerator.GenerateExpression(value) End Function Friend Overrides Function InterpolatedStringExpression(startToken As SyntaxToken, content As IEnumerable(Of SyntaxNode), endToken As SyntaxToken) As SyntaxNode Return SyntaxFactory.InterpolatedStringExpression( startToken, SyntaxFactory.List(content.Cast(Of InterpolatedStringContentSyntax)), endToken) End Function Friend Overrides Function InterpolatedStringText(textToken As SyntaxToken) As SyntaxNode Return SyntaxFactory.InterpolatedStringText(textToken) End Function Friend Overrides Function InterpolatedStringTextToken(content As String) As SyntaxToken Return SyntaxFactory.InterpolatedStringTextToken(content, "") End Function Friend Overrides Function Interpolation(syntaxNode As SyntaxNode) As SyntaxNode Return SyntaxFactory.Interpolation(DirectCast(syntaxNode, ExpressionSyntax)) End Function Friend Overrides Function NumericLiteralToken(text As String, value As ULong) As SyntaxToken Return SyntaxFactory.Literal(text, value) End Function Public Overrides Function DefaultExpression(type As ITypeSymbol) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overrides Function DefaultExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overloads Overrides Function ElementAccessExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function ExpressionStatement(expression As SyntaxNode) As SyntaxNode If TypeOf expression Is StatementSyntax Then Return expression End If Return SyntaxFactory.ExpressionStatement(DirectCast(expression, ExpressionSyntax)) End Function Public Overloads Overrides Function GenericName(identifier As String, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return GenericName(identifier.ToIdentifierToken(), typeArguments) End Function Friend Overrides Function GenericName(identifier As SyntaxToken, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.GenericName( identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function IdentifierName(identifier As String) As SyntaxNode Return identifier.ToIdentifierName() End Function Public Overrides Function IfStatement(condition As SyntaxNode, trueStatements As IEnumerable(Of SyntaxNode), Optional falseStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim ifStmt = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), DirectCast(condition, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.ThenKeyword)) If falseStatements Is Nothing Then Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, Nothing ) End If ' convert nested if-blocks into else-if parts Dim statements = falseStatements.ToList() If statements.Count = 1 AndAlso TypeOf statements(0) Is MultiLineIfBlockSyntax Then Dim mifBlock = DirectCast(statements(0), MultiLineIfBlockSyntax) ' insert block's if-part onto head of elseIf-parts Dim elseIfBlocks = mifBlock.ElseIfBlocks.Insert(0, SyntaxFactory.ElseIfBlock( SyntaxFactory.ElseIfStatement(SyntaxFactory.Token(SyntaxKind.ElseIfKeyword), mifBlock.IfStatement.Condition, SyntaxFactory.Token(SyntaxKind.ThenKeyword)), mifBlock.Statements) ) Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), elseIfBlocks, mifBlock.ElseBlock ) End If Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, SyntaxFactory.ElseBlock(GetStatementList(falseStatements)) ) End Function Private Function GetStatementList(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes Is Nothing Then Return Nothing Else Return SyntaxFactory.List(nodes.Select(AddressOf AsStatement)) End If End Function Private Function AsStatement(node As SyntaxNode) As StatementSyntax Dim expr = TryCast(node, ExpressionSyntax) If expr IsNot Nothing Then Return SyntaxFactory.ExpressionStatement(expr) Else Return DirectCast(node, StatementSyntax) End If End Function Public Overloads Overrides Function InvocationExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function IsTypeExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TypeOfIsExpression(Parenthesize(expression), DirectCast(type, TypeSyntax)) End Function Public Overrides Function TypeOfExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.GetTypeExpression(DirectCast(type, TypeSyntax)) End Function Public Overrides Function LogicalAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndAlsoExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LogicalNotExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(expression)) End Function Public Overrides Function LogicalOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrElseExpression(Parenthesize(left), Parenthesize(right)) End Function Friend Overrides Function MemberAccessExpressionWorker(expression As SyntaxNode, simpleName As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleMemberAccessExpression( ParenthesizeLeft(expression), SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(simpleName, SimpleNameSyntax)) End Function Friend Overrides Function ConditionalAccessExpression(expression As SyntaxNode, whenNotNull As SyntaxNode) As SyntaxNode Return SyntaxFactory.ConditionalAccessExpression( DirectCast(expression, ExpressionSyntax), DirectCast(whenNotNull, ExpressionSyntax)) End Function Friend Overrides Function MemberBindingExpression(name As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleMemberAccessExpression(DirectCast(name, SimpleNameSyntax)) End Function Friend Overrides Function ElementBindingExpression(argumentList As SyntaxNode) As SyntaxNode Return SyntaxFactory.InvocationExpression(expression:=Nothing, argumentList:=DirectCast(argumentList, ArgumentListSyntax)) End Function ' parenthesize the left-side of a dot or target of an invocation if not unnecessary Private Function ParenthesizeLeft(expression As SyntaxNode) As ExpressionSyntax Dim expressionSyntax = DirectCast(expression, ExpressionSyntax) If TypeOf expressionSyntax Is TypeSyntax _ OrElse expressionSyntax.IsMeMyBaseOrMyClass() _ OrElse expressionSyntax.IsKind(SyntaxKind.ParenthesizedExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.InvocationExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return expressionSyntax Else Return expressionSyntax.Parenthesize() End If End Function Public Overrides Function MultiplyExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.MultiplyExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function NegateExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.UnaryMinusExpression(Parenthesize(expression)) End Function Private Function AsExpressionList(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ExpressionSyntax) Return SyntaxFactory.SeparatedList(Of ExpressionSyntax)(expressions.OfType(Of ExpressionSyntax)()) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, size As SyntaxNode) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(AsArgument(size))) Dim initializer = SyntaxFactory.CollectionInitializer() Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList() Dim initializer = SyntaxFactory.CollectionInitializer(AsExpressionList(elements)) Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overloads Overrides Function ObjectCreationExpression(typeName As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( Nothing, DirectCast(typeName, TypeSyntax), CreateArgumentList(arguments), Nothing) End Function Public Overrides Function QualifiedName(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), DirectCast(right, SimpleNameSyntax)) End Function Friend Overrides Function GlobalAliasedName(name As SyntaxNode) As SyntaxNode Return QualifiedName(SyntaxFactory.GlobalName(), name) End Function Public Overrides Function ReferenceEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReferenceNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsNotExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReturnStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ReturnStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Friend Overrides Function YieldReturnStatement(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.YieldStatement(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function ThisExpression() As SyntaxNode Return SyntaxFactory.MeExpression() End Function Public Overrides Function ThrowStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ThrowStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThrowExpression(expression As SyntaxNode) As SyntaxNode Throw New NotSupportedException("ThrowExpressions are not supported in Visual Basic") End Function Public Overrides Function NameExpression(namespaceOrTypeSymbol As INamespaceOrTypeSymbol) As SyntaxNode Return namespaceOrTypeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(typeSymbol As ITypeSymbol) As SyntaxNode Return typeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(specialType As SpecialType) As SyntaxNode Select Case specialType Case SpecialType.System_Boolean Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BooleanKeyword)) Case SpecialType.System_Byte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)) Case SpecialType.System_Char Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)) Case SpecialType.System_Decimal Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)) Case SpecialType.System_Double Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)) Case SpecialType.System_Int16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)) Case SpecialType.System_Int32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword)) Case SpecialType.System_Int64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)) Case SpecialType.System_Object Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) Case SpecialType.System_SByte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)) Case SpecialType.System_Single Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SingleKeyword)) Case SpecialType.System_String Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)) Case SpecialType.System_UInt16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)) Case SpecialType.System_UInt32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntegerKeyword)) Case SpecialType.System_UInt64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)) Case SpecialType.System_DateTime Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DateKeyword)) Case Else Throw New NotSupportedException("Unsupported SpecialType") End Select End Function Public Overloads Overrides Function UsingStatement(type As SyntaxNode, identifier As String, expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=Nothing, variables:=SyntaxFactory.SingletonSeparatedList(VariableDeclarator(type, identifier.ToModifiedIdentifier, expression))), GetStatementList(statements)) End Function Public Overloads Overrides Function UsingStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=DirectCast(expression, ExpressionSyntax), variables:=Nothing), GetStatementList(statements)) End Function Public Overrides Function LockStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SyncLockBlock( SyntaxFactory.SyncLockStatement( expression:=DirectCast(expression, ExpressionSyntax)), GetStatementList(statements)) End Function Public Overrides Function ValueEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.EqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ValueNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotEqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Private Function CreateArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax Return SyntaxFactory.ArgumentList(CreateArguments(arguments)) End Function Private Function CreateArguments(arguments As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ArgumentSyntax) Return SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument)) End Function Private Function AsArgument(argOrExpression As SyntaxNode) As ArgumentSyntax Return If(TryCast(argOrExpression, ArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Private Function AsSimpleArgument(argOrExpression As SyntaxNode) As SimpleArgumentSyntax Return If(TryCast(argOrExpression, SimpleArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Public Overloads Overrides Function LocalDeclarationStatement(type As SyntaxNode, identifier As String, Optional initializer As SyntaxNode = Nothing, Optional isConst As Boolean = False) As SyntaxNode Return LocalDeclarationStatement(type, identifier.ToIdentifierToken, initializer, isConst) End Function Friend Overloads Overrides Function LocalDeclarationStatement(type As SyntaxNode, identifier As SyntaxToken, Optional initializer As SyntaxNode = Nothing, Optional isConst As Boolean = False) As SyntaxNode Return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.TokenList(SyntaxFactory.Token(If(isConst, SyntaxKind.ConstKeyword, SyntaxKind.DimKeyword))), SyntaxFactory.SingletonSeparatedList(VariableDeclarator(type, SyntaxFactory.ModifiedIdentifier(identifier), initializer))) End Function Friend Overrides Function WithInitializer(variableDeclarator As SyntaxNode, initializer As SyntaxNode) As SyntaxNode Return DirectCast(variableDeclarator, VariableDeclaratorSyntax).WithInitializer(DirectCast(initializer, EqualsValueSyntax)) End Function Friend Overrides Function EqualsValueClause(operatorToken As SyntaxToken, value As SyntaxNode) As SyntaxNode Return SyntaxFactory.EqualsValue(operatorToken, DirectCast(value, ExpressionSyntax)) End Function Private Function VariableDeclarator(type As SyntaxNode, name As ModifiedIdentifierSyntax, Optional expression As SyntaxNode = Nothing) As VariableDeclaratorSyntax Return SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(name), If(type Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))), If(expression Is Nothing, Nothing, SyntaxFactory.EqualsValue(DirectCast(expression, ExpressionSyntax)))) End Function Public Overloads Overrides Function SwitchStatement(expression As SyntaxNode, caseClauses As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SelectBlock( SyntaxFactory.SelectStatement(DirectCast(expression, ExpressionSyntax)), SyntaxFactory.List(caseClauses.Cast(Of CaseBlockSyntax))) End Function Public Overloads Overrides Function SwitchSection(expressions As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(GetCaseClauses(expressions)), GetStatementList(statements)) End Function Friend Overrides Function SwitchSectionFromLabels(labels As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(SyntaxFactory.SeparatedList(labels.Cast(Of CaseClauseSyntax))), GetStatementList(statements)) End Function Public Overrides Function DefaultSwitchSection(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseElseBlock( SyntaxFactory.CaseElseStatement(SyntaxFactory.ElseCaseClause()), GetStatementList(statements)) End Function Private Function GetCaseClauses(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of CaseClauseSyntax) Dim cases = SyntaxFactory.SeparatedList(Of CaseClauseSyntax) If expressions IsNot Nothing Then cases = cases.AddRange(expressions.Select(Function(e) SyntaxFactory.SimpleCaseClause(DirectCast(e, ExpressionSyntax)))) End If Return cases End Function Private Function AsCaseClause(expression As SyntaxNode) As CaseClauseSyntax Return SyntaxFactory.SimpleCaseClause(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function ExitSwitchStatement() As SyntaxNode Return SyntaxFactory.ExitSelectStatement() End Function Public Overloads Overrides Function ValueReturningLambdaExpression(parameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(parameters)), DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), AsStatement(expression)) End Function Public Overloads Overrides Function ValueReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndFunctionStatement()) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndSubStatement()) End Function Public Overrides Function LambdaParameter(identifier As String, Optional type As SyntaxNode = Nothing) As SyntaxNode Return ParameterDeclaration(identifier, type) End Function Public Overrides Function ArrayTypeExpression(type As SyntaxNode) As SyntaxNode Dim arrayType = TryCast(type, ArrayTypeSyntax) If arrayType IsNot Nothing Then Return arrayType.WithRankSpecifiers(arrayType.RankSpecifiers.Add(SyntaxFactory.ArrayRankSpecifier())) Else Return SyntaxFactory.ArrayType(DirectCast(type, TypeSyntax), SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())) End If End Function Public Overrides Function NullableTypeExpression(type As SyntaxNode) As SyntaxNode Dim nullableType = TryCast(type, NullableTypeSyntax) If nullableType IsNot Nothing Then Return nullableType Else Return SyntaxFactory.NullableType(DirectCast(type, TypeSyntax)) End If End Function Friend Overrides Function CreateTupleType(elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast(Of TupleElementSyntax)())) End Function Public Overrides Function TupleElementExpression(type As SyntaxNode, Optional name As String = Nothing) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.TypedTupleElement(DirectCast(type, TypeSyntax)) Else Return SyntaxFactory.NamedTupleElement(name.ToIdentifierToken(), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))) End If End Function Public Overrides Function WithTypeArguments(name As SyntaxNode, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode If name.IsKind(SyntaxKind.IdentifierName) OrElse name.IsKind(SyntaxKind.GenericName) Then Dim sname = DirectCast(name, SimpleNameSyntax) Return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))) ElseIf name.IsKind(SyntaxKind.QualifiedName) Then Dim qname = DirectCast(name, QualifiedNameSyntax) Return SyntaxFactory.QualifiedName(qname.Left, DirectCast(WithTypeArguments(qname.Right, typeArguments), SimpleNameSyntax)) ElseIf name.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim sma = DirectCast(name, MemberAccessExpressionSyntax) Return SyntaxFactory.MemberAccessExpression(name.Kind(), sma.Expression, sma.OperatorToken, DirectCast(WithTypeArguments(sma.Name, typeArguments), SimpleNameSyntax)) Else Throw New NotSupportedException() End If End Function Public Overrides Function SubtractExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SubtractExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function DivideExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.DivideExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ModuloExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.ModuloExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseNotExpression(operand As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(operand)) End Function Public Overrides Function CoalesceExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.BinaryConditionalExpression(DirectCast(left, ExpressionSyntax), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function LessThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LessThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function TryCatchStatement(tryStatements As IEnumerable(Of SyntaxNode), catchClauses As IEnumerable(Of SyntaxNode), Optional finallyStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.TryBlock( GetStatementList(tryStatements), If(catchClauses IsNot Nothing, SyntaxFactory.List(catchClauses.Cast(Of CatchBlockSyntax)()), Nothing), If(finallyStatements IsNot Nothing, SyntaxFactory.FinallyBlock(GetStatementList(finallyStatements)), Nothing) ) End Function Public Overrides Function CatchClause(type As SyntaxNode, identifier As String, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CatchBlock( SyntaxFactory.CatchStatement( SyntaxFactory.IdentifierName(identifier), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), whenClause:=Nothing ), GetStatementList(statements) ) End Function Public Overrides Function WhileStatement(condition As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.WhileBlock( SyntaxFactory.WhileStatement(DirectCast(condition, ExpressionSyntax)), GetStatementList(statements)) End Function Friend Overrides Function RefExpression(expression As SyntaxNode) As SyntaxNode Return expression End Function #End Region #Region "Declarations" Private Function AsReadOnlyList(Of T)(sequence As IEnumerable(Of T)) As IReadOnlyList(Of T) Dim list = TryCast(sequence, IReadOnlyList(Of T)) If list Is Nothing Then list = sequence.ToImmutableReadOnlyListOrEmpty() End If Return list End Function Private Shared s_fieldModifiers As DeclarationModifiers = DeclarationModifiers.Const Or DeclarationModifiers.[New] Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.Static Or DeclarationModifiers.WithEvents Private Shared s_methodModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.Async Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared s_constructorModifiers As DeclarationModifiers = DeclarationModifiers.Static Private Shared s_propertyModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared s_indexerModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared s_classModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Private Shared s_structModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared s_interfaceModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared s_accessorModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Virtual Private Function GetAllowedModifiers(kind As SyntaxKind) As DeclarationModifiers Select Case kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement Return s_classModifiers Case SyntaxKind.EnumBlock, SyntaxKind.EnumStatement Return DeclarationModifiers.[New] Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationModifiers.[New] Case SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement Return s_interfaceModifiers Case SyntaxKind.StructureBlock, SyntaxKind.StructureStatement Return s_structModifiers Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubBlock, SyntaxKind.SubStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement Return s_methodModifiers Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement Return s_constructorModifiers Case SyntaxKind.FieldDeclaration Return s_fieldModifiers Case SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement Return s_propertyModifiers Case SyntaxKind.EventBlock, SyntaxKind.EventStatement Return s_propertyModifiers Case SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return s_accessorModifiers Case SyntaxKind.EnumMemberDeclaration Case SyntaxKind.Parameter Case SyntaxKind.LocalDeclarationStatement Case Else Return DeclarationModifiers.None End Select End Function Public Overrides Function FieldDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional initializer As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.FieldDeclaration( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_fieldModifiers, DeclarationKind.Field), declarators:=SyntaxFactory.SingletonSeparatedList(VariableDeclarator(type, name.ToModifiedIdentifier, initializer))) End Function Public Overrides Function MethodDeclaration( identifier As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement = SyntaxFactory.MethodStatement( kind:=If(returnType Is Nothing, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement), attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_methodModifiers, DeclarationKind.Method), subOrFunctionKeyword:=If(returnType Is Nothing, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=identifier.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing), handlesClause:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.MethodBlock( kind:=If(returnType Is Nothing, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock), subOrFunctionStatement:=statement, statements:=GetStatementList(statements), endSubOrFunctionStatement:=If(returnType Is Nothing, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())) End If End Function Public Overrides Function OperatorDeclaration(kind As OperatorKind, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement As OperatorStatementSyntax Dim asClause = If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing) Dim parameterList = GetParameterList(parameters) Dim operatorToken = SyntaxFactory.Token(GetTokenKind(kind)) Dim modifierList As SyntaxTokenList = GetModifierList(accessibility, modifiers And s_methodModifiers, DeclarationKind.Operator) If kind = OperatorKind.ImplicitConversion OrElse kind = OperatorKind.ExplicitConversion Then modifierList = modifierList.Add(SyntaxFactory.Token( If(kind = OperatorKind.ImplicitConversion, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword))) statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) Else statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) End If If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.OperatorBlock( operatorStatement:=statement, statements:=GetStatementList(statements), endOperatorStatement:=SyntaxFactory.EndOperatorStatement()) End If End Function Private Function GetTokenKind(kind As OperatorKind) As SyntaxKind Select Case kind Case OperatorKind.ImplicitConversion, OperatorKind.ExplicitConversion Return SyntaxKind.CTypeKeyword Case OperatorKind.Addition Return SyntaxKind.PlusToken Case OperatorKind.BitwiseAnd Return SyntaxKind.AndKeyword Case OperatorKind.BitwiseOr Return SyntaxKind.OrKeyword Case OperatorKind.Division Return SyntaxKind.SlashToken Case OperatorKind.Equality Return SyntaxKind.EqualsToken Case OperatorKind.ExclusiveOr Return SyntaxKind.XorKeyword Case OperatorKind.False Return SyntaxKind.IsFalseKeyword Case OperatorKind.GreaterThan Return SyntaxKind.GreaterThanToken Case OperatorKind.GreaterThanOrEqual Return SyntaxKind.GreaterThanEqualsToken Case OperatorKind.Inequality Return SyntaxKind.LessThanGreaterThanToken Case OperatorKind.LeftShift Return SyntaxKind.LessThanLessThanToken Case OperatorKind.LessThan Return SyntaxKind.LessThanToken Case OperatorKind.LessThanOrEqual Return SyntaxKind.LessThanEqualsToken Case OperatorKind.LogicalNot Return SyntaxKind.NotKeyword Case OperatorKind.Modulus Return SyntaxKind.ModKeyword Case OperatorKind.Multiply Return SyntaxKind.AsteriskToken Case OperatorKind.RightShift Return SyntaxKind.GreaterThanGreaterThanToken Case OperatorKind.Subtraction Return SyntaxKind.MinusToken Case OperatorKind.True Return SyntaxKind.IsTrueKeyword Case OperatorKind.UnaryNegation Return SyntaxKind.MinusToken Case OperatorKind.UnaryPlus Return SyntaxKind.PlusToken Case Else Throw New ArgumentException($"Operator {kind} cannot be generated in Visual Basic.") End Select End Function Private Function GetParameterList(parameters As IEnumerable(Of SyntaxNode)) As ParameterListSyntax Return If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList()) End Function Public Overrides Function ParameterDeclaration(name As String, Optional type As SyntaxNode = Nothing, Optional initializer As SyntaxNode = Nothing, Optional refKind As RefKind = Nothing) As SyntaxNode Return SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=GetParameterModifiers(refKind, initializer), identifier:=name.ToModifiedIdentifier(), asClause:=If(type IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), Nothing), [default]:=If(initializer IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(initializer, ExpressionSyntax)), Nothing)) End Function Private Function GetParameterModifiers(refKind As RefKind, initializer As SyntaxNode) As SyntaxTokenList Dim tokens As SyntaxTokenList = Nothing If initializer IsNot Nothing Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword)) End If If refKind <> RefKind.None Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword)) End If Return tokens End Function Public Overrides Function GetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.GetAccessorBlock( SyntaxFactory.GetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function SetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.SetAccessorBlock( SyntaxFactory.SetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function WithAccessorDeclarations(declaration As SyntaxNode, accessorDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim propertyBlock = GetPropertyBlock(declaration) If propertyBlock Is Nothing Then Return declaration End If propertyBlock = propertyBlock.WithAccessors( SyntaxFactory.List(accessorDeclarations.OfType(Of AccessorBlockSyntax))) Dim hasGetAccessor = propertyBlock.Accessors.Any(SyntaxKind.GetAccessorBlock) Dim hasSetAccessor = propertyBlock.Accessors.Any(SyntaxKind.SetAccessorBlock) If hasGetAccessor AndAlso Not hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.ReadOnly), PropertyBlockSyntax) ElseIf Not hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.WriteOnly), PropertyBlockSyntax) ElseIf hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock).WithIsReadOnly(False).WithIsWriteOnly(False)), PropertyBlockSyntax) End If Return If(propertyBlock.Accessors.Count = 0, propertyBlock.PropertyStatement, DirectCast(propertyBlock, SyntaxNode)) End Function Private Function GetPropertyBlock(declaration As SyntaxNode) As PropertyBlockSyntax Dim propertyBlock = TryCast(declaration, PropertyBlockSyntax) If propertyBlock IsNot Nothing Then Return propertyBlock End If Dim propertyStatement = TryCast(declaration, PropertyStatementSyntax) If propertyStatement IsNot Nothing Then Return SyntaxFactory.PropertyBlock(propertyStatement, SyntaxFactory.List(Of AccessorBlockSyntax)) End If Return Nothing End Function Public Overrides Function PropertyDeclaration( identifier As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_propertyModifiers, DeclarationKind.Property), identifier:=identifier.ToIdentifierToken(), parameterList:=Nothing, asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Public Overrides Function IndexerDeclaration( parameters As IEnumerable(Of SyntaxNode), type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_indexerModifiers, DeclarationKind.Indexer, isDefault:=True), identifier:=SyntaxFactory.Identifier("Item"), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax))), asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Private Function AccessorBlock(kind As SyntaxKind, statements As IEnumerable(Of SyntaxNode), type As SyntaxNode) As AccessorBlockSyntax Select Case kind Case SyntaxKind.GetAccessorBlock Return CreateGetAccessorBlock(statements) Case SyntaxKind.SetAccessorBlock Return CreateSetAccessorBlock(type, statements) Case SyntaxKind.AddHandlerAccessorBlock Return CreateAddHandlerAccessorBlock(type, statements) Case SyntaxKind.RemoveHandlerAccessorBlock Return CreateRemoveHandlerAccessorBlock(type, statements) Case Else Return Nothing End Select End Function Private Function CreateGetAccessorBlock(statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Return SyntaxFactory.AccessorBlock( SyntaxKind.GetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.GetAccessorStatement, SyntaxFactory.Token(SyntaxKind.GetKeyword)), GetStatementList(statements), SyntaxFactory.EndGetStatement()) End Function Private Function CreateSetAccessorBlock(type As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.SetAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.SetAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.SetKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndSetStatement()) End Function Private Function CreateAddHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.AddHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.AddHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndAddHandlerStatement()) End Function Private Function CreateRemoveHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.RemoveHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RemoveHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RemoveHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndRemoveHandlerStatement()) End Function Private Function CreateRaiseEventAccessorBlock(parameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim parameterList = GetParameterList(parameters) Return SyntaxFactory.AccessorBlock( SyntaxKind.RaiseEventAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RaiseEventAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RaiseEventKeyword), parameterList:=parameterList), GetStatementList(statements), SyntaxFactory.EndRaiseEventStatement()) End Function Public Overrides Function AsPublicInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPublicInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPublicInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=True) declaration = WithAccessibility(declaration, Accessibility.Public) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Public Overrides Function AsPrivateInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPrivateInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPrivateInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=False) declaration = WithAccessibility(declaration, Accessibility.Private) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, GetNameAsIdentifier(interfaceTypeName) & "_" & memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Private Function GetInterfaceMemberName(declaration As SyntaxNode) As String Dim clause = GetImplementsClause(declaration) If clause IsNot Nothing Then Dim qname = clause.InterfaceMembers.FirstOrDefault(Function(n) n.Right IsNot Nothing) If qname IsNot Nothing Then Return qname.Right.ToString() End If End If Return GetName(declaration) End Function Private Function GetImplementsClause(declaration As SyntaxNode) As ImplementsClauseSyntax Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.ImplementsClause Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).ImplementsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ImplementsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).ImplementsClause Case Else Return Nothing End Select End Function Private Function WithImplementsClause(declaration As SyntaxNode, clause As ImplementsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return mb.WithSubOrFunctionStatement(mb.SubOrFunctionStatement.WithImplementsClause(clause)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithImplementsClause(clause) Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithPropertyStatement(pb.PropertyStatement.WithImplementsClause(clause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithImplementsClause(clause) Case Else Return declaration End Select End Function Private Function GetNameAsIdentifier(type As SyntaxNode) As String Dim name = TryCast(type, IdentifierNameSyntax) If name IsNot Nothing Then Return name.Identifier.ValueText End If Dim gname = TryCast(type, GenericNameSyntax) If gname IsNot Nothing Then Return gname.Identifier.ValueText & "_" & gname.TypeArgumentList.Arguments.Select(Function(t) GetNameAsIdentifier(t)).Aggregate(Function(a, b) a & "_" & b) End If Dim qname = TryCast(type, QualifiedNameSyntax) If qname IsNot Nothing Then Return GetNameAsIdentifier(qname.Right) End If Return "[" & type.ToString() & "]" End Function Private Function WithBody(declaration As SyntaxNode, allowDefault As Boolean) As SyntaxNode declaration = Me.WithModifiersInternal(declaration, Me.GetModifiers(declaration) - DeclarationModifiers.Abstract) Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return SyntaxFactory.MethodBlock( kind:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxKind.FunctionBlock, SyntaxKind.SubBlock), subOrFunctionStatement:=method, endSubOrFunctionStatement:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxFactory.EndFunctionStatement(), SyntaxFactory.EndSubStatement())) End If Dim prop = TryCast(declaration, PropertyStatementSyntax) If prop IsNot Nothing Then prop = prop.WithModifiers(WithIsDefault(prop.Modifiers, GetIsDefault(prop.Modifiers) And allowDefault, GetDeclarationKind(declaration))) Dim accessors = New List(Of AccessorBlockSyntax) accessors.Add(CreateGetAccessorBlock(Nothing)) If (Not prop.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) Then accessors.Add(CreateSetAccessorBlock(prop.AsClause.Type, Nothing)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=prop, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If Return declaration End Function Private Function GetIsDefault(modifierList As SyntaxTokenList) As Boolean Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim isDefault As Boolean Me.GetAccessibilityAndModifiers(modifierList, access, modifiers, isDefault) Return isDefault End Function Private Function WithIsDefault(modifierList As SyntaxTokenList, isDefault As Boolean, kind As DeclarationKind) As SyntaxTokenList Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim currentIsDefault As Boolean Me.GetAccessibilityAndModifiers(modifierList, access, modifiers, currentIsDefault) If currentIsDefault <> isDefault Then Return GetModifierList(access, modifiers, kind, isDefault) Else Return modifierList End If End Function Public Overrides Function ConstructorDeclaration( Optional name As String = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseConstructorArguments As IEnumerable(Of SyntaxNode) = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim stats = GetStatementList(statements) If (baseConstructorArguments IsNot Nothing) Then Dim baseCall = DirectCast(Me.ExpressionStatement(Me.InvocationExpression(Me.MemberAccessExpression(Me.BaseExpression(), SyntaxFactory.IdentifierName("New")), baseConstructorArguments)), StatementSyntax) stats = stats.Insert(0, baseCall) End If Return SyntaxFactory.ConstructorBlock( subNewStatement:=SyntaxFactory.SubNewStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_constructorModifiers, DeclarationKind.Constructor), parameterList:=If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList())), statements:=stats) End Function Public Overrides Function ClassDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseType As SyntaxNode = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.ClassBlock( classStatement:=SyntaxFactory.ClassStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_classModifiers, DeclarationKind.Class), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(baseType IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax))), Nothing), [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=AsClassMembers(members)) End Function Private Function AsClassMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsClassMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsClassMember(node As SyntaxNode) As StatementSyntax Return TryCast(AsIsolatedDeclaration(node), StatementSyntax) End Function Public Overrides Function StructDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.StructureBlock( structureStatement:=SyntaxFactory.StructureStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_structModifiers, DeclarationKind.Struct), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=Nothing, [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=If(members IsNot Nothing, SyntaxFactory.List(members.Cast(Of StatementSyntax)()), Nothing)) End Function Private Function AsStructureMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsStructureMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsStructureMember(node As SyntaxNode) As StatementSyntax Return TryCast(node, StatementSyntax) End Function Public Overrides Function InterfaceDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.InterfaceBlock( interfaceStatement:=SyntaxFactory.InterfaceStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, DeclarationModifiers.None, DeclarationKind.Interface), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), [implements]:=Nothing, members:=AsInterfaceMembers(members)) End Function Private Function AsInterfaceMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsInterfaceMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Friend Overrides Function AsInterfaceMember(node As SyntaxNode) As SyntaxNode If node IsNot Nothing Then Select Case node.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return AsInterfaceMember(DirectCast(node, MethodBlockSyntax).BlockStatement) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return Isolate(node, Function(d) DirectCast(d, MethodStatementSyntax).WithModifiers(Nothing)) Case SyntaxKind.PropertyBlock Return AsInterfaceMember(DirectCast(node, PropertyBlockSyntax).PropertyStatement) Case SyntaxKind.PropertyStatement Return Isolate( node, Function(d) Dim propertyStatement = DirectCast(d, PropertyStatementSyntax) Dim mods = SyntaxFactory.TokenList(propertyStatement.Modifiers.Where(Function(tk) tk.IsKind(SyntaxKind.ReadOnlyKeyword) Or tk.IsKind(SyntaxKind.DefaultKeyword))) Return propertyStatement.WithModifiers(mods) End Function) Case SyntaxKind.EventBlock Return AsInterfaceMember(DirectCast(node, EventBlockSyntax).EventStatement) Case SyntaxKind.EventStatement Return Isolate(node, Function(d) DirectCast(d, EventStatementSyntax).WithModifiers(Nothing).WithCustomKeyword(Nothing)) End Select End If Return Nothing End Function Public Overrides Function EnumDeclaration( name As String, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.EnumBlock( enumStatement:=SyntaxFactory.EnumStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EnumStatement), DeclarationKind.Enum), identifier:=name.ToIdentifierToken(), underlyingType:=Nothing), members:=AsEnumMembers(members)) End Function Public Overrides Function EnumMember(name As String, Optional expression As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.EnumMemberDeclaration( attributeLists:=Nothing, identifier:=name.ToIdentifierToken(), initializer:=If(expression IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(expression, ExpressionSyntax)), Nothing)) End Function Private Function AsEnumMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsEnumMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsEnumMember(node As SyntaxNode) As StatementSyntax Dim id = TryCast(node, IdentifierNameSyntax) If id IsNot Nothing Then Return DirectCast(EnumMember(id.Identifier.ValueText), EnumMemberDeclarationSyntax) End If Return TryCast(node, EnumMemberDeclarationSyntax) End Function Public Overrides Function DelegateDeclaration( name As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Dim kind = If(returnType Is Nothing, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement) Return SyntaxFactory.DelegateStatement( kind:=kind, attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(kind), DeclarationKind.Delegate), subOrFunctionKeyword:=If(kind = SyntaxKind.DelegateSubStatement, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(kind = SyntaxKind.DelegateFunctionStatement, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing)) End Function Public Overrides Function CompilationUnit(declarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CompilationUnit().WithImports(AsImports(declarations)).WithMembers(AsNamespaceMembers(declarations)) End Function Private Function AsImports(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of ImportsStatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.Select(AddressOf AsNamespaceImport).OfType(Of ImportsStatementSyntax)())) End Function Private Function AsNamespaceImport(node As SyntaxNode) As SyntaxNode Dim name = TryCast(node, NameSyntax) If name IsNot Nothing Then Return Me.NamespaceImportDeclaration(name) End If Return TryCast(node, ImportsStatementSyntax) End Function Private Function AsNamespaceMembers(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.OfType(Of StatementSyntax)().Where(Function(s) Not TypeOf s Is ImportsStatementSyntax))) End Function Public Overrides Function NamespaceImportDeclaration(name As SyntaxNode) As SyntaxNode Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(SyntaxFactory.SimpleImportsClause(DirectCast(name, NameSyntax)))) End Function Public Overrides Function AliasImportDeclaration(aliasIdentifierName As String, name As SyntaxNode) As SyntaxNode If TypeOf name Is NameSyntax Then Return SyntaxFactory.ImportsStatement(SyntaxFactory.SeparatedList(Of ImportsClauseSyntax).Add( SyntaxFactory.SimpleImportsClause( SyntaxFactory.ImportAliasClause(aliasIdentifierName), CType(name, NameSyntax)))) End If Throw New ArgumentException("name is not a NameSyntax.", NameOf(name)) End Function Public Overrides Function NamespaceDeclaration(name As SyntaxNode, nestedDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim imps As IEnumerable(Of StatementSyntax) = AsImports(nestedDeclarations) Dim members As IEnumerable(Of StatementSyntax) = AsNamespaceMembers(nestedDeclarations) ' put imports at start Dim statements = imps.Concat(members) Return SyntaxFactory.NamespaceBlock( SyntaxFactory.NamespaceStatement(DirectCast(name, NameSyntax)), members:=SyntaxFactory.List(statements)) End Function Public Overrides Function Attribute(name As SyntaxNode, Optional attributeArguments As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim attr = SyntaxFactory.Attribute( target:=Nothing, name:=DirectCast(name, TypeSyntax), argumentList:=AsArgumentList(attributeArguments)) Return AsAttributeList(attr) End Function Private Function AsArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax If arguments IsNot Nothing Then Return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument))) Else Return Nothing End If End Function Public Overrides Function AttributeArgument(name As String, expression As SyntaxNode) As SyntaxNode Return Argument(name, RefKind.None, expression) End Function Public Overrides Function ClearTrivia(Of TNode As SyntaxNode)(node As TNode) As TNode If node IsNot Nothing Then Return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker).WithTrailingTrivia(SyntaxFactory.ElasticMarker) Else Return Nothing End If End Function Private Function AsAttributeLists(attributes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of AttributeListSyntax) If attributes IsNot Nothing Then Return SyntaxFactory.List(attributes.Select(AddressOf AsAttributeList)) Else Return Nothing End If End Function Private Function AsAttributeList(node As SyntaxNode) As AttributeListSyntax Dim attr = TryCast(node, AttributeSyntax) If attr IsNot Nothing Then Return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(WithNoTarget(attr))) Else Return WithNoTargets(DirectCast(node, AttributeListSyntax)) End If End Function Private Overloads Function WithNoTargets(attrs As AttributeListSyntax) As AttributeListSyntax If (attrs.Attributes.Any(Function(a) a.Target IsNot Nothing)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Overloads Function WithNoTarget(attr As AttributeSyntax) As AttributeSyntax Return attr.WithTarget(Nothing) End Function Friend Overrides Function GetTypeInheritance(declaration As SyntaxNode) As ImmutableArray(Of SyntaxNode) Dim typeDecl = TryCast(declaration, TypeBlockSyntax) If typeDecl Is Nothing Then Return ImmutableArray(Of SyntaxNode).Empty End If Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() builder.AddRange(typeDecl.Inherits) builder.AddRange(typeDecl.Implements) Return builder.ToImmutableAndFree() End Function Public Overrides Function GetAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetAttributeLists(declaration)) End Function Public Overrides Function InsertAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertAttributesInternal(d, index, attributes)) End Function Private Function InsertAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingAttributes = Me.GetAttributes(declaration) If index >= 0 AndAlso index < existingAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingAttributes(index), newAttributes) ElseIf existingAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingAttributes(existingAttributes.Count - 1), newAttributes) Else Dim lists = Me.GetAttributeLists(declaration) Return Me.WithAttributeLists(declaration, lists.AddRange(AsAttributeLists(attributes))) End If End Function Private Shared Function HasAssemblyTarget(attr As AttributeSyntax) As Boolean Return attr.Target IsNot Nothing AndAlso attr.Target.AttributeModifier.IsKind(SyntaxKind.AssemblyKeyword) End Function Private Overloads Function WithAssemblyTargets(attrs As AttributeListSyntax) As AttributeListSyntax If attrs.Attributes.Any(Function(a) Not HasAssemblyTarget(a)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Overloads Function WithAssemblyTarget(attr As AttributeSyntax) As AttributeSyntax If Not HasAssemblyTarget(attr) Then Return attr.WithTarget(SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))) Else Return attr End If End Function Public Overrides Function GetReturnAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetReturnAttributeLists(declaration)) End Function Public Overrides Function InsertReturnAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return Isolate(declaration, Function(d) InsertReturnAttributesInternal(d, index, attributes)) Case Else Return declaration End Select End Function Private Function InsertReturnAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingReturnAttributes = Me.GetReturnAttributes(declaration) If index >= 0 AndAlso index < existingReturnAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingReturnAttributes(index), newAttributes) ElseIf existingReturnAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingReturnAttributes(existingReturnAttributes.Count - 1), newAttributes) Else Dim lists = Me.GetReturnAttributeLists(declaration) Dim newLists = lists.AddRange(newAttributes) Return Me.WithReturnAttributeLists(declaration, newLists) End If End Function Private Function GetReturnAttributeLists(declaration As SyntaxNode) As SyntaxList(Of AttributeListSyntax) Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Select Case declaration.Kind() Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return asClause.Attributes End Select End If Return Nothing End Function Private Function WithReturnAttributeLists(declaration As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode If declaration Is Nothing Then Return Nothing End If Select Case declaration.Kind() Case SyntaxKind.FunctionBlock Dim fb = DirectCast(declaration, MethodBlockSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return fb.WithSubOrFunctionStatement(fb.SubOrFunctionStatement.WithAsClause(asClause)) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return ms.WithAsClause(asClause) Case SyntaxKind.DelegateFunctionStatement Dim df = DirectCast(declaration, DelegateStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return df.WithAsClause(asClause) Case SyntaxKind.SimpleAsClause Return DirectCast(declaration, SimpleAsClauseSyntax).WithAttributeLists(SyntaxFactory.List(lists)) Case Else Return Nothing End Select End Function Private Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of AttributeListSyntax) Select Case node.Kind Case SyntaxKind.CompilationUnit Return SyntaxFactory.List(DirectCast(node, CompilationUnitSyntax).Attributes.SelectMany(Function(s) s.AttributeLists)) Case SyntaxKind.ClassBlock Return DirectCast(node, ClassBlockSyntax).BlockStatement.AttributeLists Case SyntaxKind.ClassStatement Return DirectCast(node, ClassStatementSyntax).AttributeLists Case SyntaxKind.StructureBlock Return DirectCast(node, StructureBlockSyntax).BlockStatement.AttributeLists Case SyntaxKind.StructureStatement Return DirectCast(node, StructureStatementSyntax).AttributeLists Case SyntaxKind.InterfaceBlock Return DirectCast(node, InterfaceBlockSyntax).BlockStatement.AttributeLists Case SyntaxKind.InterfaceStatement Return DirectCast(node, InterfaceStatementSyntax).AttributeLists Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists Case SyntaxKind.EnumStatement Return DirectCast(node, EnumStatementSyntax).AttributeLists Case SyntaxKind.EnumMemberDeclaration Return DirectCast(node, EnumMemberDeclarationSyntax).AttributeLists Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).AttributeLists Case SyntaxKind.FieldDeclaration Return DirectCast(node, FieldDeclarationSyntax).AttributeLists Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock Return DirectCast(node, MethodBlockSyntax).BlockStatement.AttributeLists Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(node, MethodStatementSyntax).AttributeLists Case SyntaxKind.ConstructorBlock Return DirectCast(node, ConstructorBlockSyntax).BlockStatement.AttributeLists Case SyntaxKind.SubNewStatement Return DirectCast(node, SubNewStatementSyntax).AttributeLists Case SyntaxKind.Parameter Return DirectCast(node, ParameterSyntax).AttributeLists Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).PropertyStatement.AttributeLists Case SyntaxKind.PropertyStatement Return DirectCast(node, PropertyStatementSyntax).AttributeLists Case SyntaxKind.OperatorBlock Return DirectCast(node, OperatorBlockSyntax).BlockStatement.AttributeLists Case SyntaxKind.OperatorStatement Return DirectCast(node, OperatorStatementSyntax).AttributeLists Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).EventStatement.AttributeLists Case SyntaxKind.EventStatement Return DirectCast(node, EventStatementSyntax).AttributeLists Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax).AccessorStatement.AttributeLists Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(node, AccessorStatementSyntax).AttributeLists Case Else Return Nothing End Select End Function Private Function WithAttributeLists(node As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode Dim arg = SyntaxFactory.List(lists) Select Case node.Kind Case SyntaxKind.CompilationUnit 'convert to assembly target arg = SyntaxFactory.List(lists.Select(Function(lst) Me.WithAssemblyTargets(lst))) ' add as single attributes statement Return DirectCast(node, CompilationUnitSyntax).WithAttributes(SyntaxFactory.SingletonList(SyntaxFactory.AttributesStatement(arg))) Case SyntaxKind.ClassBlock Return DirectCast(node, ClassBlockSyntax).WithClassStatement(DirectCast(node, ClassBlockSyntax).ClassStatement.WithAttributeLists(arg)) Case SyntaxKind.ClassStatement Return DirectCast(node, ClassStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.StructureBlock Return DirectCast(node, StructureBlockSyntax).WithStructureStatement(DirectCast(node, StructureBlockSyntax).StructureStatement.WithAttributeLists(arg)) Case SyntaxKind.StructureStatement Return DirectCast(node, StructureStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.InterfaceBlock Return DirectCast(node, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(node, InterfaceBlockSyntax).InterfaceStatement.WithAttributeLists(arg)) Case SyntaxKind.InterfaceStatement Return DirectCast(node, InterfaceStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).WithEnumStatement(DirectCast(node, EnumBlockSyntax).EnumStatement.WithAttributeLists(arg)) Case SyntaxKind.EnumStatement Return DirectCast(node, EnumStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumMemberDeclaration Return DirectCast(node, EnumMemberDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.FieldDeclaration Return DirectCast(node, FieldDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(node, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(node, MethodBlockSyntax).SubOrFunctionStatement.WithAttributeLists(arg)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(node, MethodStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.ConstructorBlock Return DirectCast(node, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(node, ConstructorBlockSyntax).SubNewStatement.WithAttributeLists(arg)) Case SyntaxKind.SubNewStatement Return DirectCast(node, SubNewStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.Parameter Return DirectCast(node, ParameterSyntax).WithAttributeLists(arg) Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).WithPropertyStatement(DirectCast(node, PropertyBlockSyntax).PropertyStatement.WithAttributeLists(arg)) Case SyntaxKind.PropertyStatement Return DirectCast(node, PropertyStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.OperatorBlock Return DirectCast(node, OperatorBlockSyntax).WithOperatorStatement(DirectCast(node, OperatorBlockSyntax).OperatorStatement.WithAttributeLists(arg)) Case SyntaxKind.OperatorStatement Return DirectCast(node, OperatorStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).WithEventStatement(DirectCast(node, EventBlockSyntax).EventStatement.WithAttributeLists(arg)) Case SyntaxKind.EventStatement Return DirectCast(node, EventStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax).WithAccessorStatement(DirectCast(node, AccessorBlockSyntax).AccessorStatement.WithAttributeLists(arg)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(node, AccessorStatementSyntax).WithAttributeLists(arg) Case Else Return node End Select End Function Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Field End If Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Private Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Private Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Private Function Isolate(declaration As SyntaxNode, editor As Func(Of SyntaxNode, SyntaxNode)) As SyntaxNode Dim isolated = AsIsolatedDeclaration(declaration) Return PreserveTrivia(isolated, editor) End Function Private Function GetFullDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetFullDeclaration(declaration.Parent) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return declaration.Parent End If Case SyntaxKind.Attribute If declaration.Parent IsNot Nothing Then Return declaration.Parent End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause If declaration.Parent IsNot Nothing Then Return declaration.Parent End If End Select Return declaration End Function Private Function AsIsolatedDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim full = GetFullDeclaration(declaration) If full IsNot declaration Then Return WithSingleVariable(full, DirectCast(declaration, ModifiedIdentifierSyntax)) End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list IsNot Nothing Then Return list.WithAttributes(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, AttributeSyntax))) End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim stmt = TryCast(declaration.Parent, ImportsStatementSyntax) If stmt IsNot Nothing Then Return stmt.WithImportsClauses(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, ImportsClauseSyntax))) End If End Select Return declaration End Function Private Function WithSingleVariable(declaration As SyntaxNode, variable As ModifiedIdentifierSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) Return vd.WithNames(SyntaxFactory.SingletonSeparatedList(variable)) Case Else Return declaration End Select End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Overrides Function GetName(declaration As SyntaxNode) As String Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier.ValueText Case SyntaxKind.EnumMemberDeclaration Return DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier.ValueText Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Identifier.ValueText Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier.ValueText Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Identifier.ValueText Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier.ValueText Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Identifier.ValueText Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Identifier.Identifier.ValueText Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name.ToString() Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If GetDeclarationCount(fd) = 1 Then Return fd.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If GetDeclarationCount(ld) = 1 Then Return ld.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) If vd.Names.Count = 1 Then Return vd.Names(0).Identifier.ValueText End If Case SyntaxKind.ModifiedIdentifier Return DirectCast(declaration, ModifiedIdentifierSyntax).Identifier.ValueText Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).Name.ToString() Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return list.Attributes(0).Name.ToString() End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Return GetName(stmt.ImportsClauses(0)) End If Case SyntaxKind.SimpleImportsClause Return DirectCast(declaration, SimpleImportsClauseSyntax).Name.ToString() End Select Return String.Empty End Function Public Overrides Function WithName(declaration As SyntaxNode, name As String) As SyntaxNode Return Isolate(declaration, Function(d) WithNameInternal(d, name)) End Function Private Function WithNameInternal(declaration As SyntaxNode, name As String) As SyntaxNode Dim id = name.ToIdentifierToken() Select Case declaration.Kind Case SyntaxKind.ClassBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.StructureBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.InterfaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.EnumBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier, id) Case SyntaxKind.EnumMemberDeclaration Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier, id) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, DelegateStatementSyntax).Identifier, id) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier, id) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodStatementSyntax).Identifier, id) Case SyntaxKind.PropertyBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier, id) Case SyntaxKind.PropertyStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyStatementSyntax).Identifier, id) Case SyntaxKind.EventBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.Parameter Return ReplaceWithTrivia(declaration, DirectCast(declaration, ParameterSyntax).Identifier.Identifier, id) Case SyntaxKind.NamespaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name, Me.DottedName(name)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 AndAlso ld.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 AndAlso fd.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.Attribute Return ReplaceWithTrivia(declaration, DirectCast(declaration, AttributeSyntax).Name, Me.DottedName(name)) Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0).Name, Me.DottedName(name)) End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Dim clause = stmt.ImportsClauses(0) Select Case clause.Kind Case SyntaxKind.SimpleImportsClause Return ReplaceWithTrivia(declaration, DirectCast(clause, SimpleImportsClauseSyntax).Name, Me.DottedName(name)) End Select End If End Select Return declaration End Function Public Overrides Function [GetType](declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return [GetType](vd) End If Case Else Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Return asClause.Type End If End Select Return Nothing End Function Public Overrides Function WithType(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithTypeInternal(d, type)) End Function Private Function WithTypeInternal(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode If type Is Nothing Then declaration = AsSub(declaration) Else declaration = AsFunction(declaration) End If Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then If type IsNot Nothing Then Select Case asClause.Kind Case SyntaxKind.SimpleAsClause asClause = DirectCast(asClause, SimpleAsClauseSyntax).WithType(DirectCast(type, TypeSyntax)) Case SyntaxKind.AsNewClause Dim asNew = DirectCast(asClause, AsNewClauseSyntax) Select Case asNew.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ObjectCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) Case SyntaxKind.ArrayCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ArrayCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) End Select End Select Else asClause = Nothing End If ElseIf type IsNot Nothing Then asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) End If Return WithAsClause(declaration, asClause) End Function Private Function GetAsClause(declaration As SyntaxNode) As AsClauseSyntax Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).AsClause Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.AsClause Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).AsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.AsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).AsClause Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.AsClause Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).AsClause Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).AsClause Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).AsClause End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).AsClause End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).AsClause Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return vd.AsClause End If End Select Return Nothing End Function Private Function WithAsClause(declaration As SyntaxNode, asClause As AsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithAsClause(asClause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithAsClause(asClause) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).WithAsClause(asClause) End Select Return declaration End Function Private Function AsFunction(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsFunctionInternal) End Function Private Function AsFunctionInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock Dim sb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.FunctionBlock, DirectCast(AsFunction(sb.BlockStatement), MethodStatementSyntax), sb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, sb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(sb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, sb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SubStatement Dim ss = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.FunctionStatement, ss.AttributeLists, ss.Modifiers, SyntaxFactory.Token(ss.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ss.DeclarationKeyword.TrailingTrivia), ss.Identifier, ss.TypeParameterList, ss.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object")), ss.HandlesClause, ss.ImplementsClause) Case SyntaxKind.DelegateSubStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateFunctionStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case SyntaxKind.MultiLineSubLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineFunctionLambdaExpression, DirectCast(AsFunction(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineSubLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineFunctionLambdaExpression, DirectCast(AsFunction(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.SubLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.FunctionLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareSubStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareFunctionStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case Else Return declaration End Select End Function Private Function AsSub(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsSubInternal) End Function Private Function AsSubInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.SubBlock, DirectCast(AsSub(mb.BlockStatement), MethodStatementSyntax), mb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, mb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(mb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, mb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.SubStatement, ms.AttributeLists, ms.Modifiers, SyntaxFactory.Token(ms.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ms.DeclarationKeyword.TrailingTrivia), ms.Identifier, ms.TypeParameterList, ms.ParameterList, asClause:=Nothing, handlesClause:=ms.HandlesClause, implementsClause:=ms.ImplementsClause) Case SyntaxKind.DelegateFunctionStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateSubStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, asClause:=Nothing) Case SyntaxKind.MultiLineFunctionLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineSubLambdaExpression, DirectCast(AsSub(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineSubLambdaExpression, DirectCast(AsSub(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.FunctionLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.SubLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareFunctionStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareSubStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, asClause:=Nothing) Case Else Return declaration End Select End Function Public Overrides Function GetModifiers(declaration As SyntaxNode) As DeclarationModifiers Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return mods End Function Public Overrides Function WithModifiers(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Return Isolate(declaration, Function(d) Me.WithModifiersInternal(d, modifiers)) End Function Private Function WithModifiersInternal(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim currentMods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, currentMods, isDefault) If (currentMods <> modifiers) Then Dim newTokens = GetModifierList(acc, modifiers And GetAllowedModifiers(declaration.Kind), GetDeclarationKind(declaration), isDefault) Return WithModifierTokens(declaration, Merge(tokens, newTokens)) Else Return declaration End If End Function Private Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Private Function WithModifierTokens(declaration As SyntaxNode, tokens As SyntaxTokenList) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithClassStatement(DirectCast(declaration, ClassBlockSyntax).ClassStatement.WithModifiers(tokens)) Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).WithModifiers(tokens) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithStructureStatement(DirectCast(declaration, StructureBlockSyntax).StructureStatement.WithModifiers(tokens)) Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).WithModifiers(tokens) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(declaration, InterfaceBlockSyntax).InterfaceStatement.WithModifiers(tokens)) Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).WithEnumStatement(DirectCast(declaration, EnumBlockSyntax).EnumStatement.WithModifiers(tokens)) Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).WithModifiers(tokens) Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).WithModuleStatement(DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.WithModifiers(tokens)) Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).WithModifiers(tokens) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithModifiers(tokens) Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).WithModifiers(tokens) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithModifiers(tokens)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(declaration, ConstructorBlockSyntax).SubNewStatement.WithModifiers(tokens)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).WithModifiers(tokens) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithModifiers(tokens) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithModifiers(tokens)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithModifiers(tokens) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithOperatorStatement(DirectCast(declaration, OperatorBlockSyntax).OperatorStatement.WithModifiers(tokens)) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithModifiers(tokens)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithModifiers(tokens) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithAccessorStatement( DirectCast(Me.WithModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement, tokens), AccessorStatementSyntax)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).WithModifiers(tokens) Case Else Return declaration End Select End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function WithAccessibility(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not CanHaveAccessibility(declaration) AndAlso accessibility <> Accessibility.NotApplicable Then Return declaration End If Return Isolate(declaration, Function(d) Me.WithAccessibilityInternal(d, accessibility)) End Function Private Function WithAccessibilityInternal(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not CanHaveAccessibility(declaration) Then Return declaration End If Dim tokens = GetModifierTokens(declaration) Dim currentAcc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, currentAcc, mods, isDefault) If currentAcc = accessibility Then Return declaration End If Dim newTokens = GetModifierList(accessibility, mods, GetDeclarationKind(declaration), isDefault) 'GetDeclarationKind returns None for Field if the count is > 1 'To handle multiple declarations on a field if the Accessibility is NotApplicable, we need to add the Dim If declaration.Kind = SyntaxKind.FieldDeclaration AndAlso accessibility = Accessibility.NotApplicable AndAlso newTokens.Count = 0 Then ' Add the Dim newTokens = newTokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return WithModifierTokens(declaration, Merge(tokens, newTokens)) End Function Friend Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Private Function GetModifierList(accessibility As Accessibility, modifiers As DeclarationModifiers, kind As DeclarationKind, Optional isDefault As Boolean = False) As SyntaxTokenList Dim _list = SyntaxFactory.TokenList() If isDefault Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword)) End If Select Case (accessibility) Case Accessibility.Internal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.Public _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Private _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Protected _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedAndInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.NotApplicable Case Else Throw New NotSupportedException(String.Format("Accessibility '{0}' not supported.", accessibility)) End Select If modifiers.IsAbstract Then If kind = DeclarationKind.Class Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword)) End If End If If modifiers.IsNew Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword)) End If If modifiers.IsSealed Then If kind = DeclarationKind.Class Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword)) End If End If If modifiers.IsOverride Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword)) End If If modifiers.IsVirtual Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword)) End If If modifiers.IsStatic Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If modifiers.IsAsync Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)) End If If modifiers.IsConst Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) End If If modifiers.IsReadOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If modifiers.IsWriteOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword)) End If If modifiers.IsUnsafe Then Throw New NotSupportedException("Unsupported modifier") ''''_list = _list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)) End If If modifiers.IsWithEvents Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If ' partial must be last If modifiers.IsPartial Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)) End If If (kind = DeclarationKind.Field AndAlso _list.Count = 0) Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return _list End Function Private Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Private Function GetTypeParameters(typeParameterNames As IEnumerable(Of String)) As TypeParameterListSyntax If typeParameterNames Is Nothing Then Return Nothing End If Dim typeParameterList = SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(Function(name) SyntaxFactory.TypeParameter(name)))) If typeParameterList.Parameters.Count = 0 Then typeParameterList = Nothing End If Return typeParameterList End Function Public Overrides Function WithTypeParameters(declaration As SyntaxNode, typeParameterNames As IEnumerable(Of String)) As SyntaxNode Dim typeParameterList = GetTypeParameters(typeParameterNames) Return ReplaceTypeParameterList(declaration, Function(old) typeParameterList) End Function Private Function ReplaceTypeParameterList(declaration As SyntaxNode, replacer As Func(Of TypeParameterListSyntax, TypeParameterListSyntax)) As SyntaxNode Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return method.WithTypeParameterList(replacer(method.TypeParameterList)) End If Dim methodBlock = TryCast(declaration, MethodBlockSyntax) If methodBlock IsNot Nothing Then Return methodBlock.WithSubOrFunctionStatement(methodBlock.SubOrFunctionStatement.WithTypeParameterList(replacer(methodBlock.SubOrFunctionStatement.TypeParameterList))) End If Dim classBlock = TryCast(declaration, ClassBlockSyntax) If classBlock IsNot Nothing Then Return classBlock.WithClassStatement(classBlock.ClassStatement.WithTypeParameterList(replacer(classBlock.ClassStatement.TypeParameterList))) End If Dim structureBlock = TryCast(declaration, StructureBlockSyntax) If structureBlock IsNot Nothing Then Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithTypeParameterList(replacer(structureBlock.StructureStatement.TypeParameterList))) End If Dim interfaceBlock = TryCast(declaration, InterfaceBlockSyntax) If interfaceBlock IsNot Nothing Then Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithTypeParameterList(replacer(interfaceBlock.InterfaceStatement.TypeParameterList))) End If Return declaration End Function Friend Overrides Function WithExplicitInterfaceImplementations(declaration As SyntaxNode, explicitInterfaceImplementations As ImmutableArray(Of IMethodSymbol)) As SyntaxNode If TypeOf declaration Is MethodStatementSyntax Then Dim methodStatement = DirectCast(declaration, MethodStatementSyntax) Dim interfaceMembers = explicitInterfaceImplementations.Select(AddressOf GenerateInterfaceMember) Return methodStatement.WithImplementsClause( SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(interfaceMembers))) ElseIf TypeOf declaration Is MethodBlockSyntax Then Dim methodBlock = DirectCast(declaration, MethodBlockSyntax) Return methodBlock.WithSubOrFunctionStatement( DirectCast(WithExplicitInterfaceImplementations(methodBlock.SubOrFunctionStatement, explicitInterfaceImplementations), MethodStatementSyntax)) End If Return declaration End Function Private Function GenerateInterfaceMember(method As IMethodSymbol) As QualifiedNameSyntax Dim interfaceName = method.ContainingType.GenerateTypeSyntax() Return SyntaxFactory.QualifiedName( DirectCast(interfaceName, NameSyntax), SyntaxFactory.IdentifierName(method.Name)) End Function Public Overrides Function WithTypeConstraint(declaration As SyntaxNode, typeParameterName As String, kinds As SpecialTypeConstraintKind, Optional types As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim constraints = SyntaxFactory.SeparatedList(Of ConstraintSyntax) If types IsNot Nothing Then constraints = constraints.AddRange(types.Select(Function(t) SyntaxFactory.TypeConstraint(DirectCast(t, TypeSyntax)))) End If If (kinds And SpecialTypeConstraintKind.Constructor) <> 0 Then constraints = constraints.Add(SyntaxFactory.NewConstraint(SyntaxFactory.Token(SyntaxKind.NewKeyword))) End If Dim isReferenceType = (kinds And SpecialTypeConstraintKind.ReferenceType) <> 0 Dim isValueType = (kinds And SpecialTypeConstraintKind.ValueType) <> 0 If isReferenceType Then constraints = constraints.Insert(0, SyntaxFactory.ClassConstraint(SyntaxFactory.Token(SyntaxKind.ClassKeyword))) ElseIf isValueType Then constraints = constraints.Insert(0, SyntaxFactory.StructureConstraint(SyntaxFactory.Token(SyntaxKind.StructureKeyword))) End If Dim clause As TypeParameterConstraintClauseSyntax = Nothing If constraints.Count = 1 Then clause = SyntaxFactory.TypeParameterSingleConstraintClause(constraints(0)) ElseIf constraints.Count > 1 Then clause = SyntaxFactory.TypeParameterMultipleConstraintClause(constraints) End If Return ReplaceTypeParameterList(declaration, Function(old) WithTypeParameterConstraints(old, typeParameterName, clause)) End Function Private Function WithTypeParameterConstraints(typeParameterList As TypeParameterListSyntax, typeParameterName As String, clause As TypeParameterConstraintClauseSyntax) As TypeParameterListSyntax If typeParameterList IsNot Nothing Then Dim typeParameter = typeParameterList.Parameters.FirstOrDefault(Function(tp) tp.Identifier.ToString() = typeParameterName) If typeParameter IsNot Nothing Then Return typeParameterList.WithParameters(typeParameterList.Parameters.Replace(typeParameter, typeParameter.WithTypeParameterConstraintClause(clause))) End If End If Return typeParameterList End Function Public Overrides Function GetParameters(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = GetParameterList(declaration) If list IsNot Nothing Then Return list.Parameters Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End If End Function Public Overrides Function InsertParameters(declaration As SyntaxNode, index As Integer, parameters As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = GetParameterList(declaration) Dim newList = GetParameterList(parameters) If currentList IsNot Nothing Then Return WithParameterList(declaration, currentList.WithParameters(currentList.Parameters.InsertRange(index, newList.Parameters))) Else Return WithParameterList(declaration, newList) End If End Function Public Overrides Function GetSwitchSections(switchStatement As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End If Return statement.CaseBlocks End Function Public Overrides Function InsertSwitchSections(switchStatement As SyntaxNode, index As Integer, switchSections As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return switchStatement End If Return statement.WithCaseBlocks( statement.CaseBlocks.InsertRange(index, switchSections.Cast(Of CaseBlockSyntax))) End Function Friend Shared Function GetParameterList(declaration As SyntaxNode) As ParameterListSyntax Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.ParameterList Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.ParameterList Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.ParameterList Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).ParameterList Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).ParameterList Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).ParameterList Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(declaration, DeclareStatementSyntax).ParameterList Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).ParameterList Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ParameterList Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).ParameterList Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.ParameterList Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).ParameterList Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.ParameterList Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.ParameterList Case Else Return Nothing End Select End Function Private Function WithParameterList(declaration As SyntaxNode, list As ParameterListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithBlockStatement(DirectCast(declaration, MethodBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithBlockStatement(DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithBlockStatement(DirectCast(declaration, OperatorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithParameterList(list) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithParameterList(list) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithParameterList(list) Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(declaration, DeclareStatementSyntax).WithParameterList(list) Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.PropertyBlock If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithParameterList(list)) End If Case SyntaxKind.PropertyStatement If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyStatementSyntax).WithParameterList(list) End If Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithParameterList(list)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithParameterList(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) End Select Return declaration End Function Public Overrides Function GetExpression(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return AsExpression(DirectCast(declaration, SingleLineLambdaExpressionSyntax).Body) Case Else Dim ev = GetEqualsValue(declaration) If ev IsNot Nothing Then Return ev.Value End If End Select Return Nothing End Function Private Function AsExpression(node As SyntaxNode) As ExpressionSyntax Dim es = TryCast(node, ExpressionStatementSyntax) If es IsNot Nothing Then Return es.Expression End If Return DirectCast(node, ExpressionSyntax) End Function Public Overrides Function WithExpression(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithExpressionInternal(d, expression)) End Function Private Function WithExpressionInternal(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Dim expr = DirectCast(expression, ExpressionSyntax) Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(expr) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndFunctionStatement()) End If Case SyntaxKind.MultiLineFunctionLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineFunctionLambdaExpression, mll.SubOrFunctionHeader, expr) End If Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(AsStatement(expr)) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndSubStatement()) End If Case SyntaxKind.MultiLineSubLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineSubLambdaExpression, mll.SubOrFunctionHeader, AsStatement(expr)) End If Case Else Dim currentEV = GetEqualsValue(declaration) If currentEV IsNot Nothing Then Return WithEqualsValue(declaration, currentEV.WithValue(expr)) Else Return WithEqualsValue(declaration, SyntaxFactory.EqualsValue(expr)) End If End Select Return declaration End Function Private Function GetEqualsValue(declaration As SyntaxNode) As EqualsValueSyntax Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Default Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).Initializer End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).Initializer End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).Initializer End Select Return Nothing End Function Private Function WithEqualsValue(declaration As SyntaxNode, ev As EqualsValueSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithDefault(ev) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithInitializer(ev)) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithInitializer(ev)) End If End Select Return declaration End Function Public Overrides Function GetNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(Me.GetUnflattenedNamespaceImports(declaration)) End Function Private Function GetUnflattenedNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Imports Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function InsertNamespaceImports(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertNamespaceImportsInternal(d, index, [imports])) End Function Private Function InsertNamespaceImportsInternal(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newImports = AsImports([imports]) Dim existingImports = Me.GetNamespaceImports(declaration) If index >= 0 AndAlso index < existingImports.Count Then Return Me.InsertNodesBefore(declaration, existingImports(index), newImports) ElseIf existingImports.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingImports(existingImports.Count - 1), newImports) Else Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithImports(cu.Imports.AddRange(newImports)) Case Else Return declaration End Select End If End Function Public Overrides Function GetMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Flatten(GetUnflattenedMembers(declaration)) End Function Private Function GetUnflattenedMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Members Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).Members Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Members Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Members Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Members Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).Members Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Private Function AsMembersOf(declaration As SyntaxNode, members As IEnumerable(Of SyntaxNode)) As IEnumerable(Of StatementSyntax) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return AsNamespaceMembers(members) Case SyntaxKind.NamespaceBlock Return AsNamespaceMembers(members) Case SyntaxKind.ClassBlock Return AsClassMembers(members) Case SyntaxKind.StructureBlock Return AsClassMembers(members) Case SyntaxKind.InterfaceBlock Return AsInterfaceMembers(members) Case SyntaxKind.EnumBlock Return AsEnumMembers(members) Case Else Return SpecializedCollections.EmptyEnumerable(Of StatementSyntax) End Select End Function Public Overrides Function InsertMembers(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertMembersInternal(d, index, members)) End Function Private Function InsertMembersInternal(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newMembers = Me.AsMembersOf(declaration, members) Dim existingMembers = Me.GetMembers(declaration) If index >= 0 AndAlso index < existingMembers.Count Then Return Me.InsertNodesBefore(declaration, existingMembers(index), members) ElseIf existingMembers.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingMembers(existingMembers.Count - 1), members) End If Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithMembers(cu.Members.AddRange(newMembers)) Case SyntaxKind.NamespaceBlock Dim ns = DirectCast(declaration, NamespaceBlockSyntax) Return ns.WithMembers(ns.Members.AddRange(newMembers)) Case SyntaxKind.ClassBlock Dim cb = DirectCast(declaration, ClassBlockSyntax) Return cb.WithMembers(cb.Members.AddRange(newMembers)) Case SyntaxKind.StructureBlock Dim sb = DirectCast(declaration, StructureBlockSyntax) Return sb.WithMembers(sb.Members.AddRange(newMembers)) Case SyntaxKind.InterfaceBlock Dim ib = DirectCast(declaration, InterfaceBlockSyntax) Return ib.WithMembers(ib.Members.AddRange(newMembers)) Case SyntaxKind.EnumBlock Dim eb = DirectCast(declaration, EnumBlockSyntax) Return eb.WithMembers(eb.Members.AddRange(newMembers)) Case Else Return declaration End Select End Function Public Overrides Function GetStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock Return DirectCast(declaration, MethodBlockBaseSyntax).Statements Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).Statements Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).Statements Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function WithStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) WithStatementsInternal(d, statements)) End Function Private Function WithStatementsInternal(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetStatementList(statements) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithStatements(list) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithStatements(list) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithStatements(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithStatements(list) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndFunctionStatement()) Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndSubStatement()) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithStatements(list) Case Else Return declaration End Select End Function Public Overrides Function GetAccessors(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Public Overrides Function InsertAccessors(declaration As SyntaxNode, index As Integer, accessors As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = GetAccessorList(declaration) Dim newList = AsAccessorList(accessors, declaration.Kind) If Not currentList.IsEmpty Then Return WithAccessorList(declaration, currentList.InsertRange(index, newList)) Else Return WithAccessorList(declaration, newList) End If End Function Private Function GetAccessorList(declaration As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return Nothing End Select End Function Private Function WithAccessorList(declaration As SyntaxNode, accessorList As SyntaxList(Of AccessorBlockSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithAccessors(accessorList) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithAccessors(accessorList) Case Else Return declaration End Select End Function Private Function AsAccessorList(nodes As IEnumerable(Of SyntaxNode), parentKind As SyntaxKind) As SyntaxList(Of AccessorBlockSyntax) Return SyntaxFactory.List(nodes.Select(Function(n) AsAccessor(n, parentKind)).Where(Function(n) n IsNot Nothing)) End Function Private Function AsAccessor(node As SyntaxNode, parentKind As SyntaxKind) As AccessorBlockSyntax Select Case parentKind Case SyntaxKind.PropertyBlock Select Case node.Kind Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select Case SyntaxKind.EventBlock Select Case node.Kind Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select End Select Return Nothing End Function Private Function CanHaveAccessors(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.PropertyBlock, SyntaxKind.EventBlock Return True Case Else Return False End Select End Function Public Overrides Function GetGetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function WithGetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function GetSetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.SetAccessorBlock) End Function Public Overrides Function WithSetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.SetAccessorBlock) End Function Private Function GetAccessorStatements(declaration As SyntaxNode, kind As SyntaxKind) As IReadOnlyList(Of SyntaxNode) Dim accessor = Me.GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then Return Me.GetStatements(accessor) Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Private Function WithAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode), kind As SyntaxKind) As SyntaxNode Dim accessor = Me.GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then accessor = DirectCast(Me.WithStatements(accessor, statements), AccessorBlockSyntax) Return Me.WithAccessorBlock(declaration, kind, accessor) ElseIf Me.CanHaveAccessors(declaration.Kind) Then accessor = Me.AccessorBlock(kind, statements, Me.ClearTrivia(Me.GetType(declaration))) Return Me.WithAccessorBlock(declaration, kind, accessor) Else Return declaration End If End Function Private Function GetAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind) As AccessorBlockSyntax Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case Else Return Nothing End Select End Function Private Function WithAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind, accessor As AccessorBlockSyntax) As SyntaxNode Dim currentAccessor = Me.GetAccessorBlock(declaration, kind) If currentAccessor IsNot Nothing Then Return Me.ReplaceNode(declaration, currentAccessor, accessor) ElseIf accessor IsNot Nothing Then Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithAccessors(pb.Accessors.Add(accessor)) Case SyntaxKind.EventBlock Dim eb = DirectCast(declaration, EventBlockSyntax) Return eb.WithAccessors(eb.Accessors.Add(accessor)) End Select End If Return declaration End Function Public Overrides Function EventDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Return SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), DeclarationKind.Event), customKeyword:=Nothing, eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) End Function Public Overrides Function CustomEventDeclaration( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return CustomEventDeclarationWithRaise(name, type, accessibility, modifiers, parameters, addAccessorStatements, removeAccessorStatements) End Function Public Function CustomEventDeclarationWithRaise( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional raiseAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim accessors = New List(Of AccessorBlockSyntax)() If modifiers.IsAbstract Then addAccessorStatements = Nothing removeAccessorStatements = Nothing raiseAccessorStatements = Nothing Else If addAccessorStatements Is Nothing Then addAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If removeAccessorStatements Is Nothing Then removeAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If raiseAccessorStatements Is Nothing Then raiseAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If End If accessors.Add(CreateAddHandlerAccessorBlock(type, addAccessorStatements)) accessors.Add(CreateRemoveHandlerAccessorBlock(type, removeAccessorStatements)) accessors.Add(CreateRaiseEventAccessorBlock(parameters, raiseAccessorStatements)) Dim evStatement = SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), DeclarationKind.Event), customKeyword:=SyntaxFactory.Token(SyntaxKind.CustomKeyword), eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) Return SyntaxFactory.EventBlock( eventStatement:=evStatement, accessors:=SyntaxFactory.List(accessors), endEventStatement:=SyntaxFactory.EndEventStatement()) End Function Public Overrides Function GetAttributeArguments(attributeDeclaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = GetArgumentList(attributeDeclaration) If list IsNot Nothing Then Return list.Arguments Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Public Overrides Function InsertAttributeArguments(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(attributeDeclaration, Function(d) InsertAttributeArgumentsInternal(d, index, attributeArguments)) End Function Private Function InsertAttributeArgumentsInternal(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetArgumentList(attributeDeclaration) Dim newArguments = AsArgumentList(attributeArguments) If list Is Nothing Then list = newArguments Else list = list.WithArguments(list.Arguments.InsertRange(index, newArguments.Arguments)) End If Return WithArgumentList(attributeDeclaration, list) End Function Private Function GetArgumentList(declaration As SyntaxNode) As ArgumentListSyntax Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return al.Attributes(0).ArgumentList End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).ArgumentList End Select Return Nothing End Function Private Function WithArgumentList(declaration As SyntaxNode, argumentList As ArgumentListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0), al.Attributes(0).WithArgumentList(argumentList)) End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).WithArgumentList(argumentList) End Select Return declaration End Function Public Overrides Function GetBaseAndInterfaceTypes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.GetInherits(declaration).SelectMany(Function(ih) ih.Types).Concat(Me.GetImplements(declaration).SelectMany(Function(imp) imp.Types)).ToImmutableReadOnlyListOrEmpty() End Function Public Overrides Function AddBaseType(declaration As SyntaxNode, baseType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.ClassBlock) Then Dim existingBaseType = Me.GetInherits(declaration).SelectMany(Function(inh) inh.Types).FirstOrDefault() If existingBaseType IsNot Nothing Then Return declaration.ReplaceNode(existingBaseType, baseType.WithTriviaFrom(existingBaseType)) Else Return Me.WithInherits(declaration, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax)))) End If Else Return declaration End If End Function Public Overrides Function AddInterfaceType(declaration As SyntaxNode, interfaceType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.InterfaceBlock) Then Dim inh = Me.GetInherits(declaration) Dim last = inh.SelectMany(Function(s) s.Types).LastOrDefault() If inh.Count = 1 AndAlso last IsNot Nothing Then Dim inh0 = inh(0) Dim newInh0 = PreserveTrivia(inh0.TrackNodes(last), Function(_inh0) InsertNodesAfter(_inh0, _inh0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, inh0, newInh0) Else Return Me.WithInherits(declaration, inh.Add(SyntaxFactory.InheritsStatement(DirectCast(interfaceType, TypeSyntax)))) End If Else Dim imp = Me.GetImplements(declaration) Dim last = imp.SelectMany(Function(s) s.Types).LastOrDefault() If imp.Count = 1 AndAlso last IsNot Nothing Then Dim imp0 = imp(0) Dim newImp0 = PreserveTrivia(imp0.TrackNodes(last), Function(_imp0) InsertNodesAfter(_imp0, _imp0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, imp0, newImp0) Else Return Me.WithImplements(declaration, imp.Add(SyntaxFactory.ImplementsStatement(DirectCast(interfaceType, TypeSyntax)))) End If End If End Function Private Function GetInherits(declaration As SyntaxNode) As SyntaxList(Of InheritsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Inherits Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Inherits Case Else Return Nothing End Select End Function Private Function WithInherits(declaration As SyntaxNode, list As SyntaxList(Of InheritsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithInherits(list) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInherits(list) Case Else Return declaration End Select End Function Private Function GetImplements(declaration As SyntaxNode) As SyntaxList(Of ImplementsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Implements Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Implements Case Else Return Nothing End Select End Function Private Function WithImplements(declaration As SyntaxNode, list As SyntaxList(Of ImplementsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithImplements(list) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithImplements(list) Case Else Return declaration End Select End Function #End Region #Region "Remove, Replace, Insert" Public Overrides Function ReplaceNode(root As SyntaxNode, declaration As SyntaxNode, newDeclaration As SyntaxNode) As SyntaxNode If newDeclaration Is Nothing Then Return Me.RemoveNode(root, declaration) End If If root.Span.Contains(declaration.Span) Then Dim newFullDecl = Me.AsIsolatedDeclaration(newDeclaration) Dim fullDecl = Me.GetFullDeclaration(declaration) ' special handling for replacing at location of a sub-declaration If fullDecl IsNot declaration AndAlso fullDecl.IsKind(newFullDecl.Kind) Then ' try to replace inline if possible If GetDeclarationCount(newFullDecl) = 1 Then Dim newSubDecl = Me.GetSubDeclarations(newFullDecl)(0) If AreInlineReplaceableSubDeclarations(declaration, newSubDecl) Then Return MyBase.ReplaceNode(root, declaration, newSubDecl) End If End If ' otherwise replace by splitting full-declaration into two parts and inserting newDeclaration between them Dim index = MyBase.IndexOf(Me.GetSubDeclarations(fullDecl), declaration) Return Me.ReplaceSubDeclaration(root, fullDecl, index, newFullDecl) End If ' attempt normal replace Return MyBase.ReplaceNode(root, declaration, newFullDecl) Else Return MyBase.ReplaceNode(root, declaration, newDeclaration) End If End Function ' return true if one sub-declaration can be replaced in-line with another sub-declaration Private Function AreInlineReplaceableSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.ModifiedIdentifier, SyntaxKind.Attribute, SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) End Select Return False End Function Private Function AreSimilarExceptForSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean If decl1 Is Nothing OrElse decl2 Is Nothing Then Return False End If Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.FieldDeclaration Dim fd1 = DirectCast(decl1, FieldDeclarationSyntax) Dim fd2 = DirectCast(decl2, FieldDeclarationSyntax) Return SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists) AndAlso SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) Case SyntaxKind.LocalDeclarationStatement Dim ld1 = DirectCast(decl1, LocalDeclarationStatementSyntax) Dim ld2 = DirectCast(decl2, LocalDeclarationStatementSyntax) Return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers) Case SyntaxKind.VariableDeclarator Dim vd1 = DirectCast(decl1, VariableDeclaratorSyntax) Dim vd2 = DirectCast(decl2, VariableDeclaratorSyntax) Return SyntaxFactory.AreEquivalent(vd1.AsClause, vd2.AsClause) AndAlso SyntaxFactory.AreEquivalent(vd2.Initializer, vd1.Initializer) AndAlso AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) Case SyntaxKind.AttributeList, SyntaxKind.ImportsStatement Return True End Select Return False End Function Public Overrides Function InsertNodesBefore(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertDeclarationsBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If End Function Private Function InsertDeclarationsBeforeInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If Dim subDecls = Me.GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index > 0 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index, newDeclarations)) End If Return MyBase.InsertNodesBefore(root, fullDecl, newDeclarations) End Function Public Overrides Function InsertNodesAfter(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If End Function Private Function InsertNodesAfterInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If Dim subDecls = Me.GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index >= 0 AndAlso index < count - 1 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index + 1, newDeclarations)) End If Return MyBase.InsertNodesAfter(root, fullDecl, newDeclarations) End Function Private Function SplitAndInsert(multiPartDeclaration As SyntaxNode, subDeclarations As IReadOnlyList(Of SyntaxNode), index As Integer, newDeclarations As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode) Dim count = subDeclarations.Count Dim newNodes = New List(Of SyntaxNode)() newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) newNodes.AddRange(newDeclarations) newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) Return newNodes End Function ' replaces sub-declaration by splitting multi-part declaration first Private Function ReplaceSubDeclaration(root As SyntaxNode, declaration As SyntaxNode, index As Integer, newDeclaration As SyntaxNode) As SyntaxNode Dim newNodes = New List(Of SyntaxNode)() Dim count = GetDeclarationCount(declaration) If index >= 0 AndAlso index < count Then If (index > 0) Then ' make a single declaration with only the sub-declarations before the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) End If newNodes.Add(newDeclaration) If (index < count - 1) Then ' make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) End If ' replace declaration with multiple declarations Return ReplaceRange(root, declaration, newNodes) Else Return root End If End Function Private Function WithSubDeclarationsRemoved(declaration As SyntaxNode, index As Integer, count As Integer) As SyntaxNode Return Me.RemoveNodes(declaration, Me.GetSubDeclarations(declaration).Skip(index).Take(count)) End Function Private Function GetSubDeclarations(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Declarators.SelectMany(Function(d) d.Names).ToImmutableReadOnlyListOrEmpty() Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Declarators.SelectMany(Function(d) d.Names).ToImmutableReadOnlyListOrEmpty() Case SyntaxKind.AttributeList Return DirectCast(declaration, AttributeListSyntax).Attributes Case SyntaxKind.ImportsStatement Return DirectCast(declaration, ImportsStatementSyntax).ImportsClauses Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Private Function Flatten(members As IReadOnlyList(Of SyntaxNode)) As IReadOnlyList(Of SyntaxNode) If members.Count = 0 OrElse Not members.Any(Function(m) GetDeclarationCount(m) > 1) Then Return members End If Dim list = New List(Of SyntaxNode) Flatten(members, list) Return list.ToImmutableReadOnlyListOrEmpty() End Function Private Sub Flatten(members As IReadOnlyList(Of SyntaxNode), list As List(Of SyntaxNode)) For Each m In members If GetDeclarationCount(m) > 1 Then Select Case m.Kind Case SyntaxKind.FieldDeclaration Flatten(DirectCast(m, FieldDeclarationSyntax).Declarators, list) Case SyntaxKind.LocalDeclarationStatement Flatten(DirectCast(m, LocalDeclarationStatementSyntax).Declarators, list) Case SyntaxKind.VariableDeclarator Flatten(DirectCast(m, VariableDeclaratorSyntax).Names, list) Case SyntaxKind.AttributesStatement Flatten(DirectCast(m, AttributesStatementSyntax).AttributeLists, list) Case SyntaxKind.AttributeList Flatten(DirectCast(m, AttributeListSyntax).Attributes, list) Case SyntaxKind.ImportsStatement Flatten(DirectCast(m, ImportsStatementSyntax).ImportsClauses, list) Case Else list.Add(m) End Select Else list.Add(m) End If Next End Sub Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode) As SyntaxNode Return RemoveNode(root, declaration, DefaultRemoveOptions) End Function Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) Me.RemoveNodeInternal(r, r.GetCurrentNode(declaration), options)) Else Return MyBase.RemoveNode(root, declaration, options) End If End Function Private Function RemoveNodeInternal(root As SyntaxNode, node As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode ' special case handling for nodes that remove their parents too Select Case node.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(node.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing AndAlso vd.Names.Count = 1 Then ' remove entire variable declarator if only name Return RemoveNodeInternal(root, vd, options) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(node) AndAlso GetDeclarationCount(node.Parent) = 1 Then ' remove entire parent declaration if this is the only declarator Return RemoveNodeInternal(root, node.Parent, options) End If Case SyntaxKind.AttributeList Dim attrList = DirectCast(node, AttributeListSyntax) Dim attrStmt = TryCast(attrList.Parent, AttributesStatementSyntax) If attrStmt IsNot Nothing AndAlso attrStmt.AttributeLists.Count = 1 Then ' remove entire attribute statement if this is the only attribute list Return RemoveNodeInternal(root, attrStmt, options) End If Case SyntaxKind.Attribute Dim attrList = TryCast(node.Parent, AttributeListSyntax) If attrList IsNot Nothing AndAlso attrList.Attributes.Count = 1 Then ' remove entire attribute list if this is the only attribute Return RemoveNodeInternal(root, attrList, options) End If Case SyntaxKind.SimpleArgument If IsChildOf(node, SyntaxKind.ArgumentList) AndAlso IsChildOf(node.Parent, SyntaxKind.Attribute) Then Dim argList = DirectCast(node.Parent, ArgumentListSyntax) If argList.Arguments.Count = 1 Then ' remove attribute's arg list if this is the only argument Return RemoveNodeInternal(root, argList, options) End If End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim imps = DirectCast(node.Parent, ImportsStatementSyntax) If imps.ImportsClauses.Count = 1 Then ' remove entire imports statement if this is the only clause Return RemoveNodeInternal(root, node.Parent, options) End If Case Else Dim parent = node.Parent If parent IsNot Nothing Then Select Case parent.Kind Case SyntaxKind.ImplementsStatement Dim imp = DirectCast(parent, ImplementsStatementSyntax) If imp.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If Case SyntaxKind.InheritsStatement Dim inh = DirectCast(parent, InheritsStatementSyntax) If inh.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If End Select End If End Select ' do it the normal way Return root.RemoveNode(node, options) End Function Friend Overrides Function IdentifierName(identifier As SyntaxToken) As SyntaxNode Return SyntaxFactory.IdentifierName(identifier) End Function Friend Overrides Function Identifier(text As String) As SyntaxToken Return SyntaxFactory.Identifier(text) End Function Friend Overrides Function NamedAnonymousObjectMemberDeclarator(identifier As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NamedFieldInitializer( DirectCast(identifier, IdentifierNameSyntax), DirectCast(expression, ExpressionSyntax)) End Function Friend Overrides Function IsRegularOrDocComment(trivia As SyntaxTrivia) As Boolean Return trivia.IsRegularOrDocComment() End Function #End Region End Class End Namespace
Imports System.IO Imports System Imports Aspose.Pdf Namespace AsposePdfGenerator.Hyperlinks Public Class HyperlinkNonPdfFile Public Shared Sub Run() ' ExStart:HyperlinkNonPdfFile ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir_AsposePdfGenerator_Hyperlinks() ' Instantiate Pdf document object Dim pdf1 As New Aspose.Pdf.Generator.Pdf() ' Create a section in the Pdf Dim sec1 As Aspose.Pdf.Generator.Section = pdf1.Sections.Add() ' Create text paragraph with the reference of a section Dim text1 As New Aspose.Pdf.Generator.Text(sec1) ' Add the text paragraph in the paragraphs collection of the section sec1.Paragraphs.Add(text1) ' Add a text segment in the text paragraph Dim segment1 As Aspose.Pdf.Generator.Segment = text1.Segments.Add("this is a external file link") ' Assign a new instance of hyperlink to hyperlink property of segment segment1.Hyperlink = New Aspose.Pdf.Generator.Hyperlink() ' Set the link type of the text segment to File segment1.Hyperlink.LinkType = Aspose.Pdf.Generator.HyperlinkType.File ' Set the path of the external Non-Pdf file segment1.Hyperlink.LinkFile = dataDir & Convert.ToString("aspose-logo.jpg") dataDir = dataDir & Convert.ToString("HyperlinkNonPdfFile_out_.pdf") ' Save the Pdf pdf1.Save(dataDir) ' ExEnd:HyperlinkNonPdfFile End Sub End Class End Namespace
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class startfromhere Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.Label3 = New System.Windows.Forms.Label Me.Label2 = New System.Windows.Forms.Label Me.Label1 = New System.Windows.Forms.Label Me.Label4 = New System.Windows.Forms.Label Me.SuspendLayout() ' 'Label3 ' Me.Label3.AccessibleRole = System.Windows.Forms.AccessibleRole.None Me.Label3.AutoEllipsis = True Me.Label3.BackColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(28, Byte), Integer), CType(CType(128, Byte), Integer), CType(CType(250, Byte), Integer)) Me.Label3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.Label3.CausesValidation = False Me.Label3.Font = New System.Drawing.Font("Calibri", 11.25!) Me.Label3.Location = New System.Drawing.Point(12, 205) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(382, 23) Me.Label3.TabIndex = 3 Me.Label3.Text = "Loading..." Me.Label3.TextAlign = System.Drawing.ContentAlignment.TopCenter ' 'Label2 ' Me.Label2.BackColor = System.Drawing.Color.FromArgb(CType(CType(60, Byte), Integer), CType(CType(120, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.Label2.Location = New System.Drawing.Point(9, 205) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(15, 23) Me.Label2.TabIndex = 4 ' 'Label1 ' Me.Label1.AccessibleRole = System.Windows.Forms.AccessibleRole.None Me.Label1.AutoEllipsis = True Me.Label1.BackColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Label1.CausesValidation = False Me.Label1.Font = New System.Drawing.Font("Calibri", 11.25!) Me.Label1.ForeColor = System.Drawing.Color.Black Me.Label1.Location = New System.Drawing.Point(131, 182) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(263, 23) Me.Label1.TabIndex = 5 Me.Label1.Text = "Loading..." Me.Label1.TextAlign = System.Drawing.ContentAlignment.TopCenter ' 'Label4 ' Me.Label4.AccessibleRole = System.Windows.Forms.AccessibleRole.None Me.Label4.AutoEllipsis = True Me.Label4.BackColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Label4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.Label4.CausesValidation = False Me.Label4.Font = New System.Drawing.Font("Calibri", 11.25!) Me.Label4.Location = New System.Drawing.Point(-53, -27) Me.Label4.Name = "Label4" Me.Label4.Size = New System.Drawing.Size(476, 266) Me.Label4.TabIndex = 6 Me.Label4.Text = "Loading..." Me.Label4.TextAlign = System.Drawing.ContentAlignment.TopCenter ' 'startfromhere ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.Black Me.BackgroundImage = Global.Car_Load.My.Resources.Resources.car_load Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.ClientSize = New System.Drawing.Size(420, 248) Me.Controls.Add(Me.Label1) Me.Controls.Add(Me.Label2) Me.Controls.Add(Me.Label3) Me.Controls.Add(Me.Label4) Me.ForeColor = System.Drawing.Color.White Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "startfromhere" Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "startfromhere" Me.TopMost = True Me.ResumeLayout(False) End Sub Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents Label4 As System.Windows.Forms.Label End Class
'------------------------------------------------------------------------------ ' <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 <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.PA_6_W_Weinert.My.MySettings Get Return Global.PA_6_W_Weinert.My.MySettings.Default End Get End Property End Module End Namespace
Module Module1 Interface IPorovnatelny(Of T) Function JeVacsiAko(P2 As T) As Boolean End Interface Interface IVypisatelny Function Vypis() As String End Interface Class Animal Implements IPorovnatelny(Of Animal), IComparable(Of Animal), IVypisatelny Private fVyska As Integer, fJmeno As String Public Sub New(Jmeno As String, Vyska As Integer) fVyska = Vyska : fJmeno = Jmeno End Sub Public Function JeVacsiAko(P2 As Animal) As Boolean Implements IPorovnatelny(Of Animal).JeVacsiAko Return fVyska > P2.Vyska End Function #Region "Properties" Public Property Vyska As Integer Get Return fVyska End Get Set(value As Integer) fVyska = value End Set End Property Public Property Jmeno As String Get Return fJmeno End Get Set(value As String) fJmeno = value End Set End Property #End Region Public Function CompareTo(other As Animal) As Integer Implements System.IComparable(Of Animal).CompareTo If fVyska > other.Vyska Then Return -1 ElseIf fVyska < other.Vyska Then Return 1 Else Return 0 End If End Function Public Overrides Function ToString() As String Return Jmeno & " " & fVyska.ToString() End Function Public Function Vypis() As String Implements IVypisatelny.Vypis Return fVyska.ToString() End Function End Class Class Zoznam(Of T As {IPorovnatelny(Of T), IComparable(Of T), IVypisatelny}) Dim Pole(1) As T Dim TmpPole As T() Dim I As Integer = 0 : Dim Tmp As T Public Sub Add(H As T) If I = Pole.Length Then TmpPole = New T(Pole.Length * 2) {} For Index As Integer = 0 To Pole.Length - 1 TmpPole(Index) = Pole(Index) Next Pole = TmpPole : TmpPole = Nothing End If Pole(I) = H I += 1 End Sub Public Sub Swap(ByRef P1 As T, ByRef P2 As T) Tmp = P1 : P1 = P2 : P2 = Tmp End Sub Public Sub Sort() 'BubbleSort ' JePrvyVacsiPrvky(o1 as T, o2 as T) == > For J As Integer = 0 To I - 2 For K As Integer = 0 To I - 2 If Pole(K).JeVacsiAko(Pole(K + 1)) Then Swap(Pole(K), Pole(K + 1)) End If Next Next End Sub Public Sub Vypis() For Index As Integer = 0 To I - 1 Console.WriteLine(Pole(Index).Vypis) Next Dim L As List(Of String) End Sub End Class Sub Main() Dim S As New Zoznam(Of Animal) S.Add(New Animal("zirafa", 5103)) : S.Add(New Animal("slon", 2817)) S.Add(New Animal("tiger", 1200)) : S.Add(New Animal("opica", 251)) S.Sort() S.Vypis() Console.ReadLine() End Sub End Module
Public Class Sea '########################################################################################################### 'Attributes Public Const generation As Boolean = True Public Const matter As Boolean = True Public Const form As Boolean = True Public Const type_universe As String = "F.U.W.E" 'Finite Universe Without Edge '########################################################################################################### 'Construct Public Sub New() Console.WriteLine("Instancia de Sea, realizada correctamente") End Sub '########################################################################################################### 'Methods 'Generator Public Sub Sea_Generator() If ((generation = True) And (form = True) And (matter = True) And (type_universe = "F.U.W.E")) Then 'Sea Properties Marine_Rescue.pan_sea.Visible = True End If End Sub End Class
'------------------------------------------------------------------------------ ' <auto-generated> ' Dieser Code wurde von einem Tool generiert. ' Laufzeitversion: 4.0.30319.42000 ' ' Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn ' der Code erneut generiert wird. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "Funktion zum automatischen Speichern von My.Settings" #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.HVIFControl.My.MySettings Get Return Global.HVIFControl.My.MySettings.Default End Get End Property End Module End Namespace
Namespace DataElements Friend Class I47 Inherits StringElement Friend Sub New() MyBase.New(1, 8) End Sub End Class End Namespace
Namespace Configuration Public Class TimeSpanConvertor #Region " Public Constants " Public Shared TIMESPAN_SUFFIXES As Char() = _ New Char() {"s", "e", "c", "m", "i", "n", "h", "o", "u", "r", "d", "a", "y", "t"} Public Shared TIMESPAN_DAY As String = "day" Public Shared TIMESPAN_DAYS As String = TIMESPAN_DAY & "s" Public Shared TIMESPAN_DAY_SHORT As String = "d" Public Shared TIMESPAN_HOUR As String = "hour" Public Shared TIMESPAN_HOURS As String = TIMESPAN_HOUR & "s" Public Shared TIMESPAN_HOUR_SHORT As String = "h" Public Shared TIMESPAN_MIN As String = "min" Public Shared TIMESPAN_MINS As String = TIMESPAN_MIN & "s" Public Shared TIMESPAN_MINUTE As String = "minute" Public Shared TIMESPAN_MINUTES As String = TIMESPAN_MINUTE & "s" Public Shared TIMESPAN_MINUTE_SHORT As String = "m" Public Shared TIMESPAN_SEC As String = "sec" Public Shared TIMESPAN_SECS As String = TIMESPAN_SEC & "s" Public Shared TIMESPAN_SECOND As String = "second" Public Shared TIMESPAN_SECONDS As String = TIMESPAN_SECOND & "s" Public Shared TIMESPAN_SECOND_SHORT As String = "s" Public Shared TIMESPAN_MS As String = "msec" Public Shared TIMESPAN_MSS As String = TIMESPAN_MS & "s" Public Shared TIMESPAN_MILLISECOND As String = "millisecond" Public Shared TIMESPAN_MILLISECONDS As String = TIMESPAN_MILLISECOND & "s" Public Shared TIMESPAN_MILLISECOND_SHORT As String = "ms" Public Shared TIMESPAN_TICK As String = "tick" Public Shared TIMESPAN_TICKS As String = TIMESPAN_TICK & "s" Public Shared TIMESPAN_TICK_SHORT As String = "t" #End Region #Region " Public Parsing Methods " ''' <summary> ''' Public Parsing Method. ''' </summary> ''' <param name="value">The Value to Parse.</param> ''' <param name="successfulParse">A ByRef/Out Parameter used to indicate whether the Parse was successful or not.</param> ''' <returns>The Parsed Object or Nothing.</returns> ''' <remarks>This method can only currently parse simple timespans.</remarks> Public Function ParseTimeSpanFromString( _ <ParsingInParameterAttribute()> ByVal value As String, _ <ParsingSuccessParameter()> ByRef successfulParse As Boolean, _ <ParsingTypeParameter()> ByVal typeToParseTo As Type _ ) As Object Dim ret_TimeSpan As TimeSpan If value.EndsWith(TIMESPAN_SEC) OrElse _ value.EndsWith(TIMESPAN_SECS) OrElse _ value.EndsWith(TIMESPAN_SECOND) OrElse _ value.EndsWith(TIMESPAN_SECONDS) Then ret_TimeSpan = New TimeSpan(0, 0, 0, _ Integer.Parse(value.TrimEnd(TIMESPAN_SUFFIXES), _ System.Globalization.CultureInfo.InvariantCulture)) successfulParse = True ElseIf value.EndsWith(TIMESPAN_MIN) OrElse _ value.EndsWith(TIMESPAN_MINS) OrElse _ value.EndsWith(TIMESPAN_MINUTE) OrElse _ value.EndsWith(TIMESPAN_MINUTES) OrElse _ value.EndsWith(TIMESPAN_MINUTE_SHORT) Then ret_TimeSpan = New TimeSpan(0, 0, _ Integer.Parse(value.TrimEnd(TIMESPAN_SUFFIXES), _ System.Globalization.CultureInfo.InvariantCulture), 0) successfulParse = True ElseIf value.EndsWith(TIMESPAN_HOUR) OrElse _ value.EndsWith(TIMESPAN_HOURS) OrElse _ value.EndsWith(TIMESPAN_HOUR_SHORT) Then ret_TimeSpan = New TimeSpan(0, _ Integer.Parse(value.TrimEnd(TIMESPAN_SUFFIXES), _ System.Globalization.CultureInfo.InvariantCulture), 0, 0) successfulParse = True ElseIf value.EndsWith(TIMESPAN_DAY) OrElse _ value.EndsWith(TIMESPAN_DAYS) OrElse _ value.EndsWith(TIMESPAN_DAY_SHORT) Then ret_TimeSpan = New TimeSpan( _ Integer.Parse(value.TrimEnd(TIMESPAN_SUFFIXES), _ System.Globalization.CultureInfo.InvariantCulture), 0, 0, 0) successfulParse = True End If Return ret_TimeSpan End Function ''' <summary> ''' Public Method Handling the Parsing of a Colour. ''' </summary> ''' <param name="value">The Colour Value to Parse.</param> ''' <param name="successfulParse">A ByRef/Out Parameter used to indicate whether the Parse was successful or not.</param> ''' <returns>The Parsed Object or Nothing.</returns> ''' <remarks></remarks> Public Function ParseStringFromTimespan( _ <ParsingInParameterAttribute()> ByVal value As TimeSpan, _ <ParsingSuccessParameter()> ByRef successfulParse As Boolean, _ Optional ByVal shortFormat As Boolean = False _ ) As String If Not value = Nothing Then Dim hasParent As Boolean = False Dim strBuilder As New System.Text.StringBuilder If Not value.Days = 0 Then hasParent = True strBuilder.Append(value.Days) If Not shortFormat Then strBuilder.Append(SPACE) If shortFormat Then strBuilder.Append(TIMESPAN_DAY_SHORT) ElseIf value.Days > 1 OrElse value.Days < -1 Then strBuilder.Append(TIMESPAN_DAYS) Else strBuilder.Append(TIMESPAN_DAY) End If End If If Not value.Hours = 0 Then If hasParent Then strBuilder.Append(COMMA) strBuilder.Append(SPACE) End If hasParent = True strBuilder.Append(value.Hours) If Not shortFormat Then strBuilder.Append(SPACE) If shortFormat Then strBuilder.Append(TIMESPAN_HOUR_SHORT) ElseIf value.Hours > 1 OrElse value.Hours < -1 Then strBuilder.Append(TIMESPAN_HOURS) Else strBuilder.Append(TIMESPAN_HOUR) End If End If If Not value.Minutes = 0 Then If hasParent Then strBuilder.Append(COMMA) strBuilder.Append(SPACE) End If hasParent = True strBuilder.Append(value.Minutes) If Not shortFormat Then strBuilder.Append(SPACE) If shortFormat Then strBuilder.Append(TIMESPAN_MINUTE_SHORT) ElseIf value.Minutes > 1 OrElse value.Minutes < -1 Then strBuilder.Append(TIMESPAN_MINS) Else strBuilder.Append(TIMESPAN_MIN) End If End If If Not value.Seconds = 0 Then If hasParent Then strBuilder.Append(COMMA) strBuilder.Append(SPACE) End If hasParent = True strBuilder.Append(value.Seconds) If Not shortFormat Then strBuilder.Append(SPACE) If shortFormat Then strBuilder.Append(TIMESPAN_SECOND_SHORT) ElseIf value.Seconds > 1 OrElse value.Seconds < -1 Then strBuilder.Append(TIMESPAN_SECS) Else strBuilder.Append(TIMESPAN_SEC) End If End If If value.Days = 0 _ AndAlso value.Hours = 0 _ AndAlso value.Minutes = 0 _ AndAlso value.Seconds < 60 _ AndAlso value.Milliseconds > 0 Then If hasParent Then strBuilder.Append(COMMA) strBuilder.Append(SPACE) End If hasParent = True strBuilder.Append(value.Milliseconds) If Not shortFormat Then strBuilder.Append(SPACE) If shortFormat Then strBuilder.Append(TIMESPAN_MILLISECOND_SHORT) ElseIf value.Milliseconds > 1 OrElse value.Milliseconds < -1 Then strBuilder.Append(TIMESPAN_MSS) Else strBuilder.Append(TIMESPAN_MS) End If End If If value.Days = 0 _ AndAlso value.Hours = 0 _ AndAlso value.Minutes = 0 _ AndAlso value.Seconds = 0 _ AndAlso value.Milliseconds < 10 Then If hasParent Then strBuilder.Append(COMMA) strBuilder.Append(SPACE) End If hasParent = True strBuilder.Append(value.Ticks) If Not shortFormat Then strBuilder.Append(SPACE) If shortFormat Then strBuilder.Append(TIMESPAN_TICK_SHORT) ElseIf value.Ticks > 1 OrElse value.Ticks < -1 Then strBuilder.Append(TIMESPAN_TICKS) Else strBuilder.Append(TIMESPAN_TICK) End If End If successfulParse = True Return strBuilder.ToString Else successfulParse = False Return String.Empty End If End Function #End Region End Class End Namespace
Imports System Module plus_petit Dim eof As Boolean Dim buffer As String Function readChar_() As Char If buffer Is Nothing OrElse buffer.Length = 0 Then Dim tmp As String = Console.ReadLine() eof = (tmp Is Nothing) buffer = tmp + Chr(10) End If Return buffer(0) End Function Sub consommeChar() readChar_() buffer = buffer.Substring(1) End Sub Sub stdin_sep() Do If eof Then Return End If Dim c As Char = readChar_() If c = " "C Or c = Chr(13) Or c = Chr(9) Or c = Chr(10) Then consommeChar() Else Return End If Loop End Sub Function readInt() As Integer Dim i As Integer = 0 Dim s as Char = readChar_() Dim sign As Integer = 1 If s = "-"C Then sign = -1 consommeChar() End If Do Dim c as Char = readChar_() If c <= "9"C And c >= "0"C Then i = i * 10 + Asc(c) - Asc("0"C) consommeChar() Else return i * sign End If Loop End Function Function go0(ByRef tab as Integer(), ByVal a as Integer, ByVal b as Integer) As Integer Dim m As Integer = (a + b) \ 2 If a = m Then If tab(a) = m Then Return b Else Return a End If End If Dim i As Integer = a Dim j As Integer = b Do While i < j Dim e As Integer = tab(i) If e < m Then i = i + 1 Else j = j - 1 tab(i) = tab(j) tab(j) = e End If Loop If i < m Then Return go0(tab, a, m) Else Return go0(tab, m, b) End If End Function Function plus_petit0(ByRef tab as Integer(), ByVal len as Integer) As Integer Return go0(tab, 0, len) End Function Sub Main() Dim len As Integer = 0 len = readInt stdin_sep Dim tab(len - 1) As Integer For i As Integer = 0 To len - 1 Dim tmp As Integer = 0 tmp = readInt stdin_sep tab(i) = tmp Next Console.Write(plus_petit0(tab, len)) End Sub End Module
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.TextTransitionZ.My.MySettings Get Return Global.TextTransitionZ.My.MySettings.Default End Get End Property End Module End Namespace
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A ExecutableCodeBinder provides context for looking up labels within a context represented by a syntax node, ''' and also implementation of GetBinder. ''' </summary> Friend MustInherit Class ExecutableCodeBinder Inherits Binder Private ReadOnly _syntaxRoot As SyntaxNode Private ReadOnly _descendantBinderFactory As DescendantBinderFactory Private _labelsMap As MultiDictionary(Of String, SourceLabelSymbol) Private _labels As ImmutableArray(Of SourceLabelSymbol) = Nothing Public Sub New(root As SyntaxNode, containingBinder As Binder) MyBase.New(containingBinder) _syntaxRoot = root _descendantBinderFactory = New DescendantBinderFactory(Me, root) End Sub Friend ReadOnly Property Labels As ImmutableArray(Of SourceLabelSymbol) Get If _labels.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange(_labels, BuildLabels(), Nothing) End If Return _labels End Get End Property ' Build a read only array of all the local variables declared in this statement list. Private Function BuildLabels() As ImmutableArray(Of SourceLabelSymbol) Dim labels = ArrayBuilder(Of SourceLabelSymbol).GetInstance() Dim syntaxVisitor = New LabelVisitor(labels, DirectCast(ContainingMember, MethodSymbol), Me) Select Case _syntaxRoot.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression syntaxVisitor.Visit(DirectCast(_syntaxRoot, SingleLineLambdaExpressionSyntax).Body) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression syntaxVisitor.VisitList(DirectCast(_syntaxRoot, MultiLineLambdaExpressionSyntax).Statements) Case Else syntaxVisitor.Visit(_syntaxRoot) End Select If labels.Count > 0 Then Return labels.ToImmutableAndFree() Else labels.Free() Return ImmutableArray(Of SourceLabelSymbol).Empty End If End Function Private ReadOnly Property LabelsMap As MultiDictionary(Of String, SourceLabelSymbol) Get If Me._labelsMap Is Nothing Then Interlocked.CompareExchange(Me._labelsMap, BuildLabelsMap(Me.Labels), Nothing) End If Return Me._labelsMap End Get End Property Private Shared ReadOnly s_emptyLabelMap As MultiDictionary(Of String, SourceLabelSymbol) = New MultiDictionary(Of String, SourceLabelSymbol)(0, IdentifierComparison.Comparer) Private Shared Function BuildLabelsMap(labels As ImmutableArray(Of SourceLabelSymbol)) As MultiDictionary(Of String, SourceLabelSymbol) If Not labels.IsEmpty Then Dim map = New MultiDictionary(Of String, SourceLabelSymbol)(labels.Length, IdentifierComparison.Comparer) For Each label In labels map.Add(label.Name, label) Next Return map Else ' Return an empty map if there aren't any labels. ' LookupLabelByNameToken and other methods assumes a non null map ' is returned from the LabelMap property. Return s_emptyLabelMap End If End Function Friend Overrides Function LookupLabelByNameToken(labelName As SyntaxToken) As LabelSymbol Dim name As String = labelName.ValueText For Each labelSymbol As LabelSymbol In Me.LabelsMap(name) If labelSymbol.LabelName = labelName Then Return labelSymbol End If Next Return MyBase.LookupLabelByNameToken(labelName) End Function Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(lookupResult.IsClear) If (options And LookupOptions.LabelsOnly) = LookupOptions.LabelsOnly AndAlso LabelsMap IsNot Nothing Then Dim labels = Me.LabelsMap(name) Select Case labels.Count Case 0 ' Not found Case 1 lookupResult.SetFrom(SingleLookupResult.Good(labels.Single())) Case Else ' There are several labels with the same name, so we are going through the list ' of labels and pick one with the smallest location to make the choice deterministic Dim bestSymbol As SourceLabelSymbol = Nothing Dim bestLocation As Location = Nothing For Each symbol In labels Debug.Assert(symbol.Locations.Length = 1) Dim sourceLocation As Location = symbol.Locations(0) If bestSymbol Is Nothing OrElse Me.Compilation.CompareSourceLocations(bestLocation, sourceLocation) > 0 Then bestSymbol = symbol bestLocation = sourceLocation End If Next lookupResult.SetFrom(SingleLookupResult.Good(bestSymbol)) End Select End If End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) ' UNDONE: additional filtering based on options? If Not Labels.IsEmpty AndAlso (options And LookupOptions.LabelsOnly) = LookupOptions.LabelsOnly Then Dim labels = Me.Labels For Each labelSymbol In labels nameSet.AddSymbol(labelSymbol, labelSymbol.Name, 0) Next End If End Sub Public Overrides Function GetBinder(stmtList As SyntaxList(Of StatementSyntax)) As Binder Return _descendantBinderFactory.GetBinder(stmtList) End Function Public Overrides Function GetBinder(node As SyntaxNode) As Binder Return _descendantBinderFactory.GetBinder(node) End Function Public ReadOnly Property Root As SyntaxNode Get Return _descendantBinderFactory.Root End Get End Property ' Get the map that maps from syntax nodes to binders. Public ReadOnly Property NodeToBinderMap As ImmutableDictionary(Of SyntaxNode, BlockBaseBinder) Get Return _descendantBinderFactory.NodeToBinderMap End Get End Property ' Get the map that maps from statement lists to binders. Friend ReadOnly Property StmtListToBinderMap As ImmutableDictionary(Of SyntaxList(Of StatementSyntax), BlockBaseBinder) Get Return _descendantBinderFactory.StmtListToBinderMap End Get End Property #If DEBUG Then ' Implicit variable declaration (Option Explicit Off) relies on identifiers ' being bound in order. Also, most of our tests run with Option Explicit On. To test that ' we bind identifiers in order even with Option Explicit On, in DEBUG we check the order or ' binding of simple names when compiling a whole method body (i.e., during batch compilation, ' not SemanticModel services). ' ' We check lambda separately from method bodies (even though in theory they should be checked ' together) because there are cases where lambda are bound out of order. ' ' See SourceMethodSymbol.GetBoundMethodBody for where this is enabled. ' ' See BindSimpleName for where CheckSimpleNameBinderOrder is called. ' We just store the positions of simple names that have been checked. Private _checkSimpleNameBindingOrder As Boolean = False ' The set of offsets of simple names that have already been bound. Private _boundSimpleNames As HashSet(Of Integer) ' The largest position that has been bound. Private _lastBoundSimpleName As Integer = -1 Public Overrides Sub CheckSimpleNameBindingOrder(node As SimpleNameSyntax) If _checkSimpleNameBindingOrder Then Dim position = node.SpanStart ' There are cases where we bind the same name multiple times -- for example, For loop ' variables, and debug checks with local type inference. Hence we only check the first time we ' see a simple name. If Not _boundSimpleNames.Contains(position) Then ' If this assert fires, it indicates that simple names are not being bound in order. ' This indicates that binding with Option Explicit Off likely will exhibit a bug. Debug.Assert(position >= _lastBoundSimpleName, "Did not bind simple names in order. Option Explicit Off probably will not behave correctly.") _boundSimpleNames.Add(position) _lastBoundSimpleName = Math.Max(_lastBoundSimpleName, position) End If End If End Sub ' We require simple name binding order checks to be enabled, because the SemanticModel APIs ' will bind things not in order. We only enable them during binding of a full method body or lambda body. Public Overrides Sub EnableSimpleNameBindingOrderChecks(enable As Boolean) If enable Then Debug.Assert(Not _checkSimpleNameBindingOrder) Debug.Assert(_boundSimpleNames Is Nothing) _boundSimpleNames = New HashSet(Of Integer) _checkSimpleNameBindingOrder = True Else _boundSimpleNames = Nothing _checkSimpleNameBindingOrder = False End If End Sub #End If Public Class LabelVisitor Inherits StatementSyntaxWalker Private ReadOnly _labels As ArrayBuilder(Of SourceLabelSymbol) Private ReadOnly _containingMethod As MethodSymbol Private ReadOnly _binder As Binder Public Sub New(labels As ArrayBuilder(Of SourceLabelSymbol), containingMethod As MethodSymbol, binder As Binder) Me._labels = labels Me._containingMethod = containingMethod Me._binder = binder End Sub Public Overrides Sub VisitLabelStatement(node As LabelStatementSyntax) _labels.Add(New SourceLabelSymbol(node.LabelToken, _containingMethod, _binder)) End Sub End Class End Class End Namespace
Imports System.Resources Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("Age of Empires III Profile Generator")> <Assembly: AssemblyDescription("Age of Empires III Profile Generator")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("Age of Empires III Profile Generator")> <Assembly: AssemblyCopyright("")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("bfb2116a-8118-42f2-88f5-881d634ecfd8")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")> <Assembly: NeutralResourcesLanguageAttribute("en-GB")>
Namespace Xeora.VSAddIn.Tools <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class CompilerForm 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) If disposing AndAlso components IsNot Nothing Then components.Dispose() End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Dim DataGridViewCellStyle4 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle5 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle6 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Me.cbShowPassword = New System.Windows.Forms.CheckBox() Me.ProgressBar = New System.Windows.Forms.ProgressBar() Me.butCompile = New System.Windows.Forms.Button() Me.dgvDomains = New System.Windows.Forms.DataGridView() Me.Selected = New System.Windows.Forms.DataGridViewCheckBoxColumn() Me.Domain = New System.Windows.Forms.DataGridViewTextBoxColumn() Me.cbSecure = New System.Windows.Forms.DataGridViewCheckBoxColumn() Me.PasswordText = New System.Windows.Forms.DataGridViewTextBoxColumn() Me.PasswordHidden = New System.Windows.Forms.DataGridViewTextBoxColumn() Me.lCurrentProcess = New System.Windows.Forms.Label() Me.cbCheckAll = New System.Windows.Forms.CheckBox() CType(Me.dgvDomains, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'cbShowPassword ' Me.cbShowPassword.AutoSize = True Me.cbShowPassword.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(162, Byte)) Me.cbShowPassword.Location = New System.Drawing.Point(23, 381) Me.cbShowPassword.Margin = New System.Windows.Forms.Padding(6) Me.cbShowPassword.Name = "cbShowPassword" Me.cbShowPassword.Size = New System.Drawing.Size(219, 33) Me.cbShowPassword.TabIndex = 6 Me.cbShowPassword.Text = "Show Password" Me.cbShowPassword.UseVisualStyleBackColor = True Me.cbShowPassword.Visible = False ' 'ProgressBar ' Me.ProgressBar.Location = New System.Drawing.Point(77, 380) Me.ProgressBar.Margin = New System.Windows.Forms.Padding(6) Me.ProgressBar.Name = "ProgressBar" Me.ProgressBar.Size = New System.Drawing.Size(715, 35) Me.ProgressBar.TabIndex = 7 ' 'butCompile ' Me.butCompile.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(162, Byte)) Me.butCompile.Location = New System.Drawing.Point(804, 374) Me.butCompile.Margin = New System.Windows.Forms.Padding(6) Me.butCompile.Name = "butCompile" Me.butCompile.Size = New System.Drawing.Size(150, 44) Me.butCompile.TabIndex = 3 Me.butCompile.Text = "Compile" Me.butCompile.UseVisualStyleBackColor = True ' 'dgvDomains ' Me.dgvDomains.AllowUserToAddRows = False Me.dgvDomains.AllowUserToDeleteRows = False Me.dgvDomains.AllowUserToResizeRows = False Me.dgvDomains.ClipboardCopyMode = System.Windows.Forms.DataGridViewClipboardCopyMode.Disable DataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Control DataGridViewCellStyle4.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(162, Byte)) DataGridViewCellStyle4.ForeColor = System.Drawing.SystemColors.WindowText DataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvDomains.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle4 Me.dgvDomains.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize Me.dgvDomains.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.Selected, Me.Domain, Me.cbSecure, Me.PasswordText, Me.PasswordHidden}) Me.dgvDomains.Location = New System.Drawing.Point(23, 22) Me.dgvDomains.MultiSelect = False Me.dgvDomains.Name = "dgvDomains" DataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle5.BackColor = System.Drawing.SystemColors.Control DataGridViewCellStyle5.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.875!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(162, Byte)) DataGridViewCellStyle5.ForeColor = System.Drawing.SystemColors.WindowText DataGridViewCellStyle5.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle5.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvDomains.RowHeadersDefaultCellStyle = DataGridViewCellStyle5 DataGridViewCellStyle6.BackColor = System.Drawing.Color.White DataGridViewCellStyle6.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.875!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(162, Byte)) DataGridViewCellStyle6.ForeColor = System.Drawing.Color.Black DataGridViewCellStyle6.SelectionBackColor = System.Drawing.Color.White DataGridViewCellStyle6.SelectionForeColor = System.Drawing.Color.Black Me.dgvDomains.RowsDefaultCellStyle = DataGridViewCellStyle6 Me.dgvDomains.RowTemplate.Height = 50 Me.dgvDomains.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect Me.dgvDomains.Size = New System.Drawing.Size(931, 344) Me.dgvDomains.TabIndex = 0 ' 'Selected ' Me.Selected.FalseValue = "0" Me.Selected.HeaderText = "" Me.Selected.Name = "Selected" Me.Selected.Resizable = System.Windows.Forms.DataGridViewTriState.[False] Me.Selected.TrueValue = "1" Me.Selected.Width = 50 ' 'Domain ' Me.Domain.HeaderText = "Domain ID" Me.Domain.Name = "Domain" Me.Domain.ReadOnly = True Me.Domain.Resizable = System.Windows.Forms.DataGridViewTriState.[False] Me.Domain.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable Me.Domain.Width = 250 ' 'cbSecure ' Me.cbSecure.FalseValue = "0" Me.cbSecure.HeaderText = "Secure" Me.cbSecure.Name = "cbSecure" Me.cbSecure.Resizable = System.Windows.Forms.DataGridViewTriState.[False] Me.cbSecure.TrueValue = "1" Me.cbSecure.Width = 120 ' 'PasswordText ' Me.PasswordText.HeaderText = "Password" Me.PasswordText.MaxInputLength = 50 Me.PasswordText.Name = "PasswordText" Me.PasswordText.Resizable = System.Windows.Forms.DataGridViewTriState.[False] Me.PasswordText.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable Me.PasswordText.Width = 400 ' 'PasswordHidden ' Me.PasswordHidden.HeaderText = "" Me.PasswordHidden.Name = "PasswordHidden" Me.PasswordHidden.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable Me.PasswordHidden.Visible = False ' 'lCurrentProcess ' Me.lCurrentProcess.AutoSize = True Me.lCurrentProcess.Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(162, Byte)) Me.lCurrentProcess.Location = New System.Drawing.Point(17, 378) Me.lCurrentProcess.Name = "lCurrentProcess" Me.lCurrentProcess.Size = New System.Drawing.Size(33, 36) Me.lCurrentProcess.TabIndex = 11 Me.lCurrentProcess.Text = "0" ' 'cbCheckAll ' Me.cbCheckAll.AutoSize = True Me.cbCheckAll.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(162, Byte)) Me.cbCheckAll.Location = New System.Drawing.Point(75, 33) Me.cbCheckAll.Margin = New System.Windows.Forms.Padding(6) Me.cbCheckAll.Name = "cbCheckAll" Me.cbCheckAll.Size = New System.Drawing.Size(28, 27) Me.cbCheckAll.TabIndex = 1 Me.cbCheckAll.UseVisualStyleBackColor = True ' 'CompilerForm ' Me.AcceptButton = Me.butCompile Me.AutoScaleDimensions = New System.Drawing.SizeF(12.0!, 25.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(978, 436) Me.Controls.Add(Me.cbCheckAll) Me.Controls.Add(Me.lCurrentProcess) Me.Controls.Add(Me.dgvDomains) Me.Controls.Add(Me.butCompile) Me.Controls.Add(Me.ProgressBar) Me.Controls.Add(Me.cbShowPassword) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle Me.Margin = New System.Windows.Forms.Padding(6) Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "CompilerForm" Me.ShowIcon = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "XeoraCube Domain Compiler" CType(Me.dgvDomains, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents cbShowPassword As System.Windows.Forms.CheckBox Friend WithEvents ProgressBar As System.Windows.Forms.ProgressBar Friend WithEvents butCompile As System.Windows.Forms.Button Friend WithEvents dgvDomains As DataGridView Friend WithEvents Selected As DataGridViewCheckBoxColumn Friend WithEvents Domain As DataGridViewTextBoxColumn Friend WithEvents cbSecure As DataGridViewCheckBoxColumn Friend WithEvents PasswordText As DataGridViewTextBoxColumn Friend WithEvents PasswordHidden As DataGridViewTextBoxColumn Friend WithEvents lCurrentProcess As Label Friend WithEvents cbCheckAll As CheckBox End Class End Namespace
' 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 Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.UseCollectionInitializer Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseCollectionInitializer <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseCollectionInitializer), [Shared]> Friend Class VisualBasicUseCollectionInitializerCodeFixProvider Inherits AbstractUseCollectionInitializerCodeFixProvider(Of SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, InvocationExpressionSyntax, ExpressionStatementSyntax, VariableDeclaratorSyntax) Protected Overrides Function GetNewStatement( statement As StatementSyntax, objectCreation As ObjectCreationExpressionSyntax, matches As ImmutableArray(Of ExpressionStatementSyntax)) As StatementSyntax Dim newStatement = statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)) Dim totalTrivia = ArrayBuilder(Of SyntaxTrivia).GetInstance() totalTrivia.AddRange(statement.GetLeadingTrivia()) totalTrivia.Add(SyntaxFactory.ElasticMarker) For Each match In matches For Each trivia In match.GetLeadingTrivia() If trivia.Kind = SyntaxKind.CommentTrivia Then totalTrivia.Add(trivia) totalTrivia.Add(SyntaxFactory.ElasticMarker) End If Next Next Return newStatement.WithLeadingTrivia(totalTrivia) End Function Private Function GetNewObjectCreation( objectCreation As ObjectCreationExpressionSyntax, matches As ImmutableArray(Of ExpressionStatementSyntax)) As ObjectCreationExpressionSyntax Dim initializer = SyntaxFactory.ObjectCollectionInitializer( CreateCollectionInitializer(matches)) If objectCreation.ArgumentList IsNot Nothing AndAlso objectCreation.ArgumentList.Arguments.Count = 0 Then objectCreation = objectCreation.WithType(objectCreation.Type.WithTrailingTrivia(objectCreation.ArgumentList.GetTrailingTrivia())). WithArgumentList(Nothing) End If Return objectCreation.WithoutTrailingTrivia(). WithInitializer(initializer). WithTrailingTrivia(objectCreation.GetTrailingTrivia()) End Function Private Function CreateCollectionInitializer( matches As ImmutableArray(Of ExpressionStatementSyntax)) As CollectionInitializerSyntax Dim nodesAndTokens = New List(Of SyntaxNodeOrToken) For i = 0 To matches.Length - 1 Dim expressionStatement = matches(i) Dim newExpression As ExpressionSyntax Dim invocationExpression = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax) Dim arguments = invocationExpression.ArgumentList.Arguments If arguments.Count = 1 Then newExpression = arguments(0).GetExpression() Else newExpression = SyntaxFactory.CollectionInitializer( SyntaxFactory.SeparatedList( arguments.Select(Function(a) a.GetExpression()), arguments.GetSeparators())) End If newExpression = newExpression.WithLeadingTrivia(SyntaxFactory.ElasticMarker) If i < matches.Length - 1 Then nodesAndTokens.Add(newExpression) Dim comma = SyntaxFactory.Token(SyntaxKind.CommaToken). WithTrailingTrivia(expressionStatement.GetTrailingTrivia()) nodesAndTokens.Add(comma) Else newExpression = newExpression.WithTrailingTrivia(expressionStatement.GetTrailingTrivia()) nodesAndTokens.Add(newExpression) End If Next Return SyntaxFactory.CollectionInitializer( SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed), SyntaxFactory.SeparatedList(Of ExpressionSyntax)(nodesAndTokens), SyntaxFactory.Token(SyntaxKind.CloseBraceToken)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.Serialization Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting <DataContract> Friend NotInheritable Class VisualBasicSyntaxFormattingOptions Inherits SyntaxFormattingOptions Implements IEquatable(Of VisualBasicSyntaxFormattingOptions) Public Shared ReadOnly [Default] As New VisualBasicSyntaxFormattingOptions() Public Shared Shadows Function Create(options As AnalyzerConfigOptions, fallbackOptions As VisualBasicSyntaxFormattingOptions) As VisualBasicSyntaxFormattingOptions fallbackOptions = If(fallbackOptions, [Default]) Return New VisualBasicSyntaxFormattingOptions() With { .Common = options.GetCommonSyntaxFormattingOptions(fallbackOptions.Common) } End Function Public Overrides Function [With](lineFormatting As LineFormattingOptions) As SyntaxFormattingOptions Return New VisualBasicSyntaxFormattingOptions() With { .Common = New CommonOptions() With { .LineFormatting = lineFormatting, .SeparateImportDirectiveGroups = SeparateImportDirectiveGroups, .AccessibilityModifiersRequired = AccessibilityModifiersRequired } } End Function Public Overrides Function Equals(obj As Object) As Boolean Return Equals(TryCast(obj, VisualBasicSyntaxFormattingOptions)) End Function Public Overloads Function Equals(other As VisualBasicSyntaxFormattingOptions) As Boolean Implements IEquatable(Of VisualBasicSyntaxFormattingOptions).Equals Return other IsNot Nothing AndAlso Common.Equals(other.Common) End Function Public Overrides Function GetHashCode() As Integer Return Common.GetHashCode() End Function End Class End Namespace
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Success 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(Success)) Me.DescriptionLabel = New System.Windows.Forms.Label() Me.CloseBtn = New System.Windows.Forms.Button() Me.TitleLabel = New System.Windows.Forms.Label() Me.BottomPanel = New System.Windows.Forms.Panel() Me.GenuineSoftwareLogo = New System.Windows.Forms.PictureBox() Me.BenefitsLinkLabel = New System.Windows.Forms.LinkLabel() Me.BottomPanel.SuspendLayout() CType(Me.GenuineSoftwareLogo, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'DescriptionLabel ' Me.DescriptionLabel.AutoSize = True Me.DescriptionLabel.Font = New System.Drawing.Font("Segoe UI", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.DescriptionLabel.Location = New System.Drawing.Point(32, 70) Me.DescriptionLabel.Name = "DescriptionLabel" Me.DescriptionLabel.Size = New System.Drawing.Size(391, 51) Me.DescriptionLabel.TabIndex = 1 Me.DescriptionLabel.Text = "Activation helps verify that your copy of Windows is genuine. With" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "a genuine cop" & "y of Windows 7, you are eligible to receive all" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "available updates and product s" & "upport from Microsoft." ' 'CloseBtn ' Me.CloseBtn.BackColor = System.Drawing.SystemColors.Control Me.CloseBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.CloseBtn.FlatStyle = System.Windows.Forms.FlatStyle.System Me.CloseBtn.Location = New System.Drawing.Point(530, 8) Me.CloseBtn.Name = "CloseBtn" Me.CloseBtn.Size = New System.Drawing.Size(75, 23) Me.CloseBtn.TabIndex = 0 Me.CloseBtn.Text = "Close" Me.CloseBtn.UseVisualStyleBackColor = True ' 'TitleLabel ' Me.TitleLabel.AutoSize = True Me.TitleLabel.Font = New System.Drawing.Font("Segoe UI", 12.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.TitleLabel.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(108, Byte), Integer), CType(CType(189, Byte), Integer)) Me.TitleLabel.Location = New System.Drawing.Point(32, 32) Me.TitleLabel.Name = "TitleLabel" Me.TitleLabel.Size = New System.Drawing.Size(199, 23) Me.TitleLabel.TabIndex = 0 Me.TitleLabel.Text = "Activation was successful" ' 'BottomPanel ' Me.BottomPanel.BackColor = System.Drawing.SystemColors.Control Me.BottomPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.BottomPanel.Controls.Add(Me.CloseBtn) Me.BottomPanel.Location = New System.Drawing.Point(-1, 472) Me.BottomPanel.Name = "BottomPanel" Me.BottomPanel.Size = New System.Drawing.Size(619, 42) Me.BottomPanel.TabIndex = 3 ' 'GenuineSoftwareLogo ' Me.GenuineSoftwareLogo.Image = CType(resources.GetObject("GenuineSoftwareLogo.Image"), System.Drawing.Image) Me.GenuineSoftwareLogo.Location = New System.Drawing.Point(465, 80) Me.GenuineSoftwareLogo.Name = "GenuineSoftwareLogo" Me.GenuineSoftwareLogo.Size = New System.Drawing.Size(112, 61) Me.GenuineSoftwareLogo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize Me.GenuineSoftwareLogo.TabIndex = 8 Me.GenuineSoftwareLogo.TabStop = False ' 'BenefitsLinkLabel ' Me.BenefitsLinkLabel.AutoSize = True Me.BenefitsLinkLabel.Font = New System.Drawing.Font("Segoe UI", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.BenefitsLinkLabel.LinkColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(126, Byte), Integer), CType(CType(220, Byte), Integer)) Me.BenefitsLinkLabel.Location = New System.Drawing.Point(32, 135) Me.BenefitsLinkLabel.Name = "BenefitsLinkLabel" Me.BenefitsLinkLabel.Size = New System.Drawing.Size(347, 17) Me.BenefitsLinkLabel.TabIndex = 2 Me.BenefitsLinkLabel.TabStop = True Me.BenefitsLinkLabel.Text = "Learn more online about the benefits of genuine Windows" ' 'Success ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.SystemColors.ButtonHighlight Me.CancelButton = Me.CloseBtn Me.ClientSize = New System.Drawing.Size(617, 512) Me.Controls.Add(Me.BenefitsLinkLabel) Me.Controls.Add(Me.GenuineSoftwareLogo) Me.Controls.Add(Me.DescriptionLabel) Me.Controls.Add(Me.TitleLabel) Me.Controls.Add(Me.BottomPanel) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MaximizeBox = False Me.MinimizeBox = False Me.MinimumSize = New System.Drawing.Size(633, 551) Me.Name = "Success" Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Windows Activation" Me.TopMost = True Me.BottomPanel.ResumeLayout(False) CType(Me.GenuineSoftwareLogo, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents DescriptionLabel As Label Friend WithEvents CloseBtn As Button Friend WithEvents TitleLabel As Label Friend WithEvents BottomPanel As Panel Friend WithEvents GenuineSoftwareLogo As PictureBox Friend WithEvents BenefitsLinkLabel As LinkLabel End Class
'''<summary>The RTCDTMFToneChangeEvent interface represents events sent to indicate that DTMF tones have started or finished playing. This interface is used by the tonechange event.</summary> <DynamicInterface(GetType(EcmaScriptObject))> Public Interface [RTCDTMFToneChangeEvent] '''<summary>A DOMString specifying the tone which has begun playing, or an empty string ("") if the previous tone has finished playing.</summary> ReadOnly Property [tone] As String '''<summary>Returns a new RTCDTMFToneChangeEvent. It takes two parameters, the first being a DOMString representing the type of the event (always "tonechange"); the second a dictionary containing the initial state of the properties of the event.</summary> Property [RTCDTMFToneChangeEvent] As RTCDTMFToneChangeEvent End Interface
' 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.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.DocumentationComments <Export(GetType(ICommandHandler))> <ContentType(ContentTypeNames.VisualBasicContentType)> <Name(PredefinedCommandHandlerNames.DocumentationComments)> <Order(After:=PredefinedCommandHandlerNames.Rename)> <Order(After:=PredefinedCompletionNames.CompletionCommandHandler)> Friend Class DocumentationCommentCommandHandler Inherits AbstractDocumentationCommentCommandHandler(Of DocumentationCommentTriviaSyntax, DeclarationStatementSyntax) <ImportingConstructor()> Public Sub New( waitIndicator As IWaitIndicator, undoHistoryRegistry As ITextUndoHistoryRegistry, editorOperationsFactoryService As IEditorOperationsFactoryService) MyBase.New(waitIndicator, undoHistoryRegistry, editorOperationsFactoryService) End Sub Protected Overrides ReadOnly Property ExteriorTriviaText As String Get Return "'''" End Get End Property Protected Overrides Function GetContainingMember(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As DeclarationStatementSyntax Return syntaxTree.GetRoot(cancellationToken).FindToken(position).GetContainingMember() End Function Protected Overrides Function SupportsDocumentationComments(member As DeclarationStatementSyntax) As Boolean If member Is Nothing Then Return False End If Select Case member.Kind Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock, SyntaxKind.EnumBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock, SyntaxKind.ClassStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement, SyntaxKind.StructureStatement, SyntaxKind.EnumStatement, SyntaxKind.EnumMemberDeclaration, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement, SyntaxKind.PropertyStatement, SyntaxKind.OperatorStatement, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.SubNewStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.DeclareSubStatement Return True Case Else Return False End Select End Function Protected Overrides Function HasDocumentationComment(member As DeclarationStatementSyntax) As Boolean If member Is Nothing Then Return False End If Return member.GetFirstToken().LeadingTrivia.Any(SyntaxKind.DocumentationCommentTrivia) End Function Private Function SupportsDocumentationCommentReturnsClause(member As DeclarationStatementSyntax) As Boolean If member Is Nothing Then Return False End If Select Case member.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.FunctionStatement, SyntaxKind.DeclareFunctionStatement Return True Case SyntaxKind.PropertyStatement Return Not DirectCast(member, PropertyStatementSyntax).Modifiers.Any(SyntaxKind.WriteOnlyKeyword) Case Else Return False End Select End Function Protected Overrides Function GetPrecedingDocumentationCommentCount(member As DeclarationStatementSyntax) As Integer Dim firstToken = member.GetFirstToken() Dim count = firstToken.LeadingTrivia.Sum(Function(t) If(t.Kind = SyntaxKind.DocumentationCommentTrivia, 1, 0)) Dim previousToken = firstToken.GetPreviousToken() If previousToken.Kind <> SyntaxKind.None Then count += previousToken.TrailingTrivia.Sum(Function(t) If(t.Kind = SyntaxKind.DocumentationCommentTrivia, 1, 0)) End If Return count End Function Protected Overrides Function IsMemberDeclaration(member As DeclarationStatementSyntax) As Boolean Return member.IsMemberDeclaration() End Function Protected Overrides Function GetDocumentationCommentStubLines(member As DeclarationStatementSyntax) As List(Of String) Dim list = New List(Of String) list.Add("''' <summary>") list.Add("''' ") list.Add("''' </summary>") Dim typeParameterList = member.GetTypeParameterList() If typeParameterList IsNot Nothing Then For Each typeParam In typeParameterList.Parameters list.Add("''' <typeparam name=""" & typeParam.Identifier.ToString() & """></typeparam>") Next End If Dim parameterList = member.GetParameterList() If parameterList IsNot Nothing Then For Each param In parameterList.Parameters list.Add("''' <param name=""" & param.Identifier.Identifier.ToString() & """></param>") Next End If If SupportsDocumentationCommentReturnsClause(member) Then list.Add("''' <returns></returns>") End If Return list End Function Protected Overrides Function IsSingleExteriorTrivia(documentationComment As DocumentationCommentTriviaSyntax, Optional allowWhitespace As Boolean = False) As Boolean If documentationComment Is Nothing Then Return False End If If documentationComment.Content.Count <> 1 Then Return False End If Dim xmlText = TryCast(documentationComment.Content(0), XmlTextSyntax) If xmlText Is Nothing Then Return False End If Dim textTokens = xmlText.TextTokens If Not textTokens.Any Then Return False End If If Not allowWhitespace AndAlso textTokens.Count <> 1 Then Return False End If If textTokens.Any(Function(t) Not String.IsNullOrWhiteSpace(t.ToString())) Then Return False End If Dim lastTextToken = textTokens.Last() Dim firstTextToken = textTokens.First() Return lastTextToken.Kind = SyntaxKind.DocumentationCommentLineBreakToken AndAlso firstTextToken.LeadingTrivia.Count = 1 AndAlso firstTextToken.LeadingTrivia.ElementAt(0).Kind = SyntaxKind.DocumentationCommentExteriorTrivia AndAlso firstTextToken.LeadingTrivia.ElementAt(0).ToString() = "'''" AndAlso lastTextToken.TrailingTrivia.Count = 0 End Function Private Function GetTextTokensFollowingExteriorTrivia(xmlText As XmlTextSyntax) As IList(Of SyntaxToken) Dim result = New List(Of SyntaxToken) Dim tokenList = xmlText.TextTokens For Each token In tokenList.Reverse() result.Add(token) If token.LeadingTrivia.Any(SyntaxKind.DocumentationCommentExteriorTrivia) Then Exit For End If Next result.Reverse() Return result End Function Protected Overrides Function EndsWithSingleExteriorTrivia(documentationComment As DocumentationCommentTriviaSyntax) As Boolean If documentationComment Is Nothing Then Return False End If Dim xmlText = TryCast(documentationComment.Content.LastOrDefault(), XmlTextSyntax) If xmlText Is Nothing Then Return False End If Dim textTokens = GetTextTokensFollowingExteriorTrivia(xmlText) If textTokens.Any(Function(t) Not String.IsNullOrWhiteSpace(t.ToString())) Then Return False End If Dim lastTextToken = textTokens.LastOrDefault() Dim firstTextToken = textTokens.FirstOrDefault() Return lastTextToken.Kind = SyntaxKind.DocumentationCommentLineBreakToken AndAlso firstTextToken.LeadingTrivia.Count = 1 AndAlso firstTextToken.LeadingTrivia.ElementAt(0).Kind = SyntaxKind.DocumentationCommentExteriorTrivia AndAlso firstTextToken.LeadingTrivia.ElementAt(0).ToString() = "'''" AndAlso lastTextToken.TrailingTrivia.Count = 0 End Function Protected Overrides Function IsMultilineDocComment(documentationComment As DocumentationCommentTriviaSyntax) As Boolean Return False End Function Protected Overrides Function GetTokenToRight(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxToken If position >= syntaxTree.GetText(cancellationToken).Length Then Return Nothing End If Return syntaxTree.GetRoot(cancellationToken).FindTokenOnRightOfPosition( position, includeDirectives:=True, includeDocumentationComments:=True) End Function Protected Overrides Function GetTokenToLeft(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxToken If position < 1 Then Return Nothing End If Return syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition( position - 1, includeDirectives:=True, includeDocumentationComments:=True) End Function Protected Overrides Function IsDocCommentNewLine(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.DocumentationCommentLineBreakToken End Function Protected Overrides Function IsEndOfLineTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides ReadOnly Property AddIndent As Boolean Get Return False End Get End Property Friend Overrides Function HasSkippedTrailingTrivia(token As SyntaxToken) As Boolean Return token.TrailingTrivia.Any(Function(t) t.Kind() = SyntaxKind.SkippedTokensTrivia) End Function End Class End Namespace
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Form2 Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.Panelx = New System.Windows.Forms.Panel Me.Label2 = New System.Windows.Forms.Label Me.Button1 = New System.Windows.Forms.Button Me.ListBox2 = New System.Windows.Forms.ListBox Me.Label1 = New System.Windows.Forms.Label Me.ListBox1 = New System.Windows.Forms.ListBox Me.Button2 = New System.Windows.Forms.Button Me.Panelx.SuspendLayout() Me.SuspendLayout() ' 'Panelx ' Me.Panelx.Controls.Add(Me.Button2) Me.Panelx.Controls.Add(Me.Label2) Me.Panelx.Controls.Add(Me.Button1) Me.Panelx.Controls.Add(Me.ListBox2) Me.Panelx.Controls.Add(Me.Label1) Me.Panelx.Controls.Add(Me.ListBox1) Me.Panelx.Location = New System.Drawing.Point(2, 12) Me.Panelx.Name = "Panelx" Me.Panelx.Size = New System.Drawing.Size(383, 336) Me.Panelx.TabIndex = 26 ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Location = New System.Drawing.Point(27, 245) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(114, 13) Me.Label2.TabIndex = 4 Me.Label2.Text = "Advanced, don't touch:" ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(264, 4) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(102, 19) Me.Button1.TabIndex = 3 Me.Button1.Text = "Hide" Me.Button1.UseVisualStyleBackColor = True ' 'ListBox2 ' Me.ListBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.ListBox2.Font = New System.Drawing.Font("Calibri", 12.0!) Me.ListBox2.HorizontalExtent = 20 Me.ListBox2.ItemHeight = 19 Me.ListBox2.Items.AddRange(New Object() {"0,1,2,3", "0,1,3,2", "0,2,1,3", "0,2,3,1", "0,3,1,2", "0,3,2,1", "1,0,2,3", "1,0,3,2", "1,2,0,3", "1,2,3,0", "1,3,2,0", "1,3,0,2", "2,0,1,3", "2,0,3,1", "2,1,0,3", "2,1,3,0", "2,3,1,0", "2,3,0,1", "3,0,1,2", "3,0,2,1", "3,1,0,2", "3,1,2,0", "3,2,0,1", "3,2,1,0"}) Me.ListBox2.Location = New System.Drawing.Point(30, 261) Me.ListBox2.MinimumSize = New System.Drawing.Size(25, 10) Me.ListBox2.Name = "ListBox2" Me.ListBox2.Size = New System.Drawing.Size(336, 59) Me.ListBox2.TabIndex = 2 ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Location = New System.Drawing.Point(19, 10) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(89, 13) Me.Label1.TabIndex = 1 Me.Label1.Text = "Select Animation:" ' 'ListBox1 ' Me.ListBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.ListBox1.Font = New System.Drawing.Font("Calibri", 12.0!) Me.ListBox1.HorizontalExtent = 20 Me.ListBox1.ItemHeight = 19 Me.ListBox1.Location = New System.Drawing.Point(30, 63) Me.ListBox1.MinimumSize = New System.Drawing.Size(25, 10) Me.ListBox1.Name = "ListBox1" Me.ListBox1.Size = New System.Drawing.Size(336, 154) Me.ListBox1.TabIndex = 0 ' 'Button2 ' Me.Button2.Location = New System.Drawing.Point(264, 223) Me.Button2.Name = "Button2" Me.Button2.Size = New System.Drawing.Size(96, 18) Me.Button2.TabIndex = 5 Me.Button2.Text = "OK" Me.Button2.UseVisualStyleBackColor = True ' 'Form2 ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(388, 351) Me.ControlBox = False Me.Controls.Add(Me.Panelx) Me.Font = New System.Drawing.Font("Calibri", 8.25!) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow Me.Name = "Form2" Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual Me.Panelx.ResumeLayout(False) Me.Panelx.PerformLayout() Me.ResumeLayout(False) End Sub Friend WithEvents Panelx As System.Windows.Forms.Panel Friend WithEvents Label1 As System.Windows.Forms.Label Public WithEvents ListBox1 As System.Windows.Forms.ListBox Public WithEvents ListBox2 As System.Windows.Forms.ListBox Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents Button2 As System.Windows.Forms.Button End Class
'------------------------------------------------------------------------------ ' <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 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.ADS.My.MySettings Get Return Global.ADS.My.MySettings.Default End Get End Property End Module End Namespace
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "fPropiedades_Clientes" '-------------------------------------------------------------------------------------------' Partial Class fPropiedades_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() Dim lcTipo As String = goServicios.mObtenerCampoFormatoSQL(goEmpresa.pcCodigo & "Clientes") loComandoSeleccionar.AppendLine(" SELECT") loComandoSeleccionar.AppendLine(" Clientes.Cod_Cli,") loComandoSeleccionar.AppendLine(" Clientes.Nom_Cli,") loComandoSeleccionar.AppendLine(" Propiedades.Nom_Pro,") loComandoSeleccionar.AppendLine(" Campos_Propiedades.Cod_Pro,") loComandoSeleccionar.AppendLine(" Campos_Propiedades.Tip_Pro,") loComandoSeleccionar.AppendLine(" Campos_Propiedades.Val_Log,") loComandoSeleccionar.AppendLine(" Campos_Propiedades.Val_Num,") loComandoSeleccionar.AppendLine(" Campos_Propiedades.Val_Car,") loComandoSeleccionar.AppendLine(" Campos_Propiedades.Val_Fec,") loComandoSeleccionar.AppendLine(" Campos_Propiedades.Val_Mem") loComandoSeleccionar.AppendLine(" FROM Clientes") loComandoSeleccionar.AppendLine(" JOIN Campos_Propiedades ON (Campos_Propiedades.Cod_Reg = Clientes.Cod_Cli)") loComandoSeleccionar.AppendLine(" JOIN Propiedades ON (Propiedades.Cod_Pro = Campos_Propiedades.Cod_Pro)") loComandoSeleccionar.AppendLine(" WHERE") loComandoSeleccionar.AppendLine(" Campos_Propiedades.Origen = 'Clientes'") loComandoSeleccionar.AppendLine(" AND" & cusAplicacion.goFormatos.pcCondicionPrincipal) loComandoSeleccionar.AppendLine("ORDER BY Campos_Propiedades.Tip_Pro ASC") 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("fPropiedades_Clientes", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvfPropiedades_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 '-------------------------------------------------------------------------------------------' ' RAC: 11/03/11: Código Inicial '-------------------------------------------------------------------------------------------' ' RAC: 29/03/11: Mejora en la configuracion del archivo rpt y la consulta para que se ' pudiera ver el logo de la empresa '-------------------------------------------------------------------------------------------'
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ' Handler the parts of binding for member lookup. Partial Friend Class Binder Friend Sub LookupMember(lookupResult As LookupResult, container As NamespaceOrTypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, useSiteDiagnostics) End Sub Friend Sub LookupMember(lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, useSiteDiagnostics) End Sub Friend Sub LookupMember(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, useSiteDiagnostics) End Sub Friend Sub LookupMemberImmediate(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.LookupImmediate(lookupResult, container, name, arity, options, Me, useSiteDiagnostics) End Sub Friend Sub LookupExtensionMethods( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) Debug.Assert(options.IsValid()) Debug.Assert(lookupResult.IsClear) options = BinderSpecificLookupOptions(options) MemberLookup.LookupForExtensionMethods(lookupResult, container, name, arity, options, Me, useSiteDiagnostics) End Sub Friend Sub LookupMemberInModules(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.LookupInModules(lookupResult, container, name, arity, options, Me, useSiteDiagnostics) End Sub Friend Sub AddMemberLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceOrTypeSymbol, options As LookupOptions) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.AddLookupSymbolsInfo(nameSet, container, options, Me) End Sub ' Validates a symbol to check if it ' a) has the right arity ' b) is accessible. (accessThroughType is passed in for protected access checks) ' c) matches the lookup options. ' A non-empty SingleLookupResult with the result is returned. ' ' For symbols from outside of this compilation the method also checks ' if the symbol is marked with 'Microsoft.VisualBasic.Embedded' attribute. ' ' If arity passed in is -1, no arity checks are done. Friend Function CheckViability(sym As Symbol, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As SingleLookupResult Debug.Assert(sym IsNot Nothing) If Not sym.CanBeReferencedByNameIgnoringIllegalCharacters Then Return SingleLookupResult.Empty End If If (options And LookupOptions.LabelsOnly) <> 0 Then ' If LabelsOnly is set then the symbol must be a label otherwise return empty If options = LookupOptions.LabelsOnly AndAlso sym.Kind = SymbolKind.Label Then Return SingleLookupResult.Good(sym) End If ' Mixing LabelsOnly with any other flag returns an empty result Return SingleLookupResult.Empty End If If (options And LookupOptions.MustNotBeReturnValueVariable) <> 0 Then '§11.4.4 Simple Name Expressions ' If the identifier matches a local variable, the local variable matched is ' the implicit function or Get accessor return local variable, and the expression ' is part of an invocation expression, invocation statement, or an AddressOf ' expression, then no match occurs and resolution continues. ' ' LookupOptions.MustNotBeReturnValueVariable is set if "the expression ' is part of an invocation expression, invocation statement, or an AddressOf ' expression", and we then skip return value variables. ' We'll always bind to the containing method or property instead further on in the lookup process. If sym.Kind = SymbolKind.Local AndAlso DirectCast(sym, LocalSymbol).IsFunctionValue Then Return SingleLookupResult.Empty End If End If Dim unwrappedSym = sym Dim asAlias = TryCast(sym, AliasSymbol) If asAlias IsNot Nothing Then unwrappedSym = asAlias.Target End If ' Check for external symbols marked with 'Microsoft.VisualBasic.Embedded' attribute If Me.Compilation.SourceModule IsNot unwrappedSym.ContainingModule AndAlso unwrappedSym.IsHiddenByEmbeddedAttribute() Then Return SingleLookupResult.Empty End If If unwrappedSym.Kind = SymbolKind.NamedType AndAlso unwrappedSym.EmbeddedSymbolKind = EmbeddedSymbolKind.EmbeddedAttribute AndAlso Me.SyntaxTree IsNot Nothing AndAlso Me.SyntaxTree.GetEmbeddedKind = EmbeddedSymbolKind.None Then ' Only allow direct access to Microsoft.VisualBasic.Embedded attribute ' from user code if current compilation embeds Vb Core If Not Me.Compilation.Options.EmbedVbCoreRuntime Then Return SingleLookupResult.Empty End If End If ' Do arity checking, unless specifically asked not to. ' Only types and namespaces in VB shadow by arity. All other members shadow ' regardless of arity. So, we only check arity on types. If arity <> -1 Then Select Case sym.Kind Case SymbolKind.NamedType, SymbolKind.ErrorType Dim actualArity As Integer = DirectCast(sym, NamedTypeSymbol).Arity If actualArity <> arity Then Return SingleLookupResult.WrongArity(sym, WrongArityErrid(actualArity, arity)) End If Case SymbolKind.TypeParameter, SymbolKind.Namespace If arity <> 0 Then ' type parameters and namespaces are always arity 0 Return SingleLookupResult.WrongArity(unwrappedSym, WrongArityErrid(0, arity)) End If Case SymbolKind.Alias ' Since raw generics cannot be imported, the import aliases would always refer to ' constructed types when referring to generics. So any other generic arity besides ' -1 or 0 are invalid. If arity <> 0 Then ' aliases are always arity 0, but error refers to the taget ' Note, Dev11 doesn't stop lookup in case of arity mismatch for an alias. Return SingleLookupResult.WrongArity(unwrappedSym, WrongArityErrid(0, arity)) End If Case SymbolKind.Method ' Unlike types and namespaces, we always stop looking if we find a method with the right name but wrong arity. ' The arity matching rules for methods are customizable for the LookupOptions; when binding expressions ' we always pass AllMethodsOfAnyArity and allow overload resolution to filter methods. The other flags ' are for binding API scenarios. Dim actualArity As Integer = DirectCast(sym, MethodSymbol).Arity If actualArity <> arity AndAlso Not ((options And LookupOptions.AllMethodsOfAnyArity) <> 0) Then Return SingleLookupResult.WrongArityAndStopLookup(sym, WrongArityErrid(actualArity, arity)) End If Case Else ' Unlike types and namespace, we stop looking if we find other symbols with wrong arity. ' All these symbols have arity 0. If arity <> 0 Then Return SingleLookupResult.WrongArityAndStopLookup(sym, WrongArityErrid(0, arity)) End If End Select End If If (options And LookupOptions.IgnoreAccessibility) = 0 Then Dim accessCheckResult = CheckAccessibility(unwrappedSym, useSiteDiagnostics, If((options And LookupOptions.UseBaseReferenceAccessibility) <> 0, Nothing, accessThroughType)) ' Check if we are in 'MyBase' resolving mode and we need to ignore 'accessThroughType' to make protected members accessed If accessCheckResult <> VisualBasic.AccessCheckResult.Accessible Then Return SingleLookupResult.Inaccessible(sym, GetInaccessibleErrorInfo(sym)) End If End If If (options And Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustNotBeInstance) <> 0 AndAlso sym.IsInstanceMember Then Return Global.Microsoft.CodeAnalysis.VisualBasic.SingleLookupResult.MustNotBeInstance(sym, Global.Microsoft.CodeAnalysis.VisualBasic.ERRID.ERR_ObjectReferenceNotSupplied) ElseIf (options And Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustBeInstance) <> 0 AndAlso Not sym.IsInstanceMember Then Return Global.Microsoft.CodeAnalysis.VisualBasic.SingleLookupResult.MustBeInstance(sym) ' there is no error message for this End If Return SingleLookupResult.Good(sym) End Function Friend Function GetInaccessibleErrorInfo(sym As Symbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As DiagnosticInfo CheckAccessibility(sym, useSiteDiagnostics) ' For diagnostics. Return GetInaccessibleErrorInfo(sym) End Function Friend Function GetInaccessibleErrorInfo(sym As Symbol) As DiagnosticInfo Dim unwrappedSym = sym Dim asAlias = TryCast(sym, AliasSymbol) If asAlias IsNot Nothing Then unwrappedSym = asAlias.Target ElseIf sym.Kind = SymbolKind.Method Then sym = DirectCast(sym, MethodSymbol).ConstructedFrom End If Dim diagInfo As DiagnosticInfo ' for inaccessible members (in e.g. AddressOf expressions, DEV10 shows a ERR_InaccessibleMember3 diagnostic) ' TODO maybe this condition needs to be adjusted to be shown in cases of e.g. inaccessible properties If unwrappedSym.Kind = SymbolKind.Method AndAlso unwrappedSym.ContainingSymbol IsNot Nothing Then diagInfo = New BadSymbolDiagnostic(sym, ERRID.ERR_InaccessibleMember3, sym.ContainingSymbol.Name, sym, AccessCheck.GetAccessibilityForErrorMessage(sym, Me.Compilation.Assembly)) Else diagInfo = New BadSymbolDiagnostic(sym, ERRID.ERR_InaccessibleSymbol2, CustomSymbolDisplayFormatter.QualifiedName(sym), AccessCheck.GetAccessibilityForErrorMessage(sym, sym.ContainingAssembly)) End If Debug.Assert(diagInfo.Severity = DiagnosticSeverity.Error) Return diagInfo End Function ''' <summary> ''' Used by Add*LookupSymbolsInfo* to determine whether the symbol is of interest. ''' Distinguish from <see cref="CheckViability"/>, which performs an analogous task for LookupSymbols*. ''' </summary> ''' <remarks> ''' Does not consider <see cref="Symbol.CanBeReferencedByName"/> - that is left to the caller. ''' </remarks> Friend Function CanAddLookupSymbolInfo(sym As Symbol, options As LookupOptions, accessThroughType As TypeSymbol) As Boolean Dim singleResult = CheckViability(sym, -1, options, accessThroughType, useSiteDiagnostics:=Nothing) If sym IsNot Nothing AndAlso (options And LookupOptions.MethodsOnly) <> 0 AndAlso sym.Kind <> SymbolKind.Method Then Return False End If If singleResult.IsGoodOrAmbiguous Then ' Its possible there is an error (ambiguity, wrong arity) associated with result. ' We still return true here, because binding finds that symbol and doesn't continue. ' NOTE: We're going to let the SemanticModel check for symbols that can't be ' referenced by name. That way, it can either filter them or not, depending ' on whether a name was passed to LookupSymbols. Return True End If Return False End Function ' return the error id for mismatched arity. Private Shared Function WrongArityErrid(actualArity As Integer, arity As Integer) As ERRID If actualArity < arity Then If actualArity = 0 Then Return ERRID.ERR_TypeOrMemberNotGeneric1 Else Return ERRID.ERR_TooManyGenericArguments1 End If Else Debug.Assert(actualArity > arity, "arities shouldn't match") Return ERRID.ERR_TooFewGenericArguments1 End If End Function ' Check is a symbol has a speakable name. Private Shared Function HasSpeakableName(sym As Symbol) As Boolean ' TODO: this probably should move to Symbol -- e.g., Symbol.CanBeBoundByName If sym.Kind = SymbolKind.Method Then Select Case DirectCast(sym, MethodSymbol).MethodKind Case MethodKind.Ordinary, MethodKind.ReducedExtension, MethodKind.DelegateInvoke, MethodKind.UserDefinedOperator, MethodKind.Conversion, MethodKind.DeclareMethod Return True Case Else Return False End Select End If Return True End Function ''' <summary> ''' This class handles binding of members of namespaces and types. ''' The key member is Lookup, which handles looking up a name ''' in a namespace or type, by name and arity, and produces a ''' lookup result. ''' </summary> Private Class MemberLookup ''' <summary> ''' Lookup a member name in a namespace or type, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Public Shared Sub Lookup(lookupResult As LookupResult, container As NamespaceOrTypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) If container.IsNamespace Then Lookup(lookupResult, DirectCast(container, NamespaceSymbol), name, arity, options, binder, useSiteDiagnostics) Else Lookup(lookupResult, DirectCast(container, TypeSymbol), name, arity, options, binder, useSiteDiagnostics) End If End Sub ' Lookup all the names available on the given container, that match the given lookup options. ' The supplied binder is used for accessibility checking. Public Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceOrTypeSymbol, options As LookupOptions, binder As Binder) If container.IsNamespace Then AddLookupSymbolsInfo(nameSet, DirectCast(container, NamespaceSymbol), options, binder) Else AddLookupSymbolsInfo(nameSet, DirectCast(container, TypeSymbol), options, binder) End If End Sub ''' <summary> ''' Lookup a member name in a namespace, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Public Shared Sub Lookup(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(lookupResult.IsClear) LookupImmediate(lookupResult, container, name, arity, options, binder, useSiteDiagnostics) ' Result in the namespace takes precedence over results in containing modules. If lookupResult.StopFurtherLookup Then Return End If Dim currentResult = LookupResult.GetInstance() LookupInModules(currentResult, container, name, arity, options, binder, useSiteDiagnostics) lookupResult.MergeAmbiguous(currentResult, AmbiguousInModuleError) currentResult.Free() End Sub ''' <summary> ''' Lookup an immediate (without decending into modules) member name in a namespace, ''' returning a LookupResult that summarizes the results of the lookup. ''' See LookupResult structure for a detailed discussion of the meaning of the results. ''' The supplied binder is used for accessibility checks and base class suppression. ''' </summary> Public Shared Sub LookupImmediate(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(lookupResult.IsClear) Dim sourceModule = binder.Compilation.SourceModule #If DEBUG Then Dim haveSeenNamespace As Boolean = False #End If For Each sym In container.GetMembers(name) #If DEBUG Then If sym.Kind = SymbolKind.Namespace Then Debug.Assert(Not haveSeenNamespace, "Expected namespaces to be merged into a single symbol.") haveSeenNamespace = True End If #End If Dim currentResult As SingleLookupResult = binder.CheckViability(sym, arity, options, Nothing, useSiteDiagnostics) lookupResult.MergeMembersOfTheSameNamespace(currentResult, sourceModule) Next End Sub ''' <summary> ''' Lookup a member name in modules of a namespace, ''' returning a LookupResult that summarizes the results of the lookup. ''' See LookupResult structure for a detailed discussion of the meaning of the results. ''' The supplied binder is used for accessibility checks and base class suppression. ''' </summary> Public Shared Sub LookupInModules(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(lookupResult.IsClear) Dim firstModule As Boolean = True Dim sourceModule = binder.Compilation.SourceModule ' NOTE: while looking up the symbol in modules we should ignore base class options = options Or LookupOptions.IgnoreExtensionMethods Or LookupOptions.NoBaseClassLookup ' Next, do a lookup in each contained module and merge the results. For Each containedModule As NamedTypeSymbol In container.GetModuleMembers() If firstModule Then Lookup(lookupResult, containedModule, name, arity, options, binder, useSiteDiagnostics) firstModule = False Else Dim currentResult = LookupResult.GetInstance() Lookup(currentResult, containedModule, name, arity, options, binder, useSiteDiagnostics) ' Symbols in source take priority over symbols in a referenced assembly. If currentResult.StopFurtherLookup AndAlso currentResult.Symbols.Count > 0 AndAlso lookupResult.StopFurtherLookup AndAlso lookupResult.Symbols.Count > 0 Then Dim currentFromSource = currentResult.Symbols(0).ContainingModule Is sourceModule Dim contenderFromSource = lookupResult.Symbols(0).ContainingModule Is sourceModule If currentFromSource Then If Not contenderFromSource Then ' current is better lookupResult.SetFrom(currentResult) currentResult.Free() Continue For End If ElseIf contenderFromSource Then ' contender is better currentResult.Free() Continue For End If End If lookupResult.MergeAmbiguous(currentResult, AmbiguousInModuleError) currentResult.Free() End If Next End Sub Private Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceSymbol, options As LookupOptions, binder As Binder) ' Add names from the namespace For Each sym In container.GetMembersUnordered() ' UNDONE: filter by options If binder.CanAddLookupSymbolInfo(sym, options, Nothing) Then nameSet.AddSymbol(sym, sym.Name, sym.GetArity()) End If Next ' Next, add names from each contained module. For Each containedModule As NamedTypeSymbol In container.GetModuleMembers() AddLookupSymbolsInfo(nameSet, containedModule, options, binder) Next End Sub ' Create a diagnostic for ambiguous names in multiple modules. Private Shared ReadOnly AmbiguousInModuleError As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic) = Function(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic Dim name As String = syms(0).Name Dim deferredFormattedList As New FormattedSymbolList(syms.Select(Function(sym) sym.ContainingType)) Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInModules2, syms, name, deferredFormattedList) End Function ''' <summary> ''' Lookup a member name in a type, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Friend Shared Sub Lookup(lookupResult As LookupResult, type As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(lookupResult.IsClear) Select Case type.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure, TypeKind.Delegate, TypeKind.Array, TypeKind.Enum LookupInClass(lookupResult, type, name, arity, options, type, binder, useSiteDiagnostics) Case TypeKind.Submission LookupInSubmissions(lookupResult, type, name, arity, options, binder, useSiteDiagnostics) Case TypeKind.Interface LookupInInterface(lookupResult, DirectCast(type, NamedTypeSymbol), name, arity, options, binder, useSiteDiagnostics) Case TypeKind.TypeParameter LookupInTypeParameter(lookupResult, DirectCast(type, TypeParameterSymbol), name, arity, options, binder, useSiteDiagnostics) Case TypeKind.Error ' Error types have no members. Return Case Else Throw ExceptionUtilities.UnexpectedValue(type.TypeKind) End Select End Sub Private Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) Select Case container.TypeKind Case TypeKind.Class, TypeKind.Structure, TypeKind.Delegate, TypeKind.Array, TypeKind.Enum AddLookupSymbolsInfoInClass(nameSet, container, options, binder) Case TypeKind.Module AddLookupSymbolsInfoInClass(nameSet, container, options Or LookupOptions.NoBaseClassLookup, binder) Case TypeKind.Submission AddLookupSymbolsInfoInSubmissions(nameSet, container, options, binder) Case TypeKind.Interface AddLookupSymbolsInfoInInterface(nameSet, DirectCast(container, NamedTypeSymbol), options, binder) Case TypeKind.TypeParameter AddLookupSymbolsInfoInTypeParameter(nameSet, DirectCast(container, TypeParameterSymbol), options, binder) Case TypeKind.Error ' Error types have no members. Return Case Else Throw ExceptionUtilities.UnexpectedValue(container.TypeKind) End Select End Sub ''' <summary> ''' Lookup a member name in a module, class, struct, enum, or delegate, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checks and base class suppression. ''' </summary> Private Shared Sub LookupInClass(result As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(result.IsClear) Dim methodsOnly As Boolean = CheckAndClearMethodsOnlyOption(options) ' Lookup proceeds up the base class chain. Dim currentType = container Do Dim hitNonoverloadingSymbol As Boolean = False Dim currentResult = LookupResult.GetInstance() LookupWithoutInheritance(currentResult, currentType, name, arity, options, accessThroughType, binder, useSiteDiagnostics) If result.IsGoodOrAmbiguous AndAlso currentResult.IsGoodOrAmbiguous AndAlso Not LookupResult.CanOverload(result.Symbols(0), currentResult.Symbols(0)) Then ' We hit another good symbol that can't overload this one. That doesn't affect the lookup result, but means we have to stop ' looking for more members. See bug #14078 for example. hitNonoverloadingSymbol = True End If result.MergeOverloadedOrPrioritized(currentResult, True) currentResult.Free() ' If the type is from a winmd file and implements any of the special WinRT collection ' projections, then we may need to add projected interface members Dim namedType = TryCast(currentType, NamedTypeSymbol) If namedType IsNot Nothing AndAlso namedType.ShouldAddWinRTMembers Then FindWinRTMembers(result, namedType, binder, useSiteDiagnostics, lookupMembersNotDefaultProperties:=True, name:=name, arity:=arity, options:=options) End If If hitNonoverloadingSymbol Then Exit Do ' still do extension methods. End If If result.StopFurtherLookup Then ' If we found a non-overloadable symbol, we can stop now. Note that even if we find a method without the Overloads ' modifier, we cannot stop because we need to check for extension methods. If result.HasSymbol Then If Not result.Symbols.First.IsOverloadable Then If methodsOnly Then Exit Do ' Need to look for extension methods. End If Return End If End If End If ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) <> 0 OrElse binder.IgnoreBaseClassesInLookup Then currentType = Nothing Else currentType = currentType.GetDirectBaseTypeWithDefinitionUseSiteDiagnostics(binder.BasesBeingResolved, useSiteDiagnostics) End If Loop While currentType IsNot Nothing ClearLookupResultIfNotMethods(methodsOnly, result) LookupForExtensionMethodsIfNeedTo(result, container, name, arity, options, binder, useSiteDiagnostics) End Sub Delegate Sub WinRTLookupDelegate(iface As NamedTypeSymbol, binder As Binder, result As LookupResult, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) ''' <summary> ''' This function generalizes the idea of producing a set of non-conflicting ''' WinRT members of a given type based on the results of some arbitrary lookup ''' closure (which produces a LookupResult signifying success as IsGood). ''' ''' A non-conflicting WinRT member lookup looks for all members of projected ''' WinRT interfaces which are implemented by a given type, discarding any ''' which have equal signatures. ''' ''' If <paramref name="lookupMembersNotDefaultProperties" /> is true then ''' this function lookups up members with the given <paramref name="name" />, ''' <paramref name="arity" />, and <paramref name="options" />. Otherwise, it looks for default properties. ''' </summary> Private Shared Sub FindWinRTMembers(result As LookupResult, type As NamedTypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo), lookupMembersNotDefaultProperties As Boolean, Optional name As String = Nothing, Optional arity As Integer = -1, Optional options As LookupOptions = Nothing) ' If we have no conflict with existing members, we also have to check ' if we have a conflict with other interface members. An example would be ' a type which implements both IIterable (IEnumerable) and IMap ' (IDictionary).There are two different GetEnumerator methods from each ' interface. Thus, we don't know which method to choose. The solution? ' Don't add any GetEnumerator method. Dim comparer = MemberSignatureComparer.WinRTComparer Dim allMembers = New HashSet(Of Symbol)(comparer) Dim conflictingMembers = New HashSet(Of Symbol)(comparer) ' Add all viable members from type lookup If result.IsGood Then For Each sym In result.Symbols ' Fields can't be present in the HashSet because they can't be compared ' with a MemberSignatureComparer ' TODO: Add field support in the C# and VB member comparers and then ' delete this check If sym.Kind <> SymbolKind.Field Then allMembers.Add(sym) End If Next End If Dim tmp = LookupResult.GetInstance() ' Dev11 searches all declared and undeclared base interfaces For Each iface In type.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics) If IsWinRTProjectedInterface(iface, binder.Compilation) Then If lookupMembersNotDefaultProperties Then Debug.Assert(name IsNot Nothing) LookupWithoutInheritance(tmp, iface, name, arity, options, iface, binder, useSiteDiagnostics) Else LookupDefaultPropertyInSingleType(tmp, iface, iface, binder, useSiteDiagnostics) End If ' only add viable members If tmp.IsGood Then For Each sym In tmp.Symbols If Not allMembers.Add(sym) Then conflictingMembers.Add(sym) End If Next End If tmp.Clear() End If Next tmp.Free() If result.IsGood Then For Each sym In result.Symbols If sym.Kind <> SymbolKind.Field Then allMembers.Remove(sym) conflictingMembers.Remove(sym) End If Next End If For Each sym In allMembers If Not conflictingMembers.Contains(sym) Then ' since we only added viable members, every lookupresult should be viable result.MergeOverloadedOrPrioritized( New SingleLookupResult(LookupResultKind.Good, sym, Nothing), checkIfCurrentHasOverloads:=False) End If Next End Sub Private Shared Function IsWinRTProjectedInterface(iFace As NamedTypeSymbol, compilation As VisualBasicCompilation) As Boolean Dim idictSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IDictionary_KV) Dim iroDictSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IReadOnlyDictionary_KV) Dim iListSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_IList) Dim iCollectionSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_ICollection) Dim inccSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Specialized_INotifyCollectionChanged) Dim inpcSymbol = compilation.GetWellKnownType(WellKnownType.System_ComponentModel_INotifyPropertyChanged) Dim iFaceOriginal = iFace.OriginalDefinition Dim iFaceSpecial = iFaceOriginal.SpecialType ' Types match the list given in dev11 IMPORTER::GetWindowsRuntimeInterfacesToFake Return iFaceSpecial = SpecialType.System_Collections_Generic_IEnumerable_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IList_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_ICollection_T OrElse iFaceOriginal = idictSymbol OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IReadOnlyCollection_T OrElse iFaceOriginal = iroDictSymbol OrElse iFaceSpecial = SpecialType.System_Collections_IEnumerable OrElse iFaceOriginal = iListSymbol OrElse iFaceOriginal = iCollectionSymbol OrElse iFaceOriginal = inccSymbol OrElse iFaceOriginal = inpcSymbol End Function ''' <summary> ''' Lookup a member name in a submission chain. ''' </summary> ''' <remarks> ''' We start with the current submission class and walk the submission chain back to the first submission. ''' The search has two phases ''' 1) We are looking for any symbol matching the given name, arity, and options. If we don't find any the search is over. ''' If we find an overloadable symbol(s) (a method or a property) we start looking for overloads of this kind ''' (lookingForOverloadsOfKind) of symbol in phase 2. ''' 2) If a visited submission contains a matching member of a kind different from lookingForOverloadsOfKind we stop ''' looking further. Otherwise, if we find viable overload(s) we add them into the result. Overloads modifier is ignored. ''' </remarks> Private Shared Sub LookupInSubmissions(result As LookupResult, submissionClass As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert(result.IsClear) Dim submissionSymbols = LookupResult.GetInstance() Dim nonViable = LookupResult.GetInstance() Dim lookingForOverloadsOfKind As SymbolKind? = Nothing Dim submission = binder.Compilation Do submissionSymbols.Clear() If submission.ScriptClass IsNot Nothing Then LookupWithoutInheritance(submissionSymbols, submission.ScriptClass, name, arity, options, submissionClass, binder, useSiteDiagnostics) End If ' TOOD (tomat): import aliases If lookingForOverloadsOfKind Is Nothing Then If Not submissionSymbols.IsGoodOrAmbiguous Then ' skip non-viable members, but remember them in case no viable members are found in previous submissions: nonViable.MergePrioritized(submissionSymbols) submission = submission.PreviousSubmission Continue Do End If ' always overload (ignore Overloads modifier): result.MergeOverloadedOrPrioritized(submissionSymbols, checkIfCurrentHasOverloads:=False) Dim first = submissionSymbols.Symbols.First If Not first.IsOverloadable Then Exit Do End If ' we are now looking for any kind of member regardless of the original binding restrictions: options = options And Not LookupOptions.NamespacesOrTypesOnly lookingForOverloadsOfKind = first.Kind Else ' found a member we are not looking for - the overload set is final now If submissionSymbols.HasSymbol AndAlso submissionSymbols.Symbols.First.Kind <> lookingForOverloadsOfKind.Value Then Exit Do End If ' found a viable overload If submissionSymbols.IsGoodOrAmbiguous Then ' merge overloads Debug.Assert(result.Symbols.All(Function(s) s.IsOverloadable)) ' always overload (ignore Overloads modifier): result.MergeOverloadedOrPrioritized(submissionSymbols, checkIfCurrentHasOverloads:=False) End If End If submission = submission.PreviousSubmission Loop Until submission Is Nothing If Not result.HasSymbol Then result.SetFrom(nonViable) End If ' TODO (tomat): extension methods submissionSymbols.Free() nonViable.Free() End Sub Public Shared Sub LookupDefaultProperty(result As LookupResult, container As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Select Case container.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure LookupDefaultPropertyInClass(result, DirectCast(container, NamedTypeSymbol), binder, useSiteDiagnostics) Case TypeKind.Interface LookupDefaultPropertyInInterface(result, DirectCast(container, NamedTypeSymbol), binder, useSiteDiagnostics) Case TypeKind.TypeParameter LookupDefaultPropertyInTypeParameter(result, DirectCast(container, TypeParameterSymbol), binder, useSiteDiagnostics) End Select End Sub Private Shared Sub LookupDefaultPropertyInClass( result As LookupResult, type As NamedTypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) Debug.Assert(type.IsClassType OrElse type.IsModuleType OrElse type.IsStructureType OrElse type.IsDelegateType) Dim accessThroughType As NamedTypeSymbol = type While type IsNot Nothing If LookupDefaultPropertyInSingleType(result, type, accessThroughType, binder, useSiteDiagnostics) Then Return End If ' If this is a WinRT type, we should also look for default properties in the ' implemented projected interfaces If type.ShouldAddWinRTMembers Then FindWinRTMembers(result, type, binder, useSiteDiagnostics, lookupMembersNotDefaultProperties:=False) If result.IsGood Then Return End If End If type = type.BaseTypeWithDefinitionUseSiteDiagnostics(useSiteDiagnostics) End While End Sub ' See Semantics::LookupDefaultPropertyInInterface. Private Shared Sub LookupDefaultPropertyInInterface( result As LookupResult, [interface] As NamedTypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) Debug.Assert([interface].IsInterfaceType) If LookupDefaultPropertyInSingleType(result, [interface], [interface], binder, useSiteDiagnostics) Then Return End If For Each baseInterface In [interface].InterfacesNoUseSiteDiagnostics baseInterface.OriginalDefinition.AddUseSiteDiagnostics(useSiteDiagnostics) LookupDefaultPropertyInBaseInterface(result, baseInterface, binder, useSiteDiagnostics) If result.HasDiagnostic Then Return End If Next End Sub Private Shared Sub LookupDefaultPropertyInTypeParameter(result As LookupResult, typeParameter As TypeParameterSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(useSiteDiagnostics) If constraintClass IsNot Nothing Then LookupDefaultPropertyInClass(result, constraintClass, binder, useSiteDiagnostics) If Not result.IsClear Then Return End If End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteDiagnostics) If lookIn IsNot Nothing Then For Each baseInterface In lookIn LookupDefaultPropertyInBaseInterface(result, baseInterface.InterfaceType, binder, useSiteDiagnostics) If result.HasDiagnostic Then Return End If Next End If End Sub ' See Semantics::LookupDefaultPropertyInBaseInterface. Private Shared Sub LookupDefaultPropertyInBaseInterface( result As LookupResult, type As NamedTypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) If type.IsErrorType() Then Return End If Debug.Assert(type.IsInterfaceType) Debug.Assert(Not result.HasDiagnostic) Dim tmpResult = LookupResult.GetInstance() Try LookupDefaultPropertyInInterface(tmpResult, type, binder, useSiteDiagnostics) If Not tmpResult.HasSymbol Then Return End If If tmpResult.HasDiagnostic OrElse Not result.HasSymbol Then result.SetFrom(tmpResult) Return End If ' At least one member was found on another interface. ' Report an ambiguity error if the two interfaces are distinct. Dim symbolA = result.Symbols(0) Dim symbolB = tmpResult.Symbols(0) If symbolA.ContainingSymbol <> symbolB.ContainingSymbol Then result.MergeAmbiguous(tmpResult, AddressOf GenerateAmbiguousDefaultPropertyDiagnostic) End If Finally tmpResult.Free() End Try End Sub ' Return True if a default property is defined on the type. Private Shared Function LookupDefaultPropertyInSingleType( result As LookupResult, type As NamedTypeSymbol, accessThroughType As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) As Boolean Dim defaultPropertyName = type.DefaultPropertyName If String.IsNullOrEmpty(defaultPropertyName) Then Return False End If Select Case type.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure LookupInClass( result, type, defaultPropertyName, arity:=0, options:=LookupOptions.Default, accessThroughType:=accessThroughType, binder:=binder, useSiteDiagnostics:=useSiteDiagnostics) Case TypeKind.Interface Debug.Assert(accessThroughType Is type) LookupInInterface( result, type, defaultPropertyName, arity:=0, options:=LookupOptions.Default, binder:=binder, useSiteDiagnostics:=useSiteDiagnostics) Case TypeKind.TypeParameter Throw ExceptionUtilities.UnexpectedValue(type.TypeKind) End Select Return result.HasSymbol End Function Private Shared Function GenerateAmbiguousDefaultPropertyDiagnostic(symbols As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic Debug.Assert(symbols.Length > 1) Dim symbolA = symbols(0) Dim containingSymbolA = symbolA.ContainingSymbol For i = 1 To symbols.Length - 1 Dim symbolB = symbols(i) Dim containingSymbolB = symbolB.ContainingSymbol If containingSymbolA <> containingSymbolB Then ' "Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'." Return New AmbiguousSymbolDiagnostic(ERRID.ERR_DefaultPropertyAmbiguousAcrossInterfaces4, symbols, symbolA, containingSymbolA, symbolB, containingSymbolB) End If Next ' Expected ambiguous symbols Throw ExceptionUtilities.Unreachable End Function Private Shared Sub LookupForExtensionMethodsIfNeedTo( result As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) If result.IsGood AndAlso ((options And LookupOptions.EagerlyLookupExtensionMethods) = 0 OrElse result.Symbols(0).Kind <> SymbolKind.Method) Then Return End If Dim currentResult = LookupResult.GetInstance() LookupForExtensionMethods(currentResult, container, name, arity, options, binder, useSiteDiagnostics) MergeInternalXmlHelperValueIfNecessary(currentResult, container, name, arity, options, binder, useSiteDiagnostics) result.MergeOverloadedOrPrioritized(currentResult, checkIfCurrentHasOverloads:=False) currentResult.Free() End Sub Private Shared Function ShouldLookupExtensionMethods(options As LookupOptions, container As TypeSymbol) As Boolean Return options.ShouldLookupExtensionMethods AndAlso Not container.IsObjectType() AndAlso Not container.IsShared AndAlso Not container.IsModuleType() End Function Public Shared Sub LookupForExtensionMethods( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) Debug.Assert(lookupResult.IsClear) If Not ShouldLookupExtensionMethods(options, container) Then lookupResult.SetFrom(SingleLookupResult.Empty) Return End If ' Proceed up the chain of binders, collecting extension methods Dim originalBinder = binder Dim currentBinder = binder Dim methods = ArrayBuilder(Of MethodSymbol).GetInstance() Dim proximity As Integer = 0 ' We don't want to process the same methods more than once, but the same extension method ' might be in scope in several different binders. For example, within a type, within ' imported the same type, within imported namespace containing the type. ' So, taking into consideration the fact that CollectProbableExtensionMethodsInSingleBinder ' groups methods from the same containing type together, we will keep track of the types and ' will process all the methods from the same containing type at once. Dim seenContainingTypes As New HashSet(Of NamedTypeSymbol)() Do methods.Clear() currentBinder.CollectProbableExtensionMethodsInSingleBinder(name, methods, originalBinder) Dim i As Integer = 0 Dim count As Integer = methods.Count While i < count Dim containingType As NamedTypeSymbol = methods(i).ContainingType If seenContainingTypes.Add(containingType) AndAlso ((options And LookupOptions.IgnoreAccessibility) <> 0 OrElse AccessCheck.IsSymbolAccessible(containingType, binder.Compilation.Assembly, useSiteDiagnostics)) Then ' Process all methods from the same type together. Do ' Try to reduce this method and merge with the current result Dim reduced As MethodSymbol = methods(i).ReduceExtensionMethod(container, proximity) If reduced IsNot Nothing Then lookupResult.MergeOverloadedOrPrioritizedExtensionMethods(binder.CheckViability(reduced, arity, options, reduced.ContainingType, useSiteDiagnostics)) End If i += 1 Loop While i < count AndAlso containingType Is methods(i).ContainingSymbol Else ' We already processed extension methods from this container before or the whole container is not accessible, ' skip the whole group of methods from this containing type. Do i += 1 Loop While i < count AndAlso containingType Is methods(i).ContainingSymbol End If End While ' Continue to containing binders. proximity += 1 currentBinder = currentBinder.m_containingBinder Loop While currentBinder IsNot Nothing methods.Free() End Sub ''' <summary> ''' Include the InternalXmlHelper.Value extension property in the LookupResult ''' if the container implements IEnumerable(Of XElement), the name is "Value", ''' and the arity is 0. ''' </summary> Private Shared Sub MergeInternalXmlHelperValueIfNecessary( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) If (arity <> 0) OrElse Not IdentifierComparison.Equals(name, StringConstants.ValueProperty) Then Return End If Dim compilation = binder.Compilation If (options And LookupOptions.NamespacesOrTypesOnly) <> 0 OrElse Not container.IsOrImplementsIEnumerableOfXElement(compilation, useSiteDiagnostics) Then Return End If Dim symbol = compilation.GetWellKnownTypeMember(WellKnownMember.My_InternalXmlHelper__Value) Dim singleResult As SingleLookupResult If symbol Is Nothing Then ' Match the native compiler which reports ERR_XmlFeaturesNotAvailable in this case. Dim useSiteError = ErrorFactory.ErrorInfo(ERRID.ERR_XmlFeaturesNotAvailable) singleResult = New SingleLookupResult(LookupResultKind.NotReferencable, binder.GetErrorSymbol(name, useSiteError), useSiteError) Else Dim reduced = New ReducedExtensionPropertySymbol(DirectCast(symbol, PropertySymbol)) singleResult = binder.CheckViability(reduced, arity, options, reduced.ContainingType, useSiteDiagnostics) End If lookupResult.MergePrioritized(singleResult) End Sub Private Shared Sub AddLookupSymbolsInfoOfExtensionMethods(nameSet As LookupSymbolsInfo, container As TypeSymbol, newInfo As LookupSymbolsInfo, binder As Binder) Dim lookup = LookupResult.GetInstance() For Each name In newInfo.Names lookup.Clear() LookupForExtensionMethods(lookup, container, name, 0, LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreAccessibility, binder, useSiteDiagnostics:=Nothing) If lookup.IsGood Then For Each method As MethodSymbol In lookup.Symbols nameSet.AddSymbol(method, method.Name, method.Arity) Next End If Next lookup.Free() End Sub Public Shared Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) If Not ShouldLookupExtensionMethods(options, container) Then Return End If ' We will not reduce extension methods for the purpose of this operation, ' they will still be shared methods. options = options And (Not Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustBeInstance) ' Proceed up the chain of binders, collecting names of extension methods Dim currentBinder As Binder = binder Dim newInfo = LookupSymbolsInfo.GetInstance() Do currentBinder.AddExtensionMethodLookupSymbolsInfoInSingleBinder(newInfo, options, binder) ' Continue to containing binders. currentBinder = currentBinder.m_containingBinder Loop While currentBinder IsNot Nothing AddLookupSymbolsInfoOfExtensionMethods(nameSet, container, newInfo, binder) newInfo.Free() ' Include "Value" for InternalXmlHelper.Value if necessary. Dim compilation = binder.Compilation Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing If container.IsOrImplementsIEnumerableOfXElement(compilation, useSiteDiagnostics) AndAlso useSiteDiagnostics.IsNullOrEmpty Then nameSet.AddSymbol(Nothing, StringConstants.ValueProperty, 0) End If End Sub ''' <summary> ''' Checks if two interfaces have a base-derived relationship ''' </summary> Private Shared Function IsDerivedInterface( base As NamedTypeSymbol, derived As NamedTypeSymbol, basesBeingResolved As ConsList(Of Symbol), <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) As Boolean Debug.Assert(base.IsInterface) Debug.Assert(derived.IsInterface) If derived.OriginalDefinition = base.OriginalDefinition Then Return False End If ' if we are not resolving bases we can just go through AllInterfaces list If basesBeingResolved Is Nothing Then For Each i In derived.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics) If i = base Then Return True End If Next Return False End If ' we are resolving bases so should use a private helper that relies only on Declared interfaces Return IsDerivedInterface(base, derived, basesBeingResolved, New HashSet(Of Symbol), useSiteDiagnostics) End Function Private Shared Function IsDerivedInterface( base As NamedTypeSymbol, derived As NamedTypeSymbol, basesBeingResolved As ConsList(Of Symbol), verified As HashSet(Of Symbol), <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) As Boolean Debug.Assert(base <> derived, "should already be verified for equality") Debug.Assert(base.IsInterface) Debug.Assert(derived.IsInterface) verified.Add(derived) ' not afraid of cycles here as we will not verify same symbol twice Dim interfaces = derived.GetDeclaredInterfacesWithDefinitionUseSiteDiagnostics(basesBeingResolved, useSiteDiagnostics) If Not interfaces.IsDefaultOrEmpty Then For Each i In interfaces If i = base Then Return True End If If verified.Contains(i) Then ' seen this already Continue For End If If IsDerivedInterface( base, i, basesBeingResolved, verified, useSiteDiagnostics) Then Return True End If Next End If Return False End Function Private Structure InterfaceInfo Implements IEquatable(Of InterfaceInfo) Public ReadOnly InterfaceType As NamedTypeSymbol Public ReadOnly InComInterfaceContext As Boolean Public ReadOnly DescendantDefinitions As ImmutableHashSet(Of NamedTypeSymbol) Public Sub New(interfaceType As NamedTypeSymbol, inComInterfaceContext As Boolean, Optional descendantDefinitions As ImmutableHashSet(Of NamedTypeSymbol) = Nothing) Me.InterfaceType = interfaceType Me.InComInterfaceContext = inComInterfaceContext Me.DescendantDefinitions = descendantDefinitions End Sub Public Overrides Function GetHashCode() As Integer Return Hash.Combine(Me.InterfaceType.GetHashCode(), Me.InComInterfaceContext.GetHashCode()) End Function Public Overloads Overrides Function Equals(obj As Object) As Boolean Return TypeOf obj Is InterfaceInfo AndAlso Equals(DirectCast(obj, InterfaceInfo)) End Function Public Overloads Function Equals(other As InterfaceInfo) As Boolean Implements IEquatable(Of InterfaceInfo).Equals Return Me.InterfaceType.Equals(other.InterfaceType) AndAlso Me.InComInterfaceContext = other.InComInterfaceContext End Function End Structure Private Shared Sub LookupInInterface(lookupResult As LookupResult, container As NamedTypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) Debug.Assert(lookupResult.IsClear) Dim methodsOnly As Boolean = CheckAndClearMethodsOnlyOption(options) ' look in these types. Start with container, add more accordingly. Dim info As New InterfaceInfo(container, False) Dim lookIn As New Queue(Of InterfaceInfo) lookIn.Enqueue(info) Dim processed As New HashSet(Of InterfaceInfo) processed.Add(info) LookupInInterfaces(lookupResult, container, lookIn, processed, name, arity, options, binder, methodsOnly, useSiteDiagnostics) ' If no viable or ambiguous results, look in Object. If Not lookupResult.IsGoodOrAmbiguous AndAlso (options And LookupOptions.NoSystemObjectLookupForInterfaces) = 0 Then Dim currentResult = LookupResult.GetInstance() Dim obj As NamedTypeSymbol = binder.SourceModule.ContainingAssembly.GetSpecialType(SpecialType.System_Object) LookupInClass(currentResult, obj, name, arity, options Or LookupOptions.IgnoreExtensionMethods, obj, binder, useSiteDiagnostics) If currentResult.IsGood Then lookupResult.SetFrom(currentResult) End If currentResult.Free() End If ClearLookupResultIfNotMethods(methodsOnly, lookupResult) LookupForExtensionMethodsIfNeedTo(lookupResult, container, name, arity, options, binder, useSiteDiagnostics) Return End Sub Private Shared Sub LookupInInterfaces(lookupResult As LookupResult, container As TypeSymbol, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), name As String, arity As Integer, options As LookupOptions, binder As Binder, methodsOnly As Boolean, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) Debug.Assert(lookupResult.IsClear) Dim basesBeingResolved As ConsList(Of Symbol) = binder.BasesBeingResolved() Dim isEventsOnlySpecified As Boolean = (options And LookupOptions.EventsOnly) <> 0 Dim currentResult = LookupResult.GetInstance() Do Dim info As InterfaceInfo = lookIn.Dequeue() Debug.Assert(processed.Contains(info)) Debug.Assert(currentResult.IsClear) LookupWithoutInheritance(currentResult, info.InterfaceType, name, arity, options, container, binder, useSiteDiagnostics) ' if result does not shadow we will have bases to visit If Not (currentResult.StopFurtherLookup AndAlso AnyShadows(currentResult)) Then If (options And LookupOptions.NoBaseClassLookup) = 0 AndAlso Not binder.IgnoreBaseClassesInLookup Then AddBaseInterfacesToTheSearch(binder, info, lookIn, processed, useSiteDiagnostics) End If End If Dim leaveEventsOnly As Boolean? = Nothing If info.InComInterfaceContext Then leaveEventsOnly = isEventsOnlySpecified End If If lookupResult.IsGood AndAlso currentResult.IsGood Then ' We have _another_ viable result while lookupResult is already viable. Use special interface merging rules. MergeInterfaceLookupResults(lookupResult, currentResult, basesBeingResolved, leaveEventsOnly, useSiteDiagnostics) Else If currentResult.IsGood AndAlso leaveEventsOnly.HasValue Then FilterSymbolsInLookupResult(currentResult, SymbolKind.Event, leaveInsteadOfRemoving:=leaveEventsOnly.Value) End If lookupResult.MergePrioritized(currentResult) End If currentResult.Clear() Loop While lookIn.Count <> 0 currentResult.Free() If methodsOnly AndAlso lookupResult.IsGood Then ' We need to filter out non-method symbols from 'currentResult' ' before merging with 'lookupResult' FilterSymbolsInLookupResult(lookupResult, SymbolKind.Method, leaveInsteadOfRemoving:=True) End If ' it may look like a Good result, but it may have ambiguities inside ' so we need to check that to be sure. If lookupResult.IsGood Then Dim ambiguityDiagnostics As AmbiguousSymbolDiagnostic = Nothing Dim symbols As ArrayBuilder(Of Symbol) = lookupResult.Symbols For i As Integer = 0 To symbols.Count - 2 Dim interface1 = DirectCast(symbols(i).ContainingType, NamedTypeSymbol) For j As Integer = i + 1 To symbols.Count - 1 If Not LookupResult.CanOverload(symbols(i), symbols(j)) Then ' Symbols cannot overload each other. ' If they were from the same interface, LookupWithoutInheritance would make the result ambiguous. ' If they were from interfaces related through inheritance, one of them would shadow another, ' MergeInterfaceLookupResults handles that. ' Therefore, this symbols are from unrelated interfaces. ambiguityDiagnostics = New AmbiguousSymbolDiagnostic( ERRID.ERR_AmbiguousAcrossInterfaces3, symbols.ToImmutable, name, symbols(i).ContainingType, symbols(j).ContainingType) GoTo ExitForFor End If Next Next ExitForFor: If ambiguityDiagnostics IsNot Nothing Then lookupResult.SetFrom(New SingleLookupResult(LookupResultKind.Ambiguous, symbols.First, ambiguityDiagnostics)) End If End If End Sub Private Shared Sub FilterSymbolsInLookupResult(result As LookupResult, kind As SymbolKind, leaveInsteadOfRemoving As Boolean) Debug.Assert(result.IsGood) Dim resultSymbols As ArrayBuilder(Of Symbol) = result.Symbols Debug.Assert(resultSymbols.Count > 0) Dim i As Integer = 0 Dim j As Integer = 0 While j < resultSymbols.Count Dim symbol As Symbol = resultSymbols(j) If (symbol.Kind = kind) = leaveInsteadOfRemoving Then resultSymbols(i) = resultSymbols(j) i += 1 End If j += 1 End While resultSymbols.Clip(i) If i = 0 Then result.Clear() End If End Sub Private Shared Sub LookupInTypeParameter(lookupResult As LookupResult, typeParameter As TypeParameterSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Dim methodsOnly = CheckAndClearMethodsOnlyOption(options) LookupInTypeParameterNoExtensionMethods(lookupResult, typeParameter, name, arity, options, binder, useSiteDiagnostics) ClearLookupResultIfNotMethods(methodsOnly, lookupResult) LookupForExtensionMethodsIfNeedTo(lookupResult, typeParameter, name, arity, options, binder, useSiteDiagnostics) End Sub Private Shared Sub LookupInTypeParameterNoExtensionMethods(result As LookupResult, typeParameter As TypeParameterSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Debug.Assert((options And LookupOptions.MethodsOnly) = 0) options = options Or LookupOptions.IgnoreExtensionMethods ' §4.9.2: "the class constraint hides members in interface constraints, which ' hide members in System.ValueType (if Structure constraint is specified), ' which hides members in Object." ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(useSiteDiagnostics) If constraintClass IsNot Nothing Then LookupInClass(result, constraintClass, name, arity, options, constraintClass, binder, useSiteDiagnostics) If result.StopFurtherLookup Then Return End If End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteDiagnostics) If lookIn IsNot Nothing Then ' §4.9.2: "If a member with the same name appears in more than one interface ' constraint the member is unavailable (as in multiple interface inheritance)" Dim interfaceResult = LookupResult.GetInstance() Debug.Assert((options And LookupOptions.MethodsOnly) = 0) LookupInInterfaces(interfaceResult, typeParameter, lookIn, processed, name, arity, options, binder, False, useSiteDiagnostics) result.MergePrioritized(interfaceResult) interfaceResult.Free() If Not result.IsClear Then Return End If End If ' Look up in System.ValueType or System.Object. If constraintClass Is Nothing Then Debug.Assert(result.IsClear) Dim baseType = GetTypeParameterBaseType(typeParameter) LookupInClass(result, baseType, name, arity, options, baseType, binder, useSiteDiagnostics) End If End Sub Private Shared Function CheckAndClearMethodsOnlyOption(ByRef options As LookupOptions) As Boolean If (options And LookupOptions.MethodsOnly) <> 0 Then options = CType(options And (Not LookupOptions.MethodsOnly), LookupOptions) Return True End If Return False End Function Private Shared Sub ClearLookupResultIfNotMethods(methodsOnly As Boolean, lookupResult As LookupResult) If methodsOnly AndAlso lookupResult.HasSymbol AndAlso lookupResult.Symbols(0).Kind <> SymbolKind.Method Then lookupResult.Clear() End If End Sub Private Shared Sub AddInterfaceConstraints(typeParameter As TypeParameterSymbol, ByRef allInterfaces As Queue(Of InterfaceInfo), ByRef processedInterfaces As HashSet(Of InterfaceInfo), <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) For Each constraintType In typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics) Select Case constraintType.TypeKind Case TypeKind.Interface Dim newInfo As New InterfaceInfo(DirectCast(constraintType, NamedTypeSymbol), False) If processedInterfaces Is Nothing OrElse Not processedInterfaces.Contains(newInfo) Then If processedInterfaces Is Nothing Then allInterfaces = New Queue(Of InterfaceInfo) processedInterfaces = New HashSet(Of InterfaceInfo) End If allInterfaces.Enqueue(newInfo) processedInterfaces.Add(newInfo) End If Case TypeKind.TypeParameter AddInterfaceConstraints(DirectCast(constraintType, TypeParameterSymbol), allInterfaces, processedInterfaces, useSiteDiagnostics) End Select Next End Sub ''' <summary> ''' Merges two lookup results while eliminating symbols that are shadowed. ''' Note that the final result may contain unrelated and possibly conflicting symbols as ''' this helper is not intended to catch ambiguities. ''' </summary> ''' <param name="leaveEventsOnly"> ''' If is not Nothing and False filters out all Event symbols, and if is not Nothing ''' and True filters out all non-Event symbols, nos not have any effect otherwise. ''' Is used for special handling of Events inside COM interfaces. ''' </param> Private Shared Sub MergeInterfaceLookupResults( knownResult As LookupResult, newResult As LookupResult, BasesBeingResolved As ConsList(Of Symbol), leaveEventsOnly As Boolean?, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) Debug.Assert(knownResult.Kind = newResult.Kind) Dim knownSymbols As ArrayBuilder(Of Symbol) = knownResult.Symbols Dim newSymbols As ArrayBuilder(Of Symbol) = newResult.Symbols Dim newSymbolContainer = newSymbols.First().ContainingType For i As Integer = 0 To knownSymbols.Count - 1 Dim knownSymbol = knownSymbols(i) ' Nothing means that the symbol has been eliminated via shadowing If knownSymbol Is Nothing Then Continue For End If Dim knownSymbolContainer = knownSymbol.ContainingType For j As Integer = 0 To newSymbols.Count - 1 Dim newSymbol As Symbol = newSymbols(j) ' Nothing means that the symbol has been eliminated via shadowing If newSymbol Is Nothing Then Continue For End If ' Special-case events in case we are inside COM interface If leaveEventsOnly.HasValue AndAlso (newSymbol.Kind = SymbolKind.Event) <> leaveEventsOnly.Value Then newSymbols(j) = Nothing Continue For End If If knownSymbol = newSymbol Then ' this is the same result as we already have, remove from the new set newSymbols(j) = Nothing Continue For End If ' container of the first new symbol should be container of all others Debug.Assert(newSymbolContainer = newSymbol.ContainingType) ' Are the known and new symbols of the right kinds to overload? Dim cantOverloadEachOther = Not LookupResult.CanOverload(knownSymbol, newSymbol) If IsDerivedInterface(base:=newSymbolContainer, derived:=knownSymbolContainer, basesBeingResolved:=BasesBeingResolved, useSiteDiagnostics:=useSiteDiagnostics) Then ' if currently known is more derived and shadows the new one ' it shadows all the new ones and we are done If IsShadows(knownSymbol) OrElse cantOverloadEachOther Then ' no need to continue with merge. new symbols are all shadowed ' and they cannot shadow anything in the old set Debug.Assert(Not knownSymbols.Any(Function(s) s Is Nothing)) newResult.Clear() Return End If ElseIf IsDerivedInterface(base:=knownSymbolContainer, derived:=newSymbolContainer, basesBeingResolved:=BasesBeingResolved, useSiteDiagnostics:=useSiteDiagnostics) Then ' if new is more derived and shadows ' the current one should be dropped ' NOTE that we continue iterating as more known symbols may be "shadowed out" by the current. If IsShadows(newSymbol) OrElse cantOverloadEachOther Then knownSymbols(i) = Nothing ' all following known symbols in the same container are shadowed by the new one ' we can do a quick check and remove them here For k = i + 1 To knownSymbols.Count - 1 Dim otherKnown As Symbol = knownSymbols(k) If otherKnown IsNot Nothing AndAlso otherKnown.ContainingType = knownSymbolContainer Then knownSymbols(k) = Nothing End If Next End If End If ' we can get here if results are completely unrelated. ' However we do not know if they are conflicting as either one could be "shadowed out" in later iterations. ' for now we let both known and new stay Next Next CompactAndAppend(knownSymbols, newSymbols) newResult.Clear() End Sub ''' <summary> ''' first.Where(t IsNot Nothing).Concat(second.Where(t IsNot Nothing)) ''' </summary> Private Shared Sub CompactAndAppend(first As ArrayBuilder(Of Symbol), second As ArrayBuilder(Of Symbol)) Dim i As Integer = 0 ' skip non nulls While i < first.Count If first(i) Is Nothing Then Exit While End If i += 1 End While ' compact the rest Dim j As Integer = i + 1 While j < first.Count Dim item As Symbol = first(j) If item IsNot Nothing Then first(i) = item i += 1 End If j += 1 End While ' clip to compacted size first.Clip(i) ' append non nulls from second i = 0 While i < second.Count Dim items As Symbol = second(i) If items IsNot Nothing Then first.Add(items) End If i += 1 End While End Sub ''' <summary> ''' ''' </summary> Private Shared Sub AddBaseInterfacesToTheSearch(binder As Binder, currentInfo As InterfaceInfo, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) Dim interfaces As ImmutableArray(Of NamedTypeSymbol) = currentInfo.InterfaceType.GetDirectBaseInterfacesNoUseSiteDiagnostics(binder.BasesBeingResolved) If Not interfaces.IsDefaultOrEmpty Then Dim inComInterfaceContext As Boolean = currentInfo.InComInterfaceContext OrElse currentInfo.InterfaceType.CoClassType IsNot Nothing Dim descendants As ImmutableHashSet(Of NamedTypeSymbol) If binder.BasesBeingResolved Is Nothing Then descendants = Nothing Else ' We need to watch out for cycles in inheritance chain since they are not broken while bases are being resolved. If currentInfo.DescendantDefinitions Is Nothing Then descendants = ImmutableHashSet.Create(currentInfo.InterfaceType.OriginalDefinition) Else descendants = currentInfo.DescendantDefinitions.Add(currentInfo.InterfaceType.OriginalDefinition) End If End If For Each i In interfaces If descendants IsNot Nothing AndAlso descendants.Contains(i.OriginalDefinition) Then ' About to get in an inheritance cycle Continue For End If i.OriginalDefinition.AddUseSiteDiagnostics(useSiteDiagnostics) Dim newInfo As New InterfaceInfo(i, inComInterfaceContext, descendants) If processed.Add(newInfo) Then lookIn.Enqueue(newInfo) End If Next End If End Sub ''' <summary> ''' if any symbol in the list Shadows. This implies that name is not visible through the base. ''' </summary> Private Shared Function AnyShadows(result As LookupResult) As Boolean For Each sym As Symbol In result.Symbols If sym.IsShadows Then Return True End If Next Return False End Function ' Find all names in a non-interface type, consider inheritance. Private Shared Sub AddLookupSymbolsInfoInClass(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) ' We need a check for SpecialType.System_Void as its base type is ' ValueType but we don't wish to return any members for void type If container IsNot Nothing And container.SpecialType = SpecialType.System_Void Then Return End If ' Lookup proceeds up the base class chain. Dim currentType = container Do AddLookupSymbolsInfoWithoutInheritance(nameSet, currentType, options, container, binder) ' If the type is from a winmd file and implements any of the special WinRT collection ' projections, then we may need to add projected interface members Dim namedType = TryCast(currentType, NamedTypeSymbol) If namedType IsNot Nothing AndAlso namedType.ShouldAddWinRTMembers Then AddWinRTMembersLookupSymbolsInfo(nameSet, namedType, options, container, binder) End If ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) <> 0 OrElse binder.IgnoreBaseClassesInLookup Then currentType = Nothing Else currentType = currentType.GetDirectBaseTypeNoUseSiteDiagnostics(binder.BasesBeingResolved) End If Loop While currentType IsNot Nothing ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, container, options, binder) ' Special case: if we're in a constructor of a class or structure, then we can call constructors on ourself or our immediate base ' (via Me.New or MyClass.New or MyBase.New). We don't have enough info to check the constraints that the constructor must be ' the specific tokens Me, MyClass, or MyBase, or that its the first statement in the constructor, so services must do ' that check if it wants to show that. ' Roslyn Bug 9701. Dim containingMethod = TryCast(binder.ContainingMember, MethodSymbol) If containingMethod IsNot Nothing AndAlso containingMethod.MethodKind = MethodKind.Constructor AndAlso (container.TypeKind = TypeKind.Class OrElse container.TypeKind = TypeKind.Structure) AndAlso (containingMethod.ContainingType = container OrElse containingMethod.ContainingType.BaseTypeNoUseSiteDiagnostics = container) Then nameSet.AddSymbol(Nothing, WellKnownMemberNames.InstanceConstructorName, 0) End If End Sub Private Shared Sub AddLookupSymbolsInfoInSubmissions(nameSet As LookupSymbolsInfo, submissionClass As TypeSymbol, options As LookupOptions, binder As Binder) Dim submission = binder.Compilation Do ' TODO (tomat): import aliases If submission.ScriptClass IsNot Nothing Then AddLookupSymbolsInfoWithoutInheritance(nameSet, submission.ScriptClass, options, submissionClass, binder) End If submission = submission.PreviousSubmission Loop Until submission Is Nothing ' TODO (tomat): extension methods End Sub ' Find all names in an interface type, consider inheritance. Private Shared Sub AddLookupSymbolsInfoInInterface(nameSet As LookupSymbolsInfo, container As NamedTypeSymbol, options As LookupOptions, binder As Binder) Dim info As New InterfaceInfo(container, False) Dim lookIn As New Queue(Of InterfaceInfo) lookIn.Enqueue(info) Dim processed As New HashSet(Of InterfaceInfo) processed.Add(info) AddLookupSymbolsInfoInInterfaces(nameSet, container, lookIn, processed, options, binder) ' Look in Object. AddLookupSymbolsInfoInClass(nameSet, binder.SourceModule.ContainingAssembly.GetSpecialType(SpecialType.System_Object), options Or LookupOptions.IgnoreExtensionMethods, binder) ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, container, options, binder) End Sub Private Shared Sub AddLookupSymbolsInfoInInterfaces(nameSet As LookupSymbolsInfo, container As TypeSymbol, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), options As LookupOptions, binder As Binder) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Do Dim currentType As InterfaceInfo = lookIn.Dequeue AddLookupSymbolsInfoWithoutInheritance(nameSet, currentType.InterfaceType, options, container, binder) ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) = 0 AndAlso Not binder.IgnoreBaseClassesInLookup Then AddBaseInterfacesToTheSearch(binder, currentType, lookIn, processed, useSiteDiagnostics) End If Loop While lookIn.Count <> 0 End Sub Private Shared Sub AddLookupSymbolsInfoInTypeParameter(nameSet As LookupSymbolsInfo, typeParameter As TypeParameterSymbol, options As LookupOptions, binder As Binder) AddLookupSymbolsInfoInTypeParameterNoExtensionMethods(nameSet, typeParameter, options, binder) ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, typeParameter, options, binder) End Sub Private Shared Sub AddLookupSymbolsInfoInTypeParameterNoExtensionMethods(nameSet As LookupSymbolsInfo, typeParameter As TypeParameterSymbol, options As LookupOptions, binder As Binder) options = options Or LookupOptions.IgnoreExtensionMethods ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(Nothing) If constraintClass IsNot Nothing Then AddLookupSymbolsInfoInClass(nameSet, constraintClass, options, binder) End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteDiagnostics:=Nothing) If lookIn IsNot Nothing Then AddLookupSymbolsInfoInInterfaces(nameSet, typeParameter, lookIn, processed, options, binder) End If ' Look up in System.ValueType or System.Object. If constraintClass Is Nothing Then Dim baseType = GetTypeParameterBaseType(typeParameter) AddLookupSymbolsInfoInClass(nameSet, baseType, options, binder) End If End Sub ''' <summary> ''' Lookup a member name in a type without considering inheritance, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. ''' </summary> Private Shared Sub LookupWithoutInheritance(lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo) ) Dim members As ImmutableArray(Of Symbol) = ImmutableArray(Of Symbol).Empty If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = LookupOptions.NamespacesOrTypesOnly Then ' Only named types have members that are types. Go through all the types in this type and ' validate them. If there's multiple, give an error. If TypeOf container Is NamedTypeSymbol Then members = ImmutableArray.Create(Of Symbol, NamedTypeSymbol)(container.GetTypeMembers(name)) End If ElseIf (options And LookupOptions.LabelsOnly) = 0 Then members = container.GetMembers(name) End If Debug.Assert(lookupResult.IsClear) ' Go through each member of the type, and combine them into a single result. Overloadable members ' are combined together, while other duplicates cause an ambiguity error. If Not members.IsDefaultOrEmpty Then Dim imported As Boolean = container.ContainingModule IsNot binder.SourceModule For Each sym In members lookupResult.MergeMembersOfTheSameType(binder.CheckViability(sym, arity, options, accessThroughType, useSiteDiagnostics), imported) Next End If End Sub ' Find all names in a type, without considering inheritance. Private Shared Sub AddLookupSymbolsInfoWithoutInheritance(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder) ' UNDONE: validate symbols with something that looks like ValidateSymbol. If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = LookupOptions.NamespacesOrTypesOnly Then ' Only named types have members that are types. Go through all the types in this type and ' validate them. If TypeOf container Is NamedTypeSymbol Then For Each sym In container.GetTypeMembersUnordered() If binder.CanAddLookupSymbolInfo(sym, options, accessThroughType) Then nameSet.AddSymbol(sym, sym.Name, sym.Arity) End If Next End If ElseIf (options And LookupOptions.LabelsOnly) = 0 Then ' Go through each member of the type. For Each sym In container.GetMembersUnordered() If binder.CanAddLookupSymbolInfo(sym, options, accessThroughType) Then nameSet.AddSymbol(sym, sym.Name, sym.GetArity()) End If Next End If End Sub Private Shared Sub AddWinRTMembersLookupSymbolsInfo( nameSet As LookupSymbolsInfo, type As NamedTypeSymbol, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder ) ' Dev11 searches all declared and undeclared base interfaces For Each iface In type.AllInterfacesNoUseSiteDiagnostics If IsWinRTProjectedInterface(iface, binder.Compilation) Then AddLookupSymbolsInfoWithoutInheritance(nameSet, iface, options, accessThroughType, binder) End If Next End Sub Private Shared Function GetTypeParameterBaseType(typeParameter As TypeParameterSymbol) As NamedTypeSymbol ' The default base type should only be used if there is no explicit class constraint. Debug.Assert(typeParameter.GetClassConstraint(Nothing) Is Nothing) Return typeParameter.ContainingAssembly.GetSpecialType(If(typeParameter.HasValueTypeConstraint, SpecialType.System_ValueType, SpecialType.System_Object)) End Function End Class End Class End Namespace
'********************************************************* ' ' Copyright (c) Microsoft. All rights reserved. ' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY ' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR ' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ' '********************************************************* Imports Windows.UI.Xaml Imports Windows.UI.Xaml.Controls Imports Windows.UI.Xaml.Navigation Imports SDKTemplate Imports System Imports System.Threading.Tasks Imports System.Net Imports System.IO Imports System.Xml Imports Windows.Storage ''' <summary> ''' An empty page that can be used on its own or navigated to within a Frame. ''' </summary> Partial Public NotInheritable Class XmlReaderWriterScenario Inherits SDKTemplate.Common.LayoutAwarePage ' A pointer back to the main page. This is needed if you want to call methods in MainPage such ' as NotifyUser() Private rootPage As MainPage = MainPage.Current Public Sub New() Me.InitializeComponent() End Sub ''' <summary> ''' Invoked when this page is about to be displayed in a Frame. ''' </summary> ''' <param name="e">Event data that describes how this page was reached. The Parameter ''' property is typically used to configure the page.</param> Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs) End Sub ''' <summary> ''' This is the click handler for the 'DoSomething' button. You would replace this with your own handler ''' if you have a button or buttons on this page. ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Async Sub DoSomething_Click(sender As Object, e As RoutedEventArgs) Dim b As Button = TryCast(sender, Button) If b IsNot Nothing Then rootPage.NotifyUser("You clicked the " & b.Content.ToString & " button", NotifyType.StatusMessage) End If Dim filename As String = "manchester_us.xml" Try Await ProcessWithReaderWriter(filename) ' show the content of the file just created Using s As Stream = Await KnownFolders.PicturesLibrary.OpenStreamForReadAsync(filename) Using sr As New StreamReader(s) OutputTextBlock1.Text = sr.ReadToEnd() End Using End Using Catch ex As UnauthorizedAccessException OutputTextBlock1.Text = "Exception happend, Message:" & ex.Message Catch webEx As System.Net.WebException OutputTextBlock1.Text = "Exception happend, Message:" & webEx.Message & " Have you updated the bing map key in function ProcessWithReaderWriter()?" End Try End Sub Private Async Function ProcessWithReaderWriter(filename As String) As Task ' you need to acquire a Bing Maps key. See http://www.bingmapsportal.com/ Dim bingMapKey As String = "INSERT_YOUR_BING_MAPS_KEY" ' the following uri will returns a response with xml content Dim uri As New Uri(String.Format("http://dev.virtualearth.net/REST/v1/Locations?q=manchester&o=xml&key={0}", bingMapKey)) Dim request As WebRequest = WebRequest.Create(uri) ' if needed, specify credential here ' request.Credentials = new NetworkCredential(); ' GetResponseAsync() returns immediately after the header is ready Dim response As WebResponse = Await request.GetResponseAsync() Dim inputStream As Stream = response.GetResponseStream() Dim xrs As New XmlReaderSettings() With {.Async = True, .CloseInput = True} Using reader As XmlReader = XmlReader.Create(inputStream, xrs) Dim xws As New XmlWriterSettings() With {.Async = True, .Indent = True, .CloseOutput = True} Dim outputStream As Stream = Await KnownFolders.PicturesLibrary.OpenStreamForWriteAsync(filename, CreationCollisionOption.OpenIfExists) Using writer As XmlWriter = XmlWriter.Create(outputStream, xws) Dim prefix As String = "" Dim ns As String = "" Await writer.WriteStartDocumentAsync() Await writer.WriteStartElementAsync(prefix, "Locations", ns) ' iterate through the REST message, and find the Mancesters in US then write to file While Await reader.ReadAsync() ' take element nodes with name "Address" If reader.NodeType = XmlNodeType.Element AndAlso reader.Name = "Address" Then ' create a XmlReader from the Address element Using subReader As XmlReader = reader.ReadSubtree() Dim isInUS As Boolean = False While Await subReader.ReadAsync() ' check if the CountryRegion element contains "United States" If subReader.Name = "CountryRegion" Then Dim value As String = Await subReader.ReadInnerXmlAsync() If value.Contains("United States") Then isInUS = True End If End If ' write the FormattedAddress node of the reader, if the address is within US If isInUS AndAlso subReader.NodeType = XmlNodeType.Element AndAlso subReader.Name = "FormattedAddress" Then Await writer.WriteNodeAsync(subReader, False) End If End While End Using End If End While Await writer.WriteEndElementAsync() Await writer.WriteEndDocumentAsync() End Using End Using End Function End Class
Imports System.Security.Cryptography Namespace HTTPSocket Public Module Encryption Public Function RSA_Encrypt(ByVal Input As String, ByVal Key As String) As String Dim output As String Using RSA As New RSACryptoServiceProvider(2048) RSA.PersistKeyInCsp = False RSA.FromXmlString(Key) Dim buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(Input) Dim encrypted As Byte() = RSA.Encrypt(buffer, True) output = Convert.ToBase64String(encrypted) End Using Return output End Function Public Function RSA_Decrypt(ByVal Input As String, ByVal Key As String) As String Dim plain As Byte() Using rsa As New RSACryptoServiceProvider(2048) rsa.PersistKeyInCsp = False rsa.FromXmlString(Key) Dim buffer As Byte() = Convert.FromBase64String(Input) plain = rsa.Decrypt(buffer, True) End Using Return System.Text.Encoding.UTF8.GetString(plain) End Function End Module End Namespace
Imports System.Data Imports System.Data.SqlClient Public Class patient_allocation Private connectionString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kitti\source\repos\final-wellmeadown\final-wellmeadown\wellmeadown-final.mdf;Integrated Security=True;Connect Timeout=30" Dim sqlSelectQuery As String = "select pa.* , w.ward_name , w.location , w.[tel extn] , s.first_name from m_patient_allocation as pa, ward as w , staff as s where pa.staff_number = s.staff_number and pa.ward_number = w.ward_name" Dim sqlConnection As New SqlConnection(connectionString) Dim sqlCommand As New SqlCommand(sqlSelectQuery, sqlConnection) Dim sqlReader As SqlDataReader Private Sub patient_allocation_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'TODO: This line of code loads data into the '_wellmeadown_finalDataSet1.patient' table. You can move, or remove it, as needed. Me.PatientTableAdapter.Fill(Me._wellmeadown_finalDataSet1.patient) 'TODO: This line of code loads data into the '_wellmeadown_finalDataSet1.d_patient_allocation' table. You can move, or remove it, as needed. Me.D_patient_allocationTableAdapter.Fill(Me._wellmeadown_finalDataSet1.d_patient_allocation) 'TODO: This line of code loads data into the '_wellmeadown_finalDataSet.ward' table. You can move, or remove it, as needed. Me.WardTableAdapter.Fill(Me._wellmeadown_finalDataSet.ward) 'TODO: This line of code loads data into the '_wellmeadown_finalDataSet.m_patient_allocation' table. You can move, or remove it, as needed. Me.M_patient_allocationTableAdapter.Fill(Me._wellmeadown_finalDataSet.m_patient_allocation) btn_add.Text = "add" btn_edit.Text = "edit" End Sub Private Sub ReadMydata(connection As String) Dim sqlSelectQuery As String = "select * from m_patient_allocation " Dim sqlConnection As New SqlConnection(connectionString) Dim sqlCommand As New SqlCommand(sqlSelectQuery, sqlConnection) Dim sqlReader As SqlDataReader sqlConnection.Open() sqlReader = sqlCommand.ExecuteReader() sqlReader.Read() Patient_allocation_numberTextBox.Text = sqlReader.Item("Patient_allocation_number") Ward_numberTextBox.Text = sqlReader.Item("Ward_number") Staff_numberTextBox.Text = sqlReader.Item("Staff_number") sqlReader.Close() sqlConnection.Close() End Sub Private Sub ReadMydata2(connection As String) Dim sqlSelectQuery As String = "select * from d_patient_allocation " Dim sqlConnection As New SqlConnection(connectionString) Dim sqlCommand As New SqlCommand(sqlSelectQuery, sqlConnection) Dim sqlReader As SqlDataReader sqlConnection.Open() sqlReader = sqlCommand.ExecuteReader() sqlReader.Read() Patient_allocation_numberTextBox.Text = sqlReader.Item("patient_allocation_number") TextBox1.Text = sqlReader.Item("patient_number") DateTimePicker1.Value = sqlReader.Item("on_waiting_list") TextBox5.Text = sqlReader.Item("expected_stay_(days)") DateTimePicker2.Value = sqlReader.Item("date_placed") DateTimePicker3.Value = sqlReader.Item("date_lave") DateTimePicker4.Value = sqlReader.Item("actual_leave") TextBox9.Text = sqlReader.Item("bed_number") sqlReader.Close() sqlConnection.Close() End Sub Private Sub btn_add_Click(dender As Object, e As EventArgs) Handles btn_add.Click If btn_add.Text = "add" Then btn_edit.Text = "cancle" Else MessageBox.Show("บันทึกข้อมูล " & First_nameTextBox.Text & " สำเร็จ", "ข้อความจากระบบ", MessageBoxButtons.OK, MessageBoxIcon.Information) InsertMyData(connectionString) ReadMydata(connectionString) End If End Sub Private Sub btn_delete_Click(sender As Object, e As EventArgs) Handles btn_delete.Click MessageBox.Show("ลบข้อมูลวอร์ด " & Ward_numberTextBox.Text & Ward_nameTextBox.Text & " สำเร็จ", "ข้อความจากระบบ", MessageBoxButtons.OK, MessageBoxIcon.Information) Dim sqlDelete2 As String = ("DELETE FROM d_patient_allocation where patient_allocation_number = " & Patient_allocation_numberTextBox.Text) Dim sqlCommand2 As New SqlCommand(sqlDelete2, sqlConnection) sqlConnection.Close() sqlConnection.Open() sqlCommand2.ExecuteNonQuery() Dim sqlDelete As String = ("DELETE FROM m_patient_allocation where patient_allocation_number = " & Patient_allocation_numberTextBox.Text) Dim sqlCommand As New SqlCommand(sqlDelete, sqlConnection) sqlConnection.Close() sqlConnection.Open() sqlCommand.ExecuteNonQuery() ListView1.Items.Clear() End Sub Private Sub InsertMyData(connectionString As String) Dim sqlInsert As String = ("insert into m_patient_allocation (patient_allocation_number,Ward_number,Staff_number) values (" & Patient_allocation_numberTextBox.Text & ",'" & Ward_numberTextBox.Text & "','" & Staff_numberTextBox.Text & "')") Debug.WriteLine(sqlInsert) Dim sqlCommand As New SqlCommand(sqlInsert, sqlConnection) sqlConnection.Close() sqlConnection.Open() sqlCommand.ExecuteNonQuery() End Sub Private Sub InsertMyData2(connectionString As String) Dim sqlInsert As String = ("insert into d_patient_allocation (patient_allocation_number ,patient_number ,on_waiting_list ,[expected_stay_(days)] , date_placed , date_lave , actual_leave , bed_number) values(" & Patient_allocation_numberTextBox.Text & ",'" & TextBox1.Text & "' ,'" & DateTimePicker1.Value.ToString("MM/dd/yyyy") & "' ," & TextBox5.Text & " ,'" & DateTimePicker2.Value.ToString("MM/dd/yyyy") & "' ,'" & DateTimePicker3.Value.ToString("MM/dd/yyyy") & "' ,'" & DateTimePicker4.Value.ToString("MM/dd/yyyy") & "','" & TextBox9.Text & "')") Debug.WriteLine(sqlInsert) Dim sqlCommand As New SqlCommand(sqlInsert, sqlConnection) sqlConnection.Close() sqlConnection.Open() sqlCommand.ExecuteNonQuery() End Sub Sub deleteData(connectionString As String) MessageBox.Show(" ลบข้อมูล " & First_nameTextBox.Text & " สำเร็จ", "ข้อความจากระบบ", MessageBoxButtons.OK, MessageBoxIcon.Information) Dim sqlDelete As String = ("DELETE FROM m_patient_allocation where patient_allocation_number = " & Patient_allocation_numberTextBox.Text) Debug.WriteLine(sqlDelete) Dim sqlCommand As New SqlCommand(sqlDelete, sqlConnection) sqlConnection.Close() sqlConnection.Open() sqlCommand.ExecuteNonQuery() End Sub Private Sub btn_edit_Click(dender As Object, e As EventArgs) Handles btn_edit.Click If btn_edit.Text = "edit" Then MessageBox.Show("ลบข้อมูลวอร์ด " & Ward_numberTextBox.Text & Ward_nameTextBox.Text & " สำเร็จ", "ข้อความจากระบบ", MessageBoxButtons.OK, MessageBoxIcon.Information) UpdateMyData(connectionString) ReadMydata(connectionString) Else btn_edit.Text = "edit" End If End Sub Private Sub UpdateMyData(connectionString As String) Dim sqlUpdate As String = "Update m_patient_allocation set Ward_number = '" & Ward_numberTextBox.Text & "' ,Staff_number = '" & Staff_numberTextBox.Text & "' where patient_allocation_number = " & Patient_allocation_numberTextBox.Text Debug.WriteLine(sqlUpdate) Dim sqlCommand As New SqlCommand(sqlUpdate, sqlConnection) sqlConnection.Close() sqlConnection.Open() sqlCommand.ExecuteNonQuery() End Sub Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click MessageBox.Show("บันทึกข้อมูลวอร์ด " & Ward_numberTextBox.Text & Ward_nameTextBox.Text & " สำเร็จ", "ข้อความจากระบบ", MessageBoxButtons.OK, MessageBoxIcon.Information) InsertMyData(connectionString) ReadMydata(connectionString) btn_edit.Text = "edit" End Sub Sub add() Dim item As New ListViewItem If TextBox9.Text = "" Then MessageBox.Show("กรุณากรอกข้อมูลให้ครบถถ้วน ", "ข้อความจากระบบ", MessageBoxButtons.OK, MessageBoxIcon.Information) Else If ListView1.Items.Count = 0 Then item = ListView1.Items.Add(TextBox1.Text) item.SubItems.Add(TextBox2.Text) item.SubItems.Add(TextBox3.Text) item.SubItems.Add(DateTimePicker1.Value.ToString("MM/dd/yyyy")) item.SubItems.Add(TextBox5.Text) item.SubItems.Add(DateTimePicker2.Value.ToString("MM/dd/yyyy")) item.SubItems.Add(DateTimePicker3.Value.ToString("MM/dd/yyyy")) item.SubItems.Add(DateTimePicker4.Value.ToString("MM/dd/yyyy")) item.SubItems.Add(TextBox9.Text) InsertMyData2(connectionString) ReadMydata2(connectionString) Else With ListView1 Dim itm As ListViewItem itm = .FindItemWithText(TextBox9.Text, True, 0, True) If Not itm Is Nothing Then MessageBox.Show("ข้อมูลของเตียง " & TextBox9.Text & " มีอยู่ในตารางอยู่แล้ว", "ข้อความจากระบบ", MessageBoxButtons.OK, MessageBoxIcon.Information) Else item = ListView1.Items.Add(TextBox1.Text) item.SubItems.Add(TextBox2.Text) item.SubItems.Add(TextBox3.Text) item.SubItems.Add(DateTimePicker1.Value.ToString("MM/dd/yyyy")) item.SubItems.Add(TextBox5.Text) item.SubItems.Add(DateTimePicker2.Value.ToString("MM/dd/yyyy")) item.SubItems.Add(DateTimePicker3.Value.ToString("MM/dd/yyyy")) item.SubItems.Add(DateTimePicker4.Value.ToString("MM/dd/yyyy")) item.SubItems.Add(TextBox9.Text) InsertMyData2(connectionString) ReadMydata2(connectionString) End If End With End If End If End Sub Private Sub btn_addview_Click(sender As Object, e As EventArgs) Handles btn_addview.Click Call add() End Sub Private Sub DeleteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ClearToolStripMenuItem.Click ListView1.Items.Clear() End Sub Private Sub RemoveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RemoveToolStripMenuItem.Click For i As Integer = ListView1.Items.Count - 1 To 0 Step -1 If ListView1.Items(i).Selected Then ListView1.Items.RemoveAt(i) Next deleteData(connectionString) End Sub Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged If ListView1.SelectedItems.Count > 0 Then TextBox1.Text = ListView1.SelectedItems(0).SubItems(0).Text TextBox2.Text = ListView1.SelectedItems(0).SubItems(1).Text TextBox3.Text = ListView1.SelectedItems(0).SubItems(2).Text DateTimePicker1.Value = ListView1.SelectedItems(0).SubItems(3).Text TextBox5.Text = ListView1.SelectedItems(0).SubItems(4).Text DateTimePicker2.Value = ListView1.SelectedItems(0).SubItems(5).Text DateTimePicker3.Value = ListView1.SelectedItems(0).SubItems(6).Text DateTimePicker4.Value = ListView1.SelectedItems(0).SubItems(7).Text TextBox9.Text = ListView1.SelectedItems(0).SubItems(8).Text End If End Sub Private Sub searchw_Click(sender As Object, e As EventArgs) Handles searchw.Click patient_allo_ward_search.Show() End Sub Private Sub btn_patient_Click(sender As Object, e As EventArgs) Handles btn_patient.Click patient.Show() Me.Close() End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles btnd_staff_allocation.Click staff_allocation.Show() Me.Close() End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btn_patient_appointment.Click Patient_appointment.Show() Me.Close() End Sub Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles btn_patient_medication.Click patient_medication.Show() Me.Close() End Sub Private Sub btn_suppiler_Click(sender As Object, e As EventArgs) Handles btn_suppiler.Click Suppiler.Show() Me.Close() End Sub Private Sub btn_vaccine_oder_Click(sender As Object, e As EventArgs) Handles btn_vaccine_oder.Click vaccine_order.Show() Me.Close() End Sub Private Sub btn_logout_Click(sender As Object, e As EventArgs) Handles btn_logout.Click LOGIN.Show() Me.Close() End Sub Private Sub btn_staff_Click(sender As Object, e As EventArgs) Handles btn_staff.Click staff.Show() Me.Close() End Sub Private Sub btn_patient_allocation_Click(sender As Object, e As EventArgs) Handles btn_patient_allocation.Click End Sub Private Sub btn_search_Click(sender As Object, e As EventArgs) Handles btn_search.Click patient_allo_search.Show() End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click patient_patient_search.Show() End Sub End Class
Imports System.Data.SqlClient Imports sys_ui Imports System.Drawing Public Class SingleSell Inherits System.Web.UI.Page Private cnSQL As SqlConnection Private strSQL As String Private cmSQL As SqlCommand Private drSQL As SqlDataReader Private object_userlog As New usrlog.usrlog Private currency As String Private Days As String Private MatAmount As String Private selloption As String Private maturity As String Private selectedItem As Integer Private cost As Decimal = 0 'Private SellPV As Decimal = 0 Private TotalProfit As Decimal = 0 Private maturityAmt As Decimal = 0 Private PortID As Integer Dim Buyback As String = "" Private SellingOption As String Private securityRef As String Private dealRef As String Private backvalue As Integer Dim comm As Decimal Dim interest As Decimal 'Private lblFV As Decimal 'Private PV As Decimal Private commrate As Decimal Private PresentV, MaturityV, intToDate ', cost As Decimal Private DealPortfolio As String Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then If Not Request.ServerVariables("QUERY_STRING") Is Nothing Then currency = Request.QueryString("currency") Days = Request.QueryString("Days") MatAmount = Request.QueryString("MatAmount") selloptionValue.Text = Request.QueryString("selloption") Else lblError.Text = alert("Please make sure all fields are selected On the newDeal Page", "Incomplete informaton") End If Call load_TBs(currency, MatAmount, Days, selloptionValue.Text) End If End Sub Public Sub load_TBs(ByVal ccy As String, ByVal amt As Double, ByVal daysR As Integer, ByVal sellOpt As String) Try If sellOpt = "Discount" Then strSQL = "select securitypurchase.tb_id,securitypurchase.dealreference from securitypurchase join" & _ " deals_live on securitypurchase.tb_id=deals_live.TB_ID and deals_live.dealreference=" & _ " securitypurchase.dealreference join dealtypes on dealtypes.deal_code=deals_live.dealtype " & _ " where dealtypes.othercharacteristics='Trading' and matured = 'N' and daystomaturity >2 and" & _ " authorisationstatus='A' and dealtypes.currency='" & Trim(ccy) & "' and daystomaturity >= " & daysR & "" & _ " and deals_live.maturityamount>=" & amt & " and entrytype='D'" ElseIf sellOpt = "Yield" Then strSQL = "select securitypurchase.tb_id,securitypurchase.dealreference from securitypurchase join" & _ " deals_live on securitypurchase.tb_id=deals_live.TB_ID and deals_live.dealreference=" & _ " securitypurchase.dealreference join dealtypes on dealtypes.deal_code=deals_live.dealtype " & _ " where dealtypes.othercharacteristics='Trading' and matured = 'N' and daystomaturity >2 and" & _ " authorisationstatus='A' and dealtypes.currency='" & Trim(ccy) & "' and daystomaturity >= " & daysR & "" & _ " and deals_live.dealamount>=" & amt & " and entrytype='Y'" Else strSQL = "select securitypurchase.tb_id,securitypurchase.dealreference from securitypurchase join" & _ " deals_live on securitypurchase.tb_id=deals_live.TB_ID and deals_live.dealreference=" & _ " securitypurchase.dealreference join dealtypes on dealtypes.deal_code=deals_live.dealtype " & _ " where dealtypes.othercharacteristics='Trading' and matured = 'N' and daystomaturity >2 and" & _ " authorisationstatus='A' and dealtypes.currency='" & Trim(ccy) & "' and daystomaturity >= " & daysR & "" End If cnSQL = New SqlConnection(Session("ConnectionString")) cnSQL.Open() cmSQL = New SqlCommand(strSQL, cnSQL) drSQL = cmSQL.ExecuteReader() 'ListTbs.Items.Clear() Do While drSQL.Read If Checkamount(Trim(drSQL.Item(0).ToString), Trim(drSQL.Item(1).ToString)) = True Then 'Dim itms As New ListViewItem(Trim(drSQL.Item(0).ToString)) 'itms.SubItems.Add(Trim(drSQL.Item(1).ToString)) 'ListTbs.Items.Add(itms) cmbTB.Items.Add(New ListItem(Trim(drSQL.Item(0).ToString) + " " + Trim(drSQL.Item(1).ToString), Trim(drSQL.Item(0).ToString))) End If Loop ' Close and Clean up objects drSQL.Close() cnSQL.Close() cmSQL.Dispose() cnSQL.Dispose() Catch ex As SqlException MsgBox(ex.Message, MsgBoxStyle.Critical) 'Log the event ***************************************************** object_userlog.SendDataToLog(Session("username") & "ERR001" & Format(Now, "dd/MM/yyyy hh:mm:ss") & ex.Message, Session("serverName"), Session("client")) '************************END**************************************** End Try End Sub Private Function Checkamount(ByVal TBid As String, ByVal DealRef As String) As Boolean Dim cnSQL1 As SqlConnection Dim cmSQL1 As SqlCommand Dim drSQL1 As SqlDataReader Dim strSQL1 As String Try 'validate username first strSQL1 = "select Dealamount,maturityamount,entrytype from deals_live where tb_id='" & TBid & "' and dealreference='" & DealRef & "'" cnSQL1 = New SqlConnection(Session("ConnectionString")) cnSQL1.Open() cmSQL1 = New SqlCommand(strSQL1, cnSQL1) drSQL1 = cmSQL1.ExecuteReader() Do While drSQL1.Read If Trim(drSQL1.Item(2)).ToString = "D" Then If CDec(drSQL1.Item(1)) <= 0 Then Return False End If Else If CDec(drSQL1.Item(0)) <= 0 Then Return False End If End If Loop ' Close and Clean up objects drSQL1.Close() cnSQL1.Close() cmSQL1.Dispose() cnSQL1.Dispose() Return True Catch ex As SqlException MsgBox(ex.Message, MsgBoxStyle.Critical) 'Log the event ***************************************************** object_userlog.SendDataToLog(Session("username") & "ERR001" & Format(Now, "dd/MM/yyyy hh:mm:ss") & ex.Message, Session("serverName"), Session("client")) '************************END**************************************** End Try End Function Protected Sub cmbTB_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbTB.SelectedIndexChanged 'Get details about the security Dim cnSQL1 As SqlConnection Dim strSQL1 As String Dim cmSQL1 As SqlCommand Dim drSQL1 As SqlDataReader Dim accruedInt As Decimal 'Get details about the security If cmbTB.SelectedValue.ToString <> "" Then Try strSQL1 = "select deals_live.dealamount as amt,securitypurchase.amtavailable,securitypurchase.dealamount as secamt,securitypurchase.interestRate as Rate,deals_live.entrytype,deals_live.Currency as curr,securitypurchase.maturitydate as matdate,deals_live.MaturityAmount as matAmt,deals_live.tenor,deals_live.daystomaturity,deals_live.Discountrate as disc,deals_live.intdaysbasis,deals_live.StartDate as start ,deals_live.intaccruedtodate,deals_live.Acceptancerate from securitypurchase join deals_live on securitypurchase.tb_id=deals_live.TB_ID " & _ " where securitypurchase.tb_id ='" & cmbTB.SelectedValue.ToString & "' and deals_live.TB_ID ='" & cmbTB.SelectedValue.ToString & "'" & _ " and securitypurchase.dealreference='" & getRef(Trim(cmbTB.SelectedValue.ToString)) & "' and" & _ " deals_live.dealreference='" & getRef(Trim(cmbTB.SelectedValue.ToString)) & "' and deals_live.othercharacteristics='Discount Purchase' " cnSQL1 = New SqlConnection(Session("ConnectionString")) cnSQL1.Open() cmSQL1 = New SqlCommand(strSQL1, cnSQL1) drSQL1 = cmSQL1.ExecuteReader() Do While drSQL1.Read If drSQL1.Item("entrytype").ToString = "D" Then avalAtPV.Text = "Amount Available" lblCostDesc2.Visible = False txtAvalableForSale.Visible = False accruedInt = CDec(drSQL1.Item("matAmt").ToString) * (CInt(drSQL1.Item("tenor")) - CInt(drSQL1.Item("daystomaturity"))) * CDec(drSQL1.Item("disc")) / (CDec(drSQL1.Item("intdaysbasis")) * 100) txtAvalableForSale.Text = CDec(drSQL1.Item("matAmt").ToString) - SecurityAttached() lblAvalableForSalePV.Text = CDec(drSQL1.Item("matAmt").ToString) - SecurityAttached() txtPurValue.Text = drSQL1.Item("secamt").ToString txtIntRate.Text = drSQL1.Item("Rate").ToString lblDesc.Text = "Maturity Value" rate.Text = "Discount Rate" DealPortfolio = "D" Else txtAvalableForSale.Text = CDec(drSQL1.Item("amt").ToString) - SecurityAttached() accruedInt = CDec(drSQL1.Item("amt").ToString) * (CInt(drSQL1.Item("tenor")) - CInt(drSQL1.Item("daystomaturity"))) * CDec(drSQL1.Item("interestrate")) / (CDec(drSQL1.Item("intdaysbasis")) * 100) lblAvalableForSalePV.Text = CDec(drSQL1.Item("amt").ToString) + accruedInt - SecurityAttached() txtPurValue.Text = drSQL1.Item("secamt").ToString txtIntRate.Text = drSQL1.Item("Rate").ToString lblDesc.Text = "Purchase Value" rate.Text = "Yield Rate" DealPortfolio = "Y" End If 'MsgBox(CDec(drSQL1.Item("matAmt").ToString)) lbltb.Text = Trim(cmbTB.SelectedValue.ToString) lblAvalableForSalePV.Text = Format(CDec(lblAvalableForSalePV.Text), "###,###,###.00") txtAvalableForSale.Text = Format(CDec(txtAvalableForSale.Text), "###,###,###.00") lblBasis.Text = drSQL1.Item("intdaysbasis").ToString lblPurchaseStart.Text = drSQL1.Item("start").ToString lblCurrency.Text = drSQL1.Item("curr").ToString txtDaysMaturity.Text = DateDiff(DateInterval.Day, CDate(Session("SysDate")), CDate(drSQL1.Item("matdate"))) txtmaturity.Text = drSQL1.Item("matdate").ToString lblTenor.Text = drSQL1.Item("tenor").ToString txtSellTenor.Text = txtDaysMaturity.Text commrate = CDec(drSQL1.Item("Acceptancerate")) comm = CDec(drSQL1.Item("amt")) * CDec(drSQL1.Item("Acceptancerate")) * Int(drSQL1.Item("tenor")) / (Int(lblBasis.Text) * 100) PresentV = CDec(drSQL1.Item("amt").ToString) interest = PresentV * CDec(lblTenor.Text) * CDec(txtIntRate.Text) / (Int(lblBasis.Text) * 100) MaturityV = PresentV + interest 'lblSellingOPT.Text = selloption 'MaturityV = CDec(drSQL.Item(12).ToString) intToDate = CDec(drSQL1.Item("intaccruedtodate").ToString) lblDealAmount.Text = CDec(drSQL1.Item("amt").ToString) lblfv.Text = CDec(drSQL1.Item("matAmt").ToString) lblpv.Text = CDec(drSQL1.Item("amt").ToString) + comm + accruedInt If Trim(rate.Text) = "Discount Rate" Then lblbreakeven.Text = BreakEvenRate(CDec(drSQL1.Item("matAmt").ToString), CDec(drSQL1.Item("amt").ToString) + comm + accruedInt, Int(drSQL1.Item("intdaysbasis").ToString), Int(drSQL1.Item("daystomaturity").ToString), DealPortfolio) 'MaturityV = CDec(drSQL.Item(12).ToString) Else lblbreakeven.Text = BreakEvenRate(MaturityV, CDec(drSQL1.Item("amt").ToString) + comm + accruedInt, Int(drSQL1.Item("intdaysbasis").ToString), Int(drSQL1.Item("daystomaturity").ToString), DealPortfolio) End If Loop ' Close and Clean up objects drSQL1.Close() cnSQL1.Close() cmSQL1.Dispose() cnSQL1.Dispose() Catch xx As NullReferenceException Catch ex As SqlException MsgBox(ex.Message, MsgBoxStyle.Critical) 'Log the event ***************************************************** object_userlog.SendDataToLog(Session("username") & "ERR001" & Format(Now, "dd/MM/yyyy hh:mm:ss") & ex.Message, Session("serverName"), Session("client")) '************************END**************************************** End Try End If End Sub Private Sub checkAmtAvailable() Dim accruedInt As Decimal 'Get details about the security If Trim(cmbTB.SelectedValue.ToString) <> "" Then Try strSQL = "select * from securitypurchase join deals_live on securitypurchase.tb_id=deals_live.TB_ID " & _ " where securitypurchase.tb_id ='" & Trim(cmbTB.SelectedValue.ToString) & "' and deals_live.TB_ID ='" & Trim(cmbTB.SelectedValue.ToString) & "'" & _ " and securitypurchase.dealreference='" & getRef(Trim(cmbTB.SelectedValue.ToString)) & "' and" & _ " deals_live.dealreference='" & getRef(Trim(cmbTB.SelectedValue.ToString)) & "' and deals_live.othercharacteristics='Discount Purchase' " cnSQL = New SqlConnection(Session("ConnectionString")) cnSQL.Open() cmSQL = New SqlCommand(strSQL, cnSQL) drSQL = cmSQL.ExecuteReader() Do While drSQL.Read If drSQL.Item("entrytype").ToString = "D" Then avalAtPV.Text = "Amount Available" lblCostDesc2.Visible = False txtAvalableForSale.Visible = False accruedInt = CDec(drSQL.Item(13).ToString) * (CInt(drSQL.Item("tenor")) - CInt(drSQL.Item("daystomaturity"))) * CDec(drSQL.Item("Discountrate")) / (CDec(drSQL.Item("intdaysbasis")) * 100) txtAvalableForSale.Text = CDec(drSQL.Item(13).ToString) - SecurityAttached() lblAvalableForSalePV.Text = CDec(drSQL.Item(13).ToString) - SecurityAttached() txtPurValue.Text = drSQL.Item(2).ToString txtIntRate.Text = drSQL.Item(3).ToString lblDesc.Text = "Maturity Value" rate.Text = "Discount Rate" DealPortfolio = "D" Else txtAvalableForSale.Text = CDec(drSQL.Item(12).ToString) - SecurityAttached() accruedInt = CDec(drSQL.Item(12).ToString) * (CInt(drSQL.Item("tenor")) - CInt(drSQL.Item("daystomaturity"))) * CDec(drSQL.Item("interestrate")) / (CDec(drSQL.Item("intdaysbasis")) * 100) lblAvalableForSalePV.Text = CDec(drSQL.Item(12).ToString) + accruedInt - SecurityAttached() txtPurValue.Text = drSQL.Item(2).ToString txtIntRate.Text = drSQL.Item(3).ToString lblDesc.Text = "Purchase Value" rate.Text = "Yield Rate" DealPortfolio = "Y" End If lbltb.Text = Trim(cmbTB.SelectedValue.ToString) lblAvalableForSalePV.Text = Format(CDec(lblAvalableForSalePV.Text), "###,###,###.00") txtAvalableForSale.Text = Format(CDec(txtAvalableForSale.Text), "###,###,###.00") txtAvalableForSale.ForeColor = Color.Blue lblBasis.Text = drSQL.Item("intdaysbasis").ToString lblPurchaseStart.Text = drSQL.Item("startdate").ToString lblCurrency.Text = drSQL.Item("currency").ToString txtDaysMaturity.Text = DateDiff(DateInterval.Day, CDate(Session("SysDate")), CDate(drSQL.Item(4))) maturity = drSQL.Item(4).ToString lblTenor.Text = drSQL.Item("tenor").ToString txtSellTenor.Text = txtDaysMaturity.Text commrate = CDec(drSQL.Item("Acceptancerate")) comm = CDec(drSQL.Item(12)) * CDec(drSQL.Item("Acceptancerate")) * Int(drSQL.Item("tenor")) / (Int(lblBasis.Text) * 100) PresentV = CDec(drSQL.Item(12).ToString) interest = PresentV * CDec(lblTenor.Text) * CDec(txtIntRate.Text) / (Int(lblBasis.Text) * 100) MaturityV = PresentV + interest 'MaturityV = CDec(drSQL.Item(12).ToString) intToDate = CDec(drSQL.Item("intaccruedtodate").ToString) lblDealAmount.Text = CDec(drSQL.Item(12).ToString) lblfv.Text = CDec(drSQL.Item(13).ToString) lblpv.Text = CDec(drSQL.Item(12).ToString) + comm + accruedInt If Trim(rate.Text) = "Discount Rate" Then lblbreakeven.Text = BreakEvenRate(CDec(drSQL.Item(13).ToString), CDec(drSQL.Item(12).ToString) + comm + accruedInt, Int(drSQL.Item("intdaysbasis").ToString), Int(drSQL.Item("daystomaturity").ToString), DealPortfolio) lblbreakeven.ForeColor = Color.Green 'MaturityV = CDec(drSQL.Item(12).ToString) Else lblbreakeven.Text = BreakEvenRate(MaturityV, CDec(drSQL.Item(12).ToString) + comm + accruedInt, Int(drSQL.Item("intdaysbasis").ToString), Int(drSQL.Item("daystomaturity").ToString), DealPortfolio) lblbreakeven.ForeColor = Color.Green End If Loop ' Close and Clean up objects drSQL.Close() cnSQL.Close() cmSQL.Dispose() cnSQL.Dispose() Catch xx As NullReferenceException Catch ex As SqlException MsgBox(ex.Message, MsgBoxStyle.Critical) 'Log the event ***************************************************** object_userlog.SendDataToLog(Session("username") & "ERR001" & Format(Now, "dd/MM/yyyy hh:mm:ss") & ex.Message, Session("serverName"), Session("client")) '************************END**************************************** End Try End If End Sub Private Function getRef(ByVal tb As String) Try strSQL = " select securitypurchase.dealreference, matured from securitypurchase join deals_live on securitypurchase.dealreference=deals_live.dealreference" & _ " where matured = 'N' and authorisationstatus='A' and deals_live.tb_id='" & tb & "' " cnSQL = New SqlConnection(Session("ConnectionString")) cnSQL.Open() cmSQL = New SqlCommand(strSQL, cnSQL) drSQL = cmSQL.ExecuteReader() Do While drSQL.Read Return Trim(drSQL.Item(0).ToString) Loop ' Close and Clean up objects drSQL.Close() cnSQL.Close() cmSQL.Dispose() cnSQL.Dispose() Catch ex As SqlException MsgBox(ex.Message, MsgBoxStyle.Critical) 'Log the event ***************************************************** object_userlog.SendDataToLog(Session("username") & "ERR001" & Format(Now, "dd/MM/yyyy hh:mm:ss") & ex.Message, Session("serverName"), Session("client")) '************************END**************************************** End Try End Function Private Function SecurityAttached() As Decimal Dim x As String Dim cnSQL1 As SqlConnection Dim cmSQL1 As SqlCommand Dim drSQL1 As SqlDataReader Dim strSQL1 As String Try 'validate username first strSQL1 = "select sum(securityamount)[hhh] from attachedsecurities where tb_id = '" & Trim(cmbTB.SelectedValue.ToString) & "' and dealreferencesecurity='" & getRef(Trim(cmbTB.SelectedValue.ToString)) & "' " cnSQL1 = New SqlConnection(Session("ConnectionString")) cnSQL1.Open() cmSQL1 = New SqlCommand(strSQL1, cnSQL1) drSQL1 = cmSQL1.ExecuteReader() If drSQL.HasRows = True Then Do While drSQL1.Read x = drSQL1.Item(0).ToString Loop End If ' Close and Clean up objects drSQL1.Close() cnSQL1.Close() cmSQL1.Dispose() cnSQL1.Dispose() If x = "" Then x = "0" Return CDec(x) Catch ex As SqlException MsgBox(ex.Message, MsgBoxStyle.Critical) 'Log the event ***************************************************** object_userlog.SendDataToLog(Session("username") & "ERR001" & Format(Now, "dd/MM/yyyy hh:mm:ss") & ex.Message, Session("serverName"), Session("client")) '************************END**************************************** End Try End Function Protected Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click txtSellTenor.Enabled = True txtSaleRate.Enabled = True txtSale.Enabled = True btnSale.Enabled = False cmbTB.Enabled = True End Sub Protected Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click Response.Redirect("newsell.aspx") End Sub Protected Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click Dim SellingAmt As Decimal Dim amount As Decimal If Trim(lblSellingOPT.Text) = "" Then MsgBox("Select Selling option.", MsgBoxStyle.Information, "Sell Option") lblSellingOPT.Focus() Exit Sub End If If Trim(lblAvalableForSalePV.Text) = "" Then Exit Sub End If If Trim(lblSellingOPT.Text).Equals("Cost") Then SellingAmt = CDec(txtAvalableForSale.Text) Else SellingAmt = CDec(lblAvalableForSalePV.Text) End If lblSellingOPT.ForeColor = Color.Green 'If Trim(Label4.Text) = "Interest Rate" Then 'amount = CDec(Label11.Text) 'Else If txtSale.Text = "" Then MsgBox("Enter Sale amount.", MsgBoxStyle.Critical, "Sale") Exit Sub End If amount = CDec(txtSale.Text) 'End If If CDec(txtSale.Text) = 0 Then MsgBox("Sale amount cannot be zero.", MsgBoxStyle.Critical, "Inconsistent operation") Exit Sub End If Try If Int(txtSellTenor.Text) > Int(lblTenor.Text) Then MsgBox("Tenor for sale cannot be greater than tenor purchase", MsgBoxStyle.Critical, "Tenor") Exit Sub End If 'check if amount is not greater than what is available to sale If SellingAmt - amount < 0 Then MsgBox("Sale amount is greater than what is available.", MsgBoxStyle.Critical, "Sale") Exit Sub End If If rate.Text = "Discount Rate" Then DiscountMethod() Else YieldMethod() End If cmbTB.Enabled = False btnSale.Enabled = True Catch xs As Exception MsgBox(xs.Message, MsgBoxStyle.Critical) End Try End Sub Private Sub DiscountMethod() Dim TotalProfit As Decimal Dim IntClient As Decimal Dim TotalInterest As Decimal Dim days As Integer Dim AccruedOnSaleAmt As Decimal Dim EffectiveRate As Decimal Dim intToDate1 As Decimal Dim comm As Decimal btnSale.Enabled = False 'Holding period Yield Variables Dim HoldingReturn As Decimal ' Holding return - Accrued interest Plus the Profit/Loss on the sale Dim AHPY As Decimal ' Annual Holding Preiod Yield If txtSellTenor.Text = "" Then Exit Sub End If If txtSaleRate.Text = "" Then MsgBox("Enter the interest rate", MsgBoxStyle.Critical) Exit Sub End If If txtSale.Text = "" Then Exit Sub End If comm = CDec(lblfv.Text) * commrate * Int(lblTenor.Text) / (Int(lblBasis.Text) * 100) If Int(txtSellTenor.Text) > Int(txtDaysMaturity.Text) Then MsgBox("Transaction will be backvalued and Breakeven rate will change.", MsgBoxStyle.Information, "Sell") intToDate1 = (CDec(lblfv.Text) * (CDec(txtIntRate.Text)) * (CDec(lblTenor.Text) - Int(txtSellTenor.Text))) / (Int(lblBasis.Text) * 100) lblbreakeven.Text = BreakEvenRate(CDec(lblfv.Text), CDec(lblpv.Text) + comm + intToDate1, Int(lblBasis.Text), Int(txtSellTenor.Text), "D") ElseIf Int(txtSellTenor.Text) < Int(txtDaysMaturity.Text) Then intToDate1 = (CDec(lblfv.Text) * (CDec(txtIntRate.Text)) * (CDec(lblTenor.Text) - Int(txtDaysMaturity.Text))) / (Int(lblBasis.Text) * 100) lblbreakeven.Text = BreakEvenRate(CDec(lblfv.Text), CDec(lblpv.Text), Int(lblBasis.Text), Int(txtSellTenor.Text), "D") Else lblbreakeven.Text = BreakEvenRate(CDec(lblfv.Text), CDec(lblpv.Text), Int(lblBasis.Text), Int(txtDaysMaturity.Text), "D") End If 'Get accrual on sell amount If Int(txtDaysMaturity.Text) < Int(txtSellTenor.Text) Then backvalue = Int(txtSellTenor.Text) - Int(txtDaysMaturity.Text) days = (Int(lblTenor.Text) - Int(txtSellTenor.Text)) 'AccruedOnSaleAmt = (CDec(txtSale.Text) * (CDec(txtIntRate.Text)) * (Int(lblTenor.Text) - Int(txtSellTenor.Text))) / (Int(lblBasis.Text) * 100) Else 'AccruedOnSaleAmt = (CDec(txtSale.Text) * (CDec(txtIntRate.Text)) * (CDec(lblTenor.Text) - Int(DaysMaturity.Text))) / (Int(lblBasis.Text) * 100) days = (CDec(lblTenor.Text) - Int(txtDaysMaturity.Text)) backvalue = 0 End If 'get present value of sell amount txtSellPV.text = CDec(txtSale.Text) * (1 - (CDec(txtSaleRate.Text) * days / (Int(lblBasis.Text) * 100))) 'SellPV = CDec(txtSale.Text) - AccruedOnSaleAmt 'Calculate total interest to be accrued on sell amount for days to maturity 'TotalInterest = CDec(txtSale.Text) * CDec(mmt.Text) * Int(txtSellTenor.Text) / (Int(lblBasis.Text) * 100) TotalInterest = (CDec(txtSale.Text) * (CDec(txtIntRate.Text)) * Int(txtSellTenor.Text)) / (Int(lblBasis.Text) * 100) 'Calculate interest due to client IntClient = CDec(txtSale.Text) * CDec(txtSaleRate.Text * Int(txtSellTenor.Text)) / (Int(lblBasis.Text) * 100) 'Calculate own profit TotalProfit = TotalInterest - IntClient If TotalProfit < 0 Then lblprofit.Text = "Capital Loss" Else lblprofit.Text = "Capital gain" End If 'Calculate the effective rate for the client 'lblEffectiveRate.Text = Math.Round((IntClient * Int(lblBasis.Text) * 100) / (CDec(txtSale.Text) * Int(txtSellTenor.Text)), 9) txtProfit.Text = Format(TotalProfit, "###,###,###.00") 'Label11.Text = Format(SellPV, "###,###,###.00") TotalInterest = (CDec(txtSale.Text) * (CDec(txtIntRate.Text)) * Int(lblTenor.Text)) / (Int(lblBasis.Text) * 100) cost = CDec(txtSale.Text) - TotalInterest lblCost.Text = Format(cost, "###,###,###.00") lblCost.ForeColor = Color.Red 'Compute the holding period Yieldtxt HoldingReturn = ((Int(lblTenor.Text) - Int(txtDaysMaturity.Text)) * (CDec(txtIntRate.Text) * CDec(txtSale.Text) / 100) / CDec(lblBasis.Text)) + TotalProfit If (Int(lblTenor.Text) - Int(txtDaysMaturity.Text)) = 0 Then AHPY = 0 Else AHPY = (HoldingReturn / cost) * (CDec(lblBasis.Text) * 100 / (Int(lblTenor.Text) - Int(txtDaysMaturity.Text))) ' (return/Amount Invested)* (DaysBasis/Number of days invested) End If AnnualisedHPY.Text = Format(AHPY, "###,###.00") 'End of AHPY Calculations txtSellTenor.Enabled = False txtSaleRate.Enabled = False txtSale.Enabled = False btnSale.Enabled = True End Sub 'calculate break even rate for purchase on sell Private Function BreakEvenRate(ByVal maturityvalue As Decimal, ByVal presentvalue As Decimal, ByVal intdaysB As Integer, ByVal daysTomaturity As Integer, ByVal RateType As String) As Decimal Dim remainAccrual As Decimal = 0 Dim brkRate As Decimal Dim x As Decimal If RateType = "Y" Then 'Formula: FV=PV(1+(Rate*Ttime/DaysBasis*100)) brkRate = ((maturityvalue / presentvalue) - 1) * (intdaysB * 100 / daysTomaturity) Else 'Formula: PV = FV(1-(Rate*Ttime/DaysBasis*100)) brkRate = (1 - (presentvalue / maturityvalue)) * (intdaysB * 100 / daysTomaturity) End If Return Math.Round(brkRate, 9) End Function Private Sub YieldMethod() Dim TotalProfit As Decimal Dim IntClient As Decimal Dim TotalInterest As Decimal Dim AccruedOnSaleAmt As Decimal 'Dim SellPV As Decimal Dim EffectiveRate As Decimal Dim intToDate1 As Decimal Dim interest As Decimal Dim DaysRun As Integer Dim MaturityAmnt As Decimal btnSale.Enabled = False 'Holding period Yield Variables Dim HoldingReturn As Decimal ' Holding return - Accrued interest Plus the Profit/Loss on the sale Dim AHPY As Decimal ' Annual Holding Preiod Yield If txtSellTenor.Text = "" Then Exit Sub End If If txtSaleRate.Text = "" Then MsgBox("Enter the interest rate", MsgBoxStyle.Critical) Exit Sub End If If txtSale.Text = "" Then Exit Sub End If interest = PresentV * CDec(lblTenor.Text) * CDec(txtIntRate.Text) / (Int(lblBasis.Text) * 100) lblfv = PresentV + interest If Int(txtSellTenor.Text) > Int(txtDaysMaturity.Text) Then 'tenor of sale is greater than days to maturity of purchase MsgBox("Transaction will be backvalued and breakeven rate will change.", MsgBoxStyle.Information, "Sell") intToDate1 = (PresentV * (CDec(txtIntRate.Text)) * (CDec(lblTenor.Text) - Int(txtSellTenor.Text))) / (Int(lblBasis.Text) * 100) lblbreakeven.Text = BreakEvenRate(CDec(lblfv.Text), PresentV + intToDate1, Int(lblBasis.Text), Int(txtSellTenor.Text), "Y") ElseIf Int(txtSellTenor.Text) < Int(txtDaysMaturity.Text) Then 'tenor of sale is less than days to maturity of purchase intToDate1 = (PresentV * (CDec(txtIntRate.Text)) * (CDec(lblTenor.Text) - Int(txtDaysMaturity.Text))) / (Int(lblBasis.Text) * 100) lblbreakeven.Text = BreakEvenRate(CDec(lblfv.Text), PresentV + intToDate1, Int(lblBasis.Text), Int(txtSellTenor.Text), "Y") Else 'tenor of sale is equal to days to maturity of purchase lblbreakeven.Text = BreakEvenRate(CDec(lblfv.Text), PresentV + intToDate, Int(lblBasis.Text), Int(txtDaysMaturity.Text), "Y") End If 'Get accrual on sell amount If Int(txtDaysMaturity.Text) < Int(txtSellTenor.Text) Then backvalue = Int(txtSellTenor.Text) - Int(txtDaysMaturity.Text) DaysRun = (CDec(lblTenor.Text) - Int(txtSellTenor.Text)) 'AccruedOnSaleAmt = (CDec(txtSale.Text) * (CDec(txtIntRate.Text)) * (CDec(lblTenor.Text) - Int(txtSellTenor.Text))) / (Int(lblBasis.Text) * 100) DaysRun = (CDec(lblTenor.Text) - Int(txtSellTenor.Text)) Else 'AccruedOnSaleAmt = (CDec(txtSale.Text) * (CDec(txtIntRate.Text)) * (CDec(lblTenor.Text) - Int(txtDaysMaturity.Text))) / (Int(lblBasis.Text) * 100) DaysRun = (CDec(lblTenor.Text) - Int(txtDaysMaturity.Text)) backvalue = 0 End If txtSellPV.Text = CDec(txtSale.Text) cost = CDec(txtSellPV.Text) / (1 + ((DaysRun * CDec(txtIntRate.Text)) / (Int(lblBasis.Text) * 100))) AccruedOnSaleAmt = CDec(txtSellPV.Text) - cost 'Calculate total interest to be accrued from inception to maturity TotalInterest = cost * Int(lblTenor.Text) * CDec(txtIntRate.Text) / (Int(lblBasis.Text) * 100) 'Client interest IntClient = CDec(txtSellPV.Text) * CDec(txtSaleRate.Text * Int(txtSellTenor.Text)) / (Int(lblBasis.Text) * 100) 'Capital gain TotalProfit = TotalInterest - IntClient - AccruedOnSaleAmt 'Calculate the effective rate for the client 'lblEffectiveRate.Text = Math.Round((IntClient * Int(lblBasis.Text) * 100) / (CDec(txtSellPV.Text) * Int(txtSellTenor.Text)), 9) 'Calculate client maturity amount MaturityAmnt = CDec(txtSale.Text) + IntClient '************************************************************************************** ''Calculate own profit 'TotalProfit = TotalInterest - IntClient If TotalProfit < 0 Then lblprofit.Text = "Capital Loss" Else lblprofit.Text = "Capital gain" End If txtProfit.Text = Format(TotalProfit, "###,###,###.00") txtProfit.ForeColor = Color.BlueViolet 'Label11.Text = Format(CDec(txtSellPV.Text), "###,###,###.00") lblCost.Text = Format(cost, "###,###,###.00") lblCost.ForeColor = Color.Red 'Compute the holding period Yield HoldingReturn = ((Int(lblTenor.Text) - Int(txtDaysMaturity.Text)) * (CDec(txtIntRate.Text) * CDec(txtSale.Text) / 100) / CDec(lblBasis.Text)) + TotalProfit If (Int(lblTenor.Text) - Int(txtDaysMaturity.Text)) = 0 Then AHPY = 0 Else AHPY = (HoldingReturn / cost) * (CDec(lblBasis.Text) * 100 / (Int(lblTenor.Text) - Int(txtDaysMaturity.Text))) ' (return/Amount Invested)* (DaysBasis/Number of days invested) End If AnnualisedHPY.Text = Format(AHPY, "###,###.00") 'End of AHPY Calculations txtSellTenor.Enabled = False txtSaleRate.Enabled = False txtSale.Enabled = False btnSale.Enabled = True End Sub Protected Sub btnSale_Click(sender As Object, e As EventArgs) Handles btnSale.Click On Error Resume Next 'Call this routing to re-validate amount available for sell checkAmtAvailable() Dim SellingAmt As Decimal Dim amount As Decimal If Trim(lblSellingOPT.Text) = "" Then MsgBox("Select Selling option.", MsgBoxStyle.Information, "Sell Option") lblSellingOPT.Focus() Exit Sub End If If Trim(lblSellingOPT.Text).Equals("Cost") Then SellingAmt = CDec(txtAvalableForSale.Text) Else SellingAmt = CDec(lblAvalableForSalePV.Text) End If If Trim(rate.Text) = "Interest Rate" Then amount = CDec(lblCost.Text) Else amount = CDec(txtSale.Text) End If If Trim(txtSaleRate.Text) = "" Then MsgBox("Enter the interest rate.", MsgBoxStyle.Critical, "Sale") Exit Sub End If If txtSale.Text = "" Then MsgBox("Enter Sale amount.", MsgBoxStyle.Critical, "Sale") Exit Sub End If 'check if amount is not greater than what is available to sale If SellingAmt - amount < 0 Then MsgBox("Sale amount is greater than what is available.", MsgBoxStyle.Critical, "Sale") Exit Sub End If If CDec(txtSale.Text) = 0 Then MsgBox("Sale amount cannot be zero.", MsgBoxStyle.Critical, "Inconsistent operation") Exit Sub End If 'If DealPortfolio = "D" Then ' DiscSale.Checked = True 'Else ' YieldSale.Checked = True 'End If ''Get the TB ID securityRef = Trim(cmbTB.SelectedValue.ToString) dealRef = getRef(Trim(cmbTB.SelectedValue.ToString)) SellingOption = "Security Sale - Single" Call saleDetails() Response.Redirect("SecuritySell.aspx") End Sub Private Sub saleDetails() Session("salestartD") = lblPurchaseStart.Text Session("saleMaturityD") = txtmaturity.Text Session("saleFutureValue") = txtSale.Text Session("saleTenor") = txtSellTenor.Text Session("saleDiscount") = txtSaleRate.Text Session("saleTB") = lbltb.Text Session("saleDealRef") = Trim(getRef(cmbTB.SelectedValue.ToString)) Session("saleOPT") = selloptionValue.Text Session("DaysBasis") = lblBasis.Text Session("currencySAle") = lblCurrency.Text Session("commrate") = commrate Session(" lblbreakeven") = lblbreakeven.Text Session("Gain") = txtProfit.Text Session("Cost") = lblCost.Text Session("PV") = CDec(txtSellPV.Text) Session("Single") = "Single" End Sub End Class
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "rCRetencion_ISLRProveedores_TUR" '-------------------------------------------------------------------------------------------' Partial Class rCRetencion_ISLRProveedores_TUR Inherits vis2formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia) Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia) Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia) Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia) Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia) Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia) Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia) Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia) Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden Dim loConsulta As New StringBuilder() loConsulta.AppendLine("SELECT Cuentas_Pagar.Tip_Ori AS Tipo_Origen,") loConsulta.AppendLine(" Cuentas_Pagar.Fec_Ini AS Fecha_Retencion,") loConsulta.AppendLine(" Cuentas_Pagar.Doc_Ori AS Numero_Pago,") loConsulta.AppendLine(" Facturas_Retenidas.Factura AS Numero_Factura,") loConsulta.AppendLine(" Facturas_Retenidas.Control AS Control_Factura,") loConsulta.AppendLine(" Retenciones_Documentos.Cod_Tip AS Tipo_Documento,") loConsulta.AppendLine(" Retenciones_Documentos.Doc_Ori AS Numero_Documento,") loConsulta.AppendLine(" Renglones_Pagos.Mon_Net AS Monto_Documento,") loConsulta.AppendLine(" Renglones_Pagos.Mon_Abo AS Monto_Abonado,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Bas AS Base_Retencion,") loConsulta.AppendLine(" Retenciones_Documentos.Por_Ret AS Porcentaje_Retenido,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Sus AS Sustraendo_Retenido,") loConsulta.AppendLine(" RTRIM(Retenciones.Cod_Ret) + ': ' + Retenciones.Nom_Ret AS Concepto,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Ret AS Monto_Retenido,") loConsulta.AppendLine(" Cuentas_Pagar.Cod_Pro AS Cod_Pro,") loConsulta.AppendLine(" Proveedores.Nom_Pro AS Nom_Pro,") loConsulta.AppendLine(" Proveedores.Rif AS Rif,") loConsulta.AppendLine(" Proveedores.Nit AS Nit,") loConsulta.AppendLine(" Proveedores.Dir_Fis AS Direccion") loConsulta.AppendLine("FROM Cuentas_Pagar") loConsulta.AppendLine(" JOIN Pagos ON Pagos.documento = Cuentas_Pagar.Doc_Ori") loConsulta.AppendLine(" JOIN Retenciones_Documentos ON Retenciones_Documentos.Documento = Pagos.documento") loConsulta.AppendLine(" AND Retenciones_Documentos.doc_des = Cuentas_Pagar.documento") loConsulta.AppendLine(" AND Retenciones_Documentos.clase = 'ISLR'") loConsulta.AppendLine(" JOIN Renglones_Pagos ON Renglones_Pagos.Documento = Pagos.documento") loConsulta.AppendLine(" AND Renglones_Pagos.Doc_Ori = Retenciones_Documentos.Doc_Ori") loConsulta.AppendLine(" JOIN Cuentas_Pagar Facturas_Retenidas") loConsulta.AppendLine(" ON Facturas_Retenidas.Documento = Retenciones_Documentos.Doc_Ori") loConsulta.AppendLine(" AND Facturas_Retenidas.Cod_Tip = Retenciones_Documentos.Cod_Tip") loConsulta.AppendLine(" JOIN Proveedores ON Proveedores.Cod_Pro = Cuentas_Pagar.Cod_Pro") loConsulta.AppendLine(" LEFT JOIN Retenciones ON Retenciones.Cod_Ret = Retenciones_Documentos.Cod_Ret") loConsulta.AppendLine("WHERE Cuentas_Pagar.Cod_Tip = 'ISLR'") loConsulta.AppendLine(" AND Cuentas_Pagar.Status <> 'Anulado'") loConsulta.AppendLine(" AND Cuentas_Pagar.Tip_Ori = 'Pagos'") loConsulta.AppendLine(" AND Cuentas_Pagar.Fec_Ini BETWEEN " & lcParametro0Desde) loConsulta.AppendLine(" AND " & lcParametro0Hasta) loConsulta.AppendLine(" AND Cuentas_Pagar.Cod_Pro BETWEEN " & lcParametro1Desde) loConsulta.AppendLine(" AND " & lcParametro1Hasta) loConsulta.AppendLine(" AND Pagos.Cod_Mon BETWEEN " & lcParametro2Desde) loConsulta.AppendLine(" AND " & lcParametro2Hasta) loConsulta.AppendLine(" AND Pagos.Cod_Suc BETWEEN " & lcParametro3Desde) loConsulta.AppendLine(" AND " & lcParametro3Hasta) loConsulta.AppendLine("UNION ALL ") loConsulta.AppendLine("SELECT Retenciones_Documentos.Tip_Ori AS Tipo_Origen,") loConsulta.AppendLine(" Ordenes_Pagos.Fec_Ini AS Fecha_Retencion,") loConsulta.AppendLine(" '' AS Numero_Pago,") loConsulta.AppendLine(" Ordenes_Pagos.Factura AS Numero_Factura,") loConsulta.AppendLine(" Ordenes_Pagos.Control AS Control_Factura,") loConsulta.AppendLine(" 'ORD/PAG' AS Tipo_Documento,") loConsulta.AppendLine(" Ordenes_Pagos.Documento AS Numero_Documento,") loConsulta.AppendLine(" Ordenes_Pagos.Mon_Net AS Monto_Documento,") loConsulta.AppendLine(" Ordenes_Pagos.Mon_Net AS Monto_Abonado,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Bas AS Base_Retencion,") loConsulta.AppendLine(" Retenciones_Documentos.Por_Ret AS Porcentaje_Retenido,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Sus AS Sustraendo_Retenido,") loConsulta.AppendLine(" RTRIM(Retenciones.Cod_Ret) + ': ' + Retenciones.Nom_Ret AS Concepto,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Ret AS Monto_Retenido,") loConsulta.AppendLine(" Ordenes_Pagos.Cod_Pro AS Cod_Pro,") loConsulta.AppendLine(" Proveedores.Nom_Pro AS Nom_Pro,") loConsulta.AppendLine(" Proveedores.Rif AS Rif,") loConsulta.AppendLine(" Proveedores.Nit AS Nit,") loConsulta.AppendLine(" Proveedores.Dir_Fis AS Direccion") loConsulta.AppendLine("FROM Retenciones_Documentos") loConsulta.AppendLine(" JOIN Ordenes_Pagos ON Ordenes_Pagos.Documento = Retenciones_Documentos.documento") loConsulta.AppendLine(" JOIN Proveedores ON Proveedores.Cod_Pro = Ordenes_Pagos.Cod_Pro") loConsulta.AppendLine(" LEFT JOIN Retenciones ON Retenciones.Cod_Ret = Retenciones_Documentos.Cod_Ret") loConsulta.AppendLine("WHERE Ordenes_Pagos.Status = 'Confirmado'") loConsulta.AppendLine(" AND Retenciones_Documentos.Tip_Ori = 'Ordenes_Pagos'") loConsulta.AppendLine(" AND Retenciones_Documentos.clase = 'ISLR'") loConsulta.AppendLine(" AND Ordenes_Pagos.Fec_Ini BETWEEN " & lcParametro0Desde) loConsulta.AppendLine(" AND " & lcParametro0Hasta) loConsulta.AppendLine(" AND Ordenes_Pagos.Cod_Pro BETWEEN " & lcParametro1Desde) loConsulta.AppendLine(" AND " & lcParametro1Hasta) loConsulta.AppendLine(" AND Ordenes_Pagos.Cod_Mon BETWEEN " & lcParametro2Desde) loConsulta.AppendLine(" AND " & lcParametro2Hasta) loConsulta.AppendLine(" AND Ordenes_Pagos.Cod_Suc BETWEEN " & lcParametro3Desde) loConsulta.AppendLine(" AND " & lcParametro3Hasta) loConsulta.AppendLine("UNION ALL ") loConsulta.AppendLine("SELECT Cuentas_Pagar.Tip_Ori AS Tipo_Origen,") loConsulta.AppendLine(" Cuentas_Pagar.Fec_Ini AS Fecha_Retencion,") loConsulta.AppendLine(" '' AS Numero_Pago,") loConsulta.AppendLine(" Documentos.Factura AS Numero_Factura,") loConsulta.AppendLine(" Documentos.Control AS Control_Factura,") loConsulta.AppendLine(" Retenciones_Documentos.Cod_Tip AS Tipo_Documento,") loConsulta.AppendLine(" Retenciones_Documentos.Doc_Ori AS Numero_Documento,") loConsulta.AppendLine(" Documentos.Mon_Net AS Monto_Documento,") loConsulta.AppendLine(" Documentos.Mon_Net AS Monto_Abonado,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Bas AS Base_Retencion,") loConsulta.AppendLine(" Retenciones_Documentos.Por_Ret AS Porcentaje_Retenido,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Sus AS Sustraendo_Retenido,") loConsulta.AppendLine(" RTRIM(Retenciones.Cod_Ret) + ': ' + Retenciones.Nom_Ret AS Concepto,") loConsulta.AppendLine(" Retenciones_Documentos.Mon_Ret AS Monto_Retenido,") loConsulta.AppendLine(" Cuentas_Pagar.Cod_Pro AS Cod_Pro,") loConsulta.AppendLine(" Proveedores.Nom_Pro AS Nom_Pro,") loConsulta.AppendLine(" Proveedores.Rif AS Rif,") loConsulta.AppendLine(" Proveedores.Nit AS Nit,") loConsulta.AppendLine(" Proveedores.Dir_Fis AS Direccion") loConsulta.AppendLine("FROM Cuentas_Pagar") loConsulta.AppendLine(" JOIN Cuentas_Pagar AS Documentos ON Documentos.documento = Cuentas_Pagar.Doc_Ori") loConsulta.AppendLine(" AND Documentos.Cod_Tip = Cuentas_Pagar.Cla_Ori") loConsulta.AppendLine(" JOIN Retenciones_Documentos ON Retenciones_Documentos.Doc_Des = Cuentas_Pagar.Documento") loConsulta.AppendLine(" AND Retenciones_Documentos.Doc_Ori = Cuentas_Pagar.Doc_Ori") loConsulta.AppendLine(" JOIN Proveedores ON Proveedores.Cod_Pro = Cuentas_Pagar.Cod_Pro") loConsulta.AppendLine(" LEFT JOIN Retenciones ON Retenciones.Cod_Ret = Retenciones_Documentos.Cod_Ret") loConsulta.AppendLine("WHERE Cuentas_Pagar.Cod_Tip = 'ISLR'") loConsulta.AppendLine(" AND Cuentas_Pagar.Status <> 'Anulado'") loConsulta.AppendLine(" AND Cuentas_Pagar.Tip_Ori = 'cuentas_pagar'") loConsulta.AppendLine(" AND Cuentas_Pagar.Fec_Ini BETWEEN " & lcParametro0Desde) loConsulta.AppendLine(" AND " & lcParametro0Hasta) loConsulta.AppendLine(" AND Cuentas_Pagar.Cod_Pro BETWEEN " & lcParametro1Desde) loConsulta.AppendLine(" AND " & lcParametro1Hasta) loConsulta.AppendLine(" AND Cuentas_Pagar.Cod_Mon BETWEEN " & lcParametro2Desde) loConsulta.AppendLine(" AND " & lcParametro2Hasta) loConsulta.AppendLine(" AND Cuentas_Pagar.Cod_Suc BETWEEN " & lcParametro3Desde) loConsulta.AppendLine(" AND " & lcParametro3Hasta) loConsulta.AppendLine("ORDER BY " & lcOrdenamiento) '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 '--------------------------------------------------' ' Carga la imagen del logo en curReportes ' '--------------------------------------------------' Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rCRetencion_ISLRProveedores_TUR", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrCRetencion_ISLRProveedores_TUR.ReportSource = loObjetoReporte Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload Try loObjetoReporte.Close() Catch loExcepcion As Exception End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo ' '-------------------------------------------------------------------------------------------' ' CMS: 21/05/09: Codigo inicial ' '-------------------------------------------------------------------------------------------' ' CMS: 28/07/09: Se modificó la consulta de modo que se obtuvieron por separado los ' ' proveedores y los beneficiarios y luego se unieron los resultados. ' ' Verificacion de registros. ' ' Metodo de Ordenamiento ' '-------------------------------------------------------------------------------------------' ' CMS: 29/07/09: Se Renonbre de Relación Global de ISLR Relativo a Relación Global de ISLR ' ' Retenido ' '-------------------------------------------------------------------------------------------' ' RJG: 20/03/10: Agregado el filtro para que distinga retenciones de IVA de las de ISLR. ' '-------------------------------------------------------------------------------------------' ' JJD: 27/11/13: Se le agrego el Logo de la empresa ' '-------------------------------------------------------------------------------------------' ' RJG: 27/02/15: Se le agrego El número de Factura (o documento) y controldel doc retenido. ' '-------------------------------------------------------------------------------------------'
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("Hilbert Curve")> <Assembly: AssemblyDescription("Hilbert Curve")> <Assembly: AssemblyCompany("xFX JumpStart")> <Assembly: AssemblyProduct("Hilbert Curve")> <Assembly: AssemblyCopyright("Copyright © 2016")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("4fea2be5-776b-497e-9975-8e1084bea531")> ' 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("2017.10.9.17")> <Assembly: AssemblyFileVersion("2017.10.9.17")>
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Partial Public Class MoveTypeTests Inherits BasicMoveTypeTestsBase <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_OnMatchingFileName() As Task Dim code = " [||]Class test1 End Class " Await TestMissingInRegularAndScriptAsync(code) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_Nested_OnMatchingFileName_Simple() As Task Dim code = " Class Outer [||]Class test1 End Class End Class " Await TestMissingInRegularAndScriptAsync(code) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function MultipleTypesInFileWithNoContainerNamespace() As Task Dim code = " [||]Class Class1 End Class Class Class2 End Class " Dim codeAfterMove = " Class Class2 End Class " Dim expectedDocumentName = "Class1.vb" Dim destinationDocumentText = "Class Class1 End Class " Await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function MoveNestedTypeToNewFile_Simple() As Task Dim code = " Public Class Class1 Class Class2[||] End Class End Class " Dim codeAfterMove = " Public Partial Class Class1 End Class " Dim expectedDocumentName = "Class2.vb" Dim destinationDocumentText = " Public Partial Class Class1 Class Class2 End Class End Class " Await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function MoveNestedTypeToNewFile_Simple_DottedName() As Task Dim code = " Public Class Class1 Class Class2[||] End Class End Class " Dim codeAfterMove = " Public Partial Class Class1 End Class " Dim expectedDocumentName = "Class1.Class2.vb" Dim destinationDocumentText = " Public Partial Class Class1 Class Class2 End Class End Class " Await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index:=1) End Function <WorkItem(14484, "https://github.com/dotnet/roslyn/issues/14484")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function MoveNestedTypeToNewFile_RemoveComments() As Task Dim code = " ''' Outer comment Public Class Class1 ''' Inner comment Class Class2[||] End Class End Class " Dim codeAfterMove = " ''' Outer comment Public Partial Class Class1 End Class " Dim expectedDocumentName = "Class1.Class2.vb" Dim destinationDocumentText = " Public Partial Class Class1 ''' Inner comment Class Class2 End Class End Class " Await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, index:=1) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestImports() As Task Dim code = " ' Used only by inner Imports System ' Not used Imports System.Collections Class Outer [||]Class Inner Sub M(d as DateTime) End Sub End Class End Class " Dim codeAfterMove = " ' Used only by inner ' Not used Imports System.Collections Partial Class Outer End Class " Dim expectedDocumentName = "Inner.vb" Dim destinationDocumentText = " ' Used only by inner Imports System ' Not used Partial Class Outer Class Inner Sub M(d as DateTime) End Sub End Class End Class " Await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText) End Function <WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestTypeInheritance() As Task Dim code = " Class Outer Inherits Something Implements ISomething [||]Class Inner Inherits Other Implements IOther Sub M(d as DateTime) End Sub End Class End Class " Dim codeAfterMove = " Partial Class Outer Inherits Something Implements ISomething End Class " Dim expectedDocumentName = "Inner.vb" Dim destinationDocumentText = " Partial Class Outer Class Inner Inherits Other Implements IOther Sub M(d as DateTime) End Sub End Class End Class " Await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText) End Function <WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestLeadingBlankLines1() As Task Dim code = "' Banner Text imports System [||]class Class1 sub Foo() Console.WriteLine() end sub end class class Class2 sub Foo() Console.WriteLine() end sub end class " Dim codeAfterMove = "' Banner Text imports System class Class2 sub Foo() Console.WriteLine() end sub end class " Dim expectedDocumentName = "Class1.vb" Dim destinationDocumentText = "' Banner Text imports System class Class1 sub Foo() Console.WriteLine() end sub end class " Await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText) End Function <WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestLeadingBlankLines2() As Task Dim code = "' Banner Text imports System class Class1 sub Foo() Console.WriteLine() end sub end class [||]class Class2 sub Foo() Console.WriteLine() end sub end class " Dim codeAfterMove = "' Banner Text imports System class Class1 sub Foo() Console.WriteLine() end sub end class " Dim expectedDocumentName = "Class2.vb" Dim destinationDocumentText = "' Banner Text imports System class Class2 sub Foo() Console.WriteLine() end sub end class " Await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText) End Function End Class End Namespace
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Othello.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
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.Rectangles_6._2Part2_.My.MySettings Get Return Global.Rectangles_6._2Part2_.My.MySettings.Default End Get End Property End Module End Namespace
' 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.Classification Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification <UseExportProvider> Public Class SyntacticChangeRangeComputerTests Private Shared Function TestCSharp(markup As String, newText As String) As Task Return Test(markup, newText, LanguageNames.CSharp) End Function Private Shared Async Function Test(markup As String, newText As String, language As String) As Task Using workspace = TestWorkspace.Create(language, compilationOptions:=Nothing, parseOptions:=Nothing, markup) Dim testDocument = workspace.Documents(0) Dim startingDocument = workspace.CurrentSolution.GetDocument(testDocument.Id) Dim spans = testDocument.SelectedSpans Assert.True(1 = spans.Count, "Test should have one spans in it representing the span to replace") Dim annotatedSpans = testDocument.AnnotatedSpans Assert.True(1 = annotatedSpans.Count, "Test should have a single {||} span representing the change span in the final document") Dim annotatedSpan = annotatedSpans.Single().Value.Single() Dim startingText = Await startingDocument.GetTextAsync() Dim startingTree = Await startingDocument.GetSyntaxTreeAsync() Dim startingRoot = Await startingTree.GetRootAsync() Dim endingText = startingText.Replace(spans(0), newText) Dim endingTree = startingTree.WithChangedText(endingText) Dim endingRoot = Await endingTree.GetRootAsync() Dim actualChange = SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(startingRoot, endingRoot, TimeSpan.MaxValue, Nothing) Dim expectedChange = New TextChangeRange( annotatedSpan, annotatedSpan.Length + newText.Length - spans(0).Length) Assert.True(expectedChange = actualChange, expectedChange.ToString() & " != " & actualChange.ToString() & vbCrLf & "Changed span was" & vbCrLf & startingText.ToString(actualChange.Span)) End Using End Function <Fact> Public Async Function TestIdentifierChangeInMethod1() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: Con[||]|}.WriteLine(0); } void M3() { } } ", "sole") End Function <Fact> Public Async Function TestIdentifierChangeInMethod2() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: Con[|sole|]|}.WriteLine(0); } void M3() { } } ", "") End Function <Fact> Public Async Function TestSplitClass1() As Task Await TestCSharp( " using X; public class C { void M1() { } {|changed: [||] void |}M2() { Console.WriteLine(0); } void M3() { } } ", "} class C2 {") End Function <Fact> Public Async Function TestMergeClass() As Task Await TestCSharp( " using X; public class C { void M1() { } {|changed: [|} class C2 {|] void |}M2() { Console.WriteLine(0); } void M3() { } } ", "") End Function <Fact> Public Async Function TestExtendComment() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [||] } void M3() { Console.WriteLine(""*/ Console.WriteLine("") |} } void M4() { } } ", "/*") End Function <Fact> Public Async Function TestRemoveComment() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [|/*|] } void M3() { Console.WriteLine(""*/ Console.WriteLine("") |} } void M4() { } } ", "") End Function <Fact> Public Async Function TestExtendCommentToEndOfFile() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [||] } void M3() { } void M4() { } } |}", "/*") End Function <Fact> Public Async Function TestDeleteFullFile() As Task Await TestCSharp( "{|changed:[| using X; public class C { void M1() { } void M2() { } void M3() { } void M4() { } } |]|}", "") End Function <Fact> Public Async Function InsertFullFile() As Task Await TestCSharp( "{|changed:[||]|}", " using X; public class C { void M1() { } void M2() { } void M3() { } void M4() { } } ") End Function <Fact> Public Async Function TestInsertDuplicateLineBelow() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { throw new NotImplementedException();[||] {|changed:|} } void M3() { } } ", " throw new NotImplementedException();") End Function <Fact> Public Async Function TestInsertDuplicateLineAbove() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() {[||] throw new NotImplementedException(); {|changed:|} } void M3() { } } ", " throw new NotImplementedException();") End Function <Fact> Public Async Function TestDeleteDuplicateLineBelow() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { throw new NotImplementedException(); {|changed: [|throw new NotImplementedException();|] } |} void M3() { } } ", "") End Function <Fact> Public Async Function TestDeleteDuplicateLineAbove() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [|throw new NotImplementedException();|] throw |}new NotImplementedException(); } void M3() { } } ", "") End Function End Class End Namespace
Public Class update_buyer Dim con As New ADODB.Connection Dim cmd As New ADODB.Recordset Private Sub update_buyer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load con.Open("dsn=bkl") cmd.Open("select * from buyerinfo ", con, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic) While Not cmd.EOF ComboBox3.Items.Add(cmd.Fields("buyer_name").Value) cmd.MoveNext() End While cmd.Close() End Sub Private Sub ComboBox3_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox3.SelectedIndexChanged cmd.Open("select * from buyerinfo where buyer_name = '" & ComboBox3.Text & "' ", con, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic) While Not cmd.EOF TextBox3.Text = cmd.Fields("address").Value ComboBox2.Text = cmd.Fields("state").Value ComboBox1.Text = cmd.Fields("city").Value TextBox5.Text = cmd.Fields("gst_number").Value 'TextBox2.Text = cmd.Fields("tin_number").Value TextBox6.Text = cmd.Fields("pan").Value TextBox4.Text = cmd.Fields("dis").Value TextBox2.Text = cmd.Fields("contact_number").Value cmd.MoveNext() End While cmd.Close() End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click cmd.Open("select * from buyerinfo where buyer_name = '" & ComboBox3.Text & "' ", con, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic) While Not cmd.EOF cmd.Fields("buyer_name").Value = ComboBox3.Text cmd.Fields("address").Value = TextBox3.Text cmd.Fields("state").Value = ComboBox2.Text cmd.Fields("city").Value = ComboBox1.Text cmd.Fields("gst_number").Value = TextBox5.Text 'TextBox2.Text = cmd.Fields("tin_number").Value cmd.Fields("pan").Value = TextBox6.Text cmd.Fields("dis").Value = TextBox4.Text cmd.Fields("contact_number").Value = TextBox2.Text cmd.MoveNext() End While cmd.Close() MsgBox("Updated Succesfully") TextBox3.Text = "" ComboBox2.Text = "" ComboBox1.Text = "" ComboBox3.Text = "" TextBox5.Text = "" TextBox6.Text = "" TextBox4.Text = "" TextBox2.Text = "" End Sub End Class
Imports System.Data.OleDb Imports System.Text.RegularExpressions Public Class RenewForm Public AuthorList(0) As String Public PublisherList(0) As String Public Shared SelectedItem As ListViewItem Public conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=lms.mdb; Persist Security Info=False;") Public Sub New() InitializeComponent() 'Filling all the data, imcluding combobox list items lbID2.Text = Form1.memberID Dim cmd As New OleDbCommand("SELECT * FROM [Loan] INNER JOIN [Book] ON Loan.ISBN = Book.ISBN WHERE Loan.memberID = @id ORDER BY [Loan].[ISBN]", conn) cmd.Parameters.AddWithValue("@id", Form1.memberID) Try conn.Open() Dim dr As OleDbDataReader = cmd.ExecuteReader Do While dr.Read() If dr.Item("returnDate").ToString = String.Empty Then cbAuthor.Items.Add(dr.Item("authors")) cbPublisher.Items.Add(dr.Item("publisher")) cbISBN.Items.Add(dr.Item(5)) cbEdition.Items.Add(dr.Item("edition")) cbYear.Items.Add(dr.Item("publishYear")) End If Loop conn.Close() Catch ex As Exception MsgBox(ex.ToString) conn.Close() End Try End Sub Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click If cbISBN.Text.ToString <> "" Then Dim response = MessageBox.Show("Are you sure you want to exit without return or renew books?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) If response = DialogResult.Yes Then Me.Dispose() End If Else Me.Dispose() End If End Sub Private Sub cbISBN_TextChanged(sender As Object, e As EventArgs) Handles cbISBN.TextChanged ClearItems() SelectLatestTransaction(cbISBN.Text.ToString) End Sub Private Sub btnRenew_Click(sender As Object, e As EventArgs) Handles btnRenew.Click 'Double validates If cbISBN.Text.ToString <> "" And lbLoanID2.Text.ToString <> "" Then Dim loanDuration As Double = Regex.Replace(cbDuration.Text, "days|day", "") Dim newExpiryDate As Date = Now.AddDays(loanDuration) 'Use old expirydate to calculate IsLate or not Dim cmd As New OleDbCommand("UPDATE Loan SET returnDate=@returnDate WHERE loanID=@loanID", conn) Dim cmd2 As New OleDbCommand("INSERT INTO [Loan] ([borrowDate],[expiryDate],[memberID],[ISBN]) VALUES (@borrowDate,@newExpiryDate,@memberID,@ISBN);", conn) cmd.Parameters.AddWithValue("@returnDate", Now.ToShortDateString) cmd.Parameters.AddWithValue("@loanID", lbLoanID2.Text.ToString) With cmd2.Parameters .AddWithValue("@borrowDate", Date.Now().ToShortDateString) .AddWithValue("@newExpiryDate", newExpiryDate.ToShortDateString) .AddWithValue("@memberID", lbID2.Text.ToString) .AddWithValue("@ISBN", cbISBN.Text.ToString) End With Try conn.Open() cmd.ExecuteNonQuery() cmd2.ExecuteNonQuery() conn.Close() If LateDate() > 0 Then 'Late renew MessageBox.Show("Book renew successful! Please pay your fine : RM" & LateDate(), "Renew with fine !", MessageBoxButtons.OK, MessageBoxIcon.Stop) Else MessageBox.Show("Book renew successfully! Thank you!", "Renew Successful!", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Me.Dispose() Catch ex As Exception MsgBox(ex.ToString) End Try ElseIf cbISBN.Text.ToString <> "" And lbLoanID2.Text.ToString = "" Then MessageBox.Show("Please enter a correct ISBN!", "Invalid ISBN!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Else 'Handle empty tb entered MessageBox.Show("Please enter the ISBN to proceed!", "Please enter ISBN!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If End Sub Private Sub btnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click 'Double validates is always better ;) If cbISBN.Text.ToString <> "" And lbLoanID2.Text.ToString <> "" Then Dim cmd As New OleDbCommand("UPDATE Loan SET returnDate=@returnDate WHERE loanID = @loanID", conn) cmd.Parameters.AddWithValue("@returnDate", Date.Now.ToShortDateString) cmd.Parameters.AddWithValue("@loanID", lbLoanID2.Text.ToString) conn.Open() Dim success As Integer = cmd.ExecuteNonQuery() conn.Close() If success > 0 And LateDate() > 0 Then MessageBox.Show("Late return of book! Please pay your fine : RM" & LateDate(), "Return with fine !", MessageBoxButtons.OK, MessageBoxIcon.Stop) ElseIf success > 0 And LateDate() <= 0 Then MessageBox.Show("Book return successfully! Thank you!", "Return Successful !", MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("Error Updating Database!", "Update error", MessageBoxButtons.OK, MessageBoxIcon.Error) End If Me.Dispose() ElseIf cbISBN.Text.ToString <> "" And lbLoanID2.Text.ToString = "" Then MessageBox.Show("Please enter a correct ISBN!", "Invalid ISBN!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Else MessageBox.Show("Please enter the ISBN to proceed!", "Please enter ISBN!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If End Sub Public Function LateDate() As Double Return DateDiff(DateInterval.Day, Date.Parse(lbExpiryDate2.Text), Date.Now) End Function Private Sub cbISBN_KeyPress(sender As Object, e As KeyPressEventArgs) Handles cbISBN.KeyPress If Char.IsControl(e.KeyChar) Or Char.IsNumber(e.KeyChar) Then Else e.Handled = True End If End Sub Public Sub SelectLatestTransaction(ISBN As String) If ISBN <> "" Then Dim cmd As New OleDbCommand("SELECT TOP 1 * FROM [Loan] INNER JOIN [Book] ON Loan.ISBN = Book.ISBN WHERE Loan.ISBN = @ISBN AND Loan.memberID = @id ORDER BY [Loan].[loanID] desc", conn) cmd.Parameters.AddWithValue("@ISBN", ISBN) cmd.Parameters.AddWithValue("@id", Form1.memberID) 'Select the latest transaction of the book Try conn.Close() conn.Open() Dim dr As OleDbDataReader = cmd.ExecuteReader If dr.HasRows = False Then MessageBox.Show("The book had never been borrowed before! Please refer to a librarian.", "Book never been borrowed!", MessageBoxButtons.OK, MessageBoxIcon.Stop) ClearItems() End If While dr.Read() 'Check if has row and if the book is already return or not If dr.HasRows And dr.Item("returnDate").ToString = String.Empty Then lbLoanID2.Text = dr.Item("loanID") lbBorrowDate2.Text = dr.Item("borrowDate") lbExpiryDate2.Text = dr.Item("expiryDate") cbISBN.Text = dr.Item("Loan.ISBN") cbAuthor.Text = dr.Item("authors") cbEdition.Text = dr.Item("edition") cbPublisher.Text = dr.Item("publisher") cbYear.Text = dr.Item("publishYear") cbType.Text = dr.Item("type") cbDuration.Text = dr.Item("loanDuration") ElseIf dr.Item("returnDate").ToString <> "" Then MessageBox.Show("The book had never been borrowed before! Please refer to a librarian.", "Book never been borrowed!", MessageBoxButtons.OK, MessageBoxIcon.Stop) ClearItems() End If End While conn.Close() Catch ex As Exception conn.Close() End Try End If End Sub Sub ClearItems() lbLoanID2.ResetText() lbExpiryDate2.ResetText() lbBorrowDate2.ResetText() cbAuthor.ResetText() cbDuration.SelectedIndex = -1 cbEdition.SelectedIndex = -1 cbPublisher.ResetText() cbType.SelectedIndex = -1 cbYear.SelectedIndex = -1 End Sub Private Sub cbAuthor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbAuthor.SelectedIndexChanged cbISBN.SelectedIndex = cbAuthor.SelectedIndex 'Once cbISBN is changed , the data will be automatically refreshed End Sub Private Sub cbPublisher_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cbPublisher.SelectedIndexChanged cbISBN.SelectedIndex = cbPublisher.SelectedIndex 'Once cbISBN is changed , the data will be automatically refreshed End Sub End Class
Imports Entities Imports Domain Public Class frmAddHerramienta Public Sub New(p As EPerson) ' Esta llamada es exigida por el diseñador. InitializeComponent() ' Agregue cualquier inicialización después de la llamada a InitializeComponent(). Person = p End Sub Private mPerson As EPerson Public Property Person() As EPerson Get Return mPerson End Get Private Set(ByVal value As EPerson) mPerson = value End Set End Property Dim com As DTool Dim unDZ As New DZone Dim com1 As DPlant Dim unHE As ETool Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click unHE.Use = txtUso.Text unHE.Type = cbxTipo.Text unHE.ZoneName.ZoneName = cbxZona.Text unHE.ProductName = txtNombre.Text com.altaHerramienta(unHE) End Sub Private Sub frmAddHerramienta_Load(sender As Object, e As EventArgs) Handles Me.Load Dim colZonas = unDZ.List cbxZona.ValueMember = "Zona_nombre" cbxZona.DisplayMember = "Zona_nombre" cbxZona.DataSource = colZonas End Sub End Class
 Imports Newtonsoft.Json.Linq Imports pxBook Imports SMC.Lib Imports System.Text.RegularExpressions Imports System.Net.Http Imports System.Threading Imports System.Reflection Imports System.ServiceModel Public Class Exporter Public Enum ExporterCommitCommand Update Create End Enum ' Klassenvariablen Private flsConn As FlsConnection Private MyConn As ProffixConnection Private pxHelper As ProffixHelper Private articleMapper As ArticleMapper ' Actions Public DoProgress As Action Public Log As Action(Of String) ' Regex-Pattern für GUID Private pattern_GUID As Regex = New Regex("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled) Private _lastExport As DateTime = Nothing Public Property LastExport As DateTime Get Return _lastExport End Get Set(ByVal value As DateTime) _lastExport = value End Set End Property Private _progress As Integer Public Property Progress As Integer Get Return _progress End Get Private Set(ByVal value As Integer) _progress = value End Set End Property Private _count As Integer Public Property Count As Integer Get Return _count End Get Private Set(ByVal value As Integer) _count = value End Set End Property Public Sub New(ByVal lastExport As DateTime, ByRef serviceClient As FlsConnection, ByRef pxHelper As ProffixHelper, ByRef Myconn As ProffixConnection) Me.LastExport = lastExport Me.flsConn = serviceClient Me.pxHelper = pxHelper Me.MyConn = Myconn articleMapper = New ArticleMapper End Sub Public Function Export() As Boolean Dim articleResult As Threading.Tasks.Task(Of JArray) Dim fehler As String = "" Dim response_FLS As String = "" Dim successful As Boolean = True Dim articleList = New List(Of pxBook.pxKommunikation.pxArtikel) Dim existsInFLS As Boolean = False Dim response As String = String.Empty Dim update_successful As Boolean = True Dim create_successful As Boolean = True Try logComplete("Artikelexport gestartet", LogLevel.Info) Progress = 0 ' **************************************************************alle FLS-Artikel: Negativbestand = 1 setzen*********************************************************** pxHelper.SetNegativBestand(response) If Not String.IsNullOrEmpty(response) Then logComplete(response, LogLevel.Exception) End If '******************************************************************************Artikel holen********************************************************************************* ' alle Artikel aus FLS holen articleResult = flsConn.CallAsyncAsJArray(My.Settings.ServiceAPIArticlesMethod) articleResult.Wait() ' alle Artikel aus Proffix holen, die erstellt/geaendert am > lastExport haben und in Gruppe FLS sind articleList = pxArtikelLaden() Count = articleList.Count '**********************************************************************Artikel vergleichen********************************************************* ' Artikel in Proffix + FLS vergleichen (ArticleNumber) For Each proffixArticle In articleList ' Defaultwert = false existsInFLS = False ' Alle Artikel aus FLS durchgehen For Each existingFLSarticle As JObject In articleResult.Result.Children '************************************************************UPDATE IN FLS******************************************************************* ' --> wenn in FLS vorhanden --> update PUT If proffixArticle.ArtikelNr = existingFLSarticle("ArticleNumber").ToString Then existsInFLS = True ' updated den Artikel in FLS (Flag existsInFLS If Not updateInFLS(proffixArticle, existingFLSarticle) Then ' geklappt soll falsch sein (und bleiben), sobald 1 update/create nicht geklappt hat --> wenn updateInFLS true zurückgibt --> geklappt nicht verändern, da sonst vorheriger Fehler ignoriert wird successful = False End If End If Next '*******************************************************************CREATE IN FLS****************************************************************** ' wenn in FLS nicht vorhanden If Not existsInFLS Then ' ... und in Proffix nicht bereits schon wieder gelöscht wurde If proffixArticle.Geloescht = 0 Then '... dann: create Article in FLS + neue Id in Proffix schreiben If Not createInFLS(proffixArticle) Then ' geklappt soll falsch sein, sobald 1 update/create nicht geklappt hat --> wenn updateInFLS true zurückgibt --> geklappt nicht verändern, da sonst vorheriger Fehler ignoriert wird successful = False End If End If End If Progress += 1 InvokeDoProgress() Next '**************************************************************LastSync updaten***************************************************************************** ' wenn bis herhin alles geklappt --> geklappt immer noch true If successful Then logComplete("Artikelexport erfolgreich beendet", LogLevel.Info) LastExport = DateTime.Now Else logComplete("Beim Artikelexport ist mindestens 1 Fehler aufgetreten. Deshalb wird das Datum des letzten Exports nicht angepasst.", LogLevel.Exception) Logger.GetInstance.Log(LogLevel.Exception, "Artikelexport beendet. Mindestens 1 Fehler bei Artikelexport") End If logComplete("", LogLevel.Info) Progress = Count InvokeDoProgress() Return successful Catch faultExce As FaultException Logger.GetInstance().Log(LogLevel.Exception, faultExce.Message) Throw faultExce 'End If Catch exce As Exception Logger.GetInstance().Log(LogLevel.Exception, exce) Throw End Try End Function Private Function pxArtikelLaden() As List(Of pxKommunikation.pxArtikel) Dim sql As String = String.Empty Dim rs As New ADODB.Recordset Dim articleList As New List(Of pxKommunikation.pxArtikel) Dim fehler As String = String.Empty sql = "Select artikelNrLAG, bezeichnung1, bezeichnung2, bezeichnung3, geloescht from lag_artikel " + _ "where Z_FLS = 1 and (erstelltam > '" + LastExport.ToString(pxHelper.dateformat + " HH:mm:ss") + "' or geaendertam > '" + LastExport.ToString(pxHelper.dateformat + " HH:mm:ss") + "')" If Not MyConn.getRecord(rs, sql, fehler) Then logComplete("Fehler beim Laden der geänderten Artikel" + fehler, LogLevel.Exception) Return Nothing Else ' geholte Artikel in einer Liste speichern Dim article As New pxKommunikation.pxArtikel While Not rs.EOF article.ArtikelNr = rs.Fields("artikelNrLAG").Value.ToString() article.Bezeichnung1 = rs.Fields("bezeichnung1").Value.ToString() article.Bezeichnung2 = rs.Fields("bezeichnung2").Value.ToString() article.Bezeichnung3 = rs.Fields("bezeichnung3").Value.ToString() article.Geloescht = CInt(rs.Fields("geloescht").Value) articleList.Add(article) rs.MoveNext() End While End If Return articleList End Function Private Function updateInFLS(ByVal proffixArticle As pxKommunikation.pxArtikel, ByVal existingFLSarticle As JObject) As Boolean Dim response_FLS As String = String.Empty Dim sql As String = String.Empty Dim rs As New ADODB.Recordset Dim fehler As String = String.Empty Try ' JSON verändern existingFLSarticle = articleMapper.Mapp(proffixArticle, existingFLSarticle) ' Artikel in FLS updaten response_FLS = flsConn.ExportChanges(existingFLSarticle("ArticleId").ToString, existingFLSarticle, ExporterCommitCommand.Update) ' Ist response_FLS keine GUID? --> update in FLS hat nicht geklappt, response_FLS enthält Fehlermeldung If Not pattern_GUID.IsMatch(response_FLS) Then logComplete("Fehler beim Updaten in FLS ArtikelNr: " + proffixArticle.ArtikelNr.ToString + " " + proffixArticle.Bezeichnung1, LogLevel.Exception, response_FLS) Throw New Exception("Fehler beim Updaten des Artikels in FLS") End If ' response_FLS ist GUID = update in FLS hat geklappt --> ArticleId in Proffix updaten If Not updateArticleIdInProffix(response_FLS, proffixArticle.ArtikelNr, fehler) Then ' Update ArticleId in Proffix hat nicht geklappt Logger.GetInstance().Log(LogLevel.Exception, "... des bereits in FLS vorhandenen Artikels. " + " ArtikelNr:" + proffixArticle.ArtikelNr + " " + proffixArticle.Bezeichnung1) Throw New Exception("Fehler beim Updaten der ArticleId in Proffix ArtikelNr ") End If ' wenn bis hierher --> update (in Artikel in FLS und ArticleId in Proffix) hat geklappt logComplete("Aktualisiert in FLS: ArticleNr " + proffixArticle.ArtikelNr + " Bezeichnung " + proffixArticle.Bezeichnung1, LogLevel.Info) Return True Catch ex As Exception logComplete("Fehler beim Updaten des Artikels in FLS ArtikelNr: " + proffixArticle.ArtikelNr, LogLevel.Exception, "Fehler in " + MethodBase.GetCurrentMethod().Name + " " + ex.Message) Return False End Try End Function Private Function createInFLS(ByVal proffixArticle As pxKommunikation.pxArtikel) As Boolean Dim newFLSarticle = New JObject Dim response_FLS As String = String.Empty Dim fehler As String = String.Empty Try ' JSON für neuen Artikel erstellen newFLSarticle = articleMapper.Mapp(proffixArticle, newFLSarticle) If LogAusfuehrlich Then Logger.GetInstance.Log(LogLevel.Info, My.Settings.ServiceAPIArticlesMethod) Logger.GetInstance.Log(LogLevel.Info, newFLSarticle.ToString) End If ' Artikel in FLS erstellen response_FLS = flsConn.ExportChanges("", newFLSarticle, ExporterCommitCommand.Create) ' Wenn InternalServerError und ArtikelName in FLS bereits vorhanden (unique) --> Fehlermeldung If response_FLS.Contains("InternalServerError") And articleNameExistsAlreadyInFLS(newFLSarticle("ArticleName").ToString) Then ' Anweisungen an User logComplete("Fehler: In FLS besteht bereits ein Artikel mit dem Artikelnamen/Bezeichnung1 """ + proffixArticle.Bezeichnung1 + """ ArtikelNr: " + newFLSarticle("ArticleNumber").ToString + "Deshalb konnte der Artikel in FLS nicht neu erstellt werden." + vbCrLf + "Sie haben folgende Möglichkeiten:" + vbCrLf + "- Ändern Sie den Artikelnamen/Bezeichnung1 """ + proffixArticle.Bezeichnung1 + """des Artikels" + vbCrLf + "- Falls der Artikel mit Artikel-Nr. " + newFLSarticle("ArticleNumber").ToString + " Artikelname/Bezeichnung1 " + proffixArticle.Bezeichnung1 + " gelöscht noch vorhanden ist, entfernen Sie das Häckchen bei ""gelöscht""", LogLevel.Exception) ' logcomplete( "- Erstellen Sie einen neuen Artikel mit der Artikel-Nr: " + newFLSarticle("ArticleNumber").ToString + "Artikelname/Bezeichnung1: " + proffixArticle.Bezeichnung1 + " und löschen Sie den Artikel mit der Artikel-Nr: " + proffixArticle.ArtikelNr) Logger.GetInstance.Log(LogLevel.Exception, "In FLS besteht bereits ein Artikel mit dem Artikelnamen/Bezeichnung """ + proffixArticle.Bezeichnung1 + """ ArtikelNr: " + newFLSarticle("ArticleNumber").ToString + " Anweisungen an Kunde im Log") Return False End If ' Ist response_FLS GUID? --> create hat geklappt, ansonsten enthält response_FLS die Fehlermeldung If Not pattern_GUID.IsMatch(response_FLS) Then logComplete("Fehler beim Erstellen in FLS: " + proffixArticle.ArtikelNr + " " + proffixArticle.Bezeichnung1, LogLevel.Exception, response_FLS) Return False End If ' response_FLS ist GUID --> in Proffix updaten If Not updateArticleIdInProffix(response_FLS, proffixArticle.ArtikelNr, fehler) Then Logger.GetInstance().Log(LogLevel.Exception, "... des soeben in FLS neu erstellten Artikels. " + " ArtikelNr:" + proffixArticle.ArtikelNr + " " + proffixArticle.Bezeichnung1) Return False End If ' wenn bis hierher --> create Artikel in FLS und update ArticleId in Proffix hat geklappt logComplete("Erstellt in FLS: " + proffixArticle.ArtikelNr + " " + proffixArticle.Bezeichnung1, LogLevel.Info) Return True Catch ex As Exception logComplete("Fehler beim Erstellen des Artikels in FLS ArtikelNr: " + proffixArticle.ArtikelNr, LogLevel.Exception, response_FLS + " " + ex.Message) Return Nothing End Try End Function ' prüft, ob Artikelname/Bezeichnung1 bereits in FLS in Artikeltabelle vorhanden ist (Feld ist unique) Private Function articleNameExistsAlreadyInFLS(ByVal articlename As String) As Boolean Dim articleResult As Threading.Tasks.Task(Of JArray) ' alle Artikel aus Artikeltabelle in FLS holen articleResult = flsConn.CallAsyncAsJArray(My.Settings.ServiceAPIArticlesMethod) articleResult.Wait() ' ist der Artikelname bereits in FLS vorhanden? For Each article In articleResult.Result.Children ' Artikelname/Bezeichnung in FLS bereits vorhanden If articlename = article("ArticleName").ToString Then Return True End If Next ' wenn bis hierher --> Artikelname in FLS in Artikeltabelle noch nicht vorhanden Return False End Function Private Function updateArticleIdInProffix(ByVal FLSarticleId As String, ByVal pxArtikelNr As String, ByRef fehler As String) As Boolean Dim sql As String = String.Empty Dim rs As New ADODB.Recordset ' Artikel mit neuer ArtikelId in Proffix schreiben sql = "Update lag_artikel set Z_ArticleId = '" + FLSarticleId + "', " + _ "geaendertVon = '" + Assembly.GetExecutingAssembly().GetName.Name + "', geaendertAm = '" + Now.ToString(pxHelper.dateformat + " HH:mm:ss") + "' " + _ "where ArtikelNrLAG = '" + pxArtikelNr + "'" If Not MyConn.getRecord(rs, sql, fehler) Then Logger.GetInstance.Log(LogLevel.Exception, "Fehler beim Updaten der ArticleId " + FLSarticleId + " in Proffix") Return False Else Return True End If End Function Private Sub InvokeDoProgress() If DoProgress IsNot Nothing Then DoProgress.Invoke() End Sub ' schreibt in Log und in Logger (File) Private Sub logComplete(ByVal logString As String, ByVal loglevel As LogLevel, Optional ByVal zusatzloggerString As String = "") If Log IsNot Nothing Then Log.Invoke(If(loglevel <> loglevel.Info, vbTab, "") + logString) Logger.GetInstance.Log(loglevel, logString + " " + zusatzloggerString) End Sub ''' <summary> ''' Anzeigen des Synchronisationsfortschritt ''' </summary> Private Sub DoExporterProgress() 'ProgressBar aktualisieren FrmMain.pbMain.Maximum = Count FrmMain.pbMain.Value = Progress End Sub End Class
' Note: For instructions on enabling IIS6 or IIS7 classic mode, ' visit http://go.microsoft.com/?LinkId=9394802 Public Class MvcApplication Inherits System.Web.HttpApplication Shared Sub RegisterRoutes(ByVal routes As RouteCollection) routes.IgnoreRoute("{resource}.axd/{*pathInfo}") ' MapRoute takes the following parameters, in order: ' (1) Route name ' (2) URL with parameters ' (3) Parameter defaults routes.MapRoute( _ "News", _ "{controller}/{action}/{id}", _ New With {.controller = "Game", .action = "Welcome", .id = UrlParameter.Optional} _ ) End Sub Sub Application_Start() AreaRegistration.RegisterAllAreas() RegisterRoutes(RouteTable.Routes) End Sub End Class
' 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 On Option Explicit On Imports System Namespace Microsoft.VisualBasic.Devices '''************************************************************************** ''' ;Clock ''' <summary> ''' A wrapper object that acts as a discovery mechanism to quickly find out ''' the current local time of the machine and the GMT time. ''' </summary> Public Class Clock '* PUBLIC ************************************************************* '''************************************************************************** ''' ;LocalTime ''' <summary> ''' Gets a DateTime that is the current local date and time on this computer. ''' </summary> ''' <value>A DateTime whose value is the current date and time.</value> Public ReadOnly Property LocalTime() As DateTime Get Return DateTime.Now End Get End Property '''************************************************************************** ''' ;GmtTime ''' <summary> ''' Gets a DateTime that is the current local date and time on this ''' computer expressed as GMT time. ''' </summary> ''' <value>A DateTime whose value is the current date and time expressed as GMT time.</value> Public ReadOnly Property GmtTime() As DateTime Get Return DateTime.UtcNow End Get End Property '''************************************************************************** ''' ;TickCount ''' <summary> ''' This property wraps the Environment.TickCount property to get the ''' number of milliseconds elapsed since the system started. ''' </summary> ''' <value>An Integer containing the amount of time in milliseconds.</value> Public ReadOnly Property TickCount() As Integer Get Return System.Environment.TickCount End Get End Property '* FRIEND ************************************************************* '* PRIVATE ************************************************************ End Class 'Clock End Namespace
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class DBModifCreate Inherits System.Windows.Forms.Form 'Das Formular überschreibt den Löschvorgang, um die Komponentenliste zu bereinigen. <System.Diagnostics.DebuggerNonUserCode()> Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Wird vom Windows Form-Designer benötigt. Private components As System.ComponentModel.IContainer 'Hinweis: Die folgende Prozedur ist für den Windows Form-Designer erforderlich. 'Das Bearbeiten ist mit dem Windows Form-Designer möglich. 'Das Bearbeiten mit dem Code-Editor ist nicht möglich. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(DBModifCreate)) Me.Cancel_Button = New System.Windows.Forms.Button() Me.OK_Button = New System.Windows.Forms.Button() Me.CreateCB = New System.Windows.Forms.Button() Me.DBModifName = New System.Windows.Forms.TextBox() Me.NameLabel = New System.Windows.Forms.Label() Me.Tablename = New System.Windows.Forms.TextBox() Me.PrimaryKeys = New System.Windows.Forms.TextBox() Me.Database = New System.Windows.Forms.TextBox() Me.IgnoreColumns = New System.Windows.Forms.TextBox() Me.addStoredProc = New System.Windows.Forms.TextBox() Me.TablenameLabel = New System.Windows.Forms.Label() Me.PrimaryKeysLabel = New System.Windows.Forms.Label() Me.DatabaseLabel = New System.Windows.Forms.Label() Me.IgnoreColumnsLabel = New System.Windows.Forms.Label() Me.AdditionalStoredProcLabel = New System.Windows.Forms.Label() Me.insertIfMissing = New System.Windows.Forms.CheckBox() Me.execOnSave = New System.Windows.Forms.CheckBox() Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components) Me.envSel = New System.Windows.Forms.ComboBox() Me.DBSeqenceDataGrid = New System.Windows.Forms.DataGridView() Me.TargetRangeAddress = New System.Windows.Forms.Label() Me.CUDflags = New System.Windows.Forms.CheckBox() Me.RepairDBSeqnce = New System.Windows.Forms.TextBox() Me.AskForExecute = New System.Windows.Forms.CheckBox() Me.IgnoreDataErrors = New System.Windows.Forms.CheckBox() Me.AutoIncFlag = New System.Windows.Forms.CheckBox() Me.EnvironmentLabel = New System.Windows.Forms.Label() Me.MoveMenu = New System.Windows.Forms.ContextMenuStrip(Me.components) Me.MoveRowUp = New System.Windows.Forms.ToolStripMenuItem() Me.MoveRowDown = New System.Windows.Forms.ToolStripMenuItem() CType(Me.DBSeqenceDataGrid, System.ComponentModel.ISupportInitialize).BeginInit() Me.MoveMenu.SuspendLayout() Me.SuspendLayout() ' 'Cancel_Button ' Me.Cancel_Button.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.Cancel_Button.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.Cancel_Button.Location = New System.Drawing.Point(401, 434) Me.Cancel_Button.Name = "Cancel_Button" Me.Cancel_Button.Size = New System.Drawing.Size(67, 23) Me.Cancel_Button.TabIndex = 3 Me.Cancel_Button.TabStop = False Me.Cancel_Button.Text = "Cancel" Me.ToolTip1.SetToolTip(Me.Cancel_Button, "discard changes in DB Modifier Creation") ' 'OK_Button ' Me.OK_Button.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.OK_Button.Location = New System.Drawing.Point(361, 434) Me.OK_Button.Name = "OK_Button" Me.OK_Button.Size = New System.Drawing.Size(34, 23) Me.OK_Button.TabIndex = 2 Me.OK_Button.TabStop = False Me.OK_Button.Text = "OK" Me.ToolTip1.SetToolTip(Me.OK_Button, "use changes done in DB Modifier Creation") Me.OK_Button.UseVisualStyleBackColor = True ' 'CreateCB ' Me.CreateCB.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.CreateCB.Location = New System.Drawing.Point(287, 434) Me.CreateCB.Name = "CreateCB" Me.CreateCB.Size = New System.Drawing.Size(68, 23) Me.CreateCB.TabIndex = 1 Me.CreateCB.TabStop = False Me.CreateCB.Text = "Create CB" Me.ToolTip1.SetToolTip(Me.CreateCB, "Create a Commandbutton for the DB Modifier Definition (max. 5 Buttons possible pe" & "r Workbook)") ' 'DBModifName ' Me.DBModifName.Location = New System.Drawing.Point(167, 3) Me.DBModifName.Name = "DBModifName" Me.DBModifName.Size = New System.Drawing.Size(297, 20) Me.DBModifName.TabIndex = 1 Me.ToolTip1.SetToolTip(Me.DBModifName, resources.GetString("DBModifName.ToolTip")) ' 'NameLabel ' Me.NameLabel.AutoSize = True Me.NameLabel.Location = New System.Drawing.Point(9, 6) Me.NameLabel.Name = "NameLabel" Me.NameLabel.Size = New System.Drawing.Size(91, 13) Me.NameLabel.TabIndex = 2 Me.NameLabel.Text = "DBModifier name:" ' 'Tablename ' Me.Tablename.Location = New System.Drawing.Point(167, 55) Me.Tablename.Name = "Tablename" Me.Tablename.Size = New System.Drawing.Size(297, 20) Me.Tablename.TabIndex = 3 Me.ToolTip1.SetToolTip(Me.Tablename, "Database Table, where Data is to be stored") ' 'PrimaryKeys ' Me.PrimaryKeys.Location = New System.Drawing.Point(167, 81) Me.PrimaryKeys.Name = "PrimaryKeys" Me.PrimaryKeys.Size = New System.Drawing.Size(297, 20) Me.PrimaryKeys.TabIndex = 4 Me.ToolTip1.SetToolTip(Me.PrimaryKeys, "Number of primary keys in DBMapper datatable (starting from the left)") ' 'Database ' Me.Database.Location = New System.Drawing.Point(167, 29) Me.Database.Name = "Database" Me.Database.Size = New System.Drawing.Size(297, 20) Me.Database.TabIndex = 2 Me.ToolTip1.SetToolTip(Me.Database, "Database to store DBMaps Data into/ do DBActions") ' 'IgnoreColumns ' Me.IgnoreColumns.Location = New System.Drawing.Point(167, 107) Me.IgnoreColumns.Name = "IgnoreColumns" Me.IgnoreColumns.Size = New System.Drawing.Size(297, 20) Me.IgnoreColumns.TabIndex = 5 Me.ToolTip1.SetToolTip(Me.IgnoreColumns, "columns to be ignored (e.g. helper columns), comma separated") ' 'addStoredProc ' Me.addStoredProc.Location = New System.Drawing.Point(167, 133) Me.addStoredProc.Name = "addStoredProc" Me.addStoredProc.Size = New System.Drawing.Size(297, 20) Me.addStoredProc.TabIndex = 6 Me.ToolTip1.SetToolTip(Me.addStoredProc, "additional stored procedure to be executed after saving") ' 'TablenameLabel ' Me.TablenameLabel.AutoSize = True Me.TablenameLabel.Location = New System.Drawing.Point(9, 58) Me.TablenameLabel.Name = "TablenameLabel" Me.TablenameLabel.Size = New System.Drawing.Size(63, 13) Me.TablenameLabel.TabIndex = 2 Me.TablenameLabel.Text = "Tablename:" ' 'PrimaryKeysLabel ' Me.PrimaryKeysLabel.AutoSize = True Me.PrimaryKeysLabel.Location = New System.Drawing.Point(9, 84) Me.PrimaryKeysLabel.Name = "PrimaryKeysLabel" Me.PrimaryKeysLabel.Size = New System.Drawing.Size(99, 13) Me.PrimaryKeysLabel.TabIndex = 2 Me.PrimaryKeysLabel.Text = "Primary keys count:" ' 'DatabaseLabel ' Me.DatabaseLabel.AutoSize = True Me.DatabaseLabel.Location = New System.Drawing.Point(9, 32) Me.DatabaseLabel.Name = "DatabaseLabel" Me.DatabaseLabel.Size = New System.Drawing.Size(56, 13) Me.DatabaseLabel.TabIndex = 2 Me.DatabaseLabel.Text = "Database:" ' 'IgnoreColumnsLabel ' Me.IgnoreColumnsLabel.AutoSize = True Me.IgnoreColumnsLabel.Location = New System.Drawing.Point(9, 110) Me.IgnoreColumnsLabel.Name = "IgnoreColumnsLabel" Me.IgnoreColumnsLabel.Size = New System.Drawing.Size(82, 13) Me.IgnoreColumnsLabel.TabIndex = 2 Me.IgnoreColumnsLabel.Text = "Ignore columns:" ' 'AdditionalStoredProcLabel ' Me.AdditionalStoredProcLabel.AutoSize = True Me.AdditionalStoredProcLabel.Location = New System.Drawing.Point(9, 136) Me.AdditionalStoredProcLabel.Name = "AdditionalStoredProcLabel" Me.AdditionalStoredProcLabel.Size = New System.Drawing.Size(139, 13) Me.AdditionalStoredProcLabel.TabIndex = 2 Me.AdditionalStoredProcLabel.Text = "Additional stored procedure:" ' 'insertIfMissing ' Me.insertIfMissing.AutoSize = True Me.insertIfMissing.Location = New System.Drawing.Point(216, 163) Me.insertIfMissing.Name = "insertIfMissing" Me.insertIfMissing.Size = New System.Drawing.Size(97, 17) Me.insertIfMissing.TabIndex = 9 Me.insertIfMissing.Text = "Insert if missing" Me.ToolTip1.SetToolTip(Me.insertIfMissing, "if set, then insert row into table if primary key is missing there. Default = Fal" & "se (only update)") Me.insertIfMissing.UseVisualStyleBackColor = True ' 'execOnSave ' Me.execOnSave.AutoSize = True Me.execOnSave.Location = New System.Drawing.Point(12, 163) Me.execOnSave.Name = "execOnSave" Me.execOnSave.Size = New System.Drawing.Size(91, 17) Me.execOnSave.TabIndex = 7 Me.execOnSave.Text = "Exec on save" Me.ToolTip1.SetToolTip(Me.execOnSave, "should DB Modifier automatically be done on Excel Workbook Saving? (default no)") Me.execOnSave.UseVisualStyleBackColor = True ' 'envSel ' Me.envSel.FormattingEnabled = True Me.envSel.Location = New System.Drawing.Point(351, 159) Me.envSel.Name = "envSel" Me.envSel.Size = New System.Drawing.Size(113, 21) Me.envSel.TabIndex = 10 Me.ToolTip1.SetToolTip(Me.envSel, "The Environment, where connection id should be taken from (if not existing, take " & "from selected Environment in DB Addin General Settings Group)") ' 'DBSeqenceDataGrid ' Me.DBSeqenceDataGrid.AllowDrop = True Me.DBSeqenceDataGrid.AllowUserToResizeRows = False Me.DBSeqenceDataGrid.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.DBSeqenceDataGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells Me.DBSeqenceDataGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize Me.DBSeqenceDataGrid.Location = New System.Drawing.Point(12, 209) Me.DBSeqenceDataGrid.MultiSelect = False Me.DBSeqenceDataGrid.Name = "DBSeqenceDataGrid" Me.DBSeqenceDataGrid.Size = New System.Drawing.Size(452, 219) Me.DBSeqenceDataGrid.TabIndex = 13 Me.ToolTip1.SetToolTip(Me.DBSeqenceDataGrid, "Define the steps for the DB Sequence in the order of their desired execution here" & ". Any DBMapper and/or DBAction can be selected.") ' 'TargetRangeAddress ' Me.TargetRangeAddress.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.TargetRangeAddress.AutoEllipsis = True Me.TargetRangeAddress.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.TargetRangeAddress.ForeColor = System.Drawing.Color.DodgerBlue Me.TargetRangeAddress.Location = New System.Drawing.Point(12, 434) Me.TargetRangeAddress.Name = "TargetRangeAddress" Me.TargetRangeAddress.Size = New System.Drawing.Size(269, 23) Me.TargetRangeAddress.TabIndex = 11 Me.ToolTip1.SetToolTip(Me.TargetRangeAddress, "click to select Target Range with Data for DBMapper or SQL DML for DBAction") ' 'CUDflags ' Me.CUDflags.AutoSize = True Me.CUDflags.Location = New System.Drawing.Point(12, 186) Me.CUDflags.Name = "CUDflags" Me.CUDflags.Size = New System.Drawing.Size(84, 17) Me.CUDflags.TabIndex = 11 Me.CUDflags.Text = "C/U/D flags" Me.ToolTip1.SetToolTip(Me.CUDflags, "if set, then only insert/update/delete row if special CUDFlags column contains i," & " u or d. Default = False (only update)") Me.CUDflags.UseVisualStyleBackColor = True ' 'RepairDBSeqnce ' Me.RepairDBSeqnce.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.RepairDBSeqnce.Location = New System.Drawing.Point(12, 209) Me.RepairDBSeqnce.Multiline = True Me.RepairDBSeqnce.Name = "RepairDBSeqnce" Me.RepairDBSeqnce.ScrollBars = System.Windows.Forms.ScrollBars.Vertical Me.RepairDBSeqnce.Size = New System.Drawing.Size(456, 219) Me.RepairDBSeqnce.TabIndex = 14 Me.ToolTip1.SetToolTip(Me.RepairDBSeqnce, "use this textbox to repair DB Sequence entries...") ' 'AskForExecute ' Me.AskForExecute.AutoSize = True Me.AskForExecute.Location = New System.Drawing.Point(102, 163) Me.AskForExecute.Name = "AskForExecute" Me.AskForExecute.Size = New System.Drawing.Size(108, 17) Me.AskForExecute.TabIndex = 8 Me.AskForExecute.Text = "Ask for execution" Me.ToolTip1.SetToolTip(Me.AskForExecute, "ask for confirmation before execution?") Me.AskForExecute.UseVisualStyleBackColor = True ' 'IgnoreDataErrors ' Me.IgnoreDataErrors.AutoSize = True Me.IgnoreDataErrors.Location = New System.Drawing.Point(101, 186) Me.IgnoreDataErrors.Name = "IgnoreDataErrors" Me.IgnoreDataErrors.Size = New System.Drawing.Size(109, 17) Me.IgnoreDataErrors.TabIndex = 12 Me.IgnoreDataErrors.Text = "Ignore data errors" Me.ToolTip1.SetToolTip(Me.IgnoreDataErrors, "if set, don't notify user of error values in cells during update/insert, null val" & "ues are used instead") Me.IgnoreDataErrors.UseVisualStyleBackColor = True ' 'AutoIncFlag ' Me.AutoIncFlag.AutoSize = True Me.AutoIncFlag.Location = New System.Drawing.Point(216, 186) Me.AutoIncFlag.Name = "AutoIncFlag" Me.AutoIncFlag.Size = New System.Drawing.Size(98, 17) Me.AutoIncFlag.TabIndex = 13 Me.AutoIncFlag.Text = "Auto Increment" Me.ToolTip1.SetToolTip(Me.AutoIncFlag, resources.GetString("AutoIncFlag.ToolTip")) Me.AutoIncFlag.UseVisualStyleBackColor = True ' 'EnvironmentLabel ' Me.EnvironmentLabel.AutoSize = True Me.EnvironmentLabel.Location = New System.Drawing.Point(316, 164) Me.EnvironmentLabel.Name = "EnvironmentLabel" Me.EnvironmentLabel.Size = New System.Drawing.Size(29, 13) Me.EnvironmentLabel.TabIndex = 6 Me.EnvironmentLabel.Text = "Env:" ' 'MoveMenu ' Me.MoveMenu.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.MoveRowUp, Me.MoveRowDown}) Me.MoveMenu.Name = "ContextMenuStrip1" Me.MoveMenu.Size = New System.Drawing.Size(165, 48) ' 'MoveRowUp ' Me.MoveRowUp.Name = "MoveRowUp" Me.MoveRowUp.Size = New System.Drawing.Size(164, 22) Me.MoveRowUp.Text = "Move Row Up" ' 'MoveRowDown ' Me.MoveRowDown.Name = "MoveRowDown" Me.MoveRowDown.Size = New System.Drawing.Size(164, 22) Me.MoveRowDown.Text = "Move Row Down" ' 'DBModifCreate ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.CancelButton = Me.Cancel_Button Me.ClientSize = New System.Drawing.Size(479, 469) Me.ControlBox = False Me.Controls.Add(Me.AutoIncFlag) Me.Controls.Add(Me.CreateCB) Me.Controls.Add(Me.OK_Button) Me.Controls.Add(Me.Cancel_Button) Me.Controls.Add(Me.IgnoreDataErrors) Me.Controls.Add(Me.EnvironmentLabel) Me.Controls.Add(Me.AskForExecute) Me.Controls.Add(Me.CUDflags) Me.Controls.Add(Me.insertIfMissing) Me.Controls.Add(Me.DBSeqenceDataGrid) Me.Controls.Add(Me.envSel) Me.Controls.Add(Me.execOnSave) Me.Controls.Add(Me.AdditionalStoredProcLabel) Me.Controls.Add(Me.IgnoreColumnsLabel) Me.Controls.Add(Me.DatabaseLabel) Me.Controls.Add(Me.PrimaryKeysLabel) Me.Controls.Add(Me.TablenameLabel) Me.Controls.Add(Me.NameLabel) Me.Controls.Add(Me.addStoredProc) Me.Controls.Add(Me.IgnoreColumns) Me.Controls.Add(Me.Database) Me.Controls.Add(Me.PrimaryKeys) Me.Controls.Add(Me.Tablename) Me.Controls.Add(Me.DBModifName) Me.Controls.Add(Me.RepairDBSeqnce) Me.Controls.Add(Me.TargetRangeAddress) Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MaximizeBox = False Me.MinimizeBox = False Me.MinimumSize = New System.Drawing.Size(490, 485) Me.Name = "DBModifCreate" Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent CType(Me.DBSeqenceDataGrid, System.ComponentModel.ISupportInitialize).EndInit() Me.MoveMenu.ResumeLayout(False) Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents OK_Button As System.Windows.Forms.Button Friend WithEvents Cancel_Button As System.Windows.Forms.Button Friend WithEvents DBModifName As Windows.Forms.TextBox Friend WithEvents NameLabel As Windows.Forms.Label Friend WithEvents Tablename As Windows.Forms.TextBox Friend WithEvents PrimaryKeys As Windows.Forms.TextBox Friend WithEvents Database As Windows.Forms.TextBox Friend WithEvents IgnoreColumns As Windows.Forms.TextBox Friend WithEvents addStoredProc As Windows.Forms.TextBox Friend WithEvents TablenameLabel As Windows.Forms.Label Friend WithEvents PrimaryKeysLabel As Windows.Forms.Label Friend WithEvents DatabaseLabel As Windows.Forms.Label Friend WithEvents IgnoreColumnsLabel As Windows.Forms.Label Friend WithEvents AdditionalStoredProcLabel As Windows.Forms.Label Friend WithEvents insertIfMissing As Windows.Forms.CheckBox Friend WithEvents execOnSave As Windows.Forms.CheckBox Friend WithEvents ToolTip1 As Windows.Forms.ToolTip Friend WithEvents envSel As Windows.Forms.ComboBox Friend WithEvents EnvironmentLabel As Windows.Forms.Label Friend WithEvents DBSeqenceDataGrid As Windows.Forms.DataGridView Friend WithEvents TargetRangeAddress As Windows.Forms.Label Friend WithEvents CUDflags As Windows.Forms.CheckBox Friend WithEvents RepairDBSeqnce As Windows.Forms.TextBox Friend WithEvents AskForExecute As Windows.Forms.CheckBox Friend WithEvents CreateCB As Windows.Forms.Button Friend WithEvents IgnoreDataErrors As Windows.Forms.CheckBox Friend WithEvents MoveMenu As Windows.Forms.ContextMenuStrip Friend WithEvents MoveRowUp As Windows.Forms.ToolStripMenuItem Friend WithEvents MoveRowDown As Windows.Forms.ToolStripMenuItem Friend WithEvents AutoIncFlag As Windows.Forms.CheckBox End Class
Imports System.Collections.Generic Imports BaseDL4JTest = org.deeplearning4j.BaseDL4JTest Imports ParagraphVectorsTest = org.deeplearning4j.models.paragraphvectors.ParagraphVectorsTest Imports org.deeplearning4j.models.embeddings.learning.impl.elements Imports org.deeplearning4j.models.embeddings.reader.impl Imports VocabWord = org.deeplearning4j.models.word2vec.VocabWord Imports Word2Vec = org.deeplearning4j.models.word2vec.Word2Vec Imports SentenceIterator = org.deeplearning4j.text.sentenceiterator.SentenceIterator Imports SentencePreProcessor = org.deeplearning4j.text.sentenceiterator.SentencePreProcessor Imports LabelAwareSentenceIterator = org.deeplearning4j.text.sentenceiterator.labelaware.LabelAwareSentenceIterator Imports CommonPreprocessor = org.deeplearning4j.text.tokenization.tokenizer.preprocessor.CommonPreprocessor Imports DefaultTokenizerFactory = org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory Imports TokenizerFactory = org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory Imports Disabled = org.junit.jupiter.api.Disabled Imports Tag = org.junit.jupiter.api.Tag Imports Test = org.junit.jupiter.api.Test Imports NativeTag = org.nd4j.common.tests.tags.NativeTag Imports TagNames = org.nd4j.common.tests.tags.TagNames Imports INDArray = org.nd4j.linalg.api.ndarray.INDArray Imports DataSet = org.nd4j.linalg.dataset.DataSet Imports Resources = org.nd4j.common.resources.Resources import static org.junit.jupiter.api.Assertions.assertArrayEquals ' ' * ****************************************************************************** ' * * ' * * ' * * This program and the accompanying materials are made available under the ' * * terms of the Apache License, Version 2.0 which is available at ' * * https://www.apache.org/licenses/LICENSE-2.0. ' * * ' * * See the NOTICE file distributed with this work for additional ' * * information regarding copyright ownership. ' * * 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. ' * * ' * * SPDX-License-Identifier: Apache-2.0 ' * ***************************************************************************** ' Namespace org.deeplearning4j.models.word2vec.iterator 'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: 'ORIGINAL LINE: @Tag(TagNames.FILE_IO) @NativeTag public class Word2VecDataSetIteratorTest extends org.deeplearning4j.BaseDL4JTest Public Class Word2VecDataSetIteratorTest Inherits BaseDL4JTest Public Overrides ReadOnly Property TimeoutMilliseconds As Long Get Return 60000L End Get End Property ''' <summary> ''' Basically all we want from this test - being able to finish without exceptions. ''' </summary> 'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: 'ORIGINAL LINE: @Test public void testIterator1() throws Exception 'JAVA TO VB CONVERTER WARNING: Method 'throws' clauses are not available in VB: Public Overridable Sub testIterator1() Dim inputFile As File = Resources.asFile("big/raw_sentences.txt") Dim iter As SentenceIterator = ParagraphVectorsTest.getIterator(IntegrationTests, inputFile) ' SentenceIterator iter = new BasicLineIterator(inputFile.getAbsolutePath()); Dim t As TokenizerFactory = New DefaultTokenizerFactory() t.TokenPreProcessor = New CommonPreprocessor() Dim vec As Word2Vec = (New Word2Vec.Builder()).minWordFrequency(10).iterations(1).learningRate(0.025).layerSize(150).seed(42).sampling(0).negativeSample(0).useHierarchicSoftmax(True).windowSize(5).modelUtils(New BasicModelUtils(Of VocabWord)()).useAdaGrad(False).iterate(iter).workers(8).tokenizerFactory(t).elementsLearningAlgorithm(New CBOW(Of VocabWord)()).build() vec.fit() Dim labels As IList(Of String) = New List(Of String)() labels.Add("positive") labels.Add("negative") Dim iterator As New Word2VecDataSetIterator(vec, getLASI(iter, labels), labels, 1) 'JAVA TO VB CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: Dim array As INDArray = iterator.next().getFeatures() Dim count As Integer = 0 Do While iterator.MoveNext() Dim ds As DataSet = iterator.Current assertArrayEquals(array.shape(), ds.Features.shape()) 'JAVA TO VB CONVERTER TODO TASK: The following line contains an assignment within expression that was not extracted by Java to VB Converter: 'ORIGINAL LINE: if(!isIntegrationTests() && count++ > 20) If Not IntegrationTests AndAlso count++ > 20 Then Exit Do 'raw_sentences.txt is 2.81 MB, takes quite some time to process. We'll only first 20 minibatches when doing unit tests End If Loop End Sub 'JAVA TO VB CONVERTER WARNING: 'final' parameters are not available in VB: 'ORIGINAL LINE: protected org.deeplearning4j.text.sentenceiterator.labelaware.LabelAwareSentenceIterator getLASI(final org.deeplearning4j.text.sentenceiterator.SentenceIterator iterator, final java.util.List<String> labels) Protected Friend Overridable Function getLASI(ByVal iterator As SentenceIterator, ByVal labels As IList(Of String)) As LabelAwareSentenceIterator iterator.reset() Return New LabelAwareSentenceIteratorAnonymousInnerClass(Me) End Function Private Class LabelAwareSentenceIteratorAnonymousInnerClass Implements LabelAwareSentenceIterator Private ReadOnly outerInstance As Word2VecDataSetIteratorTest Public Sub New(ByVal outerInstance As Word2VecDataSetIteratorTest) Me.outerInstance = outerInstance cnt = New AtomicInteger(0) End Sub Private cnt As AtomicInteger Public Function currentLabel() As String Implements LabelAwareSentenceIterator.currentLabel Return labels.get(cnt.incrementAndGet() Mod labels.size()) End Function Public Function currentLabels() As IList(Of String) Implements LabelAwareSentenceIterator.currentLabels Return Collections.singletonList(currentLabel()) End Function Public Function nextSentence() As String Return iterator.nextSentence() End Function Public Function hasNext() As Boolean Return iterator.hasNext() End Function Public Sub reset() iterator.reset() End Sub Public Sub finish() iterator.finish() End Sub Public Property PreProcessor As SentencePreProcessor Get Return iterator.getPreProcessor() End Get Set(ByVal preProcessor As SentencePreProcessor) iterator.setPreProcessor(preProcessor) End Set End Property End Class End Class End Namespace
' 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.Extensions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Sub ReorderMethodParameters_InvokeOnClassName_ShouldFail() Dim markup = <Text><![CDATA[ Class C$$ Sub M() End Sub End Class]]></Text>.NormalizedValue() TestChangeSignatureViaCommand(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedErrorText:=FeaturesResources.YouCanOnlyChangeTheSignatureOfAConstructorIndexerMethodOrDelegate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Sub ReorderMethodParameters_InvokeOnField_ShouldFail() Dim markup = <Text><![CDATA[ Class C Dim t$$ = 7 Sub M() End Sub End Class]]></Text>.NormalizedValue() TestChangeSignatureViaCommand(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedErrorText:=FeaturesResources.YouCanOnlyChangeTheSignatureOfAConstructorIndexerMethodOrDelegate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Sub ReorderMethodParameters_InsufficientParameters_None() Dim markup = <Text><![CDATA[ Class C Sub $$M() End Sub End Class]]></Text>.NormalizedValue() TestChangeSignatureViaCommand(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedErrorText:=FeaturesResources.ThisSignatureDoesNotContainParametersThatCanBeChanged) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Sub ReorderMethodParameters_InvokeOnOperator_ShouldFail() Dim markup = <Text><![CDATA[ Class C Public Shared $$Operator +(c1 As C, c2 As C) Return Nothing End Operator End Class]]></Text>.NormalizedValue() TestChangeSignatureViaCommand(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedErrorText:=FeaturesResources.YouCanOnlyChangeTheSignatureOfAConstructorIndexerMethodOrDelegate) End Sub End Class End Namespace
Public Class frmAnalytics Dim ticketClass(886) As Integer, gender(886) As String, fullName(886) As String, age(886) As Integer, farePaid(886) As String, survivalStatus(886) As Boolean Dim numberOfPassengers As Integer Private Sub btnLoadData_Click(sender As Object, e As EventArgs) Handles btnLoadData.Click FileOpen(1, "Titanic.csv", OpenMode.Input) numberOfPassengers = 0 Do While Not EOF(1) Input(1, ticketClass(numberOfPassengers)) Input(1, gender(numberOfPassengers)) Input(1, fullName(numberOfPassengers)) Input(1, age(numberOfPassengers)) Input(1, farePaid(numberOfPassengers)) Input(1, survivalStatus(numberOfPassengers)) outResults.AppendText(ticketClass(numberOfPassengers) & " " & gender(numberOfPassengers) & " " & fullName(numberOfPassengers) & " " & _ age(numberOfPassengers) & " " & farePaid(numberOfPassengers) & " " & survivalStatus(numberOfPassengers) & vbNewLine) numberOfPassengers = numberOfPassengers + 1 Loop FileClose(1) outResults.AppendText("-----" & vbNewLine) outResults.AppendText("Total passengers in file: " & numberOfPassengers) End Sub Private Sub btnSearchByName_Click(sender As Object, e As EventArgs) Handles btnSearchByName.Click Dim i As Integer, searchName As String, survivedString As String, found As Boolean, foundIndex As Integer searchName = InputBox("Enter the name of a passenger to search for:") searchName = searchName.ToLower().Trim() i = 0 found = False Do While i < numberOfPassengers And Not found If fullName(i).ToLower().Contains(searchName) Then found = True foundIndex = i End If i = i + 1 Loop If found Then If survivalStatus(foundIndex) Then survivedString = "SURVIVED" Else survivedString = "DIED" End If outResults.Text = fullName(foundIndex) & " " & ticketClass(foundIndex) & " " & age(foundIndex) & " " & farePaid(foundIndex) & " " & survivedString Else outResults.Text = searchName & " PRODUCED NO MATCHES" End If End Sub Private Sub btnPlotByGender_Click(sender As Object, e As EventArgs) Handles btnPlotByGender.Click Dim i As Integer, femaleSurvivedTotal As Integer, femaleTotal As Integer, maleSurvivedTotal As Integer, maleTotal As Integer femaleSurvivedTotal = 0 femaleTotal = 0 maleSurvivedTotal = 0 maleTotal = 0 For i = 0 To numberOfPassengers - 1 If gender(i) = "female" Then If survivalStatus(i) Then femaleSurvivedTotal = femaleSurvivedTotal + 1 End If femaleTotal = femaleTotal + 1 Else If survivalStatus(i) Then maleSurvivedTotal = maleSurvivedTotal + 1 End If maleTotal = maleTotal + 1 End If Next ' add data Dim xAxis(1) As String Dim yAxis(1) As Single xAxis(0) = "female" xAxis(1) = "male" yAxis(0) = femaleSurvivedTotal / femaleTotal * 100 yAxis(1) = maleSurvivedTotal / maleTotal * 100 plot(xAxis, yAxis, picBoxChart) outResults.Text = "Percentage of female survivors was " & FormatPercent(femaleSurvivedTotal / femaleTotal) & vbNewLine & _ "Percentage of male survivors was " & FormatPercent(maleSurvivedTotal / maleTotal) End Sub Private Sub btnPlotByClass_Click(sender As Object, e As EventArgs) Handles btnPlotByClass.Click Dim i As Integer, searchClass As Integer, survivedTotal As Integer, total As Integer searchClass = InputBox("Enter the class of a passengers plot:") survivedTotal = 0 total = 0 For i = 0 To numberOfPassengers - 1 If ticketClass(i) = searchClass Then If survivalStatus(i) Then survivedTotal = survivedTotal + 1 End If total = total + 1 End If Next If total > 0 Then outResults.Text = FormatPercent(survivedTotal / total, 2) & " of passengers from class " & searchClass & " survived." Else outResults.Text = searchClass & " class is not a valid class." End If End Sub Private Sub btnPlotByBoth_Click(sender As Object, e As EventArgs) Handles btnPlotByBoth.Click End Sub Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click End End Sub End Class
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_NoInitializer() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim s As String End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.String</Type> <Name>s</Name> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_WithLiteralInitializer() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim s As String = "Hello" End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.String</Type> <Name>s</Name> <Expression> <Literal> <String>Hello</String> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_WithInvocationInitializer1() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim s As String = Goo() End Sub Function Goo() As String Return "Hello" End Function End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.String</Type> <Name>s</Name> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> </MethodCall> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_WithInvocationInitializer2() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim s As String = Goo(1) End Sub Function Goo(i As Integer) As String Return "Hello" End Function End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.String</Type> <Name>s</Name> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> <Argument> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </Argument> </MethodCall> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_WithEscapedNameAndAsNewClause() ' Note: The behavior here is different than Dev10 where escaped keywords ' would not be escaped in the generated XML. Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim [class] as New Class1 End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>ClassLibrary1.Class1</Type> <Name>[class]</Name> <Expression> <NewClass> <Type>ClassLibrary1.Class1</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_TwoInferredDeclarators() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i = 0, j = 1 End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Int32</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Local> <Local line="3"> <Type>System.Int32</Type> <Name>j</Name> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_StaticLocal() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Static i As Integer = 1 End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Int32</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ConstLocal() ' NOTE: Dev10 didn't generate *any* XML for Const locals because it walked the ' lowered IL tree. We're now generating the same thing that C# does (which has ' generates a local without the "Const" modifier -- i.e. a bug). Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Const i As Integer = 1 End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Int32</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_TwoNamesWithAsNewClause() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim o, n As New Object() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Object</Type> <Name>o</Name> <Expression> <NewClass> <Type>System.Object</Type> </NewClass> </Expression> <Name>n</Name> <Expression> <NewClass> <Type>System.Object</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithNoBoundOrInitializer1() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i() As Integer End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Name>i</Name> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithNoBoundOrInitializer2() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i As Integer() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Name>i</Name> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithSimpleBound() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i(4) As Integer End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Name>i</Name> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Bound> <Expression> <Literal> <Number type="System.Int32">5</Number> </Literal> </Expression> </Bound> </NewArray> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithRangeBound() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i(0 To 4) As Integer End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Name>i</Name> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Bound> <Expression> <Literal> <Number type="System.Int32">5</Number> </Literal> </Expression> </Bound> </NewArray> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithSimpleAndRangeBounds() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i(3, 0 To 6) As Integer End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <ArrayType rank="2"> <Type>System.Int32</Type> </ArrayType> <Name>i</Name> <Expression> <NewArray> <ArrayType rank="2"> <Type>System.Int32</Type> </ArrayType> <Bound> <Expression> <Literal> <Number type="System.Int32">4</Number> </Literal> </Expression> </Bound> <Bound> <Expression> <Literal> <Number type="System.Int32">7</Number> </Literal> </Expression> </Bound> </NewArray> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithStringBound() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i("Goo") As Integer End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Quote line="3">Dim i("Goo") As Integer</Quote> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithStringAndCastBound() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i(CInt("Goo")) As Integer End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Quote line="3">Dim i(CInt("Goo")) As Integer</Quote> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithPropertyAccessBound() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i("Goo".Length) As Integer End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Quote line="3">Dim i("Goo".Length) As Integer</Quote> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithNoBoundAndCollectionInitializer1() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i() As Integer = {1, 2, 3} End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Name>i</Name> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Bound> <Expression> <Literal> <Number>3</Number> </Literal> </Expression> </Bound> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> <Expression> <Literal> <Number type="System.Int32">2</Number> </Literal> </Expression> <Expression> <Literal> <Number type="System.Int32">3</Number> </Literal> </Expression> </NewArray> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_ArrayWithNoBoundAndCollectionInitializer2() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Dim i As Integer() = {1, 2, 3} End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Name>i</Name> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Bound> <Expression> <Literal> <Number>3</Number> </Literal> </Expression> </Bound> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> <Expression> <Literal> <Number type="System.Int32">2</Number> </Literal> </Expression> <Expression> <Literal> <Number type="System.Int32">3</Number> </Literal> </Expression> </NewArray> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_InitializeWithStringConcatenation() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Dim s = "Text" &amp; "Text" End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block><Local line="3"> <Type>System.String</Type> <Name>s</Name> <Expression> <BinaryOperation binaryoperator="concatenate"> <Expression> <Literal> <String>Text</String> </Literal> </Expression> <Expression> <Literal> <String>Text</String> </Literal> </Expression> </BinaryOperation> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_DirectCast() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Dim s = DirectCast("Text", String) End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block><Local line="3"> <Type>System.String</Type> <Name>s</Name> <Expression> <Cast directcast="yes"> <Type>System.String</Type> <Expression> <Literal> <String>Text</String> </Literal> </Expression> </Cast> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBLocalDeclarations_TryCast() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Dim s = TryCast("Text", String) End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block><Local line="3"> <Type>System.String</Type> <Name>s</Name> <Expression> <Cast trycast="yes"> <Type>System.String</Type> <Expression> <Literal> <String>Text</String> </Literal> </Expression> </Cast> </Expression> </Local> </Block> Test(definition, expected) End Sub End Class End Namespace
Imports System.Collections.Generic Imports System.IO Imports Buffer = io.vertx.core.buffer.Buffer Imports RoutingContext = io.vertx.ext.web.RoutingContext Imports Slf4j = lombok.extern.slf4j.Slf4j Imports Persistable = org.deeplearning4j.core.storage.Persistable Imports StatsStorage = org.deeplearning4j.core.storage.StatsStorage Imports StatsStorageEvent = org.deeplearning4j.core.storage.StatsStorageEvent Imports StatsStorageListener = org.deeplearning4j.core.storage.StatsStorageListener Imports HttpMethod = org.deeplearning4j.ui.api.HttpMethod Imports Route = org.deeplearning4j.ui.api.Route Imports UIModule = org.deeplearning4j.ui.api.UIModule Imports I18NResource = org.deeplearning4j.ui.i18n.I18NResource Imports ConvolutionListenerPersistable = org.deeplearning4j.ui.model.weights.ConvolutionListenerPersistable ' ' * ****************************************************************************** ' * * ' * * ' * * This program and the accompanying materials are made available under the ' * * terms of the Apache License, Version 2.0 which is available at ' * * https://www.apache.org/licenses/LICENSE-2.0. ' * * ' * * See the NOTICE file distributed with this work for additional ' * * information regarding copyright ownership. ' * * 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. ' * * ' * * SPDX-License-Identifier: Apache-2.0 ' * ***************************************************************************** ' Namespace org.deeplearning4j.ui.module.convolutional 'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: 'ORIGINAL LINE: @Slf4j public class ConvolutionalListenerModule implements org.deeplearning4j.ui.api.UIModule Public Class ConvolutionalListenerModule Implements UIModule Private Const TYPE_ID As String = "ConvolutionalListener" Private lastStorage As StatsStorage Private lastSessionID As String Private lastWorkerID As String Private lastTimeStamp As Long Public Overridable ReadOnly Property CallbackTypeIDs As IList(Of String) Implements UIModule.getCallbackTypeIDs Get Return Collections.singletonList(TYPE_ID) End Get End Property Public Overridable ReadOnly Property Routes As IList(Of Route) Implements UIModule.getRoutes Get Dim r As New Route("/activations", HttpMethod.GET, Function(path, rc) rc.response().sendFile("templates/Activations.html")) Dim r2 As New Route("/activations/data", HttpMethod.GET, Sub(path, rc) Me.getImage(rc)) Return New List(Of Route) From {r, r2} End Get End Property Public Overridable Sub reportStorageEvents(ByVal events As ICollection(Of StatsStorageEvent)) Implements UIModule.reportStorageEvents SyncLock Me For Each sse As StatsStorageEvent In events If TYPE_ID.Equals(sse.getTypeID()) AndAlso sse.getEventType() = StatsStorageListener.EventType.PostStaticInfo Then If sse.getTimestamp() > lastTimeStamp Then lastStorage = sse.getStatsStorage() lastSessionID = sse.getSessionID() lastWorkerID = sse.getWorkerID() lastTimeStamp = sse.getTimestamp() End If End If Next sse End SyncLock End Sub Public Overridable Sub onAttach(ByVal statsStorage As StatsStorage) Implements UIModule.onAttach 'No-op End Sub Public Overridable Sub onDetach(ByVal statsStorage As StatsStorage) Implements UIModule.onDetach 'No-op End Sub Public Overridable ReadOnly Property InternationalizationResources As IList(Of I18NResource) Implements UIModule.getInternationalizationResources Get Return Collections.emptyList() End Get End Property Private Sub getImage(ByVal rc As RoutingContext) If lastTimeStamp > 0 AndAlso lastStorage IsNot Nothing Then Dim p As Persistable = lastStorage.getStaticInfo(lastSessionID, TYPE_ID, lastWorkerID) If TypeOf p Is ConvolutionListenerPersistable Then Dim clp As ConvolutionListenerPersistable = DirectCast(p, ConvolutionListenerPersistable) Dim bi As BufferedImage = clp.getImg() Dim baos As New MemoryStream() Try ImageIO.write(bi, "png", baos) Catch e As IOException log.warn("Error displaying image", e) End Try rc.response().putHeader("content-type", "image/png").end(Buffer.buffer(baos.toByteArray())) Else rc.response().putHeader("content-type", "image/png").end(Buffer.buffer(New SByte(){})) End If Else rc.response().putHeader("content-type", "image/png").end(Buffer.buffer(New SByte(){})) End If End Sub End Class End Namespace
'------------------------------------------------------------------------------ ' <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 Login '''<summary> '''main_loginl1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents main_loginl1 As Global.BSAP_UI_WebForms.main_loginl End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Form1 Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.Button1 = New System.Windows.Forms.Button() Me.TextBox1 = New System.Windows.Forms.TextBox() Me.SuspendLayout() ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(86, 105) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(124, 23) Me.Button1.TabIndex = 0 Me.Button1.Text = "Redefinição do título" Me.Button1.UseVisualStyleBackColor = True ' 'TextBox1 ' Me.TextBox1.Location = New System.Drawing.Point(97, 50) Me.TextBox1.Name = "TextBox1" Me.TextBox1.Size = New System.Drawing.Size(100, 20) Me.TextBox1.TabIndex = 1 ' 'Form1 ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(284, 261) Me.Controls.Add(Me.TextBox1) Me.Controls.Add(Me.Button1) Me.Name = "Form1" Me.Text = "Form1" Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents Button1 As Button Friend WithEvents TextBox1 As TextBox End Class
Imports System Imports System.Threading.Tasks Imports System.Collections.Generic Imports System.Numerics Imports Nethereum.Hex.HexTypes Imports Nethereum.ABI.FunctionEncoding.Attributes Namespace StandardToken.MyContractName.DTOs <[Event]("Approval")> Public Class ApprovalEventDTO <[Parameter]("address", "_owner", 1, true)> Public Property Owner As String <[Parameter]("address", "_spender", 2, true)> Public Property Spender As String <[Parameter]("uint256", "_value", 3, false)> Public Property Value As BigInteger End Class End Namespace
Public Class FeatureSchema Public Property Name As String = "" Public Property Type As String = "" Public Property abstract As Boolean = False Public Property substitutionGroup As String = "" End Class
Imports System.Data Imports cusAplicacion Partial Class rCotizaciones_dMes Inherits vis2Formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia) Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia) Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1)) Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1)) Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2)) Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2)) Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3)) Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3)) Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4)) Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4)) Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5)) Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5)) Dim lcParametro6Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6)) Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden Dim lcComandoSeleccionar As New StringBuilder() lcComandoSeleccionar.AppendLine(" SELECT SUBSTRING(departamentos.nom_dep,0,30) as nom_dep, ") lcComandoSeleccionar.AppendLine(" sum(case when DatePart(MONTH,cotizaciones.Fec_Ini) = 1 then renglones_cotizaciones.can_art1 else 0 end ) as ped_ene, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 2 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_feb, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 3 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_mar, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 4 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_abr, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 5 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_may, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 6 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_jun, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 7 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_jul, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 8 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_ago, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 9 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_sep, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 10 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_oct, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 11 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_nov, ") lcComandoSeleccionar.AppendLine(" Sum(Case when DatePart(MONTH,cotizaciones.Fec_Ini) = 12 Then renglones_cotizaciones.can_art1 Else 0 End) As ped_dic ") lcComandoSeleccionar.AppendLine("into #temporal ") lcComandoSeleccionar.AppendLine("from renglones_cotizaciones, cotizaciones, articulos, departamentos ") lcComandoSeleccionar.AppendLine(" WHERE ") lcComandoSeleccionar.AppendLine(" cotizaciones.documento=renglones_cotizaciones.documento ") lcComandoSeleccionar.AppendLine(" AND departamentos.cod_dep=articulos.cod_dep ") lcComandoSeleccionar.AppendLine(" AND renglones_cotizaciones.cod_art = articulos.cod_art ") lcComandoSeleccionar.AppendLine(" AND articulos.cod_dep = departamentos.cod_dep ") lcComandoSeleccionar.AppendLine(" AND cotizaciones.fec_ini Between " & lcParametro0Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta) lcComandoSeleccionar.AppendLine(" AND articulos.cod_art Between " & lcParametro1Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta) lcComandoSeleccionar.AppendLine(" AND cotizaciones.cod_cli Between " & lcParametro2Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) lcComandoSeleccionar.AppendLine(" AND cotizaciones.cod_ven Between " & lcParametro3Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta) lcComandoSeleccionar.AppendLine(" AND articulos.cod_dep Between " & lcParametro4Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta) lcComandoSeleccionar.AppendLine(" AND articulos.cod_art Between " & lcParametro5Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta) lcComandoSeleccionar.AppendLine(" AND cotizaciones.status IN (" & lcParametro6Desde & ")") lcComandoSeleccionar.AppendLine("GROUP BY departamentos.nom_dep ") lcComandoSeleccionar.AppendLine("select nom_dep, ") lcComandoSeleccionar.AppendLine(" ped_ene, ") lcComandoSeleccionar.AppendLine(" ped_feb, ") lcComandoSeleccionar.AppendLine(" ped_mar, ") lcComandoSeleccionar.AppendLine(" ped_abr, ") lcComandoSeleccionar.AppendLine(" ped_may, ") lcComandoSeleccionar.AppendLine(" ped_jun, ") lcComandoSeleccionar.AppendLine(" ped_jul, ") lcComandoSeleccionar.AppendLine(" ped_ago, ") lcComandoSeleccionar.AppendLine(" ped_sep, ") lcComandoSeleccionar.AppendLine(" ped_oct, ") lcComandoSeleccionar.AppendLine(" ped_nov, ") lcComandoSeleccionar.AppendLine(" ped_dic, ") lcComandoSeleccionar.AppendLine(" (ped_ene+ped_feb+ped_mar+ped_abr+ped_may+ped_jun+ped_jul+ped_ago+ped_sep+ped_oct+ped_nov+ped_dic)as total ") lcComandoSeleccionar.AppendLine(" from #temporal ") lcComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento) 'lcComandoSeleccionar.AppendLine("ORDER BY nom_dep ") Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(lcComandoSeleccionar.ToString, "curReportes") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rCotizaciones_dMes", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrCotizaciones_dMes.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 '-------------------------------------------------------------------------------------------' ' YJP: 11/05/09: Codigo inicial '-------------------------------------------------------------------------------------------' ' MAT: 16/02/11: Rediseño de la vista del reporte. '-------------------------------------------------------------------------------------------'
 Partial Class TabelDokter Inherits System.Web.UI.Page Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim dokteradapter As New DataSetDokterTableAdapters.dokterTableAdapter dokteradapter.Insert(nama_dokter.Text, jenis_kelamin.Text, spesialis.Text, kontak.Text, status.Text) dokter.Visible = True dokter.DataSource = dokteradapter.GetDataDokter() Response.Redirect("TabelRegis.aspx") End Sub End Class