code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
Imports System Imports Csla Namespace Invoices.Business Public Partial Class ProductList #Region " OnDeserialized actions " ' ''' <summary> ' ''' This method is called on a newly deserialized object ' ''' after deserialization is complete. ' ''' </summary> ' Protected Overrides Sub OnDeserialized() ' MyBase.OnDeserialized() ' add your custom OnDeserialized actions here. ' End Sub #End Region #Region " Implementation of DataPortal Hooks " ' Private Sub OnFetchPre(args As DataPortalHookArgs) ' Throw New NotImplementedException() ' End Sub ' Private Sub OnFetchPost(args As DataPortalHookArgs) ' Throw New NotImplementedException() ' End Sub #End Region End Class End Namespace
CslaGenFork/CslaGenFork
trunk/CoverageTest/Invoices/Invoices-VB/Invoices.Business/ProductList.vb
Visual Basic
mit
895
Imports Microsoft.VisualBasic Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Net Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Documents Imports System.Windows.Input Imports System.Windows.Media Imports System.Windows.Media.Animation Imports System.Windows.Shapes Namespace ArcGISSilverlightSDK Partial Public Class EditToolsUndoRedo Inherits UserControl Public Sub New() InitializeComponent() End Sub End Class End Namespace
Esri/arcgis-samples-silverlight
src/VBNet/ArcGISSilverlightSDK/Editing/EditToolsUndoRedo.xaml.vb
Visual Basic
apache-2.0
519
' 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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure.MetadataAsSource Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class MethodDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of MethodStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New MetadataMethodDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Class C Sub $$M() End Sub End Class " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Class C {|hint:{|collapse:<Foo> |}Sub $$M()|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("collapse", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Class C {|hint:{|collapse:' Summary: ' This is a summary. <Foo> |}Sub $$M()|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("collapse", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " Class C {|hint:{|collapse:' Summary: ' This is a summary. <Foo> |}Public Sub $$M()|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("collapse", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
ljw1004/roslyn
src/EditorFeatures/VisualBasicTest/Structure/MetadataAsSource/MethodDeclarationStructureTests.vb
Visual Basic
apache-2.0
2,621
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Namespace Microsoft.CodeAnalysis.VisualBasic Public Partial Class GlobalImport ' A special Diagnostic info that wraps a particular diagnostic but customized the message with ' the text of the import. Private Class ImportDiagnosticInfo Inherits DiagnosticInfo Shared Sub New() ObjectBinder.RegisterTypeReader(GetType(ImportDiagnosticInfo), Function(r) New ImportDiagnosticInfo(r)) End Sub Private ReadOnly _importText As String Private ReadOnly _startIndex As Integer Private ReadOnly _length As Integer Private ReadOnly _wrappedDiagnostic As DiagnosticInfo Private Sub New(reader As ObjectReader) MyBase.New(reader) Me._importText = reader.ReadString() Me._startIndex = reader.ReadInt32() Me._length = reader.ReadInt32() Me._wrappedDiagnostic = DirectCast(reader.ReadValue(), DiagnosticInfo) End Sub Protected Overrides Sub WriteTo(writer As ObjectWriter) MyBase.WriteTo(writer) writer.WriteString(_importText) writer.WriteInt32(_startIndex) writer.WriteInt32(_length) writer.WriteValue(_wrappedDiagnostic) End Sub Public Overrides Function GetMessage(Optional formatProvider As IFormatProvider = Nothing) As String Dim msg = ErrorFactory.IdToString(ERRID.ERR_GeneralProjectImportsError3, TryCast(formatProvider, CultureInfo)) Return String.Format(formatProvider, msg, _importText, _importText.Substring(_startIndex, _length), _wrappedDiagnostic.GetMessage(formatProvider)) End Function Public Sub New(wrappedDiagnostic As DiagnosticInfo, importText As String, startIndex As Integer, length As Integer) MyBase.New(VisualBasic.MessageProvider.Instance, wrappedDiagnostic.Code) _wrappedDiagnostic = wrappedDiagnostic _importText = importText _startIndex = startIndex _length = length End Sub End Class End Class End Namespace
jmarolf/roslyn
src/Compilers/VisualBasic/Portable/GlobalImport.ImportDiagnosticInfo.vb
Visual Basic
mit
2,557
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Public Class VisualBasicCompletionCommandHandlerTests_InternalsVisibleTo <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOtherAssembliesOfSolution() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ClassLibrary1", "ClassLibrary2", "ClassLibrary3"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOtherAssemblyIfAttributeSuffixIsPresent() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("$$ ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ClassLibrary1"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsTriggeredWhenDoubleQuoteIsEntered() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo($$ ]]> </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendTypeChars(""""c) Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ClassLibrary1"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsEmptyUntilDoubleQuotesAreEntered() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo$$ ]]> </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1"})) state.SendTypeChars("("c) Await state.WaitForAsynchronousOperationsAsync() state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1"})) state.SendTypeChars(""""c) Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ClassLibrary1"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsTriggeredWhenCharacterIsEnteredAfterOpeningDoubleQuote() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")> ]]> </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendTypeChars("a"c) Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ClassLibrary1"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredWhenCharacterIsEnteredThatIsNotRightBesideTheOpeniningDoubleQuote() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("a$$")> ]]> </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendTypeChars("b"c) Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredWhenDoubleQuoteIsEnteredAtStartOfFile() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb">$$ </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendTypeChars("a"c) Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredByArrayElementAccess() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ Namespace A Public Class C Public Sub M() Dim d = New System.Collections.Generic.Dictionary(Of String, String)() Dim v = d$$ End Sub End Class End Namespace ]]> </Document> </Project> </Workspace>) Dim AssertNoCompletionAndCompletionDoesNotContainClassLibrary1 As Func(Of Task) = Async Function() Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Assert.True( state.CurrentCompletionPresenterSession Is Nothing OrElse Not state.CompletionItemsContainsAny({"ClassLibrary1"})) End Function Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() state.SendTypeChars("("c) Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1"})) state.SendTypeChars(""""c) Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() End Using End Function Private Async Function AssertCompletionListHasItems(code As String, hasItems As Boolean) As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"> Imports System.Runtime.CompilerServices Imports System.Reflection <%= code %> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() If hasItems Then Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ClassLibrary1"})) Else If Not state.CurrentCompletionPresenterSession Is Nothing Then Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1"})) End If End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_AfterSingleDoubleQuoteAndClosing() As Task Await AssertCompletionListHasItems("<Assembly: InternalsVisibleTo(""$$)>", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_AfterText() As Task Await AssertCompletionListHasItems("<Assembly: InternalsVisibleTo(""Test$$)>", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfCursorIsInSecondParameter() As Task Await AssertCompletionListHasItems("<Assembly: InternalsVisibleTo(""Test"", ""$$", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfCursorIsClosingDoubleQuote1() As Task Await AssertCompletionListHasItems("<Assembly: InternalsVisibleTo(""Test""$$", False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfCursorIsClosingDoubleQuote2() As Task Await AssertCompletionListHasItems("<Assembly: InternalsVisibleTo(""""$$", False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamedParameterIsPresent() As Task Await AssertCompletionListHasItems("<Assembly: InternalsVisibleTo(""$$, AllInternalsVisible:=True)>", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfNumberIsEntered() As Task Await AssertCompletionListHasItems("<Assembly: InternalsVisibleTo(1$$2)>", False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfNotInternalsVisibleToAttribute() As Task Await AssertCompletionListHasItems("<Assembly: AssemblyVersion(""$$"")>", False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributeIsPresent1() As Task Await AssertCompletionListHasItems("<Assembly: AssemblyVersion(""1.0.0.0""), InternalsVisibleTo(""$$", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributeIsPresent2() As Task Await AssertCompletionListHasItems("<Assembly: InternalsVisibleTo(""$$""), AssemblyVersion(""1.0.0.0"")>", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributesAreAhead() As Task Await AssertCompletionListHasItems(" <Assembly: AssemblyVersion(""1.0.0.0"")> <Assembly: InternalsVisibleTo(""$$", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributesAreFollowing() As Task Await AssertCompletionListHasItems(" <Assembly: InternalsVisibleTo(""$$ <Assembly: AssemblyVersion(""1.0.0.0"")> <Assembly: AssemblyCompany(""Test"")>", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamespaceIsFollowing() As Task Await AssertCompletionListHasItems(" <Assembly: InternalsVisibleTo(""$$ Namespace A Public Class A End Class End Namespace", True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionHasItemsIfInteralVisibleToIsReferencedByTypeAlias() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ Imports IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute <Assembly: IVT("$$ ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ClassLibrary1"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionDoesNotContainCurrentAssembly() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")> ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.False(state.CompletionItemsContainsAny({"TestAssembly"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionInsertsAssemblyNameOnCommit() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")> ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(1, "<Assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1"")>") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionInsertsPublicKeyOnCommit() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> StrongNameProvider=<%= SigningTestHelpers.s_defaultDesktopProvider.GetType().AssemblyQualifiedName %>/> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")> ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(1, "<Assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")>") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsPublicKeyIfKeyIsSpecifiedByAttribute() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions StrongNameProvider=<%= SigningTestHelpers.s_defaultDesktopProvider.GetType().AssemblyQualifiedName %>/> <Document> &lt;Assembly: System.Reflection.AssemblyKeyFile("<%= SigningTestHelpers.PublicKeyFile %>")&gt; </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")> ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(1, "<Assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")>") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsPublicKeyIfDelayedSigningIsEnabled() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> StrongNameProvider=<%= SigningTestHelpers.s_defaultDesktopProvider.GetType().AssemblyQualifiedName %>/> DelaySign="True" /> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")> ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(1, "<Assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")>") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionListIsEmptyIfAttributeIsNotTheBCLAttribute() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: Test.InternalsVisibleTo("$$")> Namespace Test <System.AttributeUsage(System.AttributeTargets.Assembly)> _ Public NotInheritable Class InternalsVisibleToAttribute Inherits System.Attribute Public Sub New(ignore As String) End Sub End Class End Namespace ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVT() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary1")> <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary2")> <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1", "ClassLibrary2"})) Assert.True(state.CompletionItemsContainsAll({"ClassLibrary3"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTIfAssemblyNameIsAConstant() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <MetadataReferenceFromSource Language="Visual Basic" CommonReferences="true"> <Document FilePath="ReferencedDocument.vb"> Namespace A Public NotInheritable Class Constants Private Sub New() End Sub Public Const AssemblyName1 As String = "ClassLibrary1" End Class End Namespace </Document> </MetadataReferenceFromSource> <Document FilePath="A.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo(A.Constants.AssemblyName1)> <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary2")> <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1", "ClassLibrary2"})) Assert.True(state.CompletionItemsContainsAll({"ClassLibrary3"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTForDifferentSyntax() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary4"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary5"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary6"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary7"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary8"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ ' Code comment Imports System.Runtime.CompilerServices Imports System.Reflection Imports IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute ' Code comment <Assembly: InternalsVisibleTo("ClassLibrary1", AllInternalsVisible:=True)> <Assembly: AssemblyVersion("1.0.0.0"), Assembly: InternalsVisibleTo("ClassLibrary2")> <Assembly: InternalsVisibleTo("ClassLibrary3"), Assembly: AssemblyCopyright("Copyright")> <Assembly: AssemblyDescription("Description")> <Assembly: InternalsVisibleTo("ClassLibrary4")> <Assembly: InternalsVisibleTo("ClassLibrary5, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> <Assembly: InternalsVisibleTo("ClassLibrary" + "6")> <Assembly: IVT("ClassLibrary7")> <Assembly: InternalsVisibleTo("$$ Namespace A Public Class A End Class ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1", "ClassLibrary2", "ClassLibrary3", "ClassLibrary4", "ClassLibrary5", "ClassLibrary6", "ClassLibrary7"})) Assert.True(state.CompletionItemsContainsAll({"ClassLibrary8"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTWithSyntaxError() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="A.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Reflection <Assembly: InternalsVisibleTo("ClassLibrary" + 1.ToString())> ' Not a constant <Assembly: InternalsVisibleTo("$$ ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() ' ClassLibrary1 must be listed because the existing attribute argument can't be resolved to a constant. Assert.True(state.CompletionItemsContainsAll({"ClassLibrary1"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTWithMoreThanOneDocument() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="OtherDocument.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Reflection <Assembly: InternalsVisibleTo("ClassLibrary1")> <Assembly: AssemblyDescription("Description")> ]]> </Document> <Document FilePath="A.vb"><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Reflection <Assembly: InternalsVisibleTo("$$ ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.False(state.CompletionItemsContainsAny({"ClassLibrary1"})) Assert.True(state.CompletionItemsContainsAll({"ClassLibrary2"})) End Using End Function End Class End Namespace
lorcanmooney/roslyn
src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_InternalsVisibleTo.vb
Visual Basic
apache-2.0
33,027
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Globalization Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotInheritable Class MessageProvider Inherits CommonMessageProvider Implements IObjectWritable, IObjectReadable Public Shared ReadOnly Instance As MessageProvider = New MessageProvider() Private Sub New() End Sub Private Sub WriteTo(writer As ObjectWriter) Implements IObjectWritable.WriteTo ' don't write anything since we always return the shared 'Instance' when read. End Sub Private Function GetReader() As Func(Of ObjectReader, Object) Implements IObjectReadable.GetReader Return Function(r) Instance End Function Public Overrides ReadOnly Property CodePrefix As String Get ' VB uses "BC" (for Basic Compiler) to identifier its error messages. Return "BC" End Get End Property Public Overrides Function LoadMessage(code As Integer, language As CultureInfo) As String Return ErrorFactory.IdToString(DirectCast(code, ERRID), language) End Function Public Overrides Function GetMessageFormat(code As Integer) As LocalizableString Return ErrorFactory.GetMessageFormat(DirectCast(code, ERRID)) End Function Public Overrides Function GetDescription(code As Integer) As LocalizableString Return ErrorFactory.GetDescription(DirectCast(code, ERRID)) End Function Public Overrides Function GetTitle(code As Integer) As LocalizableString Return ErrorFactory.GetTitle(DirectCast(code, ERRID)) End Function Public Overrides Function GetHelpLink(code As Integer) As String Return ErrorFactory.GetHelpLink(DirectCast(code, ERRID)) End Function Public Overrides Function GetCategory(code As Integer) As String Return ErrorFactory.GetCategory(DirectCast(code, ERRID)) End Function Public Overrides Function GetSeverity(code As Integer) As DiagnosticSeverity Dim errid = DirectCast(code, ERRID) If errid = ERRID.Void Then Return InternalDiagnosticSeverity.Void ElseIf errid = ERRID.Unknown Then Return InternalDiagnosticSeverity.Unknown ElseIf ErrorFacts.IsWarning(errid) Then Return DiagnosticSeverity.Warning ElseIf ErrorFacts.IsInfo(errid) Then Return DiagnosticSeverity.Info ElseIf ErrorFacts.IsHidden(errid) Then Return DiagnosticSeverity.Hidden Else Return DiagnosticSeverity.Error End If End Function Public Overrides Function GetWarningLevel(code As Integer) As Integer Dim errorId = DirectCast(code, ERRID) If ErrorFacts.IsWarning(errorId) AndAlso code <> ERRID.WRN_BadSwitch AndAlso code <> ERRID.WRN_NoConfigInResponseFile AndAlso code <> ERRID.WRN_IgnoreModuleManifest Then Return 1 ElseIf ErrorFacts.IsInfo(errorId) OrElse ErrorFacts.IsHidden(errorId) ' Info and hidden diagnostics Return 1 Else Return 0 End If End Function Public Overrides ReadOnly Property ErrorCodeType As Type Get Return GetType(ERRID) End Get End Property Public Overrides Function CreateDiagnostic(code As Integer, location As Location, ParamArray args() As Object) As Diagnostic Return New VBDiagnostic(ErrorFactory.ErrorInfo(CType(code, ERRID), args), location) End Function Public Overrides Function ConvertSymbolToString(errorCode As Integer, symbol As ISymbol) As String ' show extra info for assembly if possible such as version, public key token etc. If symbol.Kind = SymbolKind.Assembly OrElse symbol.Kind = SymbolKind.Namespace Then Return symbol.ToString() End If ' cases where we actually want fully qualified name If errorCode = ERRID.ERR_AmbiguousAcrossInterfaces3 OrElse errorCode = ERRID.ERR_TypeConflict6 OrElse errorCode = ERRID.ERR_ExportedTypesConflict OrElse errorCode = ERRID.ERR_ForwardedTypeConflictsWithDeclaration OrElse errorCode = ERRID.ERR_ForwardedTypeConflictsWithExportedType OrElse errorCode = ERRID.ERR_ForwardedTypesConflict Then Return symbol.ToString() End If ' show fully qualified name for missing special types If errorCode = ERRID.ERR_UnreferencedAssembly3 AndAlso TypeOf symbol Is ITypeSymbol AndAlso DirectCast(symbol, ITypeSymbol).SpecialType <> SpecialType.None Then Return symbol.ToString() End If Return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.VisualBasicShortErrorMessageFormat) End Function ' Given a message identifier (e.g., CS0219), severity, warning as error and a culture, ' get the entire prefix (e.g., "error BC42024:" for VB) used on error messages. Public Overrides Function GetMessagePrefix(id As String, severity As DiagnosticSeverity, isWarningAsError As Boolean, culture As CultureInfo) As String Return String.Format(culture, "{0} {1}", If(severity = DiagnosticSeverity.Error OrElse isWarningAsError, "error", "warning"), id) End Function Public Overrides Function GetDiagnosticReport(diagnosticInfo As DiagnosticInfo, options As CompilationOptions) As ReportDiagnostic Dim hasSourceSuppression = False Return VisualBasicDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, True, diagnosticInfo.MessageIdentifier, Location.None, diagnosticInfo.Category, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, hasSourceSuppression) End Function Public Overrides ReadOnly Property ERR_FailedToCreateTempFile As Integer Get Return ERRID.ERR_UnableToCreateTempFile End Get End Property ' command line: Public Overrides ReadOnly Property ERR_ExpectedSingleScript As Integer Get Return ERRID.ERR_ExpectedSingleScript End Get End Property Public Overrides ReadOnly Property ERR_OpenResponseFile As Integer Get Return ERRID.ERR_NoResponseFile End Get End Property Public Overrides ReadOnly Property ERR_InvalidPathMap As Integer Get Return ERRID.ERR_InvalidPathMap End Get End Property Public Overrides ReadOnly Property FTL_InputFileNameTooLong As Integer Get Return ERRID.FTL_InputFileNameTooLong End Get End Property Public Overrides ReadOnly Property ERR_FileNotFound As Integer Get Return ERRID.ERR_FileNotFound End Get End Property Public Overrides ReadOnly Property ERR_NoSourceFile As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_CantOpenFileWrite As Integer Get Return ERRID.ERR_CantOpenFileWrite End Get End Property Public Overrides ReadOnly Property ERR_OutputWriteFailed As Integer Get Return ERRID.ERR_CantOpenFileWrite End Get End Property Public Overrides ReadOnly Property WRN_NoConfigNotOnCommandLine As Integer Get Return ERRID.WRN_NoConfigInResponseFile End Get End Property Public Overrides ReadOnly Property ERR_BinaryFile As Integer Get Return ERRID.ERR_BinaryFile End Get End Property Public Overrides ReadOnly Property WRN_AnalyzerCannotBeCreated As Integer Get Return ERRID.WRN_AnalyzerCannotBeCreated End Get End Property Public Overrides ReadOnly Property WRN_NoAnalyzerInAssembly As Integer Get Return ERRID.WRN_NoAnalyzerInAssembly End Get End Property Public Overrides ReadOnly Property WRN_UnableToLoadAnalyzer As Integer Get Return ERRID.WRN_UnableToLoadAnalyzer End Get End Property Public Overrides ReadOnly Property INF_UnableToLoadSomeTypesInAnalyzer As Integer Get Return ERRID.INF_UnableToLoadSomeTypesInAnalyzer End Get End Property Public Overrides ReadOnly Property ERR_CantReadRulesetFile As Integer Get Return ERRID.ERR_CantReadRulesetFile End Get End Property Public Overrides ReadOnly Property ERR_CompileCancelled As Integer Get ' TODO: Add an error code for CompileCancelled Return ERRID.ERR_None End Get End Property ' compilation options: Public Overrides ReadOnly Property ERR_BadCompilationOptionValue As Integer Get Return ERRID.ERR_InvalidSwitchValue End Get End Property ' emit options: Public Overrides ReadOnly Property ERR_InvalidDebugInformationFormat As Integer Get Return ERRID.ERR_InvalidDebugInformationFormat End Get End Property Public Overrides ReadOnly Property ERR_InvalidOutputName As Integer Get Return ERRID.ERR_InvalidOutputName End Get End Property Public Overrides ReadOnly Property ERR_InvalidFileAlignment As Integer Get Return ERRID.ERR_InvalidFileAlignment End Get End Property Public Overrides ReadOnly Property ERR_InvalidSubsystemVersion As Integer Get Return ERRID.ERR_InvalidSubsystemVersion End Get End Property ' reference manager: Public Overrides ReadOnly Property ERR_MetadataFileNotAssembly As Integer Get Return ERRID.ERR_MetaDataIsNotAssembly End Get End Property Public Overrides ReadOnly Property ERR_MetadataFileNotModule As Integer Get Return ERRID.ERR_MetaDataIsNotModule End Get End Property Public Overrides ReadOnly Property ERR_InvalidAssemblyMetadata As Integer Get Return ERRID.ERR_BadMetaDataReference1 End Get End Property Public Overrides ReadOnly Property ERR_InvalidModuleMetadata As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_ErrorOpeningAssemblyFile As Integer Get Return ERRID.ERR_BadRefLib1 End Get End Property Public Overrides ReadOnly Property ERR_ErrorOpeningModuleFile As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_MetadataFileNotFound As Integer Get Return ERRID.ERR_LibNotFound End Get End Property Public Overrides ReadOnly Property ERR_MetadataReferencesNotSupported As Integer Get Return ERRID.ERR_MetadataReferencesNotSupported End Get End Property Public Overrides ReadOnly Property ERR_LinkedNetmoduleMetadataMustProvideFullPEImage As Integer Get Return ERRID.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage End Get End Property Public Overrides Sub ReportDuplicateMetadataReferenceStrong(diagnostics As DiagnosticBag, location As Location, reference As MetadataReference, identity As AssemblyIdentity, equivalentReference As MetadataReference, equivalentIdentity As AssemblyIdentity) diagnostics.Add(ERRID.ERR_DuplicateReferenceStrong, DirectCast(location, Location), If(reference.Display, identity.GetDisplayName()), If(equivalentReference.Display, equivalentIdentity.GetDisplayName())) End Sub Public Overrides Sub ReportDuplicateMetadataReferenceWeak(diagnostics As DiagnosticBag, location As Location, reference As MetadataReference, identity As AssemblyIdentity, equivalentReference As MetadataReference, equivalentIdentity As AssemblyIdentity) diagnostics.Add(ERRID.ERR_DuplicateReference2, DirectCast(location, Location), identity.Name, If(equivalentReference.Display, equivalentIdentity.GetDisplayName())) End Sub ' signing: Public Overrides ReadOnly Property ERR_CantReadResource As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 End Get End Property Public Overrides ReadOnly Property ERR_PublicKeyFileFailure As Integer Get Return ERRID.ERR_PublicKeyFileFailure End Get End Property Public Overrides ReadOnly Property ERR_PublicKeyContainerFailure As Integer Get Return ERRID.ERR_PublicKeyContainerFailure End Get End Property ' resources: Public Overrides ReadOnly Property ERR_CantOpenWin32Resource As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 'TODO: refine (DevDiv #12914) End Get End Property Public Overrides ReadOnly Property ERR_CantOpenWin32Manifest As Integer Get Return ERRID.ERR_UnableToReadUacManifest2 End Get End Property Public Overrides ReadOnly Property ERR_CantOpenWin32Icon As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 'TODO: refine (DevDiv #12914) End Get End Property Public Overrides ReadOnly Property ERR_ErrorBuildingWin32Resource As Integer Get Return ERRID.ERR_ErrorCreatingWin32ResourceFile End Get End Property Public Overrides ReadOnly Property ERR_BadWin32Resource As Integer Get Return ERRID.ERR_ErrorCreatingWin32ResourceFile End Get End Property Public Overrides ReadOnly Property ERR_ResourceFileNameNotUnique As Integer Get Return ERRID.ERR_DuplicateResourceFileName1 End Get End Property Public Overrides ReadOnly Property ERR_ResourceNotUnique As Integer Get Return ERRID.ERR_DuplicateResourceName1 End Get End Property Public Overrides ReadOnly Property ERR_ResourceInModule As Integer Get Return ERRID.ERR_ResourceInModule End Get End Property ' pseudo-custom attributes Public Overrides ReadOnly Property ERR_PermissionSetAttributeFileReadError As Integer Get Return ERRID.ERR_PermissionSetAttributeFileReadError End Get End Property Public Overrides Sub ReportInvalidAttributeArgument(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_BadAttribute1, node.ArgumentList.Arguments(parameterIndex).GetLocation(), attribute.AttributeClass) End Sub Public Overrides Sub ReportInvalidNamedArgument(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, namedArgumentIndex As Integer, attributeClass As ITypeSymbol, parameterName As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_BadAttribute1, node.ArgumentList.Arguments(namedArgumentIndex).GetLocation(), attributeClass) End Sub Public Overrides Sub ReportParameterNotValidForType(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, namedArgumentIndex As Integer) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_ParameterNotValidForType, node.ArgumentList.Arguments(namedArgumentIndex).GetLocation()) End Sub Public Overrides Sub ReportMarshalUnmanagedTypeNotValidForFields(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, unmanagedTypeName As String, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_MarshalUnmanagedTypeNotValidForFields, node.ArgumentList.Arguments(parameterIndex).GetLocation(), unmanagedTypeName) End Sub Public Overrides Sub ReportMarshalUnmanagedTypeOnlyValidForFields(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, unmanagedTypeName As String, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, node.ArgumentList.Arguments(parameterIndex).GetLocation(), unmanagedTypeName) End Sub Public Overrides Sub ReportAttributeParameterRequired(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterName As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_AttributeParameterRequired1, node.Name.GetLocation(), parameterName) End Sub Public Overrides Sub ReportAttributeParameterRequired(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterName1 As String, parameterName2 As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_AttributeParameterRequired2, node.Name.GetLocation(), parameterName1, parameterName2) End Sub ' PDB Writer Public Overrides ReadOnly Property WRN_PdbUsingNameTooLong As Integer Get Return ERRID.WRN_PdbUsingNameTooLong End Get End Property Public Overrides ReadOnly Property WRN_PdbLocalNameTooLong As Integer Get Return ERRID.WRN_PdbLocalNameTooLong End Get End Property Public Overrides ReadOnly Property ERR_PdbWritingFailed As Integer Get Return ERRID.ERR_PDBWritingFailed End Get End Property ' PE Writer Public Overrides ReadOnly Property ERR_MetadataNameTooLong As Integer Get Return ERRID.ERR_TooLongMetadataName End Get End Property Public Overrides ReadOnly Property ERR_EncReferenceToAddedMember As Integer Get Return ERRID.ERR_EncReferenceToAddedMember End Get End Property End Class End Namespace
VPashkov/roslyn
src/Compilers/VisualBasic/Portable/Errors/MessageProvider.vb
Visual Basic
apache-2.0
20,436
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeRefactorings.ExtractMethod Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.ExtractMethod Public Class ExtractMethodTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New ExtractMethodCodeRefactoringProvider() End Function <WorkItem(540686, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540686")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestExtractReturnExpression() As Task Await TestInRegularAndScriptAsync( "Class Module1 Private Delegate Function Func(i As Integer) Shared Sub Main(args As String()) Dim temp As Integer = 2 Dim fnc As Func = Function(arg As Integer) temp = arg Return [|arg|] End Function End Sub End Class", "Class Module1 Private Delegate Function Func(i As Integer) Shared Sub Main(args As String()) Dim temp As Integer = 2 Dim fnc As Func = Function(arg As Integer) temp = arg Return {|Rename:GetArg|}(arg) End Function End Sub Private Shared Function GetArg(arg As Integer) As Integer Return arg End Function End Class") End Function <WorkItem(540755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540755")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestExtractMultilineLambda() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Dim q As Action = [|Sub() End Sub|] End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then Dim q As Action = {|Rename:GetQ|}() End Sub Private Function GetQ() As Action Return Sub() End Sub End Function End Module") End Function <WorkItem(541515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541515")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestCollectionInitializerInObjectCollectionInitializer() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main() [|Dim x As New List(Of Program) From {New Program}|] End Sub Public Property Name As String End Class", "Class Program Sub Main() {|Rename:NewMethod|}() End Sub Private Shared Sub NewMethod() Dim x As New List(Of Program) From {New Program} End Sub Public Property Name As String End Class") End Function <WorkItem(542251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542251")> <WorkItem(543030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543030")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestLambdaSelection() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q As Object If True Then q = [|Sub() End Sub|] End Sub End Module", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q As Object If True Then q = {|Rename:NewMethod|}() End Sub Private Function NewMethod() As Object Return Sub() End Sub End Function End Module") End Function <WorkItem(542904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542904")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestFormatBeforeAttribute() As Task Await TestInRegularAndScriptAsync( <Text>Module Program Sub Main(args As String()) Dim x = [|1 + 1|] End Sub &lt;Obsolete&gt; Sub Goo End Sub End Module </Text>.Value.Replace(vbLf, vbCrLf), <Text>Module Program Sub Main(args As String()) Dim x = {|Rename:GetX|}() End Sub Private Function GetX() As Integer Return 1 + 1 End Function &lt;Obsolete&gt; Sub Goo End Sub End Module </Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(545262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545262")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestInTernaryConditional() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim p As Object = Nothing Dim Obj1 = If(New With {.a = True}.a, p, [|Nothing|]) End Sub End Module", "Module Program Sub Main(args As String()) Dim p As Object = Nothing Dim Obj1 = If(New With {.a = True}.a, p, {|Rename:NewMethod|}()) End Sub Private Function NewMethod() As Object Return Nothing End Function End Module") End Function <WorkItem(545547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545547")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestInRangeArgumentUpperBound() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() Dim x(0 To [|1 + 2|]) ' Extract method End Sub End Module", "Module Program Sub Main() Dim x(0 To {|Rename:NewMethod|}()) ' Extract method End Sub Private Function NewMethod() As Integer Return 1 + 2 End Function End Module") End Function <WorkItem(545655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545655")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestInWhileUntilCondition() As Task Await TestInRegularAndScriptAsync( "Module M Sub Main() Dim x = 0 Do While [|x * x < 100|] x += 1 Loop End Sub End Module", "Module M Sub Main() Dim x = 0 Do While {|Rename:NewMethod|}(x) x += 1 Loop End Sub Private Function NewMethod(x As Integer) As Boolean Return x * x < 100 End Function End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestInInterpolation1() As Task Await TestInRegularAndScriptAsync( "Module M Sub Main() Dim v As New Object [|System.Console.WriteLine($""{v}"")|] System.Console.WriteLine(v) End Sub End Module", "Module M Sub Main() Dim v As New Object {|Rename:NewMethod|}(v) System.Console.WriteLine(v) End Sub Private Sub NewMethod(v As Object) System.Console.WriteLine($""{v}"") End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestInInterpolation2() As Task Await TestInRegularAndScriptAsync( "Module M Sub Main() Dim v As New Object System.Console.WriteLine([|$""{v}""|]) System.Console.WriteLine(v) End Sub End Module", "Module M Sub Main() Dim v As New Object System.Console.WriteLine({|Rename:NewMethod|}(v)) System.Console.WriteLine(v) End Sub Private Function NewMethod(v As Object) As String Return $""{v}"" End Function End Module") End Function <WorkItem(545829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545829")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestMissingOnImplicitMemberAccess() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() With """""""" Dim x = [|.GetHashCode|] Xor &H7F3E ' Introduce Local End With End Sub End Module", "Module Program Sub Main() {|Rename:NewMethod|}() End Sub Private Sub NewMethod() With """""""" Dim x = .GetHashCode Xor &H7F3E ' Introduce Local End With End Sub End Module") End Function <WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestPreserveCommentsBeforeDeclaration_1() As Task Await TestInRegularAndScriptAsync( <Text>Class Program Sub Main(args As String()) [|Dim one As Program = New Program() one.M() ' This is the comment Dim two As Program = New Program() two.M()|] one.M() two.M() End Sub Private Sub M() Throw New NotImplementedException() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text>Class Program Sub Main(args As String()) Dim one As Program = Nothing Dim two As Program = Nothing {|Rename:NewMethod|}(one, two) one.M() two.M() End Sub Private Shared Sub NewMethod(ByRef one As Program, ByRef two As Program) one = New Program() one.M() ' This is the comment two = New Program() two.M() End Sub Private Sub M() Throw New NotImplementedException() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestPreserveCommentsBeforeDeclaration_2() As Task Await TestInRegularAndScriptAsync( <Text>Class Program Sub Main(args As String()) [|Dim one As Program = New Program() one.M() ' This is the comment Dim two As Program = New Program(), three As Program = New Program() two.M()|] one.M() two.M() three.M() End Sub Private Sub M() Throw New NotImplementedException() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text>Class Program Sub Main(args As String()) Dim one As Program = Nothing Dim two As Program = Nothing Dim three As Program = Nothing {|Rename:NewMethod|}(one, two, three) one.M() two.M() three.M() End Sub Private Shared Sub NewMethod(ByRef one As Program, ByRef two As Program, ByRef three As Program) one = New Program() one.M() ' This is the comment two = New Program() three = New Program() two.M() End Sub Private Sub M() Throw New NotImplementedException() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)> Public Async Function TestPreserveCommentsBeforeDeclaration_3() As Task Await TestInRegularAndScriptAsync( <Text>Class Program Sub Main(args As String()) [|Dim one As Program = New Program() one.M() ' This is the comment Dim two As Program = New Program() two.M() ' Second Comment Dim three As Program = New Program() three.M()|] one.M() two.M() three.M() End Sub Private Sub M() Throw New NotImplementedException() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text>Class Program Sub Main(args As String()) Dim one As Program = Nothing Dim two As Program = Nothing Dim three As Program = Nothing {|Rename:NewMethod|}(one, two, three) one.M() two.M() three.M() End Sub Private Shared Sub NewMethod(ByRef one As Program, ByRef two As Program, ByRef three As Program) one = New Program() one.M() ' This is the comment two = New Program() two.M() ' Second Comment three = New Program() three.M() End Sub Private Sub M() Throw New NotImplementedException() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)> <WorkItem(13042, "https://github.com/dotnet/roslyn/issues/13042")> Public Async Function TestTuples() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Dim x = (1, 2)|] M(x) End Sub Private Sub M(x As (Integer, Integer)) End Sub End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace", "Class Program Sub Main(args As String()) Dim x As (Integer, Integer) = {|Rename:NewMethod|}() M(x) End Sub Private Shared Function NewMethod() As (Integer, Integer) Return (1, 2) End Function Private Sub M(x As (Integer, Integer)) End Sub End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)> <WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")> Public Async Function TestTupleDeclarationWithNames() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Dim x As (a As Integer, b As Integer) = (1, 2)|] System.Console.WriteLine(x.a) End Sub End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace", "Class Program Sub Main(args As String()) Dim x As (a As Integer, b As Integer) = {|Rename:NewMethod|}() System.Console.WriteLine(x.a) End Sub Private Shared Function NewMethod() As (a As Integer, b As Integer) Return (1, 2) End Function End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)> <WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")> Public Async Function TestTupleDeclarationWithSomeNames() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Dim x As (a As Integer, Integer) = (1, 2)|] System.Console.WriteLine(x.a) End Sub End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace", "Class Program Sub Main(args As String()) Dim x As (a As Integer, Integer) = {|Rename:NewMethod|}() System.Console.WriteLine(x.a) End Sub Private Shared Function NewMethod() As (a As Integer, Integer) Return (1, 2) End Function End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)> <WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")> Public Async Function TestTupleWith1Arity() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) Dim y = New ValueTuple(Of Integer)(1) [|y.Item1.ToString()|] End Sub End Class Structure ValueTuple(Of T1) Public Property Item1 As T1 Public Sub New(item1 As T1) End Sub End Structure", "Class Program Sub Main(args As String()) Dim y = New ValueTuple(Of Integer)(1) {|Rename:NewMethod|}(y) End Sub Private Shared Sub NewMethod(y As ValueTuple(Of Integer)) y.Item1.ToString() End Sub End Class Structure ValueTuple(Of T1) Public Property Item1 As T1 Public Sub New(item1 As T1) End Sub End Structure") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)> Public Async Function TestTupleWithInferredNames() As Task Await TestAsync( "Class Program Sub Main() Dim a = 1 Dim t = [|(a, b:=2)|] System.Console.Write(t.a) End Sub End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace", "Class Program Sub Main() Dim a = 1 Dim t = {|Rename:GetT|}(a) System.Console.Write(t.a) End Sub Private Shared Function GetT(a As Integer) As (a As Integer, b As Integer) Return (a, b:=2) End Function End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace", TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)> Public Async Function TestTupleWithInferredNames_WithVB15() As Task Await TestAsync( "Class Program Sub Main() Dim a = 1 Dim t = [|(a, b:=2)|] System.Console.Write(t.a) End Sub End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace", "Class Program Sub Main() Dim a = 1 Dim t = {|Rename:GetT|}(a) System.Console.Write(t.a) End Sub Private Shared Function GetT(a As Integer) As (a As Integer, b As Integer) Return (a, b:=2) End Function End Class Namespace System Structure ValueTuple(Of T1, T2) End Structure End Namespace", TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) End Function End Class End Namespace
mmitche/roslyn
src/EditorFeatures/VisualBasicTest/CodeActions/ExtractMethod/ExtractMethodTests.vb
Visual Basic
apache-2.0
18,958
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("LabScheduler")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("LabScheduler")> <Assembly: AssemblyCopyright("Copyright © 2014")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("a934f00a-4249-499b-8402-18bba65b7f89")> ' 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")>
lurienanofab/labscheduler
LabScheduler/My Project/AssemblyInfo.vb
Visual Basic
mit
1,141
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.225 ' ' 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.ProgressBar.Form1 End Sub End Class End Namespace
gumgl/VB.NET
ProgressBar/My Project/Application.Designer.vb
Visual Basic
mit
1,475
Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim documents As SolidEdgeFramework.Documents = Nothing Dim draftDocument As SolidEdgeDraft.DraftDocument = Nothing Dim sheet As SolidEdgeDraft.Sheet = Nothing Dim curves2d As SolidEdgeFrameworkSupport.Curves2d = Nothing Dim curve2d As SolidEdgeFrameworkSupport.Curve2d = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) documents = application.Documents draftDocument = CType(documents.Add("SolidEdge.DraftDocument"), SolidEdgeDraft.DraftDocument) sheet = draftDocument.ActiveSheet curves2d = sheet.Curves2d Dim Points = CType(New Double(), System.Array) { 0.1, 0.1, 0.2, 0.1, 0.2, 0.2, 0.1, 0.2 } curve2d = curves2d.AddByPoints(Points.Length \ 2, Points) Dim key = curve2d.Key Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeFrameworkSupport.Curve2d.Key.vb
Visual Basic
mit
1,660
Option Explicit On Option Strict On Namespace CompuMaster.Data Public Class TextRow Public Sub New(row As System.Collections.Generic.List(Of TextCell)) If row Is Nothing Then Throw New ArgumentNullException(NameOf(row)) Me.Cells = row End Sub Public Sub New(itemArray As Object()) If itemArray Is Nothing Then Throw New ArgumentNullException(NameOf(itemArray)) Dim ItemCells As New System.Collections.Generic.List(Of TextCell) For MyCounter As Integer = 0 To itemArray.Length - 1 ItemCells.Add(New TextCell(itemArray(MyCounter))) Next Me.Cells = ItemCells End Sub Public Sub New() Me.Cells = New System.Collections.Generic.List(Of TextCell) End Sub 'Public Property ParentTable As TextTable ''' <summary> ''' Contents of cells ''' </summary> Public Property Cells As System.Collections.Generic.List(Of TextCell) ''' <summary> ''' Count of cells ''' </summary> ''' <returns></returns> Public ReadOnly Property Count As Integer Get Return Me.Cells.Count End Get End Property ''' <summary> ''' Text representation of row ''' </summary> ''' <param name="cellBreakNewLine"></param> ''' <param name="dbNullText"></param> ''' <returns></returns> Public Function ToEncodedString(columnWidths As Integer(), cellSeparator As Char, cellBreakNewLine As String, dbNullText As String, suffixIfValueMustBeShortened As String) As String Dim Result As New System.Text.StringBuilder Me.AppendEncodedString(Result, TextTable.CellOutputDirection.Standard, TextTable.CellContentHorizontalAlignment.Left, TextTable.CellContentVerticalAlignment.Top, " "c, columnWidths, cellSeparator, cellBreakNewLine, dbNullText, " ", suffixIfValueMustBeShortened) Return Result.ToString End Function ''' <summary> ''' Text representation of row ''' </summary> ''' <param name="outputStringBuilder">Write all output to this StringBuilder instance</param> ''' <param name="cellDirection">Cell flow left-to-right or right-to-left</param> ''' <param name="textHorizontalAlignment">Horizontal alignment for cell text</param> ''' <param name="textVerticalAlignment">Vertical alignment for cell text</param> ''' <param name="textFillUpChar">When aligning cell text content, use this char (usually a space char) for spacing</param> ''' <param name="columnWidths">Widths of all output columns in chars</param> ''' <param name="cellSeparator">Separate cells with this char (Char 0 if no separator char shall be used)</param> ''' <param name="cellBreakNewLine">When cells contain line breaks, use this line break at end of line (not at end of row!)</param> ''' <param name="dbNullText">Text representation of DbNull.Value, e.g. empty space or a string like "NULL"</param> ''' <param name="tabText">Text representation of TAB char, e.g. 4 spaces</param> Public Sub AppendEncodedString(outputStringBuilder As System.Text.StringBuilder, cellDirection As TextTable.CellOutputDirection, textHorizontalAlignment As TextTable.CellContentHorizontalAlignment, textVerticalAlignment As TextTable.CellContentVerticalAlignment, textFillUpChar As Char, columnWidths As Integer(), cellSeparator As String, cellBreakNewLine As String, dbNullText As String, tabText As String, suffixIfCellValueIsTooLong As String) If columnWidths Is Nothing OrElse columnWidths.Length = 0 Then Throw New ArgumentNullException(NameOf(columnWidths)) '1st scan: how many lines are required to write this row Dim Lines(columnWidths.Length - 1)() As String Dim LinesCount As Integer = 1 For MyCounter As Integer = 0 To columnWidths.Length - 1 If columnWidths(MyCounter) = 0 Then 'Column to be hidden Lines(MyCounter) = New String() {} Else 'Column to be written Lines(MyCounter) = Me.Cells(MyCounter).TextLines(dbNullText, tabText) LinesCount = System.Math.Max(LinesCount, Lines(MyCounter).Length) End If Next '2nd formatted (spaced+aligned) output Dim CellTextAligned(columnWidths.Length - 1) As System.Collections.Generic.List(Of String) For ColumnCounter As Integer = 0 To columnWidths.Length - 1 If columnWidths(ColumnCounter) = 0 Then 'Column to be hidden Else 'Column to be written CellTextAligned(ColumnCounter) = New System.Collections.Generic.List(Of String)(Lines(ColumnCounter)) 'Align vertically Select Case textVerticalAlignment Case TextTable.CellContentVerticalAlignment.Top Do While CellTextAligned(ColumnCounter).Count < LinesCount 'Insert empty line on bottom CellTextAligned(ColumnCounter).Add("") Loop Case TextTable.CellContentVerticalAlignment.Bottom Do While CellTextAligned(ColumnCounter).Count < LinesCount 'Insert empty line on top CellTextAligned(ColumnCounter).Insert(0, "") Loop Case TextTable.CellContentVerticalAlignment.Middle Do While CellTextAligned(ColumnCounter).Count < LinesCount 'First, add empty line below CellTextAligned(ColumnCounter).Insert(0, "") 'If still required, add empty line above If CellTextAligned(ColumnCounter).Count < LinesCount Then CellTextAligned(ColumnCounter).Add("") End If Loop Case Else Throw New ArgumentOutOfRangeException(NameOf(textVerticalAlignment)) End Select 'Align horizontally Dim MaxLength As Integer = columnWidths(ColumnCounter) For LineCounter As Integer = 0 To CellTextAligned(ColumnCounter).Count - 1 If CellTextAligned(ColumnCounter).Item(LineCounter).Length > MaxLength Then 'Reduce text length CellTextAligned(ColumnCounter).Item(LineCounter) = DataTables.TrimStringToFixedWidth(CellTextAligned(ColumnCounter).Item(LineCounter), columnWidths(ColumnCounter), suffixIfCellValueIsTooLong) CellTextAligned(ColumnCounter).Item(LineCounter) = CellTextAligned(ColumnCounter).Item(LineCounter).Substring(0, MaxLength) End If Select Case textHorizontalAlignment Case TextTable.CellContentHorizontalAlignment.Left If CellTextAligned(ColumnCounter).Item(LineCounter).Length < MaxLength Then 'Add space chars from right CellTextAligned(ColumnCounter).Item(LineCounter) = CellTextAligned(ColumnCounter).Item(LineCounter) & New String(textFillUpChar, MaxLength - CellTextAligned(ColumnCounter).Item(LineCounter).Length) End If Case TextTable.CellContentHorizontalAlignment.Right If CellTextAligned(ColumnCounter).Item(LineCounter).Length < MaxLength Then 'Add space chars from right CellTextAligned(ColumnCounter).Item(LineCounter) = New String(textFillUpChar, MaxLength - CellTextAligned(ColumnCounter).Item(LineCounter).Length) & CellTextAligned(ColumnCounter).Item(LineCounter) End If Case TextTable.CellContentHorizontalAlignment.Center If CellTextAligned(ColumnCounter).Item(LineCounter).Length < MaxLength Then 'Add space chars from right Dim SpacesTotal As Integer = MaxLength - CellTextAligned(ColumnCounter).Item(LineCounter).Length Dim SpacesRight, SpacesLeft As Integer If (SpacesTotal And 1) = 0 Then 'even SpacesRight = SpacesTotal \ 2 SpacesLeft = SpacesRight Else 'odd SpacesRight = SpacesTotal \ 2 + 1 SpacesLeft = SpacesTotal \ 2 End If CellTextAligned(ColumnCounter).Item(LineCounter) = New String(textFillUpChar, SpacesLeft) & CellTextAligned(ColumnCounter).Item(LineCounter) & New String(textFillUpChar, SpacesRight) End If Case Else Throw New ArgumentOutOfRangeException(NameOf(textHorizontalAlignment)) End Select Next End If Next '3rd append output For LineCounter As Integer = 0 To LinesCount - 1 Dim LineStarted As Boolean = True Dim ColCounterStart, ColCounterEnd, ColCounterStepSize As Integer If cellDirection = TextTable.CellOutputDirection.Reversed Then ColCounterStart = columnWidths.Length - 1 ColCounterEnd = 0 ColCounterStepSize = -1 Else ColCounterStart = 0 ColCounterEnd = columnWidths.Length - 1 ColCounterStepSize = 1 End If For ColumnCounter As Integer = ColCounterStart To ColCounterEnd Step ColCounterStepSize If columnWidths(ColumnCounter) = 0 Then 'Column to be hidden Else 'Column to be written If LineStarted = True Then LineStarted = False Else outputStringBuilder.Append(cellSeparator) End If outputStringBuilder.Append(CellTextAligned(ColumnCounter).Item(LineCounter)) End If Next If LineCounter <> LinesCount - 1 Then outputStringBuilder.Append(cellBreakNewLine) End If Next End Sub End Class End Namespace
CompuMasterGmbH/CompuMaster.Data
CompuMaster.Data/TextRow.vb
Visual Basic
mit
11,630
'------------------------------------------------------------------------------ ' <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.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.HAConsole.My.MySettings Get Return Global.HAConsole.My.MySettings.Default End Get End Property End Module End Namespace
deandob/HAConsole
HAConsole/My Project/Settings.Designer.vb
Visual Basic
mit
2,896
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("Parentheses")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("Parentheses")> <Assembly: AssemblyCopyright("Copyright © 2013")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("f510bd40-afc3-4236-87db-0dc70d609a21")> ' 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")>
patkub/visual-basic-intro
Parentheses/Parentheses/My Project/AssemblyInfo.vb
Visual Basic
mit
1,140
Namespace adb_control Namespace filemanager Namespace io_sync Public Class ADBpull Private adb_ As New ADB() 'NOTE: this class is still in development. IT IS NOT STABLE. 'TODO: complete io_sync namespace. Private WithEvents ProgressReporter As New Timer Private Input__ As String Private Output__ As String Public Sub ADBPull(input As String, output As String) adb_.ADBExecute("pull " + AddColumnEachSide(input) + " " + AddColumnEachSide(output), True) End Sub End Class End Namespace End Namespace End Namespace
ssh9930/MYA
src/adb-control/filemanager/io_sync/ADBpull.vb
Visual Basic
mit
718
' ' Copyright Upendo Ventures, LLC ' https://upendoventures.com ' ' 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. ' Namespace WillStrohl.Modules.Lightbox Public NotInheritable Class ImageInfoMembers Public Const ImageIdField As String = "ImageId" Public Const LightboxIdField As String = "LightboxId" Public Const FileNameField As String = "FileName" Public Const TitleField As String = "Title" Public Const DescriptionField As String = "Description" Public Const DisplayOrderField As String = "DisplayOrder" Public Const LastUpdatedByField As String = "LastUpdatedBy" Public Const LastUpdatedDateField As String = "LastUpdatedDate" End Class End Namespace
hismightiness/dnnextensions
Modules/WillStrohl.LightboxGallery/Entities/ImageInfoMembers.vb
Visual Basic
mit
1,740
' Purpose: To experiment with attempting to recreate the visual elements of Rogue (Epyx) circa mid-1980's. Imports System Imports Visuals.Rogue.Lib ''' <summary> ''' TODO List ''' Start level with visibility set off everywhere and create method making visibility on following character ''' Randomly place objects on level and have character able to pick up or drop them ''' Randomly place creatures on level and have character interact with them ''' save and restore game state/levels ''' Go up and down stairs to change levels ''' </summary> Module Module1 #Region "Global Variables" '==========================================Prevent Resize 'to remove console menu options to prevent resize which destroys layout 'NOTE: snapping to edge still is a problem. 'from https://stackoverflow.com/questions/38175206/how-to-prevent-the-console-window-being-resized-in-vb-net Private Const MF_BYCOMMAND As Integer = &H0 Public Const SC_CLOSE As Integer = &HF060 Public Const SC_MINIMIZE As Integer = &HF020 Public Const SC_MAXIMIZE As Integer = &HF030 Public Const SC_SIZE As Integer = &HF000 Friend Declare Function DeleteMenu Lib "user32.dll" (ByVal hMenu As IntPtr, ByVal nPosition As Integer, ByVal wFlags As Integer) As Integer Friend Declare Function GetSystemMenu Lib "user32.dll" (hWnd As IntPtr, bRevert As Boolean) As IntPtr '==========================================end prevent resize Public currentLevel As Integer = 0 Public currentPlayer As New PlayerInfo Public gameMap(EnumsAndConsts.MapHeight, EnumsAndConsts.MapWidth, EnumsAndConsts.MapLevelsMax) As String Private ReadOnly m_ErrorHandler As New ErrorHandler Private m_CurrentObject As String = "Module1" #End Region #Region "Local Variables" Dim m_consoleController As New ConsoleController Dim m_canContinue As Boolean = True Dim m_levelMap As New LevelMap() Dim m_localRandom As New Random() #End Region Sub Main() ''==========================================Prevent Resize 'Dim handle As IntPtr 'handle = Process.GetCurrentProcess.MainWindowHandle ' Get the handle to the console window 'Dim sysMenu As IntPtr 'sysMenu = GetSystemMenu(handle, False) ' Get the handle to the system menu of the console window 'If handle <> IntPtr.Zero Then ' 'DeleteMenu(sysMenu, SC_CLOSE, MF_BYCOMMAND) ' To prevent user from closing console window ' DeleteMenu(sysMenu, SC_MINIMIZE, MF_BYCOMMAND) 'To prevent user from minimizing console window ' DeleteMenu(sysMenu, SC_MAXIMIZE, MF_BYCOMMAND) 'To prevent user from maximizing console window ' DeleteMenu(sysMenu, SC_SIZE, MF_BYCOMMAND) 'To prevent the use from re-sizing console window 'End If ''==========================================end prevent resize 'Try ' Console.SetBufferSize(80, 25) ' or whatever size you're using... 'Catch ex As exception 'End Try 'Try ' Console.SetWindowSize(80, 25) 'Catch ex As exception 'End Try 'Try ' Console.BufferWidth = 80 'Catch ex As Exception 'End Try 'Try ' Console.BufferHeight = 25 'Catch ex As Exception 'End Try Dim OrgBufferHeight%, OrgBufferWidth%, OrgWindowHeight%, OrgWindowWidth% OrgBufferHeight = Console.BufferHeight OrgBufferWidth = Console.BufferWidth OrgWindowHeight = Console.WindowHeight OrgWindowWidth = Console.WindowWidth Console.OutputEncoding = System.Text.Encoding.UTF8 ConsoleEx.Resize(80, 26) ConsoleEx.DisableMinimize() ConsoleEx.DisableMaximize() ConsoleEx.DisableResize() ConsoleEx.DisableQuickEditMode() Console.CursorVisible = False ConsoleEx.SetColor(ConsoleColor.DarkYellow, 170, 85, 0) Try ' Challenge #1: The colors in Windows 10 console applications doesn't match exactly with those in MS-DOS. ' Specifically, the color orange is actually orange in Windows 10 where the color orange is ' more of a brown color in MS-DOS. This color is used for the walls in the original Rogue. ' Challenge #2: .NET is unicode based; where as original Rogue used ASCII and (possibly) ANSI. ' This means that drawing of the walls and other special characters needs to be handled ' using the unicode table and there isn't (AFAIK) a 1:1 mapping between ASCII and unicode. 'Notes: '1 - I'm not much of a color person so I just went with DarkYellow for the brown '2 - Could not get the unicode to work out but did find the some of the ASCII characters InitializeGame("", "") While m_canContinue = True m_canContinue = ProcessGameLoop() End While End Finally ConsoleEx.EnableMinimize() ConsoleEx.EnableMaximize() ConsoleEx.EnableResize() Console.ForegroundColor = ConsoleColor.Gray Console.BackgroundColor = ConsoleColor.Black Console.SetBufferSize(OrgBufferWidth, OrgBufferHeight) Console.SetWindowSize(OrgWindowWidth, OrgWindowHeight) ConsoleEx.EnableQuickEditMode() End Try Console.ResetColor() Console.Clear() End Sub Private Function GetRandomStairLocation() As String Dim aReturnValue As String = "" Dim xLoc As Integer = 0 Dim yLoc As Integer = 0 Dim m_randomNumber As Integer = m_localRandom.Next(0, Now.Second) xLoc = 4 + m_localRandom.Next(0, EnumsAndConsts.MapWidth - 6) yLoc = 4 + m_localRandom.Next(0, EnumsAndConsts.MapHeight - 6) 'need to ensure that location is not near edge of a grid cell For xPtr As Integer = 1 To EnumsAndConsts.MapLevelGridColumnMax If xLoc <= ((xPtr - 1) * EnumsAndConsts.MapGridCellWidth) + 2 Then xLoc = ((xPtr - 1) * EnumsAndConsts.MapGridCellWidth) + 2 'too close to left edge Exit For End If If xLoc < ((xPtr) * EnumsAndConsts.MapGridCellWidth) AndAlso xLoc >= ((xPtr) * EnumsAndConsts.MapGridCellWidth) - 2 Then xLoc = ((xPtr) * EnumsAndConsts.MapGridCellWidth) - 2 'too close to right edge Exit For End If Next For yPtr As Integer = 1 To EnumsAndConsts.MapLevelGridRowMax If yLoc <= ((yPtr - 1) * EnumsAndConsts.MapGridCellHeight) + 2 Then yLoc = ((yPtr - 1) * EnumsAndConsts.MapGridCellHeight) + 2 'too close to top edge Exit For End If If yLoc < ((yPtr) * EnumsAndConsts.MapGridCellHeight) AndAlso yLoc >= ((yPtr) * EnumsAndConsts.MapGridCellHeight) - 2 Then yLoc = ((yPtr) * EnumsAndConsts.MapGridCellHeight) - 2 'too close to bottom edge Exit For End If Next If yLoc > 9 Then aReturnValue = yLoc.ToString Else aReturnValue = "0" & yLoc.ToString End If If xLoc > 9 Then aReturnValue = aReturnValue & xLoc.ToString Else aReturnValue = aReturnValue & "0" & xLoc.ToString End If Return aReturnValue End Function Private Sub InitializeGame() Dim m_levelMap As New LevelMap 'm_levelMap.EntryStairGrid = "1831" 'TODO testing only 'm_levelMap.ExitStairGrid = "0470" 'TODO testing only m_levelMap.Initialize(True) m_levelMap.DrawScreen() NearestConsoleColor.Main() Console.ReadLine() End Sub Private Sub InitializeGame(ByVal whatEntryStairLocation As String, ByVal whatExitStairLocation As String) Dim aEntryString As String = "" & whatEntryStairLocation Dim aExitString As String = "" & whatExitStairLocation Dim xLoc As Integer = 0 Dim yLoc As Integer = 0 Dim m_randomNumber As Integer = m_localRandom.Next(0, 100) Dim isGoodStair As Boolean = False Dim aTryCounter As Integer = 0 If aEntryString = "" Then aEntryString = GetRandomStairLocation() End If m_levelMap.EntryStairLocation = aEntryString m_levelMap.ExitStairLocation = aExitString If m_levelMap.EntryStairGrid = m_levelMap.ExitStairGrid Then aExitString = "" End If If aExitString = "" Then 'Need to ensure that exitstair not in same map grid as entrystair Do While isGoodStair = False And aTryCounter < 100 aExitString = GetRandomStairLocation() m_levelMap.ExitStairLocation = aExitString aTryCounter = aTryCounter + 1 If Not m_levelMap.EntryStairGrid = m_levelMap.ExitStairGrid Then isGoodStair = True End If Loop 'TODO need to handle if comes out of above loop and did not get a good random exitstairlocation End If m_levelMap = New LevelMap(aEntryString, aExitString) 'm_levelMap.EntryStairGrid = "1831" 'TODO testing only 'm_levelMap.ExitStairGrid = "0470" 'TODO testing only 'm_levelMap.Initialize(True) Integer.TryParse(aEntryString.Substring(0, 2), yLoc) Integer.TryParse(aEntryString.Substring(2, 2), xLoc) currentPlayer = New PlayerInfo() currentPlayer.CurrentMapLevel = m_levelMap.CurrentMapLevel currentPlayer.CurrentMapX = xLoc currentPlayer.CurrentMapY = yLoc m_levelMap.MoveCharacter(currentPlayer, -1, -1, xLoc, yLoc) m_levelMap.DrawScreen() End Sub Private Function ProcessGameLoop() As Boolean Dim currentMethod As String = "ProcessGameLoop" Dim currentData As String = "" Dim aReturnValue As Boolean = True Dim aChar As New Char Dim aNewExitStairLocation As String = GetRandomStairLocation() Dim isGood As Boolean = False Try aChar = m_consoleController.GetKeyBoardInput() Select Case aChar Case "h" 'left currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX - 1, currentPlayer.CurrentMapY) Case "j" 'down currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY + 1) Case "l" 'right currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX + 1, currentPlayer.CurrentMapY) Case "k" 'up currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY - 1) Case "y" 'up and left currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX - 1, currentPlayer.CurrentMapY - 1) Case "b" 'down and left currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX - 1, currentPlayer.CurrentMapY + 1) Case "u" ' up and right currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX + 1, currentPlayer.CurrentMapY - 1) Case "n" 'down and right currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX + 1, currentPlayer.CurrentMapY + 1) Case "4" 'left currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX - 1, currentPlayer.CurrentMapY) Case "2" 'down currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY + 1) Case "6" 'right currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX + 1, currentPlayer.CurrentMapY) Case "8" 'up currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY - 1) Case "7" 'up and left currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX - 1, currentPlayer.CurrentMapY - 1) Case "1" 'down and left currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX - 1, currentPlayer.CurrentMapY + 1) Case "9" ' up and right currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX + 1, currentPlayer.CurrentMapY - 1) Case "3" 'down and right currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX + 1, currentPlayer.CurrentMapY + 1) Case "<" 'up stairs If currentPlayer.CurrentMapLevel > 1 Then isGood = m_levelMap.IsEntryCell(currentPlayer.CurrentMapX, currentPlayer.CurrentMapY) If isGood = True Then 'create a random level above this one unless it is being remembered currentData = m_levelMap.MoveCharacter(currentPlayer, currentPlayer.CurrentMapX, currentPlayer.CurrentMapY, currentPlayer.CurrentMapX + 1, currentPlayer.CurrentMapY + 1) End If Else currentPlayer.Message = "Cannot go up out of dungeon!" End If End Select currentPlayer.Message = currentData m_levelMap.DrawScreen() 'TODO just quit for now 'aReturnValue = False 'InitializeGame() ' for testing show new random level for each move ' InitializeGame(m_levelMap.ExitStairLocation, aNewExitStairLocation) ' for testing show new random level for each move Catch ex As Exception m_ErrorHandler.NotifyError(m_CurrentObject, currentMethod, ex.Message, Now, ex) End Try Return aReturnValue End Function End Module
DualBrain/VbRogue
Prototyping/Visuals/Visuals/Module1.vb
Visual Basic
mit
13,844
Imports SistFoncreagro.BussinessEntities Public Interface IDocumentoRendidoRepository Function GetAllFromDOCUMENTORENDIDO() As List(Of DocumentoRendido) Function GetDOCUMENTORENDIDOByIdDocRendido(ByVal IdDocRendido) As DocumentoRendido Function GetDOCUMENTORENDIDOByIdReciboRendicion(ByVal IdReciboRendicion As Int32) As List(Of DocumentoRendido) Function GetDOCUMENTORENDIDOByIdRendicion(ByVal IdRendicion As Int32) As List(Of DocumentoRendido) Sub SaveDOCUMENTORENDIDO(ByVal _DocumentoRendido As DocumentoRendido) Sub DeleteDOCUMENTORENDIDO(ByVal IdDocRendido As Int32) End Interface
crackper/SistFoncreagro
SistFoncreagro.DataAccess/IDocumentoRendidoRepository.vb
Visual Basic
mit
613
Option Strict Off Option Explicit On Imports VB = Microsoft.VisualBasic 'Imports Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6 Friend Class frmBarcode Inherits System.Windows.Forms.Form Dim gType As Integer Private Declare Function GetTickCount Lib "kernel32" () As Integer Dim optBarcode As New List(Of RadioButton) Private Sub loadLanguage() Dim cmdExit As Button rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1817 'Barcode Printing|Checked If rsLang.RecordCount Then Me.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Me.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1818 'Printer|Checked If rsLang.RecordCount Then _Label2_0.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _Label2_0.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value 'lblPrinter = No Code/Dynamic/NA? rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1819 'Printer Type|Checked If rsLang.RecordCount Then _Label2_1.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _Label2_1.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value 'lblPrinterType = No Code/Dynamic/NA? rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1820 'Select the barcode printing type you require|Checked If rsLang.RecordCount Then Label1.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Label1.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1821 'Stock Barcode|Checked If rsLang.RecordCount Then _optBarcode_2.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _optBarcode_2.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.Filter = "LanguageLayoutLnk_LanguageID=" & 1830 'Shelf Taker|Checked If rsLang.RecordCount Then _optBarcode_1.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _optBarcode_1.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.Filter = "LanguageLayoutLnk_LanguageID=" & 1004 'Exit|Checked If rsLang.RecordCount Then cmdExit.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value cmdExit.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value End If rsLang.Filter = "LanguageLayoutLnk_LanguageID=" & 1005 'Next|Checked If rsLang.RecordCount Then cmdnext.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdnext.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsHelp.Filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'" If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp.Fields("Help_ContextID").Value End Sub Private Sub showLabels() Dim rs As ADODB.Recordset Dim lvItem As System.Windows.Forms.ListViewItem rs = getRS("SELECT Label.* From Label WHERE (((Label.Label_Type)=" & gType & ")) ORDER BY LabelID;") Me.lstBarcode.Items.Clear() Dim m As Integer Do Until rs.EOF m = Me.lstBarcode.Items.Add(rs.Fields("Label_Name").Value & " (" & "W" & rs.Fields("Label_Width").Value & "mm X H" & rs.Fields("Label_Height").Value & "mm)") lstBarcode.Items.Add(New SetItemData(m, rs.Fields("labelID").Value)) rs.MoveNext() Loop rs = getRS("SELECT * FROM PrinterOftenUsed") On Error Resume Next If TheErr <> -2147217865 Then If gType = 2 Then lstBarcode.SelectedIndex = rs.Fields("LabelIndex").Value ElseIf gType = 1 Then lstBarcode.SelectedIndex = rs.Fields("ShelfIndex").Value End If End If End Sub Private Sub printStock() Dim sql As String Dim rs As ADODB.Recordset sql = "SELECT StockItem.StockItemID, Catalogue.Catalogue_Quantity, StockItem.StockItem_Name, Catalogue.Catalogue_Barcode, Supplier.SupplierID, Supplier.Supplier_Name, PricingGroup.PricingGroupID, PricingGroup.PricingGroup_Name, Format([CatalogueChannelLnk_Price],'Currency') AS Price, barcodePersonLnk.barcodePersonLnk_PersonID, barcodePersonLnk.barcodePersonLnk_PrintQTY, Company.*, barcodePersonLnk.barcodePersonLnk_PrintQTY, Label.LabelID, Label.Label_TextStream, 'SELL BY ' & Format(NOW+[StockItem].[StockItem_ExpiryDays], 'dd/mm/yy') AS StockItem_ExpiryDays " sql = sql & "FROM Company, Label, barcodePersonLnk INNER JOIN ((((StockItem INNER JOIN Supplier ON StockItem.StockItem_SupplierID = Supplier.SupplierID) INNER JOIN PricingGroup ON StockItem.StockItem_PricingGroupID = PricingGroup.PricingGroupID) INNER JOIN Catalogue ON StockItem.StockItemID = Catalogue.Catalogue_StockItemID) INNER JOIN CatalogueChannelLnk ON (Catalogue.Catalogue_Quantity = CatalogueChannelLnk.CatalogueChannelLnk_Quantity) AND (Catalogue.Catalogue_StockItemID = CatalogueChannelLnk.CatalogueChannelLnk_StockItemID)) ON (barcodePersonLnk.barcodePersonLnk_StockItemID = Catalogue.Catalogue_StockItemID) AND (barcodePersonLnk.barcodePersonLnk_Shrink = Catalogue.Catalogue_Quantity) " sql = sql & "WHERE (((barcodePersonLnk.barcodePersonLnk_PersonID)=" & gPersonID & ") AND ((barcodePersonLnk.barcodePersonLnk_PrintQTY)<>0) AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1) AND ((Label.LabelID)=" & CInt(lstBarcode.SelectedIndex) & ")); " rs = getRS(sql) If rs.RecordCount Then 'Checks if the barcode/Shelf Talker button is clicked and displays the correct button. If _optBarcode_2.Checked = True Then If MsgBox("You have selected " & rs.RecordCount & " products to print." & vbCrLf & vbCrLf & "Are you sure you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "PRINT BARCODES") = MsgBoxResult.Yes Then If CDbl(lblPrinterType.Tag) = 1 Then printStockBarcode(rs) ElseIf CDbl(lblPrinterType.Tag) = 2 Then printStockA4(rs) ElseIf CDbl(lblPrinterType.Tag) = 3 Then PrintBarcodeDatamax(rs) End If End If ElseIf _optBarcode_1.Checked = True Then If MsgBox("You have selected " & rs.RecordCount & " products to print." & vbCrLf & vbCrLf & "Are you sure you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "PRINT SHELF TALKER") = MsgBoxResult.Yes Then If CDbl(lblPrinterType.Tag) = 1 Then printStockBarcode(rs) ElseIf CDbl(lblPrinterType.Tag) = 2 Then 'If InStr(LCase(lblPrinter), "label") Then printStockA4(rs) 'Else ' printStockA4_OLD rs 'End If ElseIf CDbl(lblPrinterType.Tag) = 3 Then PrintBarcodeDatamax(rs) End If End If End If End If End Sub Private Sub printStockBarcode(ByRef rs As ADODB.Recordset) Dim fso As New Scripting.FileSystemObject Dim lStream As Scripting.TextStream Dim lString As String Dim lArray As String() Dim lText As String Dim x As Short Do Until rs.EOF lString = rs.Fields("label_textstream").Value lArray = Split(lString, vbCrLf) lString = "" For x = 0 To UBound(lArray) lText = lArray(x) lString = lString & vbCrLf & doString(lText, rs) Next x lStream = fso.OpenTextFile("c:\aa.txt", Scripting.IOMode.ForWriting, True) lStream.Write(lString) lStream.Close() lString = "C:\AA.TXT" Call SpoolFile(lString, (lblPrinter.Text)) rs.MoveNext() Loop End Sub Private Function doString(ByRef lString As String, ByRef rs As ADODB.Recordset) As String Dim x As Short Dim lString1 As String Dim lString2 As String Dim lText As String Dim rsP As ADODB.Recordset Dim rsShrink As ADODB.Recordset If Len(lString) > 15 Then lText = Mid(lString, 16) If InStr(lText, "COMPANY NAME CENTER") Then doString = VB.Left(lString, 15) & doCenter(lText, rs.Fields("Company_Name").Value) Exit Function End If If InStr(lText, "COMPANY NAME LEFT") Then doString = VB.Left(lString, 15) & VB.Left(rs.Fields("Company_Name").Value, Len(lText)) Exit Function End If If InStr(lText, "COMPANY NAME RIGHT") Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rs.Fields("Company_Name").Value, Len(lText)) Exit Function End If If InStr(lText, "TELEPHONE CENTER") Then doString = VB.Left(lString, 15) & doCenter(lText, rs.Fields("Company_Telephone").Value) Exit Function End If If InStr(lText, "TELEPHONE LEFT") Then doString = VB.Left(lString, 15) & VB.Left(rs.Fields("Company_Telephone").Value, Len(lText)) Exit Function End If If InStr(lText, "TELEPHONE RIGHT") Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rs.Fields("Company_Telephone").Value, Len(lText)) Exit Function End If If InStr(lText, "PRICEXXXXX") Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & rs.Fields("Price").Value, Len(lText))) Exit Function End If If InStr(lText, "PRICEX") Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & Split(rs.Fields("Price").Value & ".00", ".")(0), Len(lText))) Exit Function End If If InStr(lText, "PRIC4XXXXX") Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & rs.Fields("Price").Value, Len(lText))) Exit Function End If If InStr(lText, "PRIC1XXXXX") Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & FormatNumber(rsP.Fields("PriceChannelLnk_Price").Value, 2) & " FOR ", Len(lText))) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & FormatNumber(rsP.Fields("CatalogueChannelLnk_Price").Value, 2) & " FOR ", Len(lText))) Else 'doString = Left(lString, 15) & Replace(lText, lText, Right(String(Len(lText), " ") & Split(rs("Price") & ".00", ".")(0), Len(lText))) End If End If x = x + 1 ElseIf x = 1 Then x = x + 1 ElseIf x = 2 Then x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If InStr(lText, "PRIC2XXXXX") Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then x = x + 1 ElseIf x = 1 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & FormatNumber(rsP.Fields("PriceChannelLnk_Price").Value, 2) & " FOR ", Len(lText))) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & FormatNumber(rsP.Fields("CatalogueChannelLnk_Price").Value, 2) & " FOR ", Len(lText))) Else 'doString = Left(lString, 15) & Replace(lText, lText, Right(String(Len(lText), " ") & Split(rs("Price") & ".00", ".")(0), Len(lText))) End If End If x = x + 1 ElseIf x = 2 Then x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If InStr(lText, "PRIC3XXXXX") Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then x = x + 1 ElseIf x = 1 Then x = x + 1 ElseIf x = 2 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & FormatNumber(rsP.Fields("PriceChannelLnk_Price").Value, 2) & " FOR ", Len(lText))) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & FormatNumber(rsP.Fields("CatalogueChannelLnk_Price").Value, 2) & " FOR ", Len(lText))) Else 'doString = Left(lString, 15) & Replace(lText, lText, Right(String(Len(lText), " ") & Split(rs("Price") & ".00", ".")(0), Len(lText))) End If End If x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "S1" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rsP.Fields("PriceChannelLnk_Quantity").Value, Len(lText)) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rsP.Fields("CatalogueChannelLnk_Quantity").Value, Len(lText)) Else End If End If x = x + 1 ElseIf x = 1 Then x = x + 1 ElseIf x = 2 Then x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "S2" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then x = x + 1 ElseIf x = 1 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rsP.Fields("PriceChannelLnk_Quantity").Value, Len(lText)) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rsP.Fields("CatalogueChannelLnk_Quantity").Value, Len(lText)) Else End If End If x = x + 1 ElseIf x = 2 Then x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "S3" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then x = x + 1 ElseIf x = 1 Then x = x + 1 ElseIf x = 2 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rsP.Fields("PriceChannelLnk_Quantity").Value, Len(lText)) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rsP.Fields("CatalogueChannelLnk_Quantity").Value, Len(lText)) Else End If End If x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "(P1 ea)" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)")) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)")) Else End If End If x = x + 1 ElseIf x = 1 Then x = x + 1 ElseIf x = 2 Then x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "(P2 ea)" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then x = x + 1 ElseIf x = 1 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)")) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)")) Else End If End If x = x + 1 ElseIf x = 2 Then x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "(P3 ea)" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then x = x + 1 ElseIf x = 1 Then x = x + 1 ElseIf x = 2 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)")) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)")) Else End If End If x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "(P1 EA)" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " EA)")) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " EA)")) Else End If End If x = x + 1 ElseIf x = 1 Then x = x + 1 ElseIf x = 2 Then x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "(P2 EA)" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then x = x + 1 ElseIf x = 1 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " EA)")) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " EA)")) Else End If End If x = x + 1 ElseIf x = 2 Then x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "(P3 EA)" Then rsShrink = getRS("SELECT StockItem.StockItemID, StockItem.StockItem_ShrinkID, Shrink.ShrinkID, ShrinkItem.ShrinkItem_ShrinkID, ShrinkItem.ShrinkItem_Quantity FROM (Shrink INNER JOIN StockItem ON Shrink.ShrinkID = StockItem.StockItem_ShrinkID) INNER JOIN ShrinkItem ON Shrink.ShrinkID = ShrinkItem.ShrinkItem_ShrinkID Where (((StockItem.stockitemID) = " & rs.Fields("StockItemID").Value & ")) ORDER BY StockItem.StockItemID, ShrinkItem.ShrinkItem_Quantity;") x = 0 If rsShrink.RecordCount > 0 Then Do Until rsShrink.EOF If rsShrink.Fields("ShrinkItem_Quantity").Value > 1 Then If x = 0 Then x = x + 1 ElseIf x = 1 Then x = x + 1 ElseIf x = 2 Then rsP = getRS("SELECT TOP 1 PriceChannelLnk.PriceChannelLnk_StockItemID, PriceChannelLnk.PriceChannelLnk_Quantity, PriceChannelLnk.PriceChannelLnk_ChannelID, PriceChannelLnk.PriceChannelLnk_Price From PriceChannelLnk Where (((PriceChannelLnk.PriceChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((PriceChannelLnk.PriceChannelLnk_ChannelID) = 1) And ((PriceChannelLnk.PriceChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY PriceChannelLnk.PriceChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("PriceChannelLnk_Price").Value, rsP.Fields("PriceChannelLnk_Price").Value, 1) / IIf(rsP.Fields("PriceChannelLnk_Quantity").Value, rsP.Fields("PriceChannelLnk_Quantity").Value, 1), 2) & " EA)")) Else rsP = getRS("SELECT TOP 1 CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_ChannelID, CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk Where (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) = " & rsShrink.Fields("StockItemID").Value & ") And ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID) = 1) And ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity) = " & rsShrink.Fields("ShrinkItem_Quantity").Value & ")) ORDER BY CatalogueChannelLnk.CatalogueChannelLnk_Quantity DESC;") If rsP.RecordCount > 0 Then doString = VB.Left(lString, 15) & VB.Left("(" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " ea)", Len(" (" & FormatNumber(IIf(rsP.Fields("CatalogueChannelLnk_Price").Value, rsP.Fields("CatalogueChannelLnk_Price").Value, 1) / IIf(rsP.Fields("CatalogueChannelLnk_Quantity").Value, rsP.Fields("CatalogueChannelLnk_Quantity").Value, 1), 2) & " EA)")) Else End If End If x = x + 1 End If End If rsShrink.MoveNext() Loop End If Exit Function End If If lText = "CCCC MM" Then 'doString = Left(lString, 15) & Replace(lText, lText, Left(String(Len(lText), " ") & Year(Now) & " " & Month(Now), Len(lText))) doString = VB.Left(lString, 15) & VB.Left(Year(Now) & " " & Month(Now), Len(lText)) Exit Function End If If lText = "XX" Then 'If InStr(lText, "XX") Then doString = VB.Left(lString, 15) & Replace(lText, lText, VB.Right(New String(" ", Len(lText)) & Split(rs.Fields("Price").Value, ".")(1), Len(lText))) Exit Function End If If InStr(lText, "DEPARTMENT CENTER") Then doString = VB.Left(lString, 15) & doCenter(lText, rs.Fields("PricingGroup_Name").Value) Exit Function End If If InStr(lText, "DEPARTMENT LEFT") Then doString = VB.Left(lString, 15) & VB.Left(rs.Fields("PricingGroup_Name").Value, Len(lText)) Exit Function End If If InStr(lText, "DEPARTMENT RIGHT") Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rs.Fields("PricingGroup_Name").Value, Len(lText)) Exit Function End If If InStr(lText, "BARREAD CENTER") Then doString = VB.Left(lString, 15) & doCenter(lText, rs.Fields("Catalogue_Barcode").Value) Exit Function End If If InStr(lText, "BARREAD LEFT") Then doString = VB.Left(lString, 15) & VB.Left(rs.Fields("Catalogue_Barcode").Value, Len(lText)) Exit Function End If If InStr(lText, "BARREAD RIGHT") Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rs.Fields("Catalogue_Barcode").Value, Len(lText)) Exit Function End If If InStr(lText, "BARCODEXXXXXX") Then doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & rs.Fields("Catalogue_Barcode").Value, Len(lText)) Exit Function End If If InStr(lText, "NAME 1 CENTER") Then lString1 = rs.Fields("Stockitem_Name").Value If rs.Fields("Catalogue_Quantity").Value <> 1 Then lString1 = rs.Fields("Catalogue_Quantity").Value & "X" & lString1 splitString(Len(lText), lString1, lString2) doString = VB.Left(lString, 15) & doCenter(lText, lString1) Exit Function End If If InStr(lText, "NAME 1 LEFT") Then lString1 = rs.Fields("Stockitem_Name").Value If rs.Fields("Catalogue_Quantity").Value <> 1 Then lString1 = rs.Fields("Catalogue_Quantity").Value & "X" & lString1 splitString(Len(lText), lString1, lString2) doString = VB.Left(lString, 15) & VB.Left(lString1, Len(lText)) Exit Function End If If InStr(lText, "NAME 1 RIGHT") Then lString1 = rs.Fields("Stockitem_Name").Value If rs.Fields("Catalogue_Quantity").Value <> 1 Then lString1 = rs.Fields("Catalogue_Quantity").Value & "X" & lString1 splitString(Len(lText), lString1, lString2) doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & lString1, Len(lText)) Exit Function End If If InStr(lText, "NAME 2 CENTER") Then lString1 = rs.Fields("Stockitem_Name").Value If rs.Fields("Catalogue_Quantity").Value <> 1 Then lString1 = rs.Fields("Catalogue_Quantity").Value & "X" & lString1 splitString(Len(lText), lString1, lString2) doString = VB.Left(lString, 15) & doCenter(lText, lString2) Exit Function End If If InStr(lText, "NAME 2 LEFT") Then lString1 = rs.Fields("Stockitem_Name").Value If rs.Fields("Catalogue_Quantity").Value <> 1 Then lString1 = rs.Fields("Catalogue_Quantity").Value & "X" & lString1 splitString(Len(lText), lString1, lString2) doString = VB.Left(lString, 15) & VB.Left(lString2, Len(lText)) Exit Function End If If InStr(lText, "NAME 2 RIGHT") Then lString1 = rs.Fields("Stockitem_Name").Value If rs.Fields("Catalogue_Quantity").Value <> 1 Then lString1 = rs.Fields("Catalogue_Quantity").Value & "X" & lString1 splitString(Len(lText), lString1, lString2) doString = VB.Left(lString, 15) & VB.Right(New String(" ", Len(lText)) & lString2, Len(lText)) Exit Function End If If InStr(lText, "DATE") Then lString1 = Format(Now, "yymm") doString = VB.Left(lString, 15) & Format(Now, "yymm") Exit Function End If 'Expiry Date If InStr(lText, "SELL BY") Then 'lString1 = Format((Now() + rs("StockItem_ExpiryDays")), "dd/mm/yy") 'doString = Left(lString, 15) & Format((Now() + rs("StockItem_ExpiryDays")), "dd/mm/yy") lString1 = rs.Fields("StockItem_ExpiryDays").Value doString = VB.Left(lString, 15) & rs.Fields("StockItem_ExpiryDays").Value Exit Function End If If lText = "BARCODE" Then 'If InStr(lText, "BARCODE") Then If doCheckSum(rs.Fields("Catalogue_Barcode").Value) Then Else doString = VB.Left(lString, 15) & rs.Fields("Catalogue_Barcode").Value End If Exit Function End If If InStr(lText, "600106007141") Then If doCheckSum(rs.Fields("Catalogue_Barcode").Value) Then doString = VB.Left(lString, 15) & VB.Left(rs.Fields("Catalogue_Barcode").Value & "0000", 13) End If Exit Function End If doString = lString Else If lString = "Q0001" Then doString = Replace(lString, "Q0001", "Q" & VB.Right("0000" & rs.Fields("barcodePersonLnk_PrintQTY").Value, 4)) Else doString = lString End If End If End Function Private Function doCheckSum(ByRef lString As String) As Boolean Dim lAmount As Short Dim code As String Dim i As Short Dim value As String value = lString doCheckSum = False If InStr(value, "0") Then Do Until CDbl(VB.Left(value, 1)) <> 0 value = Mid(value, 2) Loop End If If Len(value) > 9 Then value = VB.Left(value & "00000", 13) If Len(value) <> 13 Then Exit Function If value = "" Then Exit Function If InStr(value, ".") Then doCheckSum = False Else If IsNumeric(value) Then lAmount = 0 For i = 1 To Len(value) - 1 code = VB.Left(value, i) code = VB.Right(code, 1) If i Mod 2 Then lAmount = lAmount + CShort(code) Else lAmount = lAmount + CShort(code) * 3 End If Next lAmount = 10 - (lAmount Mod 10) If lAmount = 10 Then lAmount = 0 doCheckSum = lAmount = CShort(VB.Right(value, 1)) Else doCheckSum = False End If End If End Function Public Function doCenter(ByRef origText As String, ByRef newText As String) As String Dim newstring As String If Len(origText) > Len(newstring) Then If CShort((Len(origText) - Len(newText)) / 2) >= 0 Then doCenter = New String(" ", CShort((Len(origText) - Len(newText)) / 2)) & newText Else doCenter = VB.Left(newText, Len(origText)) End If Else doCenter = VB.Left(newText, Len(origText)) End If End Function Private Sub splitStringA4(ByRef lObject As Label, ByRef lWidth As Integer, ByRef HeadingString1 As String, ByRef HeadingString2 As String) Dim Printer As New Printing.PrintDocument Dim y As Short Dim x As Short Dim lHeading As String lHeading = HeadingString1 HeadingString1 = lHeading & " " HeadingString2 = "" If (lWidth - lObject.Width) < 0 Then For x = Len(lHeading) + 1 To 1 Step -1 HeadingString1 = VB.Left(lHeading, x) If (lWidth - lObject.Width + 50) > 0 Then For y = Len(HeadingString1) + 1 To 1 Step -1 If VB.Right(VB.Left(HeadingString1, y), 1) = " " Then HeadingString1 = VB.Left(HeadingString1, y - 1) If (lHeading <> HeadingString1) Then HeadingString2 = VB.Right(lHeading, Len(lHeading) - Len(HeadingString1)) End If Exit For End If Next y Exit For End If Next End If If HeadingString2 = "" Then HeadingString2 = HeadingString1 HeadingString1 = "" Else Do Until Printer.DefaultPageSettings.Bounds.Width <= lWidth 'Do Until Printer.PrinterSettings.TextWidth(HeadingString2) <= lWidth HeadingString2 = Mid(HeadingString2, 1, Len(HeadingString2) - 1) Loop End If HeadingString1 = Trim(HeadingString1) HeadingString2 = Trim(HeadingString2) End Sub Private Sub cmdNext_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdnext.Click lstBarcode_DoubleClick(lstBarcode, New System.EventArgs()) End Sub Private Sub cndExit_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cndExit.Click Me.Close() End Sub Private Sub frmBarcode_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load optBarcode.AddRange(New RadioButton() {_optBarcode_1, _optBarcode_2}) Dim rb As New RadioButton For Each rb In optBarcode AddHandler rb.CheckedChanged, AddressOf optBarcode_CheckedChanged Next Dim Printer As New Printing.PrintDocument Dim rs As ADODB.Recordset On Error Resume Next Dim TheBarcodePrName As String Dim lPrinter As String lPrinter = frmPrinter.selectPrinter() loadLanguage() If lPrinter = "" Then Me.Close() Exit Sub Else rs = getRS("SELECT * FROM PrinterOftenUsed") If rs.RecordCount Then lblPrinter.Text = lPrinter If rs("PrinterType").Value = 2 Then lblPrinterType.Tag = 1 lblPrinterType.Text = "Argox Barcode Printer" ElseIf rs("PrinterType").Value = 3 Then ' Printer.Width <= 9000 Then 'TheBarcodePrName = "Datamax Allegro" Then 'if Printer.Width <= 9000 then or if Name= DatamaxNew code for Datamax Allegro still busy lblPrinterType.Tag = 3 lblPrinterType.Text = "Other Printer" ElseIf rs("PrinterType").Value = 1 Then lblPrinterType.Tag = 2 lblPrinterType.Text = "A4 Printer" End If Else lblPrinter.Text = lPrinter If InStr(LCase(Printer.PrinterSettings.PrinterName), "label") Then lblPrinterType.Tag = 1 lblPrinterType.Text = "Argox Barcode Printer" ElseIf Printer.PrinterSettings.DefaultPageSettings.PaperSize.Width <= 9000 Then 'TheBarcodePrName = "Datamax Allegro" Then 'if Printer.Width <= 9000 then or if Name= DatamaxNew code for Datamax Allegro still busy 'a = Printer.Height lblPrinterType.Tag = 3 lblPrinterType.Text = "Other Barcode Printer" Else lblPrinterType.Tag = 2 lblPrinterType.Text = "A4 Printer" End If End If gType = 2 showLabels() End If 'Set rs = getRS("SELECT * FROM PrinterOftenUsed") If TheErr <> -2147217865 Then If gType = 2 Then 'stBarcode.SelectedIndex = rs("LabelIndex") ElseIf gType = 1 Then lstBarcode.SelectedIndex = rs("ShelfIndex").Value End If End If End Sub Private Sub lstBarcode_DoubleClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles lstBarcode.DoubleClick Dim rs As New ADODB.Recordset Dim lID As Integer Dim sBCode As String Dim cQTY As Decimal rs = getRS("SELECT * FROM PrinterOftenUsed") If rs.RecordCount > 0 Then If gType = 2 Then rs = getRS("UPDATE PrinterOftenUsed SET PrinterIndex=" & rs("PrinterIndex").Value.ToString & " ,LabelIndex = " & lstBarcode.SelectedIndex.ToString & " WHERE PrinterIndex=" & rs("PrinterIndex").Value.ToString & "") ElseIf gType = 1 Then rs = getRS("UPDATE PrinterOftenUsed SET PrinterIndex=" & rs("PrinterIndex").Value.ToString & " ,ShelfIndex=" & lstBarcode.SelectedIndex.ToString & " WHERE PrinterIndex=" & rs("PrinterIndex").Value.ToString & "") End If Else End If If lstBarcode.SelectedIndex <> -1 Then Select Case gType Case 1, 2 If scaleBCPrint = True Then lID = frmStockList.getItem If lID <> 0 Then On Error Resume Next If frmBarcodeScaleItem.loadItem(lID, cQTY, sBCode) Then printStockScale(cQTY, sBCode) 'scaleBCPrint = False End If End If Else 'old way If frmBarcodeStockitem.loadStock Then printStock() End If End If Case Else End Select End If End Sub Private Sub printStockScale(Optional ByRef cQuantity As Decimal = 0, Optional ByRef sBCode As String = "") Dim sql As String Dim rs As ADODB.Recordset Dim x As Short Dim C As Short Dim D As Short Dim CD As Short Dim strCD As String x = 0 C = 0 D = 0 CD = 0 strCD = "" Dim wCodemvarCodeID As String Dim wCodemvarLenPrice As String Dim code As String Dim chkInput As String chkInput = CStr(1) wCodemvarCodeID = VB.Right("0000" & sBCode, 4) wCodemvarLenPrice = FormatCurrency(cQuantity, 2) wCodemvarLenPrice = Replace(wCodemvarLenPrice, "R", "") wCodemvarLenPrice = Replace(wCodemvarLenPrice, ",", "") wCodemvarLenPrice = Replace(wCodemvarLenPrice, ".", "") wCodemvarLenPrice = Replace(wCodemvarLenPrice, " ", "") wCodemvarLenPrice = VB.Right("00000" & wCodemvarLenPrice, 5) chkInput = CStr(Rnd2(1, 9)) chkInput = VB.Left(chkInput, 1) code = "20" & wCodemvarCodeID & chkInput & wCodemvarLenPrice & "0" 'New CheckSum code ' & format = 4 + 5 (4 digit for item & 5 digit for price) 'If Val(wCodemvarCodeID) = 4 And Val(wCodemvarLenPrice) = 5 Then For x = 1 To 6 C = C + Val(Mid(code, x * 2, 1)) Next x C = C * 3 For x = 1 To 6 D = D + Val(Mid(code, (x * 2) - 1, 1)) Next x CD = C + D strCD = Str(CD) 'CD = 10 - (Val(Right(CD, 1))) CD = 10 - (Val(VB.Right(CStr(CD), 1))) : If CD = 10 Then CD = 0 code = VB.Left(code, 12) & CD 'End If 'New CheckSum code 'sql = "SELECT StockItem.StockItemID, Catalogue.Catalogue_Quantity, StockItem.StockItem_Name, Catalogue.Catalogue_Barcode, Supplier.SupplierID, Supplier.Supplier_Name, PricingGroup.PricingGroupID, PricingGroup.PricingGroup_Name, Format([CatalogueChannelLnk_Price],'Currency') AS Price, barcodePersonLnk.barcodePersonLnk_PersonID, barcodePersonLnk.barcodePersonLnk_PrintQTY, Company.*, barcodePersonLnk.barcodePersonLnk_PrintQTY, Label.LabelID, Label.Label_TextStream, 'SELL BY ' & Format(NOW+[StockItem].[StockItem_ExpiryDays], 'dd/mm/yy') AS StockItem_ExpiryDays " sql = "SELECT StockItem.StockItemID, Catalogue.Catalogue_Quantity, StockItem.StockItem_Name, " & code & " AS Catalogue_Barcode, Supplier.SupplierID, Supplier.Supplier_Name, PricingGroup.PricingGroupID, PricingGroup.PricingGroup_Name, '" & FormatCurrency(cQuantity, 2) & "' AS Price, barcodePersonLnk.barcodePersonLnk_PersonID, barcodePersonLnk.barcodePersonLnk_PrintQTY, Company.*, barcodePersonLnk.barcodePersonLnk_PrintQTY, Label.LabelID, Label.Label_TextStream, 'SELL BY ' & Format(NOW+[StockItem].[StockItem_ExpiryDays], 'dd/mm/yy') AS StockItem_ExpiryDays " sql = sql & "FROM Company, Label, barcodePersonLnk INNER JOIN ((((StockItem INNER JOIN Supplier ON StockItem.StockItem_SupplierID = Supplier.SupplierID) INNER JOIN PricingGroup ON StockItem.StockItem_PricingGroupID = PricingGroup.PricingGroupID) INNER JOIN Catalogue ON StockItem.StockItemID = Catalogue.Catalogue_StockItemID) INNER JOIN CatalogueChannelLnk ON (Catalogue.Catalogue_Quantity = CatalogueChannelLnk.CatalogueChannelLnk_Quantity) AND (Catalogue.Catalogue_StockItemID = CatalogueChannelLnk.CatalogueChannelLnk_StockItemID)) ON (barcodePersonLnk.barcodePersonLnk_StockItemID = Catalogue.Catalogue_StockItemID) AND (barcodePersonLnk.barcodePersonLnk_Shrink = Catalogue.Catalogue_Quantity) " sql = sql & "WHERE (((barcodePersonLnk.barcodePersonLnk_PersonID)=" & gPersonID & ") AND ((barcodePersonLnk.barcodePersonLnk_PrintQTY)<>0) AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1) AND ((Label.LabelID)=" & CInt(lstBarcode.SelectedIndex) & ")); " rs = getRS(sql) If rs.RecordCount Then 'Checks if the barcode/Shelf Talker button is clicked and displays the correct button. If _optBarcode_2.Checked = True Then If MsgBox("You have selected " & rs.RecordCount & " products to print." & vbCrLf & vbCrLf & "Are you sure you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "PRINT BARCODES") = MsgBoxResult.Yes Then If CDbl(lblPrinterType.Tag) = 1 Then printStockBarcode(rs) ElseIf CDbl(lblPrinterType.Tag) = 2 Then printStockA4(rs) ElseIf CDbl(lblPrinterType.Tag) = 3 Then PrintBarcodeDatamax(rs) End If End If ElseIf _optBarcode_1.Checked = True Then If MsgBox("You have selected " & rs.RecordCount & " products to print." & vbCrLf & vbCrLf & "Are you sure you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "PRINT SHELF TALKER") = MsgBoxResult.Yes Then If CDbl(lblPrinterType.Tag) = 1 Then printStockBarcode(rs) ElseIf CDbl(lblPrinterType.Tag) = 2 Then 'If InStr(LCase(lblPrinter), "label") Then printStockA4(rs) 'Else ' printStockA4_OLD rs 'End If ElseIf CDbl(lblPrinterType.Tag) = 3 Then PrintBarcodeDatamax(rs) End If End If End If End If End Sub Private Function Rnd2(ByRef sngLow As Single, ByRef sngHigh As Single) As Single Randomize((GetTickCount() + Now.ToOADate())) ' Reseed with system time (2 ways) Rnd2 = (Rnd() * (sngHigh - sngLow)) + sngLow End Function Private Sub optBarcode_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) If eventSender.Checked Then Dim Index As Integer Dim radBtn As New RadioButton radBtn = DirectCast(eventSender, RadioButton) Index = GetIndexer(radBtn, optBarcode) Dim stSring As String Dim rsPrinter_B As New ADODB.Recordset Dim fso As New Scripting.FileSystemObject 'Doing shelf from file If grvPrin Then If fso.FileExists(serverPath & "ShelfBarcode.dat") Then rsPrinter_B.Open(serverPath & "ShelfBarcode.dat") 'If Index = 2 Then rsPrinter_B.filter = "StockItem_SBarcode ='barcode'" 'If Index = 1 Then rsPrinter_B.filter = "StockItem_SBarcode ='shelf'" If Index = 2 Then rsPrinter_B.Filter = "StockItem_SBarcode =true" If Index = 1 Then rsPrinter_B.Filter = "StockItem_SShelf =true" If rsPrinter_B.RecordCount > 0 Then 'grvPrinType = Index Else If Index = 2 Then stSring = "Barcode Labels" If Index = 1 Then stSring = "Shelf Talkers" MsgBox("There are no StockItem(s) to print " & stSring & " from!.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly + MsgBoxStyle.Information, My.Application.Info.Title) Me.Close() End If Else MsgBox("File " & serverPath & "ShelfBarcode.dat not found.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, My.Application.Info.Title) Me.Close() End If End If gType = Index showLabels() End If End Sub Private Sub splitString(ByRef Max As Short, ByRef HeadingString1 As String, ByRef HeadingString2 As String) Dim lHeading As String lHeading = UCase(HeadingString1) lHeading = Replace(lHeading, "&", "AND") lHeading = Replace(lHeading, "'", "") HeadingString1 = lHeading & " " HeadingString2 = "" If Len(lHeading) > Max Then HeadingString1 = VB.Left(lHeading, Max + 1) Do Until VB.Right(HeadingString1, 1) = " " Or Len(HeadingString1) = 1 HeadingString1 = VB.Left(HeadingString1, Len(HeadingString1) - 1) Loop If Len(HeadingString1) = 1 Then HeadingString1 = VB.Left(lHeading, 25) HeadingString2 = Mid(lHeading, 25, 25) Else HeadingString2 = VB.Left(Trim(Mid(lHeading, Len(HeadingString1))), Max) End If End If End Sub Private Sub printStockA4(ByRef rs As ADODB.Recordset) Dim mm As Decimal Dim i As Integer Dim lline As Integer Dim bGroup As String Dim sGroup As String Dim lTop As Integer Dim lHeight As Integer Dim gOffsetLabel As Integer Dim dasd As Integer Dim Printer As New Printing.PrintDocument Dim lObject As New Printing.PrintDocument Dim y As Integer Dim x As Integer Dim rsData As ADODB.Recordset Dim currentPic As Integer Dim twipsToMM As Integer Dim lLeft As Integer Dim lWidth As Integer Dim lCol, lCols, lRows, lrow As Short On Error GoTo Err_printStockA4 dasd = Printer.PrinterSettings.DefaultPageSettings.PaperSize.Width 'Printer.PrinterSettings.DefaultPageSettings.ScaleMode = ScaleModeConstants.vbTwips 'twips 'twipsToMM = Printer.ScaleWidth 'Printer.ScaleMode = ScaleModeConstants.vbMillimeters 'mm 'twipsToMM = twipsToMM / Printer.ScaleWidth 'Printer.ScaleMode = ScaleModeConstants.vbTwips 'twips lObject = Printer Dim lString1, lString2 As String rsData = getRS("SELECT * FROM labelItem INNER JOIN label ON labelItem.labelItem_LabelID = label.labelID Where (((label.labelID) = " & rs.Fields("LabelID").Value & ")) ORDER BY label.labelID, labelItem.labelItem_Line;") lLeft = (lObject.PrinterSettings.DefaultPageSettings.PaperSize.Width - (lWidth)) / 2 + (gOffsetLabel * twipsToMM) lLeft = 0 If rsData.Fields("Label_Rotate").Value Then lWidth = rsData.Fields("label_Height").Value * twipsToMM lHeight = rsData.Fields("label_Width").Value * twipsToMM Else lWidth = rsData.Fields("label_width").Value * twipsToMM lHeight = rsData.Fields("label_Height").Value * twipsToMM End If lTop = rsData.Fields("label_Top").Value * twipsToMM lCols = CDec(Printer.PrinterSettings.DefaultPageSettings.PaperSize.Width / (lWidth + 60)) - 0.49999 lRows = CDec(Printer.PrinterSettings.DefaultPageSettings.PaperSize.Height / (lHeight + 60)) - 0.49999 sGroup = "1" If InStr(LCase(rsData.Fields("Label_Name").Value), "nursery") Then bGroup = "Yes" Else bGroup = "No" printStockA4(rs) Exit Sub End If Do Until rs.EOF rsData.MoveFirst() y = 0 If y < 0 Then y = 0 'lObject.FontName = "Tahoma" rsData.MoveFirst() If rsData.RecordCount Then lline = rsData.Fields("labelItem_Line").Value For i = 1 To rs.Fields("barcodePersonLnk_PrintQTY").Value lLeft = IIf(IsDbNull(rsData.Fields("Label_Left").Value), 0, rsData.Fields("Label_Left").Value) * twipsToMM 'lLeft = 1200 'lCol * (lWidth + 60) 'lObject.CurrentY = lrow * (lHeight + 60) rsData.MoveFirst() 'y = lObject.CurrentY 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(Me.BackColor) On Error Resume Next 'lObject.Line((lLeft, y) - (lLeft, y + 100)) 'lObject.Line((lLeft, y) - (lLeft + 100, y)) 'lObject.Line((lLeft + lWidth, y) - (lLeft + lWidth - 100, y)) 'lObject.Line((lLeft + lWidth, y) - (lLeft + lWidth, y + 100)) 'lObject.Line((lLeft + lWidth, lHeight + y) - (lLeft + lWidth, lHeight + y - 100)) 'lObject.Line((lLeft + lWidth, lHeight + y) - (lLeft + lWidth - 100, lHeight + y)) 'lObject.Line((lLeft, lHeight + y) - (lLeft, lHeight + y - 100)) 'lObject.Line((lLeft, lHeight + y) - (lLeft + 100, lHeight + y)) 'lObject.CurrentY = lrow * (lHeight + 60) + lTop 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'y = lObject.CurrentY + 10 Do Until rsData.EOF If lline <> rsData.Fields("labelItem_Line").Value Then 'y = lObject.CurrentY + 10 lline = rsData.Fields("labelItem_Line").Value End If Select Case LCase(Trim(rsData.Fields("labelItem_Field").Value)) Case "blank" 'lObject.FontSize = rsData.Fields("labelItem_Size").Value 'lObject.FontBold = rsData.Fields("labelItem_Bold").Value 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White) 'lObject.Print(" ") Case "line" 'lObject.Line((15 + lLeft, y) - (lLeft + lWidth, y), System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black)) Case "code" Select Case rsData.Fields("labelItem_Align").Value Case 1 If bGroup = "Yes" Then 'Barcode CodeType, txtData, Printer, 15, 700, 3000, 250 'Barcode "128", rs("Catalogue_Barcode"), lObject, 15, 700, lLeft + 90, Y Barcode("128", rs.Fields("Catalogue_Barcode").Value, lObject, 24, 500, 2400, CSng(y)) Else 'printBarcode(lObject, rs.Fields("Catalogue_Barcode").Value, lLeft + 90, y) End If Case 2 If bGroup = "Yes" Then Barcode("128", rs.Fields("Catalogue_Barcode").Value, lObject, 24, 500, 2400, CSng(y)) Else 'old line before jonas printBarcode lObject, rs("Catalogue_Barcode"), lLeft + 90, y 'printBarcode(lObject, rs.Fields("Catalogue_Barcode").Value, lLeft + 90, y, lWidth + lWidth - 1440) End If Case Else If bGroup = "Yes" Then 'Barcode "128", rs("Catalogue_Barcode"), lObject, 15, 700, lLeft + 90, Y Barcode("128", rs.Fields("Catalogue_Barcode").Value, lObject, 24, 500, 2400, CSng(y)) '3600 'Barcode "128", "tZst1234", lObject, 24, 700, 2500, 130 Else 'printBarcode(lObject, rs.Fields("Catalogue_Barcode").Value, lLeft, y, lWidth) End If End Select Case Else 'lObject.FontSize = rsData.Fields("labelItem_Size").Value 'lObject.FontBold = rsData.Fields("labelItem_Bold").Value 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White) mm = rsData.Fields("labelItem_Field").Value 'code for printing shrinks 'code for printing shrinks lString1 = rs.Fields(mm).Value Select Case rsData.Fields("labelItem_Align").Value Case 1 'lObject.PSet(New Point[](lLeft + 90, y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) Case 2 'lObject.PSet(New Point[](lLeft + lWidth - lObject.TextWidth(lString1) - 90, y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) Case 3 'splitStringA4(lObject, lWidth, lString1, lString2) 'lObject.PSet(New Point[](CShort(lLeft + (lWidth - lObject.TextWidth(lString1)) / 2), y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) 'y = lObject.CurrentY + 10 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White) lString1 = lString2 'lObject.PSet(New Point[](CShort(lLeft + (lWidth - lObject.TextWidth(lString1)) / 2), y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) Case Else 'lObject.PSet(New Point[](CShort(lLeft + (lWidth - lObject.TextWidth(lString1)) / 2), y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) End Select End Select If bGroup = "Yes" Then 'sGroup = "1" If sGroup <> rsData.Fields("labelItem_Sample").Value Then 'And rs("barcodePersonLnk_PrintQTY") = 1 Then If rs.Fields("barcodePersonLnk_PrintQTY").Value = 1 Then rs.moveNext() ElseIf rs.Fields("barcodePersonLnk_PrintQTY").Value >= 1 Then If i = rs.Fields("barcodePersonLnk_PrintQTY").Value And sGroup = "4" Then sGroup = "1" Exit Do ElseIf i = rs.Fields("barcodePersonLnk_PrintQTY").Value Then rs.moveNext() i = 0 End If i = i + 1 End If sGroup = rsData.Fields("labelItem_Sample").Value End If 'i = i + 1 'If i >= rs("barcodePersonLnk_PrintQTY") Then ' sGroup = rsData("labelItem_Sample") ' 'rs.moveNext ' Exit Do 'End If If rs.EOF Then Exit Do End If rsData.moveNext() Loop lCol = lCol + 1 If lCol >= lCols Then lCol = 0 lrow = lrow + 1 'If (lrow + 1) * lHeight > lObject.Height Then ' Printer.NewPage() ' If bGroup = "Yes" Then ' lrow = 0 '-1 'Else ' lrow = -1 ' End If 'End If End If If sGroup = "4" Then sGroup = "1" Next End If If bGroup = "Yes" Then If rs.EOF Then Exit Do If sGroup = "4" Then sGroup = "1" End If rs.moveNext() Loop 'Printer.EndDoc() Exit Sub Err_printStockA4: 'MsgBox Err.Description Resume Next End Sub Public Sub printBarcode(ByRef barcodePicture As PictureBox, ByRef lValue As String, ByRef lLeft As Integer, ByRef lTop As Integer, Optional ByRef lWidth As Integer = 0) Dim BF As Integer Dim x As Short Dim y As Short Dim lXML As String Dim lastArray, oddArray, evenArray, parityArray As String() Dim lString, codeType, code, lCode, HeadingString1 As String Dim HeadingString2 As String Dim i, j As Integer Dim cnt As Short Dim barArray As String() lXML = "" If doCheckSum(lValue) Then oddArray = New String() {"0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011"} evenArray = New String() {"0100111", "0110011", "0011011", "0100001", "0011101", "0111001", "0000101", "0010001", "0001001", "0010111"} lastArray = New String() {"1110010", "1100110", "1101100", "1000010", "1011100", "1001110", "1010000", "1000100", "1001000", "1110100"} parityArray = New String() {"111111", "110100", "110010", "110001", "101100", "100110", "100011", "101010", "101001", "100101"} code = VB.Left(lValue, 1) code = VB.Right(code, 1) codeType = parityArray(CShort(code)) lXML = lXML & doImage("101", 1) For i = 2 To 7 code = VB.Left(lValue, i) code = VB.Right(code, 1) lCode = VB.Left(codeType, i - 1) lCode = VB.Right(lCode, 1) If lCode = "0" Then lXML = lXML & doImage(evenArray(code), 0) Else lXML = lXML & doImage(oddArray(code), 0) End If Next lXML = lXML & doImage("01010", 1) For i = 8 To 13 code = VB.Left(lValue, i) code = VB.Right(code, 1) lXML = lXML & doImage(lastArray(code), 0) Next lXML = lXML & doImage("101", 1) Else lString = lValue For i = 1 To Len(lString) If CDbl(VB.Left(lString, 1)) = 0 Then lString = VB.Right(lString, Len(lString) - 1) Else Exit For End If Next lValue = lString oddArray = New String() {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "-", ".", " ", "$", "/", "+", "%", "~", ","} evenArray = New String() {"111331311", "311311113", "113311113", "313311111", "111331113", "311331111", "113331111", "111311313", "311311311", "113311311", "311113113", "113113113", "313113111", "111133113", "311133111", "113133111", "111113313", "311113311", "113113311", "111133311", "311111133", "113111133", "313111131", "111131133", "311131131", "113131131", "111111333", "311111331", "113111331", "111131331", "331111113", "133111113", "333111111", "131131113", "331131111", "133131111", "131111313", "331111311", "133111311", "131131311", "131313111", "131311131", "131113131", "111313131", "1311313111131131311"} lString = "131131311" lString = lString + "1" For i = 1 To Len(lValue) code = VB.Left(lValue, i) code = VB.Right(code, 1) code = UCase(code) For j = 0 To UBound(oddArray) If code = oddArray(j) Then lString = lString + evenArray(j) lString = lString + "1" j = 9999 End If Next Next lString = lString + "131131311" For i = 1 To Len(lString) code = VB.Left(lString, i) code = VB.Right(code, 1) For j = 1 To CShort(code) lCode = VB.Left(code, i) lCode = VB.Right(lCode, 1) If i Mod 2 Then lXML = lXML & System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) & "~" Else lXML = lXML & System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White) & "~" End If lXML = lXML & "20|" Next Next End If barArray = Split(lXML, "|") y = lTop If lWidth = 0 Then x = lLeft Else x = CShort(lLeft + (lWidth - UBound(barArray) * twipsPerPixel(True) / 2)) End If For cnt = LBound(barArray) To UBound(barArray) If barArray(cnt) <> "" Then If CInt(Split(barArray(cnt), "~")(0)) = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) Then 'barcodePicture.Line((x + cnt * twipsPerPixel(true), y) - (_ ' x + (cnt + 1) * twipsPerPixel(true), _ ' y + CInt(Split(barArray(cnt), "~")(1)) _ ' * twipsPerPixel(True)), CInt(Split(barArray(cnt), "~")(0)), BF) End If End If Next End Sub Function doImage(ByRef code As String, ByRef size_Renamed As Integer) As String Dim lXML As String Dim lCode As String Dim i As Short For i = 1 To Len(code) lCode = VB.Left(code, i) lCode = VB.Right(lCode, 1) If lCode = "0" Then lXML = lXML & System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White) & "~" Else lXML = lXML & System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) & "~" End If If (size_Renamed) Then lXML = lXML & 30 & "|" Else lXML = lXML & 25 & "|" End If Next doImage = lXML End Function Public Function PrintBarcodeDatamax(ByRef rs As ADODB.Recordset) As Boolean Dim sql As String Dim mm As String Dim i As Integer Dim lline As Integer Dim lTop As Integer Dim lHeight As Integer Dim Printer As New Printing.PrintDocument Dim lObject As New Printing.PrintDocument Dim y As Integer Dim x As Integer Dim rsData As ADODB.Recordset Dim currentPic As Integer Dim twipsToMM As Integer Dim lLeft As Integer Dim lWidth As Integer Dim lCol, lCols, lRows, lrow As Short Dim rsPrice As ADODB.Recordset 'Printer.ScaleMode = ScaleModeConstants.vbTwips 'twips 'twipsToMM = Printer.ScaleWidth 'Printer.ScaleMode = ScaleModeConstants.vbMillimeters 'mm 'twipsToMM = twipsToMM / Printer.ScaleWidth 'Printer.ScaleMode = ScaleModeConstants.vbTwips 'twips lObject = Printer Dim lString1, lString2 As String rsData = getRS("SELECT * FROM labelItem INNER JOIN label ON labelItem.labelItem_LabelID = label.labelID Where (((label.labelID) = " & rs.Fields("LabelID").Value & ")) ORDER BY label.labelID, labelItem.labelItem_Line;") 'lLeft = (lObject.Width - (lWidth)) / 2 + (gOffsetLabel * twipsToMM) lLeft = 0 If rsData.Fields("Label_Rotate").Value Then lWidth = rsData.Fields("label_Height").Value * twipsToMM lHeight = rsData.Fields("label_Width").Value * twipsToMM Else lWidth = rsData.Fields("label_width").Value * twipsToMM lHeight = rsData.Fields("label_Height").Value * twipsToMM End If lTop = rsData.Fields("label_Top").Value * twipsToMM 'lCols = CDec(Printer.Width / (lWidth + 60)) - 0.49999 'lRows = CDec(Printer.Height / (lHeight + 60)) - 0.49999 Do Until rs.EOF rsData.MoveFirst() y = 0 'If y < 0 Then y = 0 'lObject.FontName = "Tahoma" rsData.MoveFirst() If rsData.RecordCount Then lline = rsData.Fields("labelItem_Line").Value For i = 1 To rs.Fields("barcodePersonLnk_PrintQTY").Value lLeft = IIf(IsDBNull(rsData.Fields("Label_Left").Value), 0, rsData.Fields("Label_Left").Value) * twipsToMM 'lObject.CurrentY = lrow * (lHeight + 60) rsData.MoveFirst() 'y = lObject.CurrentY 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(Me.BackColor) On Error Resume Next 'lObject.Line((lLeft, y) - (lLeft, y + 100)) 'lObject.Line((lLeft, y) - (lLeft + 100, y)) 'lObject.Line((lLeft + lWidth, y) - (lLeft + lWidth - 100, y)) 'lObject.Line((lLeft + lWidth, y) - (lLeft + lWidth, y + 100)) 'lObject.Line((lLeft + lWidth, lHeight + y) - (lLeft + lWidth, lHeight + y - 100)) 'lObject.Line((lLeft + lWidth, lHeight + y) - (lLeft + lWidth - 100, lHeight + y)) 'lObject.Line((lLeft, lHeight + y) - (lLeft, lHeight + y - 100)) 'lObject.Line((lLeft, lHeight + y) - (lLeft + 100, lHeight + y)) 'lObject.CurrentY = lrow * (lHeight + 60) + lTop 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'y = lObject.CurrentY + 10 Do Until rsData.EOF If lline <> rsData.Fields("labelItem_Line").Value Then 'y = lObject.CurrentY + 10 lline = rsData.Fields("labelItem_Line").Value End If Select Case LCase(Trim(rsData.Fields("labelItem_Field").Value)) Case "blank" 'lObject.FontSize = rsData.Fields("labelItem_Size").Value 'lObject.FontBold = rsData.Fields("labelItem_Bold").Value 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White) 'lObject.Print(" ") Case "line" 'lObject.Line((15 + lLeft, y) - (lLeft + lWidth, y), System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black)) Case "code" Select Case rsData.Fields("labelItem_Align").Value Case 1 'printBarcode(lObject, rs.Fields("Catalogue_Barcode").Value, lLeft + 90, y) Case 2 'printBarcode(lObject, rs.Fields("Catalogue_Barcode").Value, lLeft + 90, y, lWidth + lWidth - 1440) Case Else 'printBarcode(lObject, rs.Fields("Catalogue_Barcode").Value, lLeft, y, lWidth) End Select Case Else 'lObject.FontSize = rsData.Fields("labelItem_Size").Value 'lObject.FontBold = rsData.Fields("labelItem_Bold").Value 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White) mm = rsData.Fields("labelItem_Field").Value 'code for printing shrinks If mm = "Price6" Then sql = "SELECT StockItem.StockItemID, Format([CatalogueChannelLnk_Price],'Currency') AS Price " sql = sql & "FROM (StockItem INNER JOIN Catalogue ON StockItem.StockItemID = Catalogue.Catalogue_StockItemID) INNER JOIN CatalogueChannelLnk ON StockItem.StockItemID = CatalogueChannelLnk.CatalogueChannelLnk_StockItemID " sql = sql & "WHERE (((StockItem.StockItemID)=" & rs.Fields("StockItemID").Value & ") AND ((Catalogue.Catalogue_Quantity)=6) AND ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity)=6) AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1));" rsPrice = getRS(sql) If rsPrice.RecordCount Then lString1 = rsPrice.Fields("Price").Value & " FOR 6" Else lString1 = " " End If ElseIf mm = "Price12" Then sql = "SELECT StockItem.StockItemID, Format([CatalogueChannelLnk_Price],'Currency') AS Price " sql = sql & "FROM (StockItem INNER JOIN Catalogue ON StockItem.StockItemID = Catalogue.Catalogue_StockItemID) INNER JOIN CatalogueChannelLnk ON StockItem.StockItemID = CatalogueChannelLnk.CatalogueChannelLnk_StockItemID " sql = sql & "WHERE (((StockItem.StockItemID)=" & rs.Fields("StockItemID").Value & ") AND ((Catalogue.Catalogue_Quantity)=12) AND ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity)=12) AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1));" rsPrice = getRS(sql) If rsPrice.RecordCount Then lString1 = rsPrice.Fields("Price").Value & " FOR 12" Else lString1 = " " End If ElseIf mm = "Price24" Then sql = "SELECT StockItem.StockItemID, Format([CatalogueChannelLnk_Price],'Currency') AS Price " sql = sql & "FROM (StockItem INNER JOIN Catalogue ON StockItem.StockItemID = Catalogue.Catalogue_StockItemID) INNER JOIN CatalogueChannelLnk ON StockItem.StockItemID = CatalogueChannelLnk.CatalogueChannelLnk_StockItemID " sql = sql & "WHERE (((StockItem.StockItemID)=" & rs.Fields("StockItemID").Value & ") AND ((Catalogue.Catalogue_Quantity)=24) AND ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity)=24) AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1));" rsPrice = getRS(sql) If rsPrice.RecordCount Then lString1 = rsPrice.Fields("Price").Value & " FOR 24" Else lString1 = " " End If Else lString1 = rs.Fields(mm).Value End If 'code for printing shrinks 'lString1 = rs(mm) Select Case rsData.Fields("labelItem_Align").Value Case 1 'lObject.PSet(New Point[](lLeft + 90, y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) Case 2 'lObject.PSet(New Point[](lLeft + lWidth - lObject.TextWidth(lString1) - 90, y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) Case 3 'splitStringA4(lObject, lWidth, lString1, lString2) 'lObject.PSet(New Point[](CShort(lLeft + (lWidth - lObject.TextWidth(lString1)) / 2), y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) 'y = lObject.CurrentY + 10 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White) lString1 = lString2 'lObject.PSet(New Point[](CShort(lLeft + (lWidth - lObject.TextWidth(lString1)) / 2), y)) 'lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) 'lObject.Print(lString1) Case Else 'lObject.PSet(New Point[](CShort(lLeft + (lWidth - lObject.TextWidth(lString1)) / 2), y)) ' lObject.ForeColor = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black) ' lObject.Print(lString1) End Select End Select rsData.MoveNext() Loop 'New code for tesing barcode printing 'Printer.NewPage() Next End If rs.MoveNext() Loop 'Printer.EndDoc() End Function End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmBarcode.vb
Visual Basic
mit
104,921
Namespace Commands Partial Public Class CommandInterrogatedMethod #Region " Public Constants " Public Const DEFAULT_METHODNAME As String = ASTERISK Public Const DELINEATOR_PARAMNUMBER As String = "##" #End Region #Region " Public Properties " Public ReadOnly Property IsDefault() As Boolean Get Return String.IsNullOrEmpty(Name) OrElse String.Compare(Name, DEFAULT_METHODNAME) = 0 End Get End Property #End Region #Region " Public Shared Methods " Public Shared Function GetMethods( _ ByVal commandAnalyser As TypeAnalyser _ ) As CommandInterrogatedMethod() Dim methods As MemberAnalyser() = _ commandAnalyser.ExecuteQuery( _ AnalyserQuery.QUERY_METHODS_PUBLIC_INSTANCE _ .SetPresentAttribute(GetType(CommandAttribute)) _ ) Dim l_Commands As New SortedList If Not methods Is Nothing Then For Each method As MemberAnalyser In methods Dim commandParameters As New ArrayList Dim paramCount As Integer = 0 Dim paramCountMinimum As Boolean = False Dim methodType As CommandType Dim command_Attribs As CommandAttribute() = _ method.Method.GetCustomAttributes(GetType(CommandAttribute), False) If command_Attribs.Length > 0 Then Dim command_Parameters As ParameterInfo() = method.Method.GetParameters() If CType(method.Method, MethodInfo).ReturnType Is Nothing OrElse _ CType(method.Method, MethodInfo).ReturnType Is GetType(System.Void) Then methodType = CommandType.Unknown ElseIf CType(method.Method, MethodInfo).ReturnType Is GetType(Boolean) Then methodType = CommandType.Process ElseIf CType(method.Method, MethodInfo).ReturnType Is GetType(Visualisation.IFixedWidthWriteable) Then methodType = CommandType.Format ElseIf command_Parameters.Length = 0 Then methodType = CommandType.Retrieval Else methodType = CommandType.Transform End If For i As Integer = 0 To command_Parameters.Length - 1 Dim parameter_Attribs As ConfigurableAttribute() = _ command_Parameters(i).GetCustomAttributes(GetType(ConfigurableAttribute), True) If parameter_Attribs.Length = 1 Then If DoesTypeImplementInterface(command_Parameters(i).ParameterType, GetType(Visualisation.IFixedWidthWriteable)) OrElse _ (command_Parameters(i).ParameterType.IsArray AndAlso _ DoesTypeImplementInterface(command_Parameters(i).ParameterType.GetElementType, GetType(Visualisation.IFixedWidthWriteable))) Then _ methodType = CommandType.Output If (command_Parameters(i).Position = command_Parameters.Length - 1) _ AndAlso command_Parameters(i).ParameterType.IsArray Then paramCountMinimum = True Dim l_Name As String = parameter_Attribs(0).Name If String.IsNullOrEmpty(l_Name) Then _ l_Name = command_Parameters(i).Name commandParameters.Add( _ New CommandInterrogatedParameter( _ l_Name, _ parameter_Attribs(0).Description, _ command_Parameters(i).ParameterType, _ command_Parameters(i).Position) _ ) paramCount += 1 End If Next For i As Integer = 0 To command_Attribs.Length - 1 Dim command_Name As String, display_Name As String = String.Empty If command_Attribs(i).Name = Nothing Then command_Name = DEFAULT_METHODNAME & DELINEATOR_PARAMNUMBER & paramCount Else command_Name = command_Attribs(i).Name & DELINEATOR_PARAMNUMBER & paramCount display_Name = command_Attribs(i).Name.ToLower End If l_Commands.Add(command_Name, _ New CommandInterrogatedMethod( _ display_Name, command_Attribs(i).Description, methodType, paramCount, _ paramCountMinimum, command_Parameters.Length, method, _ commandParameters.ToArray(GetType(CommandInterrogatedParameter)))) Next End If Next End If Dim retArray As CommandInterrogatedMethod() = _ Array.CreateInstance(GetType(CommandInterrogatedMethod), l_Commands.Count) l_Commands.Values.CopyTo(retArray, 0) Return retArray End Function #End Region #Region " Public Methods " Public Overridable Function Invoke( _ ByVal invokedObject As Object, _ ByVal parameters As Object(), _ ByVal environment As ICommandsExecution _ ) As Object Return InvokableMethod.Method.Invoke(invokedObject, parameters) End Function Public Overrides Function ToString() As String If Not InvokableMethod Is Nothing Then Return InvokableMethod.ToString ElseIf Not String.IsNullOrEmpty(Description) Then Return Description Else Return Name End If End Function #End Region End Class End Namespace
thiscouldbejd/Leviathan
_Commands/Partials/CommandInterrogatedMethod.vb
Visual Basic
mit
6,602
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class screenSelect 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.lblSquare = New System.Windows.Forms.Label() Me.lblTriangle = New System.Windows.Forms.Label() Me.lblRectangle = New System.Windows.Forms.Label() Me.lblPentagon = New System.Windows.Forms.Label() Me.lblHexagon = New System.Windows.Forms.Label() Me.lblCircle = New System.Windows.Forms.Label() Me.PictureBox1 = New System.Windows.Forms.PictureBox() Me.picPentagon = New System.Windows.Forms.PictureBox() Me.picRectangle = New System.Windows.Forms.PictureBox() Me.picHexagon = New System.Windows.Forms.PictureBox() Me.picCorner = New System.Windows.Forms.PictureBox() Me.picSquare = New System.Windows.Forms.PictureBox() Me.picTriangle = New System.Windows.Forms.PictureBox() Me.picCircle = New System.Windows.Forms.PictureBox() Me.PictureBox2 = New System.Windows.Forms.PictureBox() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picPentagon, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picRectangle, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picHexagon, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picCorner, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picSquare, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picTriangle, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picCircle, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.PictureBox2, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'lblSquare ' Me.lblSquare.AutoSize = True Me.lblSquare.BackColor = System.Drawing.Color.Transparent Me.lblSquare.Font = New System.Drawing.Font("Microsoft Sans Serif", 24.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblSquare.Location = New System.Drawing.Point(524, 156) Me.lblSquare.Name = "lblSquare" Me.lblSquare.Size = New System.Drawing.Size(122, 38) Me.lblSquare.TabIndex = 5 Me.lblSquare.Text = "Square" ' 'lblTriangle ' Me.lblTriangle.AutoSize = True Me.lblTriangle.BackColor = System.Drawing.Color.Transparent Me.lblTriangle.Font = New System.Drawing.Font("Microsoft Sans Serif", 24.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblTriangle.Location = New System.Drawing.Point(780, 156) Me.lblTriangle.Name = "lblTriangle" Me.lblTriangle.Size = New System.Drawing.Size(134, 38) Me.lblTriangle.TabIndex = 6 Me.lblTriangle.Text = "Triangle" ' 'lblRectangle ' Me.lblRectangle.AutoSize = True Me.lblRectangle.BackColor = System.Drawing.Color.Transparent Me.lblRectangle.Font = New System.Drawing.Font("Microsoft Sans Serif", 24.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblRectangle.Location = New System.Drawing.Point(767, 410) Me.lblRectangle.Name = "lblRectangle" Me.lblRectangle.Size = New System.Drawing.Size(164, 38) Me.lblRectangle.TabIndex = 12 Me.lblRectangle.Text = "Rectangle" ' 'lblPentagon ' Me.lblPentagon.AutoSize = True Me.lblPentagon.BackColor = System.Drawing.Color.Transparent Me.lblPentagon.Font = New System.Drawing.Font("Microsoft Sans Serif", 24.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblPentagon.Location = New System.Drawing.Point(503, 410) Me.lblPentagon.Name = "lblPentagon" Me.lblPentagon.Size = New System.Drawing.Size(156, 38) Me.lblPentagon.TabIndex = 11 Me.lblPentagon.Text = "Pentagon" ' 'lblHexagon ' Me.lblHexagon.AutoSize = True Me.lblHexagon.BackColor = System.Drawing.Color.Transparent Me.lblHexagon.Font = New System.Drawing.Font("Microsoft Sans Serif", 24.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblHexagon.Location = New System.Drawing.Point(182, 410) Me.lblHexagon.Name = "lblHexagon" Me.lblHexagon.Size = New System.Drawing.Size(148, 38) Me.lblHexagon.TabIndex = 10 Me.lblHexagon.Text = "Hexagon" ' 'lblCircle ' Me.lblCircle.AutoSize = True Me.lblCircle.BackColor = System.Drawing.Color.Transparent Me.lblCircle.Font = New System.Drawing.Font("Microsoft Sans Serif", 24.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblCircle.Location = New System.Drawing.Point(205, 156) Me.lblCircle.Name = "lblCircle" Me.lblCircle.Size = New System.Drawing.Size(101, 38) Me.lblCircle.TabIndex = 4 Me.lblCircle.Text = "Circle" ' 'PictureBox1 ' Me.PictureBox1.Image = Global.BatMath.My.Resources.Resources.HomeIcon Me.PictureBox1.Location = New System.Drawing.Point(949, 12) Me.PictureBox1.Name = "PictureBox1" Me.PictureBox1.Size = New System.Drawing.Size(63, 63) Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.PictureBox1.TabIndex = 14 Me.PictureBox1.TabStop = False ' 'picPentagon ' Me.picPentagon.BackColor = System.Drawing.Color.Transparent Me.picPentagon.Image = Global.BatMath.My.Resources.Resources.pentagon Me.picPentagon.Location = New System.Drawing.Point(510, 356) Me.picPentagon.Name = "picPentagon" Me.picPentagon.Size = New System.Drawing.Size(150, 150) Me.picPentagon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.picPentagon.TabIndex = 8 Me.picPentagon.TabStop = False ' 'picRectangle ' Me.picRectangle.BackColor = System.Drawing.Color.Transparent Me.picRectangle.Image = Global.BatMath.My.Resources.Resources.rectangle Me.picRectangle.Location = New System.Drawing.Point(774, 386) Me.picRectangle.Name = "picRectangle" Me.picRectangle.Size = New System.Drawing.Size(150, 100) Me.picRectangle.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.picRectangle.TabIndex = 7 Me.picRectangle.TabStop = False ' 'picHexagon ' Me.picHexagon.BackColor = System.Drawing.Color.Transparent Me.picHexagon.Image = Global.BatMath.My.Resources.Resources.hexagon Me.picHexagon.Location = New System.Drawing.Point(180, 356) Me.picHexagon.Name = "picHexagon" Me.picHexagon.Size = New System.Drawing.Size(150, 150) Me.picHexagon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.picHexagon.TabIndex = 9 Me.picHexagon.TabStop = False ' 'picCorner ' Me.picCorner.Image = Global.BatMath.My.Resources.Resources.atman Me.picCorner.Location = New System.Drawing.Point(0, 316) Me.picCorner.Name = "picCorner" Me.picCorner.Size = New System.Drawing.Size(380, 260) Me.picCorner.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.picCorner.TabIndex = 3 Me.picCorner.TabStop = False ' 'picSquare ' Me.picSquare.BackColor = System.Drawing.Color.Transparent Me.picSquare.Image = Global.BatMath.My.Resources.Resources.square Me.picSquare.Location = New System.Drawing.Point(510, 100) Me.picSquare.Name = "picSquare" Me.picSquare.Size = New System.Drawing.Size(150, 150) Me.picSquare.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.picSquare.TabIndex = 1 Me.picSquare.TabStop = False ' 'picTriangle ' Me.picTriangle.BackColor = System.Drawing.Color.Transparent Me.picTriangle.Image = Global.BatMath.My.Resources.Resources.triangle Me.picTriangle.Location = New System.Drawing.Point(774, 100) Me.picTriangle.Name = "picTriangle" Me.picTriangle.Size = New System.Drawing.Size(150, 150) Me.picTriangle.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.picTriangle.TabIndex = 0 Me.picTriangle.TabStop = False ' 'picCircle ' Me.picCircle.BackColor = System.Drawing.Color.Transparent Me.picCircle.Image = Global.BatMath.My.Resources.Resources.circle Me.picCircle.Location = New System.Drawing.Point(180, 100) Me.picCircle.Name = "picCircle" Me.picCircle.Size = New System.Drawing.Size(150, 150) Me.picCircle.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.picCircle.TabIndex = 13 Me.picCircle.TabStop = False ' 'PictureBox2 ' Me.PictureBox2.Image = Global.BatMath.My.Resources.Resources.iconsineed_cross_24_128 Me.PictureBox2.Location = New System.Drawing.Point(880, 12) Me.PictureBox2.Name = "PictureBox2" Me.PictureBox2.Size = New System.Drawing.Size(63, 63) Me.PictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.PictureBox2.TabIndex = 15 Me.PictureBox2.TabStop = False ' 'screenSelect ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(54, Byte), Integer), CType(CType(69, Byte), Integer), CType(CType(79, Byte), Integer)) Me.ClientSize = New System.Drawing.Size(1024, 576) Me.Controls.Add(Me.PictureBox2) Me.Controls.Add(Me.PictureBox1) Me.Controls.Add(Me.lblRectangle) Me.Controls.Add(Me.lblPentagon) Me.Controls.Add(Me.lblHexagon) Me.Controls.Add(Me.lblTriangle) Me.Controls.Add(Me.lblSquare) Me.Controls.Add(Me.lblCircle) Me.Controls.Add(Me.picPentagon) Me.Controls.Add(Me.picRectangle) Me.Controls.Add(Me.picHexagon) Me.Controls.Add(Me.picCorner) Me.Controls.Add(Me.picSquare) Me.Controls.Add(Me.picTriangle) Me.Controls.Add(Me.picCircle) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.Name = "screenSelect" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "screenSelect" CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picPentagon, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picRectangle, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picHexagon, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picCorner, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picSquare, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picTriangle, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picCircle, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.PictureBox2, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents picTriangle As System.Windows.Forms.PictureBox Friend WithEvents picSquare As System.Windows.Forms.PictureBox Friend WithEvents picCorner As System.Windows.Forms.PictureBox Friend WithEvents lblSquare As System.Windows.Forms.Label Friend WithEvents lblTriangle As System.Windows.Forms.Label Friend WithEvents lblRectangle As System.Windows.Forms.Label Friend WithEvents lblPentagon As System.Windows.Forms.Label Friend WithEvents lblHexagon As System.Windows.Forms.Label Friend WithEvents picPentagon As System.Windows.Forms.PictureBox Friend WithEvents picRectangle As System.Windows.Forms.PictureBox Friend WithEvents picHexagon As System.Windows.Forms.PictureBox Friend WithEvents lblCircle As System.Windows.Forms.Label Friend WithEvents picCircle As System.Windows.Forms.PictureBox Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox Friend WithEvents PictureBox2 As System.Windows.Forms.PictureBox End Class
OtherBarry/SDaD
BatMath/BatMath/screenSelect.Designer.vb
Visual Basic
mit
13,450
' ****************************************************************************** ' ** ' ** Yahoo! Managed ' ** Written by Marius Häusler 2011 ' ** It would be pleasant, if you contact me when you are using this code. ' ** Contact: YahooFinanceManaged@gmail.com ' ** Project Home: http://code.google.com/p/yahoo-finance-managed/ ' ** ' ****************************************************************************** ' ** ' ** Copyright 2011 Marius Häusler ' ** ' ** Licensed under the Apache License, Version 2.0 (the "License"); ' ** you may not use this file except in compliance with the License. ' ** You may obtain a copy of the License at ' ** ' ** http://www.apache.org/licenses/LICENSE-2.0 ' ** ' ** Unless required by applicable law or agreed to in writing, software ' ** distributed under the License is distributed on an "AS IS" BASIS, ' ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ' ** See the License for the specific language governing permissions and ' ** limitations under the License. ' ** ' ****************************************************************************** Namespace YahooManaged.Finance.API ''' <summary> ''' Provides methods for downloading quotes data. ''' </summary> ''' <remarks></remarks> Public Class QuotesDownload Inherits Base.Download Implements Base.IStringDownload ''' <summary> ''' Raises if an asynchronous download of quotes data completes. ''' </summary> ''' <param name="sender">The event raising object</param> ''' <param name="ea">The event args of the asynchronous download</param> ''' <remarks></remarks> Public Event AsyncDownloadCompleted(ByVal sender As Base.Download, ByVal ea As QuotesDownloadCompletedEventArgs) Friend ReadOnly mFinanceHelper As New FinanceHelper Private mCsvParser As New ImportExport.CSV Private mXmlParser As New ImportExport.XML Private mTextEncoding As System.Text.Encoding = System.Text.Encoding.Default ''' <summary> ''' The text encoding for CSV download. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property TextEncoding() As System.Text.Encoding Implements Base.IStringDownload.TextEncoding Get Return mTextEncoding End Get Set(ByVal value As System.Text.Encoding) mTextEncoding = value End Set End Property ''' <summary> ''' Downloads quotes data. ''' </summary> ''' <param name="managedID">The managed ID</param> ''' <param name="properties">The properties of each quote data. If parameter is null/Nothing, Symbol and LastTradePrizeOnly will set as property. In this case, with YQL server you will get every available property.</param> ''' <returns></returns> ''' <remarks></remarks> Public Function Download(ByVal managedID As IID, ByVal properties As IEnumerable(Of QuoteProperty)) As QuotesResponse If managedID Is Nothing Then Throw New ArgumentNullException("id", "The passed id is null.") Return Me.Download(managedID.ID, properties) End Function ''' <summary> ''' Downloads quotes data. ''' </summary> ''' <param name="unmanagedID">The unmanaged ID</param> ''' <param name="properties">The properties of each quote data. If parameter is null/Nothing, Symbol and LastTradePrizeOnly will set as property. In this case, with YQL server you will get every available property.</param> ''' <returns></returns> ''' <remarks></remarks> Public Function Download(ByVal unmanagedID As String, ByVal properties As IEnumerable(Of QuoteProperty)) As QuotesResponse If unmanagedID = String.Empty Then Throw New ArgumentNullException("unmanagedID", "The passed id is empty.") Return Me.Download(New String() {unmanagedID}, properties) End Function ''' <summary> ''' Downloads quotes data. ''' </summary> ''' <param name="managedIDs">The list of managed IDs</param> ''' <param name="properties">The properties of each quote data. If parameter is null/Nothing, Symbol and LastTradePrizeOnly will set as property. In this case, with YQL server you will get every available property.</param> ''' <returns></returns> ''' <remarks></remarks> Public Function Download(ByVal managedIDs As IEnumerable(Of IID), ByVal properties As IEnumerable(Of QuoteProperty)) As QuotesResponse If managedIDs Is Nothing Then Throw New ArgumentNullException("managedIDs", "The passed list is null.") Return Me.Download(mFinanceHelper.IIDsToStrings(managedIDs), properties) End Function ''' <summary> ''' Downloads quotes data. ''' </summary> ''' <param name="unmanagedIDs">The list of unmanaged IDs</param> ''' <param name="properties">The properties of each quote data. If parameter is null/Nothing, Symbol and LastTradePrizeOnly will set as property. In this case, with YQL server you will get every available property.</param> ''' <returns></returns> ''' <remarks></remarks> Public Function Download(ByVal unmanagedIDs As IEnumerable(Of String), ByVal properties As IEnumerable(Of QuoteProperty)) As QuotesResponse If unmanagedIDs Is Nothing Then Throw New ArgumentNullException("unmanagedIDs", "The passed list is null.") Dim prps = Me.GetPropertyArray(properties) Return Me.ToResponse(MyBase.DownloadStream(Me.DownloadURL(mHelper.EnumToArray(unmanagedIDs), prps)), prps) End Function ''' <summary> ''' Starts an asynchronous download of quotes data. ''' </summary> ''' <param name="managedID">The managed ID</param> ''' <param name="properties">The properties of each quote data. If parameter is null/Nothing, Symbol and LastTradePrizeOnly will set as property. In this case, with YQL server you will get every available property.</param> ''' <param name="userArgs">Individual user argument</param> ''' <remarks></remarks> Public Overloads Sub DownloadAsync(ByVal managedID As IID, ByVal properties As IEnumerable(Of QuoteProperty), Optional ByVal userArgs As Object = Nothing) If managedID Is Nothing Then Throw New ArgumentNullException("managedID", "The passed ID is null.") Me.DownloadAsync(managedID.ID, properties, userArgs) End Sub ''' <summary> ''' Starts an asynchronous download of quotes data. ''' </summary> ''' <param name="unmanagedID">The unmanaged ID</param> ''' <param name="properties">The properties of each quote data. If parameter is null/Nothing, Symbol and LastTradePrizeOnly will set as property. In this case, with YQL server you will get every available property.</param> ''' <param name="userArgs">Individual user argument</param> ''' <remarks></remarks> Public Overloads Sub DownloadAsync(ByVal unmanagedID As String, ByVal properties As IEnumerable(Of QuoteProperty), Optional ByVal userArgs As Object = Nothing) If unmanagedID = String.Empty Then Throw New ArgumentNullException("unmanagedID", "The passed ID is empty.") Me.DownloadAsync(New String() {unmanagedID}, properties, userArgs) End Sub ''' <summary> ''' Starts an asynchronous download of quotes data. ''' </summary> ''' <param name="managedIDs">The list of managed IDs</param> ''' <param name="properties">The properties of each quote data. If parameter is null/Nothing, Symbol and LastTradePrizeOnly will set as property. In this case, with YQL server you will get every available property.</param> ''' <param name="userArgs">Individual user argument</param> ''' <remarks></remarks> Public Overloads Sub DownloadAsync(ByVal managedIDs As IEnumerable(Of IID), ByVal properties As IEnumerable(Of QuoteProperty), Optional ByVal userArgs As Object = Nothing) If managedIDs Is Nothing Then Throw New ArgumentNullException("managedIDs", "The passed list is null.") Me.DownloadAsync(mFinanceHelper.IIDsToStrings(managedIDs), properties, userArgs) End Sub ''' <summary> ''' Starts an asynchronous download of quotes data. ''' </summary> ''' <param name="unmanagedIDs">The list of unmanaged IDs</param> ''' <param name="properties">The properties of each quote data. If parameter is null/Nothing, Symbol and LastTradePrizeOnly will set as property. In this case, with YQL server you will get every available property.</param> ''' <param name="userArgs">Individual user argument</param> ''' <remarks></remarks> Public Overloads Sub DownloadAsync(ByVal unmanagedIDs As IEnumerable(Of String), ByVal properties As IEnumerable(Of QuoteProperty), Optional ByVal userArgs As Object = Nothing) If unmanagedIDs Is Nothing Then Throw New ArgumentNullException("unmanagedIDs", "The passed list is null.") Dim prps = Me.GetPropertyArray(properties) Dim args As New AsyncDownloadArgs(userArgs, mHelper.EnumToArray(unmanagedIDs), prps) MyBase.DownloadStreamAsync(Me.DownloadURL(args.IDs, args.Properties), args) End Sub Private Function GetPropertyArray(ByVal properties As IEnumerable(Of QuoteProperty)) As QuoteProperty() If properties Is Nothing Then Throw New ArgumentNullException("properties", "The properties enumerable is null.") Dim prps As New List(Of QuoteProperty)(properties) If prps.Count = 0 Then Throw New ArgumentException("properties", "There must be minimum one property available for downloading.") Return prps.ToArray End Function ''' <summary> ''' Default constructor ''' </summary> ''' <remarks></remarks> Public Sub New() End Sub Private Sub DownloadAsync_Completed(ByVal sender As Base.Download, ByVal e As Base.StreamDownloadCompletedEventArgs) Handles MyBase.AsyncStreamDownloadCompleted If e IsNot Nothing AndAlso e.UserArgs IsNot Nothing AndAlso TypeOf e.UserArgs Is AsyncDownloadArgs Then Dim dlArgs As AsyncDownloadArgs = DirectCast(e.UserArgs, AsyncDownloadArgs) Dim args As New QuotesDownloadCompletedEventArgs(dlArgs.UserArgs, Me.ToResponse(e.Response, dlArgs.Properties), dlArgs.IDs, dlArgs.Properties) RaiseEvent AsyncDownloadCompleted(Me, args) End If End Sub Private Function DownloadURL(ByVal unmanagedIDs As IEnumerable(Of String), ByVal properties() As QuoteProperty) As String Dim lst() As String = mHelper.EnumToArray(unmanagedIDs) If lst.Length > 0 Then Dim ids As New Text.StringBuilder For Each s As String In lst ids.Append(mFinanceHelper.ReplaceDjiID(mHelper.CleanYqlParam(s))) ids.Append("+"c) Next Dim url = "http://download.finance.yahoo.com/d/quotes.csv?s=" & Uri.EscapeDataString(ids.ToString) & "&f=" & mFinanceHelper.CsvQuotePropertyTags(properties) & "&e=.csv" Return url Else Throw New NotSupportedException("An empty id list will not be supported.") End If End Function Private Function ToResponse(ByVal resp As Base.StreamResponse, ByVal properties() As QuoteProperty) As QuotesResponse Dim quotes As New List(Of QuoteData) Dim culture As New Globalization.CultureInfo("en-US") quotes.AddRange(mCsvParser.ToQuotesData(mHelper.StreamToString(resp.Result, mTextEncoding), ","c, properties, culture)) Return New QuotesResponse(resp.Connection, quotes.ToArray) End Function Private Class AsyncDownloadArgs Inherits Base.DownloadEventArgs Public IDs() As String Public Properties() As QuoteProperty Public Sub New(ByVal userArgs As Object, ByVal id() As String, ByVal prps() As QuoteProperty) MyBase.New(userArgs) Me.IDs = id Me.Properties = prps End Sub End Class End Class ''' <summary> ''' Stores the received quotes information of an asynchronous download ''' </summary> ''' <remarks></remarks> Public Class QuotesDownloadCompletedEventArgs Inherits Base.DownloadCompletedEventArgs Private mIDs() As String Private mProperties() As QuoteProperty Public ReadOnly Property IDs() As IEnumerable(Of String) Get Return mIDs End Get End Property ''' <summary> ''' Gets the properties that were queried for each quotes data instance ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property Properties() As QuoteProperty() Get Return mProperties End Get End Property ''' <summary> ''' Gets the response with quotes data. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Overloads ReadOnly Property Response() As QuotesResponse Get Return DirectCast(MyBase.Response, QuotesResponse) End Get End Property Friend Sub New(ByVal userArgs As Object, ByVal resp As QuotesResponse, ByVal ids() As String, ByVal properties() As QuoteProperty) MyBase.New(userArgs, resp) mIDs = ids mProperties = properties End Sub End Class ''' <summary> ''' Provides information and response of an asynchronous quotes download. ''' </summary> ''' <remarks></remarks> Public Class QuotesResponse Inherits Base.Response ''' <summary> ''' Gets the received quotes data. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Overloads ReadOnly Property Result() As QuoteData() Get Return TryCast(MyBase.Result, QuoteData()) End Get End Property Friend Sub New(ByVal info As Base.ConnectionInfo, ByVal result As QuoteData()) MyBase.New(info, result) End Sub End Class End Namespace
agassan/YahooManaged
MaasOne.YahooManaged/YahooManaged/Finance/API/QuotesDownload.vb
Visual Basic
apache-2.0
14,785
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Class SyntaxList Friend Class WithManyChildren Inherits SyntaxList Private ReadOnly _children As ArrayElement(Of SyntaxNode)() Friend Sub New(green As InternalSyntax.SyntaxList, parent As SyntaxNode, position As Integer) MyBase.New(green, parent, position) Me._children = New ArrayElement(Of SyntaxNode)(green.SlotCount - 1) {} End Sub Friend Overrides Function GetNodeSlot(index As Integer) As SyntaxNode Return GetRedElement(Me._children(index).Value, index) End Function Friend Overrides Function GetCachedSlot(i As Integer) As SyntaxNode Return TryCast(Me._children(i).Value, VisualBasicSyntaxNode) End Function End Class End Class End Namespace
DavidKarlas/roslyn
src/Compilers/VisualBasic/Portable/Syntax/SyntaxList.WithManyChildren.vb
Visual Basic
apache-2.0
1,359
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers <ExportCodeCleanupProvider(PredefinedCodeCleanupProviderNames.AddMissingTokens, LanguageNames.VisualBasic), [Shared]> <ExtensionOrder(After:=PredefinedCodeCleanupProviderNames.CaseCorrection, Before:=PredefinedCodeCleanupProviderNames.Format)> Friend Class AddMissingTokensCodeCleanupProvider Inherits AbstractTokensCodeCleanupProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="https://github.com/dotnet/roslyn/issues/42820")> Public Sub New() End Sub Public Overrides ReadOnly Property Name As String Get Return PredefinedCodeCleanupProviderNames.AddMissingTokens End Get End Property Protected Overrides Async Function GetRewriterAsync(document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, cancellationToken As CancellationToken) As Task(Of Rewriter) Return Await AddMissingTokensRewriter.CreateAsync(document, spans, cancellationToken).ConfigureAwait(False) End Function Private Class AddMissingTokensRewriter Inherits AbstractTokensCodeCleanupProvider.Rewriter Private ReadOnly _model As SemanticModel = Nothing Private Sub New(semanticModel As SemanticModel, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) MyBase.New(spans, cancellationToken) Me._model = semanticModel End Sub Public Shared Async Function CreateAsync(document As Document, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) As Task(Of AddMissingTokensRewriter) Dim modifiedSpan = spans.Collapse() Dim semanticModel = If(document Is Nothing, Nothing, Await document.ReuseExistingSpeculativeModelAsync(modifiedSpan, cancellationToken).ConfigureAwait(False)) Return New AddMissingTokensRewriter(semanticModel, spans, cancellationToken) End Function Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode If TypeOf node Is ExpressionSyntax Then Return VisitExpression(DirectCast(node, ExpressionSyntax)) Else Return MyBase.Visit(node) End If End Function Private Function VisitExpression(node As ExpressionSyntax) As SyntaxNode If Not ShouldRewrite(node) Then Return node End If Return AddParenthesesTransform(node, MyBase.Visit(node), Function() ' we only care whole name not part of dotted names Dim name As NameSyntax = TryCast(node, NameSyntax) If name Is Nothing OrElse TypeOf name.Parent Is NameSyntax Then Return False End If Return CheckName(name) End Function, Function(n) DirectCast(n, InvocationExpressionSyntax).ArgumentList, Function(n) SyntaxFactory.InvocationExpression(n, SyntaxFactory.ArgumentList()), Function(n) IsMethodSymbol(DirectCast(n, ExpressionSyntax))) End Function Private Function CheckName(name As NameSyntax) As Boolean If _underStructuredTrivia OrElse name.IsStructuredTrivia() OrElse name.IsMissing Then Return False End If ' can't/don't try to transform member access to invocation If TypeOf name.Parent Is MemberAccessExpressionSyntax OrElse TypeOf name.Parent Is TupleElementSyntax OrElse name.CheckParent(Of AttributeSyntax)(Function(p) p.Name Is name) OrElse name.CheckParent(Of ImplementsClauseSyntax)(Function(p) p.InterfaceMembers.Any(Function(i) i Is name)) OrElse name.CheckParent(Of UnaryExpressionSyntax)(Function(p) p.Kind = SyntaxKind.AddressOfExpression AndAlso p.Operand Is name) OrElse name.CheckParent(Of InvocationExpressionSyntax)(Function(p) p.Expression Is name) OrElse name.CheckParent(Of NamedFieldInitializerSyntax)(Function(p) p.Name Is name) OrElse name.CheckParent(Of ImplementsStatementSyntax)(Function(p) p.Types.Any(Function(t) t Is name)) OrElse name.CheckParent(Of HandlesClauseItemSyntax)(Function(p) p.EventMember Is name) OrElse name.CheckParent(Of ObjectCreationExpressionSyntax)(Function(p) p.Type Is name) OrElse name.CheckParent(Of ArrayCreationExpressionSyntax)(Function(p) p.Type Is name) OrElse name.CheckParent(Of ArrayTypeSyntax)(Function(p) p.ElementType Is name) OrElse name.CheckParent(Of SimpleAsClauseSyntax)(Function(p) p.Type Is name) OrElse name.CheckParent(Of TypeConstraintSyntax)(Function(p) p.Type Is name) OrElse name.CheckParent(Of GetTypeExpressionSyntax)(Function(p) p.Type Is name) OrElse name.CheckParent(Of TypeOfExpressionSyntax)(Function(p) p.Type Is name) OrElse name.CheckParent(Of CastExpressionSyntax)(Function(p) p.Type Is name) OrElse name.CheckParent(Of ForEachStatementSyntax)(Function(p) p.ControlVariable Is name) OrElse name.CheckParent(Of ForStatementSyntax)(Function(p) p.ControlVariable Is name) OrElse name.CheckParent(Of AssignmentStatementSyntax)(Function(p) p.Left Is name) OrElse name.CheckParent(Of TypeArgumentListSyntax)(Function(p) p.Arguments.Any(Function(i) i Is name)) OrElse name.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is name) OrElse name.CheckParent(Of CastExpressionSyntax)(Function(p) p.Type Is name) OrElse name.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.Expression Is name) OrElse name.CheckParent(Of NameOfExpressionSyntax)(Function(p) p.Argument Is name) Then Return False End If Return True End Function Private Function IsMethodSymbol(expression As ExpressionSyntax) As Boolean If Me._model Is Nothing Then Return False End If Dim symbols = Me._model.GetSymbolInfo(expression, _cancellationToken).GetAllSymbols() Return symbols.Any() AndAlso symbols.All( Function(s) (TryCast(s, IMethodSymbol)?.MethodKind).GetValueOrDefault() = MethodKind.Ordinary) End Function Private Function IsDelegateType(expression As ExpressionSyntax) As Boolean If Me._model Is Nothing Then Return False End If Dim type = Me._model.GetTypeInfo(expression, _cancellationToken).Type Return type.IsDelegateType End Function Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode Dim newNode = MyBase.VisitInvocationExpression(node) ' make sure we are not under structured trivia If _underStructuredTrivia Then Return newNode End If If Not TypeOf node.Expression Is NameSyntax AndAlso Not TypeOf node.Expression Is ParenthesizedExpressionSyntax AndAlso Not TypeOf node.Expression Is MemberAccessExpressionSyntax Then Return newNode End If Dim semanticChecker As Func(Of InvocationExpressionSyntax, Boolean) = Function(n) IsMethodSymbol(n.Expression) OrElse IsDelegateType(n.Expression) Return AddParenthesesTransform( node, newNode, Function(n) n.Expression.Span.Length > 0, Function(n) n.ArgumentList, Function(n) n.WithArgumentList(SyntaxFactory.ArgumentList()), semanticChecker) End Function Public Overrides Function VisitRaiseEventStatement(node As RaiseEventStatementSyntax) As SyntaxNode Return AddParenthesesTransform( node, MyBase.VisitRaiseEventStatement(node), Function(n) Not n.Name.IsMissing, Function(n) n.ArgumentList, Function(n) n.WithArgumentList(SyntaxFactory.ArgumentList())) End Function Public Overrides Function VisitMethodStatement(node As MethodStatementSyntax) As SyntaxNode Dim rewrittenMethod = DirectCast(AddParameterListTransform(node, MyBase.VisitMethodStatement(node), Function(n) Not n.Identifier.IsMissing), MethodStatementSyntax) Return AsyncOrIteratorFunctionReturnTypeFixer.RewriteMethodStatement(rewrittenMethod, Me._model, node, Me._cancellationToken) End Function Public Overrides Function VisitSubNewStatement(node As SubNewStatementSyntax) As SyntaxNode Return AddParameterListTransform(node, MyBase.VisitSubNewStatement(node), Function(n) Not n.NewKeyword.IsMissing) End Function Public Overrides Function VisitDeclareStatement(node As DeclareStatementSyntax) As SyntaxNode Return AddParameterListTransform(node, MyBase.VisitDeclareStatement(node), Function(n) Not n.Identifier.IsMissing) End Function Public Overrides Function VisitDelegateStatement(node As DelegateStatementSyntax) As SyntaxNode Return AddParameterListTransform(node, MyBase.VisitDelegateStatement(node), Function(n) Not n.Identifier.IsMissing) End Function Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SyntaxNode If node.AsClause IsNot Nothing Then Return MyBase.VisitEventStatement(node) End If Return AddParameterListTransform(node, MyBase.VisitEventStatement(node), Function(n) Not n.Identifier.IsMissing) End Function Public Overrides Function VisitAccessorStatement(node As AccessorStatementSyntax) As SyntaxNode Dim newNode = MyBase.VisitAccessorStatement(node) If node.DeclarationKeyword.Kind <> SyntaxKind.AddHandlerKeyword AndAlso node.DeclarationKeyword.Kind <> SyntaxKind.RemoveHandlerKeyword AndAlso node.DeclarationKeyword.Kind <> SyntaxKind.RaiseEventKeyword Then Return newNode End If Return AddParameterListTransform(node, newNode, Function(n) Not n.DeclarationKeyword.IsMissing) End Function Public Overrides Function VisitAttribute(node As AttributeSyntax) As SyntaxNode ' we decide not to auto insert parentheses for attribute Return MyBase.VisitAttribute(node) End Function Public Overrides Function VisitOperatorStatement(node As OperatorStatementSyntax) As SyntaxNode ' don't auto insert parentheses ' these methods are okay to be removed. but it is here to show other cases where parse tree node can have parentheses Return MyBase.VisitOperatorStatement(node) End Function Public Overrides Function VisitPropertyStatement(node As PropertyStatementSyntax) As SyntaxNode ' don't auto insert parentheses ' these methods are okay to be removed. but it is here to show other cases where parse tree node can have parentheses Return MyBase.VisitPropertyStatement(node) End Function Public Overrides Function VisitLambdaHeader(node As LambdaHeaderSyntax) As SyntaxNode Dim rewrittenLambdaHeader = DirectCast(MyBase.VisitLambdaHeader(node), LambdaHeaderSyntax) rewrittenLambdaHeader = AsyncOrIteratorFunctionReturnTypeFixer.RewriteLambdaHeader(rewrittenLambdaHeader, Me._model, node, Me._cancellationToken) Return AddParameterListTransform(node, rewrittenLambdaHeader, Function(n) True) End Function Private Shared Function TryFixupTrivia(Of T As SyntaxNode)(node As T, previousToken As SyntaxToken, lastToken As SyntaxToken, ByRef newNode As T) As Boolean ' initialize to initial value newNode = Nothing ' hold onto the trivia Dim prevTrailingTrivia = previousToken.TrailingTrivia ' if previous token is not part of node and if it has any trivia, don't do anything If Not node.DescendantTokens().Any(Function(token) token = previousToken) AndAlso prevTrailingTrivia.Count > 0 Then Return False End If ' remove the trivia from the token Dim previousTokenWithoutTrailingTrivia = previousToken.WithTrailingTrivia(SyntaxFactory.ElasticMarker) ' If previousToken has trailing WhitespaceTrivia, strip off the trailing WhitespaceTrivia from the lastToken. Dim lastTrailingTrivia = lastToken.TrailingTrivia If prevTrailingTrivia.Any(SyntaxKind.WhitespaceTrivia) Then lastTrailingTrivia = lastTrailingTrivia.WithoutLeadingWhitespaceOrEndOfLine() End If ' get the trivia and attach it to the last token Dim lastTokenWithTrailingTrivia = lastToken.WithTrailingTrivia(prevTrailingTrivia.Concat(lastTrailingTrivia)) ' replace tokens newNode = node.ReplaceTokens(SpecializedCollections.SingletonEnumerable(previousToken).Concat(lastToken), Function(o, m) If o = previousToken Then Return previousTokenWithoutTrailingTrivia ElseIf o = lastToken Then Return lastTokenWithTrailingTrivia End If Throw ExceptionUtilities.UnexpectedValue(o) End Function) Return True End Function Private Function AddParameterListTransform(Of T As MethodBaseSyntax)(node As T, newNode As SyntaxNode, nameChecker As Func(Of T, Boolean)) As T Dim transform As Func(Of T, T) = Function(n As T) Dim newParamList = SyntaxFactory.ParameterList() If n.ParameterList IsNot Nothing Then If n.ParameterList.HasLeadingTrivia Then newParamList = newParamList.WithLeadingTrivia(n.ParameterList.GetLeadingTrivia) End If If n.ParameterList.HasTrailingTrivia Then newParamList = newParamList.WithTrailingTrivia(n.ParameterList.GetTrailingTrivia) End If End If Dim nodeWithParams = DirectCast(n.WithParameterList(newParamList), T) If n.HasTrailingTrivia AndAlso nodeWithParams.GetLastToken() = nodeWithParams.ParameterList.CloseParenToken Then Dim trailing = n.GetTrailingTrivia nodeWithParams = DirectCast(n _ .WithoutTrailingTrivia() _ .WithParameterList(newParamList) _ .WithTrailingTrivia(trailing), T) End If Return nodeWithParams End Function Return AddParenthesesTransform(node, newNode, nameChecker, Function(n) n.ParameterList, transform) End Function Private Function AddParenthesesTransform(Of T As SyntaxNode)( originalNode As T, node As SyntaxNode, nameChecker As Func(Of T, Boolean), listGetter As Func(Of T, SyntaxNode), withTransform As Func(Of T, T), Optional semanticPredicate As Func(Of T, Boolean) = Nothing ) As T Dim newNode = DirectCast(node, T) If Not nameChecker(newNode) Then Return newNode End If Dim syntaxPredicate As Func(Of Boolean) = Function() Dim list = listGetter(originalNode) If list Is Nothing Then Return True End If Dim paramList = TryCast(list, ParameterListSyntax) If paramList IsNot Nothing Then Return paramList.Parameters = Nothing AndAlso paramList.OpenParenToken.IsMissing AndAlso paramList.CloseParenToken.IsMissing End If Dim argsList = TryCast(list, ArgumentListSyntax) Return argsList IsNot Nothing AndAlso argsList.Arguments = Nothing AndAlso argsList.OpenParenToken.IsMissing AndAlso argsList.CloseParenToken.IsMissing End Function Return AddParenthesesTransform(originalNode, node, syntaxPredicate, listGetter, withTransform, semanticPredicate) End Function Private Function AddParenthesesTransform(Of T As SyntaxNode)( originalNode As T, node As SyntaxNode, syntaxPredicate As Func(Of Boolean), listGetter As Func(Of T, SyntaxNode), transform As Func(Of T, T), Optional semanticPredicate As Func(Of T, Boolean) = Nothing ) As T Dim span = originalNode.Span If syntaxPredicate() AndAlso _spans.HasIntervalThatContains(span.Start, span.Length) AndAlso CheckSkippedTriviaForMissingToken(originalNode, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken) Then Dim transformedNode = transform(DirectCast(node, T)) ' previous token can be different per different node types. ' it could be name or close paren of type parameter list and etc. also can be different based on ' what token is omitted ' get one that actually exist and get trailing trivia of that token Dim fixedUpNode As T = Nothing Dim list = listGetter(transformedNode) Dim previousToken = list.GetFirstToken(includeZeroWidth:=True).GetPreviousToken(includeZeroWidth:=True) Dim lastToken = list.GetLastToken(includeZeroWidth:=True) If Not TryFixupTrivia(transformedNode, previousToken, lastToken, fixedUpNode) Then Return DirectCast(node, T) End If ' semanticPredicate is invoked at the last step as it is the most expensive operation which requires building the compilation for semantic validations. If semanticPredicate Is Nothing OrElse semanticPredicate(originalNode) Then Return DirectCast(fixedUpNode, T) End If End If Return DirectCast(node, T) End Function Private Shared Function CheckSkippedTriviaForMissingToken(node As SyntaxNode, ParamArray kinds As SyntaxKind()) As Boolean Dim lastToken = node.GetLastToken(includeZeroWidth:=True) If lastToken.TrailingTrivia.Count = 0 Then Return True End If Return Not lastToken _ .TrailingTrivia _ .Where(Function(t) t.Kind = SyntaxKind.SkippedTokensTrivia) _ .SelectMany(Function(t) DirectCast(t.GetStructure(), SkippedTokensTriviaSyntax).Tokens) _ .Any(Function(t) kinds.Contains(t.Kind)) End Function Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As SyntaxNode Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitIfStatement(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword) End Function Public Overrides Function VisitIfDirectiveTrivia(node As IfDirectiveTriviaSyntax) As SyntaxNode Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitIfDirectiveTrivia(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword) End Function Public Overrides Function VisitElseIfStatement(node As ElseIfStatementSyntax) As SyntaxNode Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitElseIfStatement(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword) End Function Public Overrides Function VisitTypeArgumentList(node As TypeArgumentListSyntax) As SyntaxNode Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitTypeArgumentList(node), Function(n) n.OfKeyword, SyntaxKind.OfKeyword) End Function Public Overrides Function VisitTypeParameterList(node As TypeParameterListSyntax) As SyntaxNode Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitTypeParameterList(node), Function(n) n.OfKeyword, SyntaxKind.OfKeyword) End Function Public Overrides Function VisitContinueStatement(node As ContinueStatementSyntax) As SyntaxNode Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitContinueStatement(node), Function(n) n.BlockKeyword, SyntaxKind.DoKeyword, SyntaxKind.ForKeyword, SyntaxKind.WhileKeyword) End Function Public Overrides Function VisitOptionStatement(node As OptionStatementSyntax) As SyntaxNode Select Case node.NameKeyword.Kind Case SyntaxKind.ExplicitKeyword, SyntaxKind.InferKeyword, SyntaxKind.StrictKeyword Return AddMissingOrOmittedTokenTransform(node, node, Function(n) n.ValueKeyword, SyntaxKind.OnKeyword, SyntaxKind.OffKeyword) Case Else Return node End Select End Function Public Overrides Function VisitSelectStatement(node As SelectStatementSyntax) As SyntaxNode Dim newNode = DirectCast(MyBase.VisitSelectStatement(node), SelectStatementSyntax) Return If(newNode.CaseKeyword.Kind = SyntaxKind.None, newNode.WithCaseKeyword(SyntaxFactory.Token(SyntaxKind.CaseKeyword)), newNode) End Function Private Function AddMissingOrOmittedTokenTransform(Of T As SyntaxNode)( originalNode As T, node As SyntaxNode, tokenGetter As Func(Of T, SyntaxToken), ParamArray kinds As SyntaxKind()) As T Dim newNode = DirectCast(node, T) If Not CheckSkippedTriviaForMissingToken(originalNode, kinds) Then Return newNode End If Dim newToken = tokenGetter(newNode) Dim processedToken = ProcessToken(tokenGetter(originalNode), newToken, newNode) If processedToken <> newToken Then Dim replacedNode = ReplaceOrSetToken(newNode, newToken, processedToken) Dim replacedToken = tokenGetter(replacedNode) Dim previousToken = replacedToken.GetPreviousToken(includeZeroWidth:=True) Dim fixedupNode As T = Nothing If Not TryFixupTrivia(replacedNode, previousToken, replacedToken, fixedupNode) Then Return newNode End If Return fixedupNode End If Return newNode End Function Private Function ProcessToken(originalToken As SyntaxToken, token As SyntaxToken, parent As SyntaxNode) As SyntaxToken ' special case omitted token case If IsOmitted(originalToken) Then Return ProcessOmittedToken(originalToken, token, parent) End If Dim span = originalToken.Span If Not _spans.HasIntervalThatContains(span.Start, span.Length) Then ' token is outside of the provided span Return token End If ' token is not missing or if missing token is identifier there is not much we can do If Not originalToken.IsMissing OrElse originalToken.Kind = SyntaxKind.None OrElse originalToken.Kind = SyntaxKind.IdentifierToken Then Return token End If Return ProcessMissingToken(originalToken, token) End Function Private Shared Function ReplaceOrSetToken(Of T As SyntaxNode)(originalParent As T, tokenToFix As SyntaxToken, replacementToken As SyntaxToken) As T If Not IsOmitted(tokenToFix) Then Return originalParent.ReplaceToken(tokenToFix, replacementToken) Else Return DirectCast(SetOmittedToken(originalParent, replacementToken), T) End If End Function Private Shared Function SetOmittedToken(originalParent As SyntaxNode, newToken As SyntaxToken) As SyntaxNode Select Case newToken.Kind Case SyntaxKind.ThenKeyword ' this can be regular If, an If directive, or an ElseIf Dim regularIf = TryCast(originalParent, IfStatementSyntax) If regularIf IsNot Nothing Then Dim previousToken = regularIf.Condition.GetLastToken(includeZeroWidth:=True) Dim nextToken = regularIf.GetLastToken.GetNextToken If Not InvalidOmittedToken(previousToken, nextToken) Then Return regularIf.WithThenKeyword(newToken) End If Else Dim regularElseIf = TryCast(originalParent, ElseIfStatementSyntax) If regularElseIf IsNot Nothing Then Dim previousToken = regularElseIf.Condition.GetLastToken(includeZeroWidth:=True) Dim nextToken = regularElseIf.GetLastToken.GetNextToken If Not InvalidOmittedToken(previousToken, nextToken) Then Return regularElseIf.WithThenKeyword(newToken) End If Else Dim ifDirective = TryCast(originalParent, IfDirectiveTriviaSyntax) If ifDirective IsNot Nothing Then Dim previousToken = ifDirective.Condition.GetLastToken(includeZeroWidth:=True) Dim nextToken = ifDirective.GetLastToken.GetNextToken If Not InvalidOmittedToken(previousToken, nextToken) Then Return ifDirective.WithThenKeyword(newToken) End If End If End If End If Case SyntaxKind.OnKeyword Dim optionStatement = TryCast(originalParent, OptionStatementSyntax) If optionStatement IsNot Nothing Then Return optionStatement.WithValueKeyword(newToken) End If End Select Return originalParent End Function Private Shared Function IsOmitted(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.None End Function Private Shared Function ProcessOmittedToken(originalToken As SyntaxToken, token As SyntaxToken, parent As SyntaxNode) As SyntaxToken ' multiline if statement with missing then keyword case If TypeOf parent Is IfStatementSyntax Then Dim ifStatement = DirectCast(parent, IfStatementSyntax) If Exist(ifStatement.Condition) AndAlso ifStatement.ThenKeyword = originalToken Then Return If(parent.GetAncestor(Of MultiLineIfBlockSyntax)() IsNot Nothing, CreateOmittedToken(token, SyntaxKind.ThenKeyword), token) End If End If If TryCast(parent, IfDirectiveTriviaSyntax)?.ThenKeyword = originalToken Then Return CreateOmittedToken(token, SyntaxKind.ThenKeyword) ElseIf TryCast(parent, ElseIfStatementSyntax)?.ThenKeyword = originalToken Then Return If(parent.GetAncestor(Of ElseIfBlockSyntax)() IsNot Nothing, CreateOmittedToken(token, SyntaxKind.ThenKeyword), token) ElseIf TryCast(parent, OptionStatementSyntax)?.ValueKeyword = originalToken Then Return CreateOmittedToken(token, SyntaxKind.OnKeyword) End If Return token End Function Private Shared Function InvalidOmittedToken(previousToken As SyntaxToken, nextToken As SyntaxToken) As Boolean ' if previous token has a problem, don't bother If previousToken.IsMissing OrElse previousToken.IsSkipped OrElse previousToken.Kind = 0 Then Return True End If ' if next token has a problem, do little bit more check ' if there is no next token, it is okay to insert the missing token If nextToken.Kind = 0 Then Return False End If ' if next token is missing or skipped, check whether it has EOL If nextToken.IsMissing OrElse nextToken.IsSkipped Then Return Not previousToken.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia) And Not nextToken.LeadingTrivia.Any(SyntaxKind.EndOfLineTrivia) End If Return False End Function Private Shared Function Exist(node As SyntaxNode) As Boolean Return node IsNot Nothing AndAlso node.Span.Length > 0 End Function Private Shared Function ProcessMissingToken(originalToken As SyntaxToken, token As SyntaxToken) As SyntaxToken ' auto insert missing "Of" keyword in type argument list If TryCast(originalToken.Parent, TypeArgumentListSyntax)?.OfKeyword = originalToken Then Return CreateMissingToken(token) ElseIf TryCast(originalToken.Parent, TypeParameterListSyntax)?.OfKeyword = originalToken Then Return CreateMissingToken(token) ElseIf TryCast(originalToken.Parent, ContinueStatementSyntax)?.BlockKeyword = originalToken Then Return CreateMissingToken(token) End If Return token End Function Private Shared Function CreateMissingToken(token As SyntaxToken) As SyntaxToken Return CreateToken(token, token.Kind) End Function Private Shared Function CreateOmittedToken(token As SyntaxToken, kind As SyntaxKind) As SyntaxToken Return CreateToken(token, kind) End Function End Class End Class End Namespace
jmarolf/roslyn
src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AddMissingTokensCodeCleanupProvider.vb
Visual Basic
mit
34,601
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class LocalSlotMappingTests Inherits EditAndContinueTestBase <Fact> Public Sub OutOfOrderUserLocals() Dim source = MarkedSource(" Imports System Class C Sub M() For <N:0>index</N:0> As Integer = 1 To 1 Console.WriteLine(1) Next For <N:1>index</N:1> As Integer = 1 To 2 Console.WriteLine(2) Next End Sub End Class ") Dim compilation0 = CreateCompilationWithReferences({source.Tree}, references:=LatestReferences, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source.Tree) Dim v0 = CompileAndVerify(compilation:=compilation0) v0.VerifyIL("C.M", " { // Code size 36 (0x24) .maxstack 2 .locals init (Integer V_0, //index Integer V_1) //index -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 -IL_0003: ldc.i4.1 IL_0004: call ""Sub System.Console.WriteLine(Integer)"" IL_0009: nop -IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: add.ovf IL_000d: stloc.0 ~IL_000e: ldloc.0 IL_000f: ldc.i4.1 IL_0010: ble.s IL_0003 -IL_0012: ldc.i4.1 IL_0013: stloc.1 -IL_0014: ldc.i4.2 IL_0015: call ""Sub System.Console.WriteLine(Integer)"" IL_001a: nop -IL_001b: ldloc.1 IL_001c: ldc.i4.1 IL_001d: add.ovf IL_001e: stloc.1 ~IL_001f: ldloc.1 IL_0020: ldc.i4.2 IL_0021: ble.s IL_0014 -IL_0023: ret } ", sequencePoints:="C.M") v0.VerifyPdb("C.M", " <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <encLocalSlotMap> <slot kind=""0"" offset=""9"" /> <slot kind=""0"" offset=""107"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""12"" document=""0"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""49"" document=""0"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""33"" document=""0"" /> <entry offset=""0xa"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""13"" document=""0"" /> <entry offset=""0xe"" hidden=""true"" document=""0"" /> <entry offset=""0x12"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""49"" document=""0"" /> <entry offset=""0x14"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""33"" document=""0"" /> <entry offset=""0x1b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""13"" document=""0"" /> <entry offset=""0x1f"" hidden=""true"" document=""0"" /> <entry offset=""0x23"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""12"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <namespace name=""System"" importlevel=""file"" /> <currentnamespace name="""" /> <scope startOffset=""0x1"" endOffset=""0x11""> <local name=""index"" il_index=""0"" il_start=""0x1"" il_end=""0x11"" attributes=""0"" /> </scope> <scope startOffset=""0x12"" endOffset=""0x22""> <local name=""index"" il_index=""1"" il_start=""0x12"" il_end=""0x22"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> ") Dim symReader = v0.CreateSymReader() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), Function(handle) symReader.GetEncMethodDebugInfo(handle)) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source, source), preserveLocalVariables:=True))) ' check that all user-defined and long-lived synthesized local slots are reused diff1.VerifyIL("C.M", " { // Code size 36 (0x24) .maxstack 2 .locals init (Integer V_0, //index Integer V_1) //index IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.1 IL_0004: call ""Sub System.Console.WriteLine(Integer)"" IL_0009: nop IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: add.ovf IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: ldc.i4.1 IL_0010: ble.s IL_0003 IL_0012: ldc.i4.1 IL_0013: stloc.1 IL_0014: ldc.i4.2 IL_0015: call ""Sub System.Console.WriteLine(Integer)"" IL_001a: nop IL_001b: ldloc.1 IL_001c: ldc.i4.1 IL_001d: add.ovf IL_001e: stloc.1 IL_001f: ldloc.1 IL_0020: ldc.i4.2 IL_0021: ble.s IL_0014 IL_0023: ret } ") End Sub ' <summary> ' Enc debug info Is only present in debug builds. ' </summary> <Fact> Public Sub DebugOnly() Dim source = <compilation> <file name="a.vb"> Imports System Class C Function F() As System.IDisposable Return Nothing End Function Sub M() Using F() End Using End Sub End Class </file> </compilation> Dim debug = CreateCompilationWithReferences(source, references:=LatestReferences, options:=TestOptions.DebugDll) Dim release = CreateCompilationWithReferences(source, references:=LatestReferences, options:=TestOptions.ReleaseDll) CompileAndVerify(debug).VerifyPdb("C.M", <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="B1, 88, 10, 98, B9, 30, FE, B8, AD, 46, 3F, 5, 46, 9B, AF, A9, 4F, CB, 65, B1, "/> </files> <methods> <method containingType="C" name="M"> <customDebugInfo> <encLocalSlotMap> <slot kind="4" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/> <entry offset="0x1" startLine="8" startColumn="9" endLine="8" endColumn="18" document="1"/> <entry offset="0x9" hidden="true" document="1"/> <entry offset="0xb" startLine="9" startColumn="9" endLine="9" endColumn="18" document="1"/> <entry offset="0x17" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <importsforward declaringType="C" methodName="F"/> </scope> </method> </methods> </symbols>) CompileAndVerify(release).VerifyPdb("C.M", <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="B1, 88, 10, 98, B9, 30, FE, B8, AD, 46, 3F, 5, 46, 9B, AF, A9, 4F, CB, 65, B1, "/> </files> <methods> <method containingType="C" name="M"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="9" endLine="8" endColumn="18" document="1"/> <entry offset="0x7" hidden="true" document="1"/> <entry offset="0x9" startLine="9" startColumn="9" endLine="9" endColumn="18" document="1"/> <entry offset="0x13" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x14"> <importsforward declaringType="C" methodName="F"/> </scope> </method> </methods> </symbols> ) End Sub <Fact> Public Sub ForEach() Dim source = MarkedSource(" Imports System.Collections Imports System.Collections.Generic Class C Function F1() As IEnumerable Return Nothing End Function Function F2() As List(Of Object) Return Nothing End Function Function F3() As IEnumerable Return Nothing End Function Function F4() As List(Of Object) Return Nothing End Function Sub M() <N:4><N:0>For Each x In F1()</N:0> <N:3><N:1>For Each <N:2>y</N:2> As Object In F2()</N:1> : Next</N:3> Next</N:4> <N:8><N:5>For Each x In F4()</N:5> <N:9><N:6>For Each y In F3()</N:6> : Next</N:9> <N:10><N:7>For Each z In F2()</N:7> : Next</N:10> Next</N:8> End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib({source.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source.Tree) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source, source), preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 318 (0x13e) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Object V_1, //x System.Collections.Generic.List(Of Object).Enumerator V_2, Object V_3, //y Boolean V_4, Boolean V_5, System.Collections.Generic.List(Of Object).Enumerator V_6, Object V_7, //x System.Collections.IEnumerator V_8, Object V_9, //y Boolean V_10, System.Collections.Generic.List(Of Object).Enumerator V_11, Object V_12, //z Boolean V_13, Boolean V_14) IL_0000: nop .try { IL_0001: ldarg.0 IL_0002: call ""Function C.F1() As System.Collections.IEnumerable"" IL_0007: callvirt ""Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator"" IL_000c: stloc.0 IL_000d: br.s IL_0056 IL_000f: ldloc.0 IL_0010: callvirt ""Function System.Collections.IEnumerator.get_Current() As Object"" IL_0015: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_001a: stloc.1 .try { IL_001b: ldarg.0 IL_001c: call ""Function C.F2() As System.Collections.Generic.List(Of Object)"" IL_0021: callvirt ""Function System.Collections.Generic.List(Of Object).GetEnumerator() As System.Collections.Generic.List(Of Object).Enumerator"" IL_0026: stloc.2 IL_0027: br.s IL_0037 IL_0029: ldloca.s V_2 IL_002b: call ""Function System.Collections.Generic.List(Of Object).Enumerator.get_Current() As Object"" IL_0030: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0035: stloc.3 IL_0036: nop IL_0037: ldloca.s V_2 IL_0039: call ""Function System.Collections.Generic.List(Of Object).Enumerator.MoveNext() As Boolean"" IL_003e: stloc.s V_4 IL_0040: ldloc.s V_4 IL_0042: brtrue.s IL_0029 IL_0044: leave.s IL_0055 } finally { IL_0046: ldloca.s V_2 IL_0048: constrained. ""System.Collections.Generic.List(Of Object).Enumerator"" IL_004e: callvirt ""Sub System.IDisposable.Dispose()"" IL_0053: nop IL_0054: endfinally } IL_0055: nop IL_0056: ldloc.0 IL_0057: callvirt ""Function System.Collections.IEnumerator.MoveNext() As Boolean"" IL_005c: stloc.s V_5 IL_005e: ldloc.s V_5 IL_0060: brtrue.s IL_000f IL_0062: leave.s IL_0079 } finally { IL_0064: ldloc.0 IL_0065: isinst ""System.IDisposable"" IL_006a: brfalse.s IL_0078 IL_006c: ldloc.0 IL_006d: isinst ""System.IDisposable"" IL_0072: callvirt ""Sub System.IDisposable.Dispose()"" IL_0077: nop IL_0078: endfinally } IL_0079: nop .try { IL_007a: ldarg.0 IL_007b: call ""Function C.F4() As System.Collections.Generic.List(Of Object)"" IL_0080: callvirt ""Function System.Collections.Generic.List(Of Object).GetEnumerator() As System.Collections.Generic.List(Of Object).Enumerator"" IL_0085: stloc.s V_6 IL_0087: br IL_011c IL_008c: ldloca.s V_6 IL_008e: call ""Function System.Collections.Generic.List(Of Object).Enumerator.get_Current() As Object"" IL_0093: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0098: stloc.s V_7 .try { IL_009a: ldarg.0 IL_009b: call ""Function C.F3() As System.Collections.IEnumerable"" IL_00a0: callvirt ""Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator"" IL_00a5: stloc.s V_8 IL_00a7: br.s IL_00b8 IL_00a9: ldloc.s V_8 IL_00ab: callvirt ""Function System.Collections.IEnumerator.get_Current() As Object"" IL_00b0: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_00b5: stloc.s V_9 IL_00b7: nop IL_00b8: ldloc.s V_8 IL_00ba: callvirt ""Function System.Collections.IEnumerator.MoveNext() As Boolean"" IL_00bf: stloc.s V_10 IL_00c1: ldloc.s V_10 IL_00c3: brtrue.s IL_00a9 IL_00c5: leave.s IL_00de } finally { IL_00c7: ldloc.s V_8 IL_00c9: isinst ""System.IDisposable"" IL_00ce: brfalse.s IL_00dd IL_00d0: ldloc.s V_8 IL_00d2: isinst ""System.IDisposable"" IL_00d7: callvirt ""Sub System.IDisposable.Dispose()"" IL_00dc: nop IL_00dd: endfinally } IL_00de: nop .try { IL_00df: ldarg.0 IL_00e0: call ""Function C.F2() As System.Collections.Generic.List(Of Object)"" IL_00e5: callvirt ""Function System.Collections.Generic.List(Of Object).GetEnumerator() As System.Collections.Generic.List(Of Object).Enumerator"" IL_00ea: stloc.s V_11 IL_00ec: br.s IL_00fd IL_00ee: ldloca.s V_11 IL_00f0: call ""Function System.Collections.Generic.List(Of Object).Enumerator.get_Current() As Object"" IL_00f5: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_00fa: stloc.s V_12 IL_00fc: nop IL_00fd: ldloca.s V_11 IL_00ff: call ""Function System.Collections.Generic.List(Of Object).Enumerator.MoveNext() As Boolean"" IL_0104: stloc.s V_13 IL_0106: ldloc.s V_13 IL_0108: brtrue.s IL_00ee IL_010a: leave.s IL_011b } finally { IL_010c: ldloca.s V_11 IL_010e: constrained. ""System.Collections.Generic.List(Of Object).Enumerator"" IL_0114: callvirt ""Sub System.IDisposable.Dispose()"" IL_0119: nop IL_011a: endfinally } IL_011b: nop IL_011c: ldloca.s V_6 IL_011e: call ""Function System.Collections.Generic.List(Of Object).Enumerator.MoveNext() As Boolean"" IL_0123: stloc.s V_14 IL_0125: ldloc.s V_14 IL_0127: brtrue IL_008c IL_012c: leave.s IL_013d } finally { IL_012e: ldloca.s V_6 IL_0130: constrained. ""System.Collections.Generic.List(Of Object).Enumerator"" IL_0136: callvirt ""Sub System.IDisposable.Dispose()"" IL_013b: nop IL_013c: endfinally } IL_013d: ret } ") End Sub <Fact> Public Sub SynthesizedVariablesInLambdas1() Dim source = <compilation> <file name="a.vb"> Imports System.Collections Imports System.Collections.Generic Class C Function F() As System.IDisposable Return Nothing End Function Sub M() Using F() Dim g = Function() Using F() Return Nothing End Using End Function End Using End Sub End Class </file> </compilation> Dim compilation0 = CompilationUtils.CreateCompilationWithReferences(source, references:=LatestReferences, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source) Dim v0 = CompileAndVerify(compilation:=compilation0) v0.VerifyIL("C._Lambda$__2-0()", " { // Code size 27 (0x1b) .maxstack 1 .locals init (Object V_0, System.IDisposable V_1) IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: call ""Function C.F() As System.IDisposable"" IL_0008: stloc.1 .try { IL_0009: ldnull IL_000a: stloc.0 IL_000b: leave.s IL_0019 } finally { IL_000d: nop IL_000e: ldloc.1 IL_000f: brfalse.s IL_0018 IL_0011: ldloc.1 IL_0012: callvirt ""Sub System.IDisposable.Dispose()"" IL_0017: nop IL_0018: endfinally } IL_0019: ldloc.0 IL_001a: ret } ") v0.VerifyPdb("C._Lambda$__2-0", " <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=""CB, 10, 23, 23, 67, CE, AD, BE, 85, D1, 57, F2, D2, CB, 12, A0, 4, 4F, 66, C7, "" /> </files> <methods> <method containingType=""C"" name=""_Lambda$__2-0""> <customDebugInfo> <encLocalSlotMap> <slot kind=""21"" offset=""48"" /> <slot kind=""4"" offset=""80"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""21"" endLine=""11"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""12"" startColumn=""25"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0xd"" startLine=""13"" startColumn=""21"" endLine=""13"" endColumn=""30"" document=""1"" /> <entry offset=""0x19"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""29"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <importsforward declaringType=""C"" methodName=""F"" /> </scope> </method> </methods> </symbols> ") #If TODO Then ' identify the lambda in a semantic edit Dim debugInfoProvider = v0.CreatePdbInfoProvider() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), Function(handle) debugInfoProvider.GetEncMethodDebugInfo(handle)) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) ' check that all user-defined and long-lived synthesized local slots are reused diff1.VerifyIL("C._Lambda$__1", " ") #End If End Sub <Fact> Public Sub SynthesizedVariablesInIterator() Dim source = <compilation> <file name="a.vb"> Imports System.Collections Imports System.Collections.Generic Class C Function F() As System.IDisposable Return Nothing End Function Iterator Function M() As IEnumerable(Of Integer) Using F() Yield 1 End Using Yield 2 End Function End Class </file> </compilation> Dim compilation0 = CompilationUtils.CreateCompilationWithReferences(source, references:=LatestReferences, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source) Dim v0 = CompileAndVerify(compilation:=compilation0) v0.VerifyIL("C.VB$StateMachine_2_M.MoveNext()", " { // Code size 192 (0xc0) .maxstack 3 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: switch ( IL_001f, IL_0021, IL_0021, IL_0023) IL_001d: br.s IL_0028 IL_001f: br.s IL_002a IL_0021: br.s IL_0046 IL_0023: br IL_00b3 IL_0028: ldc.i4.0 IL_0029: ret IL_002a: ldarg.0 IL_002b: ldc.i4.m1 IL_002c: dup IL_002d: stloc.1 IL_002e: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_0033: nop IL_0034: nop IL_0035: ldarg.0 IL_0036: ldarg.0 IL_0037: ldfld ""C.VB$StateMachine_2_M.$VB$Me As C"" IL_003c: callvirt ""Function C.F() As System.IDisposable"" IL_0041: stfld ""C.VB$StateMachine_2_M.$S0 As System.IDisposable"" IL_0046: nop .try { IL_0047: ldloc.1 IL_0048: ldc.i4.1 IL_0049: beq.s IL_0053 IL_004b: br.s IL_004d IL_004d: ldloc.1 IL_004e: ldc.i4.2 IL_004f: beq.s IL_0055 IL_0051: br.s IL_0057 IL_0053: br.s IL_007a IL_0055: br.s IL_0059 IL_0057: br.s IL_0066 IL_0059: ldarg.0 IL_005a: ldc.i4.m1 IL_005b: dup IL_005c: stloc.1 IL_005d: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_0062: ldc.i4.1 IL_0063: stloc.0 IL_0064: leave.s IL_00be IL_0066: ldarg.0 IL_0067: ldc.i4.1 IL_0068: stfld ""C.VB$StateMachine_2_M.$Current As Integer"" IL_006d: ldarg.0 IL_006e: ldc.i4.1 IL_006f: dup IL_0070: stloc.1 IL_0071: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_0076: ldc.i4.1 IL_0077: stloc.0 IL_0078: leave.s IL_00be IL_007a: ldarg.0 IL_007b: ldc.i4.m1 IL_007c: dup IL_007d: stloc.1 IL_007e: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_0083: leave.s IL_00a1 } finally { IL_0085: ldloc.1 IL_0086: ldc.i4.0 IL_0087: bge.s IL_00a0 IL_0089: nop IL_008a: ldarg.0 IL_008b: ldfld ""C.VB$StateMachine_2_M.$S0 As System.IDisposable"" IL_0090: brfalse.s IL_009e IL_0092: ldarg.0 IL_0093: ldfld ""C.VB$StateMachine_2_M.$S0 As System.IDisposable"" IL_0098: callvirt ""Sub System.IDisposable.Dispose()"" IL_009d: nop IL_009e: br.s IL_00a0 IL_00a0: endfinally } IL_00a1: ldarg.0 IL_00a2: ldc.i4.2 IL_00a3: stfld ""C.VB$StateMachine_2_M.$Current As Integer"" IL_00a8: ldarg.0 IL_00a9: ldc.i4.3 IL_00aa: dup IL_00ab: stloc.1 IL_00ac: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_00b1: ldc.i4.1 IL_00b2: ret IL_00b3: ldarg.0 IL_00b4: ldc.i4.m1 IL_00b5: dup IL_00b6: stloc.1 IL_00b7: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_00bc: ldc.i4.0 IL_00bd: ret IL_00be: ldloc.0 IL_00bf: ret } ") v0.VerifyPdb("C+VB$StateMachine_2_M.MoveNext", " <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="" E, DD, DB, BF, A5, 4D, 75, 50, 39, C6, 6C, D8, 6D, 49, 1B, 2A, 56, 79, F8, E8, "" /> </files> <methods> <method containingType=""C+VB$StateMachine_2_M"" name=""MoveNext""> <customDebugInfo> <encLocalSlotMap> <slot kind=""20"" offset=""-1"" /> <slot kind=""27"" offset=""-1"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""53"" document=""1"" /> <entry offset=""0x34"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" /> <entry offset=""0x46"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" hidden=""true"" document=""1"" /> <entry offset=""0x66"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x83"" hidden=""true"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0x89"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""18"" document=""1"" /> <entry offset=""0xa0"" hidden=""true"" document=""1"" /> <entry offset=""0xa1"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""16"" document=""1"" /> <entry offset=""0xbc"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""17"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc0""> <importsforward declaringType=""C"" methodName=""F"" /> </scope> </method> </methods> </symbols> ") End Sub <Fact> Public Sub SynthesizedVariablesInAsyncMethod() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Class C Function F() As System.IDisposable Return Nothing End Function Async Function M() As Task(Of Integer) Using F() End Using Await Task.FromResult(10) Return 2 End Function End Class </file> </compilation> Dim compilation0 = CompilationUtils.CreateCompilationWithReferences(source, references:=LatestReferences, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source) Dim v0 = CompileAndVerify(compilation:=compilation0) v0.VerifyIL("C.VB$StateMachine_2_M.MoveNext()", " { // Code size 233 (0xe9) .maxstack 3 .locals init (Integer V_0, Integer V_1, System.Threading.Tasks.Task(Of Integer) V_2, System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_3, C.VB$StateMachine_2_M V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_007a IL_000e: nop IL_000f: nop IL_0010: ldarg.0 IL_0011: ldarg.0 IL_0012: ldfld ""C.VB$StateMachine_2_M.$VB$Me As C"" IL_0017: callvirt ""Function C.F() As System.IDisposable"" IL_001c: stfld ""C.VB$StateMachine_2_M.$S0 As System.IDisposable"" .try { IL_0021: leave.s IL_003f } finally { IL_0023: ldloc.1 IL_0024: ldc.i4.0 IL_0025: bge.s IL_003e IL_0027: nop IL_0028: ldarg.0 IL_0029: ldfld ""C.VB$StateMachine_2_M.$S0 As System.IDisposable"" IL_002e: brfalse.s IL_003c IL_0030: ldarg.0 IL_0031: ldfld ""C.VB$StateMachine_2_M.$S0 As System.IDisposable"" IL_0036: callvirt ""Sub System.IDisposable.Dispose()"" IL_003b: nop IL_003c: br.s IL_003e IL_003e: endfinally } IL_003f: ldc.i4.s 10 IL_0041: call ""Function System.Threading.Tasks.Task.FromResult(Of Integer)(Integer) As System.Threading.Tasks.Task(Of Integer)"" IL_0046: callvirt ""Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"" IL_004b: stloc.3 IL_004c: ldloca.s V_3 IL_004e: call ""Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"" IL_0053: brtrue.s IL_0098 IL_0055: ldarg.0 IL_0056: ldc.i4.0 IL_0057: dup IL_0058: stloc.1 IL_0059: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_005e: ldarg.0 IL_005f: ldloc.3 IL_0060: stfld ""C.VB$StateMachine_2_M.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"" IL_0065: ldarg.0 IL_0066: ldflda ""C.VB$StateMachine_2_M.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"" IL_006b: ldloca.s V_3 IL_006d: ldarg.0 IL_006e: stloc.s V_4 IL_0070: ldloca.s V_4 IL_0072: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), C.VB$StateMachine_2_M)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef C.VB$StateMachine_2_M)"" IL_0077: nop IL_0078: leave.s IL_00e8 IL_007a: ldarg.0 IL_007b: ldc.i4.m1 IL_007c: dup IL_007d: stloc.1 IL_007e: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_0083: ldarg.0 IL_0084: ldfld ""C.VB$StateMachine_2_M.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"" IL_0089: stloc.3 IL_008a: ldarg.0 IL_008b: ldflda ""C.VB$StateMachine_2_M.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"" IL_0090: initobj ""System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"" IL_0096: br.s IL_0098 IL_0098: ldloca.s V_3 IL_009a: call ""Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"" IL_009f: pop IL_00a0: ldloca.s V_3 IL_00a2: initobj ""System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"" IL_00a8: ldc.i4.2 IL_00a9: stloc.0 IL_00aa: leave.s IL_00d1 } catch System.Exception { IL_00ac: dup IL_00ad: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_00b2: stloc.s V_5 IL_00b4: ldarg.0 IL_00b5: ldc.i4.s -2 IL_00b7: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_00bc: ldarg.0 IL_00bd: ldflda ""C.VB$StateMachine_2_M.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"" IL_00c2: ldloc.s V_5 IL_00c4: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"" IL_00c9: nop IL_00ca: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_00cf: leave.s IL_00e8 } IL_00d1: ldarg.0 IL_00d2: ldc.i4.s -2 IL_00d4: dup IL_00d5: stloc.1 IL_00d6: stfld ""C.VB$StateMachine_2_M.$State As Integer"" IL_00db: ldarg.0 IL_00dc: ldflda ""C.VB$StateMachine_2_M.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"" IL_00e1: ldloc.0 IL_00e2: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"" IL_00e7: nop IL_00e8: ret } ") v0.VerifyPdb("C+VB$StateMachine_2_M.MoveNext", " <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=""30, DD, 7D, 76, D3, C3, 98, A6, 4F, 3D, 96, F9, 8C, 84, 5B, EC, EC, 10, 83, C7, "" /> </files> <methods> <method containingType=""C+VB$StateMachine_2_M"" name=""MoveNext""> <customDebugInfo> <encLocalSlotMap> <slot kind=""20"" offset=""-1"" /> <slot kind=""27"" offset=""-1"" /> <slot kind=""0"" offset=""-1"" /> <slot kind=""33"" offset=""38"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""43"" document=""1"" /> <entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""18"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x23"" hidden=""true"" document=""1"" /> <entry offset=""0x27"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" /> <entry offset=""0x3e"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""34"" document=""1"" /> <entry offset=""0x4c"" hidden=""true"" document=""1"" /> <entry offset=""0xa8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""17"" document=""1"" /> <entry offset=""0xac"" hidden=""true"" document=""1"" /> <entry offset=""0xb4"" hidden=""true"" document=""1"" /> <entry offset=""0xd1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""17"" document=""1"" /> <entry offset=""0xdb"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe9""> <importsforward declaringType=""C"" methodName=""F"" /> </scope> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""M"" /> <await yield=""0x5e"" resume=""0x7a"" declaringType=""C+VB$StateMachine_2_M"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols> ") End Sub End Class End Namespace
droyad/roslyn
src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/LocalSlotMappingTests.vb
Visual Basic
apache-2.0
35,715
' 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 Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDelegateWithDynamicArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { delegate void myDelegate(dynamic d); void Foo() { dynamic d = 1; myDelegate {|Definition:del|} = n => { Console.WriteLine(n); }; [|$$del|](d); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestIndexerWithStaticParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { public int {|Definition:$$this|}[int i] { get { } } public int this[dynamic i] { get { } } } class B { public void Foo() { A a = new A(); dynamic d = 1; var a1 = a[||][1]; var a2 = a["hello"]; var a3 = a[||][d]; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestIndexerWithDynamicParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { public int this[int i] { get { } } public int {|Definition:$$this|}[dynamic i] { get { } } } class B { public void Foo() { A a = new A(); dynamic d = 1; var a1 = a[1]; var a2 = a[||]["hello"]; var a3 = a[||][d]; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function End Class End Namespace
Pvlerick/roslyn
src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicDelegatesAndIndexers.vb
Visual Basic
apache-2.0
2,209
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class XmlLiteralTests Inherits BasicTestBase <Fact()> Public Sub XDocumentTypesMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Sub Add(o As Object) End Sub End Class Public Class XElement Inherits XContainer Public Sub New(o As Object) End Sub End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XDocumentTypesMissing"> <file name="c.vb"><![CDATA[ Option Strict On Class C Private F As Object = <?xml version="1.0"?><x/><?p?> End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'XDeclaration' from assembly or module 'XDocumentTypesMissing.dll' failed. Private F As Object = <?xml version="1.0"?><x/><?p?> ~~~~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'XDocument' from assembly or module 'XDocumentTypesMissing.dll' failed. Private F As Object = <?xml version="1.0"?><x/><?p?> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'XProcessingInstruction' from assembly or module 'XDocumentTypesMissing.dll' failed. Private F As Object = <?xml version="1.0"?><x/><?p?> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XCommentTypeMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XCommentTypeMissing"> <file name="c.vb"><![CDATA[ Option Strict On Class C Private F As Object = <!-- comment --> End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'XComment' from assembly or module 'XCommentTypeMissing.dll' failed. Private F As Object = <!-- comment --> ~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XElementTypeMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Function Elements(o As Object) As Object Return Nothing End Function End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Module InternalXmlHelper End Module End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XElementTypeMissing"> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class C Private F1 As XContainer = <x/> Private F2 As Object = F1.<x> Private F3 As Object = F1.@x End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'XElement' from assembly or module 'XElementTypeMissing.dll' failed. Private F1 As XContainer = <x/> ~ BC31091: Import of type 'XElement' from assembly or module 'XElementTypeMissing.dll' failed. Private F3 As Object = F1.@x ~~~~~ BC36808: XML attributes cannot be selected from type 'XContainer'. Private F3 As Object = F1.@x ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XElementConstructorInaccessible() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class Public Class XName End Class Public Class XElement Friend Sub New(o As Object) End Sub End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class C Private F1 As XName = Nothing Private F2 As Object = <<%= F1 %>/> End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30517: Overload resolution failed because no 'New' is accessible. Private F2 As Object = <<%= F1 %>/> ~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XAttributeTypeMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Sub Add(o As Object) End Sub End Class Public Class XElement Inherits XContainer Public Sub New(o As Object) End Sub End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class Public Class XNamespace End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Class StandardModuleAttribute : Inherits System.Attribute End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XAttributeTypeMissing"> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class C Private F1 As Object = <x <%= Nothing %>/> Private F2 As Object = <x <%= "a" %>="b"/> Private F3 As Object = <x a=<%= "b" %>/> End Class Namespace My Public Module InternalXmlHelper Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As Object, o As Object) As Object Return Nothing End Function End Module End Namespace ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'XAttribute' from assembly or module 'XAttributeTypeMissing.dll' failed. Private F2 As Object = <x <%= "a" %>="b"/> ~~~~~~~~~~~~~~ BC30456: 'CreateAttribute' is not a member of 'InternalXmlHelper'. Private F3 As Object = <x a=<%= "b" %>/> ~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XAttributeConstructorMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Sub Add(o As Object) End Sub End Class Public Class XElement Inherits XContainer Public Sub New(o As Object) End Sub End Class Public Class XAttribute Public Sub New(o As Object) End Sub End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class Public Class XNamespace End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Class StandardModuleAttribute : Inherits System.Attribute End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XAttributeTypeMissing"> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class C Private F1 As Object = <x <%= Nothing %>/> Private F2 As Object = <x <%= "a" %>="b"/> Private F3 As Object = <x a=<%= "b" %>/> End Class Namespace My Public Module InternalXmlHelper Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As List(Of XAttribute), o As Object) As Object Return Nothing End Function End Module End Namespace ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30057: Too many arguments to 'Public Sub New(o As Object)'. Private F2 As Object = <x <%= "a" %>="b"/> ~~~ BC30456: 'CreateAttribute' is not a member of 'InternalXmlHelper'. Private F3 As Object = <x a=<%= "b" %>/> ~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XNameTypeMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Sub Add(o As Object) End Sub End Class Public Class XElement Inherits XContainer Public Sub New(o As Object) End Sub End Class Public Class XAttribute Public Sub New(x As Object, y As Object) End Sub End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Module InternalXmlHelper End Module End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XNameTypeMissing"> <file name="c.vb"><![CDATA[ Option Strict On Class C Private F1 As Object = <x/> Private F2 As Object = <<%= Nothing %> a="b"/> End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'XName' from assembly or module 'XNameTypeMissing.dll' failed. Private F1 As Object = <x/> ~ BC31091: Import of type 'XName' from assembly or module 'XNameTypeMissing.dll' failed. Private F2 As Object = <<%= Nothing %> a="b"/> ~ ]]></errors>) End Sub <Fact()> Public Sub XContainerTypeMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class Public Class XElement Public Sub New(o As Object) End Sub End Class Public Class XAttribute Public Sub New(x As Object, y As Object) End Sub End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Module InternalXmlHelper End Module End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XContainerTypeMissing"> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class C Private F1 As XElement = <x/> Private F2 As XElement = <x a="b"/> Private F3 As XElement = <x>c</> Private F4 As XElement = F1.<x> End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed. Private F2 As XElement = <x a="b"/> ~~~~~~~~~~ BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed. Private F3 As XElement = <x>c</> ~~~~~~~ BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed. Private F4 As XElement = F1.<x> ~~~~~~ BC36807: XML elements cannot be selected from type 'XElement'. Private F4 As XElement = F1.<x> ~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XContainerMemberNotInvocable() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Add As Object End Class Public Class XElement Inherits XContainer Public Sub New(o As Object) End Sub End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C Private F As Object = <x>c</> End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30456: 'Add' is not a member of 'XContainer'. Private F As Object = <x>c</> ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XCDataTypeMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="XCDataTypeMissing"> <file name="c.vb"> Option Strict On Module M Private F As Object = &lt;![CDATA[value]]&gt; End Module </file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors> BC31091: Import of type 'XCData' from assembly or module 'XCDataTypeMissing.dll' failed. Private F As Object = &lt;![CDATA[value]]&gt; ~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub XNamespaceTypeMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Namespace System.Xml.Linq Public Class XObject End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XNamespaceTypeMissing"> <file name="c.vb"><![CDATA[ Class C Private F = GetXmlNamespace() End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'XNamespace' from assembly or module 'XNamespaceTypeMissing.dll' failed. Private F = GetXmlNamespace() ~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XNamespaceTypeMissing_2() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Sub Add(o As Object) End Sub Public Function Elements(o As Object) As IEnumerable(Of XContainer) Return Nothing End Function End Class Public Class XElement Inherits XContainer Public Sub New(o As Object) End Sub End Class Public Class XAttribute Public Sub New(o As Object) End Sub End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XNamespaceTypeMissing_2"> <file name="c.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/"> Class C Private F = <x><%= Nothing %></> End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'InternalXmlHelper' from assembly or module 'XNamespaceTypeMissing_2.dll' failed. Private F = <x><%= Nothing %></> ~~~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'XNamespace' from assembly or module 'XNamespaceTypeMissing_2.dll' failed. Private F = <x><%= Nothing %></> ~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub XNamespaceGetMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Sub Add(o As Object) End Sub Public Function Elements(o As Object) As IEnumerable(Of XContainer) Return Nothing End Function End Class Public Class XElement Inherits XContainer Public Sub New(o As Object) End Sub End Class Public Class XAttribute Public Sub New(o As Object) End Sub End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class Public Class XNamespace End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Class StandardModuleAttribute : Inherits System.Attribute End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="XNamespaceGetMissing"> <file name="c.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/"> Imports System.Collections.Generic Imports System.Xml.Linq Class C Shared F As Object = <p:x><%= Nothing %></> End Class Namespace My Public Module InternalXmlHelper Public Function CreateNamespaceAttribute(name As XName, ns As XNamespace) As XAttribute Return Nothing End Function Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As Object, o As Object) As Object Return Nothing End Function End Module End Namespace ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30456: 'Get' is not a member of 'XNamespace'. Shared F As Object = <p:x><%= Nothing %></> ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub ExtensionTypesMissing() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer Public Sub Add(o As Object) End Sub Public Function Elements(o As Object) As IEnumerable(Of XContainer) Return Nothing End Function End Class Public Class XElement Inherits XContainer Public Sub New(o As Object) End Sub End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation name="ExtensionTypesMissing"> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class C Private F1 As XElement = <x/> Private F2 As Object = F1.<x> Private F3 As Object = F1.<x>.<y> Private F4 As Object = F1.@x End Class ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'Extensions' from assembly or module 'ExtensionTypesMissing.dll' failed. Private F3 As Object = F1.<x>.<y> ~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'IEnumerable(Of XContainer)'. Private F3 As Object = F1.<x>.<y> ~~~~~~~~~~ BC31091: Import of type 'InternalXmlHelper' from assembly or module 'ExtensionTypesMissing.dll' failed. Private F4 As Object = F1.@x ~~~~~ BC36808: XML attributes cannot be selected from type 'XElement'. Private F4 As Object = F1.@x ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub ExtensionMethodAndPropertyMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Namespace System.Xml.Linq Public Class XObject End Class Public Class XContainer End Class Public Class XElement Inherits XContainer End Class Public Class XName Public Shared Function [Get](localName As String, [namespace] As String) As XName Return Nothing End Function End Class Public Module Extensions End Module End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Class StandardModuleAttribute : Inherits System.Attribute End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class C Private F1 As XElement = Nothing Private F2 As Object = F1.<x> Private F3 As Object = F1.@x End Class Namespace My Public Module InternalXmlHelper End Module End Namespace ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30456: 'Elements' is not a member of 'XContainer'. Private F2 As Object = F1.<x> ~~~~~~ BC36807: XML elements cannot be selected from type 'XElement'. Private F2 As Object = F1.<x> ~~~~~~ BC30456: 'AttributeValue' is not a member of 'InternalXmlHelper'. Private F3 As Object = F1.@x ~~~~~ BC36808: XML attributes cannot be selected from type 'XElement'. Private F3 As Object = F1.@x ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub ValueExtensionPropertyMissing() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Namespace System.Xml.Linq Public Class XObject End Class Public Class XElement End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Class StandardModuleAttribute : Inherits System.Attribute End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class C Function F(x As IEnumerable(Of XElement)) As String Return x.Value End Function End Class Namespace My Public Module InternalXmlHelper End Module End Namespace ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Return x.Value ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub ValueExtensionPropertyUnexpectedSignature() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Imports System.Collections.Generic Imports System.Xml.Linq Namespace System.Xml.Linq Public Class XObject End Class Public Class XElement End Class End Namespace Namespace Microsoft.VisualBasic.CompilerServices Public Class StandardModuleAttribute : Inherits System.Attribute End Class End Namespace ]]></file> </compilation>) compilation1.AssertNoErrors() Dim compilation2 = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class C Function F(x As IEnumerable(Of XElement)) As String Return x.VALUE End Function End Class Namespace My Public Module InternalXmlHelper Public ReadOnly Property Value(x As IEnumerable(Of XElement), y As Object, z As Object) As Object Get Return Nothing End Get End Property End Module End Namespace ]]></file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Return x.VALUE ~~~~~~~ ]]></errors>) End Sub End Class End Namespace
OmarTawfik/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/XmlLiteralsTests_UseSiteErrors.vb
Visual Basic
apache-2.0
28,500
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Implements" keyword ''' </summary> Friend Class ImplementsKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword) Dim targetToken = context.TargetToken Dim typeBlock = targetToken.GetAncestor(Of TypeBlockSyntax)() If TypeOf typeBlock Is InterfaceBlockSyntax Then Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End If If context.IsAfterStatementOfKind( SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.ImplementsStatement, SyntaxKind.InheritsStatement) Then Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("Implements", VBFeaturesResources.Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears)) End If If context.IsFollowingParameterListOrAsClauseOfMethodDeclaration() OrElse context.IsFollowingCompletePropertyDeclaration(cancellationToken) OrElse context.IsFollowingCompleteEventDeclaration() Then If typeBlock IsNot Nothing Then ' We need to check to see if any of the partial types parts declare an implements statement. ' If not, we don't show the Implements keyword. Dim typeSymbol = context.SemanticModel.GetDeclaredSymbol(typeBlock) If typeSymbol IsNot Nothing Then For Each reference In typeSymbol.DeclaringSyntaxReferences Dim typeStatement = TryCast(reference.GetSyntax(), TypeStatementSyntax) If typeStatement IsNot Nothing AndAlso TypeOf typeStatement.Parent Is TypeBlockSyntax AndAlso DirectCast(typeStatement.Parent, TypeBlockSyntax).Implements.Count > 0 Then Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("Implements", VBFeaturesResources.Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface)) End If Next End If End If End If Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End Function End Class End Namespace
mmitche/roslyn
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/ImplementsKeywordRecommender.vb
Visual Basic
apache-2.0
3,153
''' <summary> ''' Dynamic wrapper around any <see cref="JsonValue" />. ''' </summary> <DebuggerDisplay("JsonDynamic: Value = {Value}")> Public Structure JsonDynamic ''' <summary> ''' Tests if this is JSON null. ''' </summary> Public ReadOnly Property IsNull As Boolean Get Return Me._value Is Nothing End Get End Property ''' <summary> ''' Tests if this is JSON object. ''' </summary> Public ReadOnly Property IsObject As Boolean Get Return TypeOf Me._value Is JsonObject End Get End Property ''' <summary> ''' Tests if this is JSON array. ''' </summary> Public ReadOnly Property IsArray As Boolean Get Return TypeOf Me._value Is JsonArray End Get End Property ''' <summary> ''' Tests if this is JSON string or number or boolean or null. ''' </summary> Public ReadOnly Property IsScalar As Boolean Get If Me._value Is Nothing Then Return True End If Return Not Me._value.IsObject AndAlso Not Me._value.IsArray End Get End Property ''' <summary> ''' Tests if this is JSON string. ''' </summary> Public ReadOnly Property IsString As Boolean Get Return TypeOf Me._value Is JsonString End Get End Property ''' <summary> ''' Test if this is JSON number. ''' </summary> Public ReadOnly Property IsNumber As Boolean Get Return TypeOf Me._value Is JsonNumber End Get End Property ''' <summary> ''' Tests if this is JSON boolean. ''' </summary> Public ReadOnly Property IsBoolean As Boolean Get Return TypeOf Me._value Is JsonBool End Get End Property ''' <summary> ''' Gets the number of items in array or members in object of the dynamic type. ''' </summary> ''' <exception cref="InvalidCastException">Underlying JSON value is not object or array.</exception> Public ReadOnly Property Count As Integer Get Me.ThrowIfValueIsNull() If Me._value.IsObject Then Return Me._value.AsObject().Count ElseIf Me._value.IsArray Then Return Me._value.AsArray().Count End If Throw New InvalidCastException("Json value is not object nor array.") End Get End Property ''' <summary> ''' Gets the wrapped value. ''' </summary> Public ReadOnly Property Value As JsonValue Get Return _value End Get End Property Friend ReadOnly _value As JsonValue ''' <summary> ''' Gets the memeber indexed by given <paramref name="key" />. ''' </summary> ''' <param name="key">Key of the member to return.</param> ''' <value>Member stored under given <paramref name="key" />.</value> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is Nothing.</exception> ''' <exception cref="KeyNotFoundException">The property is retrieved and <paramref name="key" /> is not found.</exception> ''' <exception cref="InvalidCastException">If underlying JSON value is not object.</exception> Default Public Property Item(key As String) As JsonDynamic Get Me.ThrowIfValueIsNull() Return Me._value.AsObject()(key).ToDynamic() End Get Set(value As JsonDynamic) Me.ThrowIfValueIsNull() Me._value.AsObject()(key) = value.Value End Set End Property ''' <summary> ''' Gets the item stored on given <paramref name="index" />. ''' </summary> ''' <param name="index">Index of the item to return.</param> ''' <value>Item stored under given <paramref name="key" />.</value> ''' <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> is less than 0 or is equal or more than <see cref="Count" />.</exception> ''' <exception cref="InvalidCastException">If underlying JSON value is not array.</exception> Default Public Property Item(index As Integer) As JsonDynamic Get Me.ThrowIfValueIsNull() Return Me._value.AsArray()(index).ToDynamic() End Get Set(value As JsonDynamic) Me.ThrowIfValueIsNull() Me._value.AsArray()(index) = value.Value End Set End Property ''' <summary> ''' Creates new dynamic wrapper around specified <see cref="JsonValue" />. ''' </summary> ''' <param name="value">The value to wrap as dynamic type. Value can be null.</param> Public Sub New(value As JsonValue) Me._value = value End Sub #Region "Object Methods" ''' <summary> ''' Adds an member with the specified key to this object. ''' </summary> ''' <param name="key">The key of the element to add.</param> ''' <param name="value">The value of the element to add. The value can be null.</param> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is null.</exception> ''' <exception cref="ArgumentException">An property with the same <paramref name="key" /> already exists.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Sub Add(key As String, value As JsonValue) Me.ThrowIfValueIsNull() Me._value.AsObject().Add(key, value) End Sub ''' <summary> ''' Adds an empty array property and returns it's instance. ''' </summary> ''' <param name="key">The key of the array to add.</param> ''' <returns>The added array as dynamic.</returns> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is null.</exception> ''' <exception cref="ArgumentException">An property with the same <paramref name="key" /> already exists.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Function AddArray(key As String) As JsonDynamic Me.ThrowIfValueIsNull() Return Me._value.AsObject().AddArray(key).ToDynamic() End Function ''' <summary> ''' Adds an empty object property and returns its instance. ''' </summary> ''' <param name="key">The key of the object to add.</param> ''' <returns>The added objec tas dynamic.</returns> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is null.</exception> ''' <exception cref="ArgumentException">An property with the same <paramref name="key" /> already exists.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Function AddObject(key As String) As JsonDynamic Return Me._value.AsObject().AddObject(key).ToDynamic() End Function ''' <summary> ''' Gets value stored under given key and returns it as dynamic type. If not such member exists than defaultValue ''' is returned. ''' </summary> ''' <param name="key">The key under which is member stored.</param> ''' <param name="defaultValue">Default value returned in case no such member exists.</param> ''' <returns>Value stored under given key as dynamic.</returns> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is null.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Function GetOrDefault(key As String, Optional defaultValue As JsonValue = Nothing) As JsonDynamic Me.ThrowIfValueIsNull() Return Me._value.AsObject().GetOrDefault(key, defaultValue).ToDynamic() End Function ''' <summary> ''' Gets value stored under given key and casts it to dynamic type. If not such member exists than defaultValue ''' is returned. ''' </summary> ''' <param name="key">The key under which is member stored.</param> ''' <param name="defaultValue">Default value returned in case no such member exists.</param> ''' <returns>Value stored under given key as dynamic.</returns> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is Nothing.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Function GetOrDefault(key As String, defaultValue As JsonDynamic) As JsonDynamic Me.ThrowIfValueIsNull() Return Me.GetOrDefault(key, defaultValue.Value) End Function ''' <summary> ''' Gets the member stored under given key. If key does not exist provided value is stored as new member. ''' </summary> ''' <param name="key">The key under which is array stored.</param> ''' <param name="addValue">The value to add if specified member does not exist.</param> ''' <returns>Value stored under given key casted to dynamic.</returns> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is Nothing.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Function GetOrAdd(key As String, addValue As JsonValue) As JsonDynamic Me.ThrowIfValueIsNull() Return Me._value.AsObject().GetOrAdd(key, addValue).ToDynamic() End Function ''' <summary> ''' Gets the member stored under given key. If key does not exist provided value is stored as new member. ''' </summary> ''' <param name="key">The key under which is array stored.</param> ''' <param name="addValue">The value to add if specified member does not exist.</param> ''' <returns>Value stored under given key casted to dynamic.</returns> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is Nothing.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Function GetOrAdd(key As String, addValue As JsonDynamic) As JsonDynamic Me.ThrowIfValueIsNull() Return Me.GetOrAdd(key, addValue.Value) End Function ''' <summary> ''' Tests whether the object contains a member with the specified key. It does not check the value of the member ''' which might be null. ''' </summary> ''' <param name="key">The key of the member to find.</param> ''' <returns>True if member with specified key member is defined in the object.</returns> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is null.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Function ContainsKey(key As String) As Boolean Me.ThrowIfValueIsNull() Return Me._value.AsObject().ContainsKey(key) End Function ''' <summary> ''' Tests whether the object contains a member with the specified key and which is not null. ''' </summary> ''' <param name="key">The key of the member to find.</param> ''' <returns>true if member with specified key exists and is not null.</returns> ''' <remarks>Equivalent to Me.ContainsKey(key) AndAlso Me(key) IsNot Nothing.</remarks> ''' <exception cref="ArgumentNullException"><paramref name="key" /> is null.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonObject" />.</exception> Public Function ContainsKeyNotNull(key As String) As Boolean Me.ThrowIfValueIsNull() Return Me._value.AsObject().ContainsKeyNotNull(key) End Function #End Region #Region "Array Methods" ''' <summary> ''' Adds an items to the end of the array. ''' </summary> ''' <param name="item">Value to add.</param> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonArray" />.</exception> Public Sub Add(item As JsonValue) Me.ThrowIfValueIsNull() Me._value.AsArray().Add(item) End Sub ''' <summary> ''' Adds an empty array to the end of the array and returns its instance. ''' </summary> ''' <returns>The added array as dynamic.</returns> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonArray" />.</exception> Public Function AddArray() As JsonDynamic Me.ThrowIfValueIsNull() Return Me._value.AsArray().AddArray().ToDynamic() End Function ''' <summary> ''' Adds an empty object and returns its instance. ''' </summary> ''' <returns>The added object as dynamic.</returns> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonArray" />.</exception> Public Function AddObject() As JsonDynamic Me.ThrowIfValueIsNull() Return Me._value.AsArray().AddObject().ToDynamic() End Function ''' <summary> ''' Adds the values of the specified collection to the end of the array. ''' </summary> ''' <param name="items">Collection of items to add.</param> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonArray" />.</exception> Public Sub AddRange(items As IEnumerable(Of JsonValue)) Me.ThrowIfValueIsNull() Me._value.AsArray().AddRange(items) End Sub ''' <summary> ''' Inserts an value into the array at the specified index. ''' </summary> ''' <param name="index">The zero-based index at which item should be inserted.</param> ''' <param name="item">The object to insert. The value can be null.</param> ''' <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> is less than 0 or is equal or more than <see cref="Count" />.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonArray" />.</exception> Public Sub Insert(index As Integer, item As JsonValue) Me.ThrowIfValueIsNull() Me._value.AsArray().Insert(index, item) End Sub ''' <summary> ''' Inserts an empty array at the specified index and returns its instance. ''' </summary> ''' <param name="index">The zero-based index at which item should be inserted.</param> ''' <returns>The inserted array as dynamic.</returns> ''' <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> is less than 0 or is equal or more than <see cref="Count" />.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonArray" />.</exception> Public Function InsertArray(index As Integer) As JsonDynamic Me.ThrowIfValueIsNull() Return Me._value.AsArray().InsertArray(index).ToDynamic() End Function ''' <summary> ''' Adds an empty object at the specified index and returns its instance. ''' </summary> ''' <param name="index">The zero-based index at which item should be inserted.</param> ''' <returns>The inserted object as dynamic.</returns> ''' <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> is less than 0 or is equal or more than <see cref="Count" />.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonArray" />.</exception> Public Function InsertObject(index As Integer) As JsonDynamic Me.ThrowIfValueIsNull() Return Me._value.AsArray().InsertObject(index).ToDynamic() End Function ''' <summary> ''' Inserts the values of a collection into the array at the specified index. ''' </summary> ''' <param name="index">The zero-based index at which items should be inserted.</param> ''' <param name="items">The collection of items which will be inserted to the specified position in the array. The collection can contains items whose value is null.</param> ''' <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> is less than 0 or is equal or more than <see cref="Count" />.</exception> ''' <exception cref="ArgumentNullException"><paramref name="items" /> is null.</exception> ''' <exception cref="InvalidCastException">If this object does not wrap <see cref="JsonArray" />.</exception> Public Sub InsertRange(index As Integer, items As IEnumerable(Of JsonValue)) Me.ThrowIfValueIsNull() Me._value.AsArray().InsertRange(index, items) End Sub #End Region #Region "GetHashCode(), Equals()" ''' <summary> ''' Determines whether current object is equal to another object. ''' </summary> ''' <param name="obj">The object to compare with the current object.</param> ''' <returns>True if the current object is equal to this, false otherwise.</returns> Public Overrides Function Equals(obj As Object) As Boolean If TypeOf obj Is JsonDynamic Then Dim other = CType(obj, JsonDynamic) Return Me.Equals(other) ElseIf TypeOf obj Is JsonValue Then Dim other = CType(obj, JsonValue) Return Me.Equals(other) ElseIf Me._value Is Nothing Then ' me represents null Return Object.Equals(obj, Nothing) Else Return False End If End Function ''' <summary> ''' Determines whether current object is equal to another object. ''' </summary> ''' <param name="other">The object to compare with the current object.</param> ''' <returns>True if the current object is equal to this, false otherwise.</returns> Public Overloads Function Equals(other As JsonDynamic) As Boolean If Me._value IsNot Nothing Then Return Me._value.Equals(other._value) ElseIf other._value IsNot Nothing Then Return False Else Return True End If End Function ''' <summary> ''' Determines whether current object is equal to another object. ''' </summary> ''' <param name="other">The object to compare with the current object.</param> ''' <returns>True if the current object is equal to this, false otherwise.</returns> Public Overloads Function Equals(other As JsonValue) As Boolean If Me._value IsNot Nothing Then Return Me._value.Equals(other) ElseIf other IsNot Nothing Then Return False Else Return True End If End Function ''' <summary> ''' Serves as a hash function for a particular type. ''' </summary> ''' <returns>A hash code for the current <see cref="T:System.Object"/>.</returns> Public Overrides Function GetHashCode() As Integer If Me._value Is Nothing Then Return 0 Else Return Me._value.GetHashCode() End If End Function #End Region #Region "Operators" ''' <summary> ''' Test whether values of its operands are equal. ''' </summary> ''' <param name="former">First value to compare.</param> ''' <param name="latter">Second value to compare.</param> ''' <returns>True if <paramref name="former" /> is equal to <paramref name="latter" />.</returns> Public Shared Operator =(former As JsonDynamic, latter As JsonDynamic) As Boolean Return former.Equals(latter) End Operator ''' <summary> ''' Test whether values of its operands are inequal. ''' </summary> ''' <param name="former">First value to compare.</param> ''' <param name="latter">Second value to compare.</param> ''' <returns>True if <paramref name="former" /> is inequal to <paramref name="latter" />.</returns> Public Shared Operator <>(former As JsonDynamic, latter As JsonDynamic) As Boolean Return Not former = latter End Operator ''' <summary> ''' Performs an explicit conversion from <see cref="JsonValue" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Narrowing Operator CType(value As JsonValue) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an explicit conversion from <see cref="JsonDynamic" /> to <see cref="JsonValue" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonValue" /> casted from the specified value.</returns> Public Shared Narrowing Operator CType(value As JsonDynamic) As JsonValue Return value._value End Operator ''' <summary> ''' Performs an implicit conversion from <see cref="String" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As String) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from <see cref="Boolean" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Boolean) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from nullable <see cref="Boolean" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Boolean?) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from <see cref="Integer" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Integer) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from <see cref="Integer" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Integer?) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from <see cref="Long" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Long) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from nullable <see cref="Long" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Long?) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from <see cref="Single" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Single) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from nullable <see cref="Single" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Single?) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from <see cref="Double" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Double) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from nullable <see cref="Double" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Double?) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from <see cref="Decimal" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Decimal) As JsonDynamic Return New JsonDynamic(value) End Operator ''' <summary> ''' Performs an implicit conversion from nullable <see cref="Decimal" /> to <see cref="JsonDynamic" />. ''' </summary> ''' <param name="value">The value to convert.</param> ''' <returns>The <see cref="JsonDynamic" /> casted from the specified value.</returns> Public Shared Widening Operator CType(value As Decimal?) As JsonDynamic Return New JsonDynamic(value) End Operator #End Region ''' <summary> ''' Gets to JSON encoded string representing this object. ''' </summary> ''' <returns>JSON string</returns> Public Function ToJson() As String Return JsonParser.Encode(Me._value, JsonEncoderOptions.ToStringDefault) End Function Private Sub ThrowIfValueIsNull() If Me._value Is Nothing Then Throw New InvalidCastException("Cannot cast dynamic null to requested type.") End If End Sub End Structure
mancze/jsonie
Jsonie/Source/JsonDynamic.vb
Visual Basic
mit
24,384
Option Infer On Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim documents As SolidEdgeFramework.Documents = Nothing Dim draftDocument As SolidEdgeDraft.DraftDocument = Nothing Dim sheet As SolidEdgeDraft.Sheet = Nothing Dim centerLines As SolidEdgeFrameworkSupport.CenterLines = Nothing Dim centerLine As SolidEdgeFrameworkSupport.CenterLine = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) documents = application.Documents draftDocument = CType(documents.Add("SolidEdge.DraftDocument"), SolidEdgeDraft.DraftDocument) sheet = draftDocument.ActiveSheet centerLines = CType(sheet.CenterLines, SolidEdgeFrameworkSupport.CenterLines) centerLine = centerLines.Add(0.25, 0.15, 0, 0.25, 0.35, 0) centerLine.Rotate(Math.PI / 2, 0.25, 0.15) Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeFrameworkSupport.CenterLine.Rotate.vb
Visual Basic
mit
1,656
Imports System.Threading Public Class Form9 Dim str(5) As String Dim itm As ListViewItem #Region " ClientAreaMove Handling " Const WM_NCHITTEST As Integer = &H84 Const HTCLIENT As Integer = &H1 Const HTCAPTION As Integer = &H2 Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) Select Case m.Msg Case WM_NCHITTEST MyBase.WndProc(m) If m.Result = HTCLIENT Then m.Result = HTCAPTION Case Else MyBase.WndProc(m) End Select End Sub #End Region Private Sub PictureBox1_MouseHover(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles PictureBox1.MouseHover PictureBox1.Image = My.Resources.ResourceManager.GetObject("green_close_hover") End Sub Private Sub PictureBox1_leave(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles PictureBox1.MouseLeave PictureBox1.Image = My.Resources.ResourceManager.GetObject("green_close_normal") End Sub Private Sub PictureBox1_down(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles PictureBox1.MouseDown PictureBox1.Image = My.Resources.ResourceManager.GetObject("green_close_press") End Sub Private Sub PictureBox1_up(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles PictureBox1.MouseUp PictureBox1.Image = My.Resources.ResourceManager.GetObject("green_close_hover") End Sub Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click Me.Hide() Timer1.Enabled = False End Sub Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.ShowInTaskbar = False Me.Opacity = Form1.Opacity End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click getprocess() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click On Error Resume Next Dim n = ListView1.CheckedItems.Count Dim x If n = 0 Then Else For Each item In ListView1.CheckedItems x = item.SubItems(2).Text() Dim p As Process = Process.GetProcessById(x) If p Is Nothing Then Return If Not p.CloseMainWindow() Then p.Kill() p.WaitForExit() p.Close() item.remove() Next End If End Sub Function getprocess() Dim processes() As Process = System.Diagnostics.Process.GetProcesses() Dim p For Each proc As Process In processes Try str(0) = proc.ProcessName str(1) = proc.MainModule.FileName str(2) = proc.Id.ToString str(3) = proc.BasePriority.ToString() str(4) = proc.WorkingSet64.ToString() p = check(proc.Id.ToString) If p = 1 Then itm = New ListViewItem(str) ListView1.Items.Add(itm) End If Catch ex As Exception End Try Next recheck() End Function Function check(ByVal pid As String) Dim n = ListView1.Items.Count Dim x If n = 0 Then check = 1 Exit Function End If For Each item In ListView1.Items x = ListView1.FindItemWithText(pid) If x Is Nothing Then check = 1 Else check = 0 End If Next End Function Function recheck() Dim n = ListView1.Items.Count Dim x Dim processes() As Process = System.Diagnostics.Process.GetProcesses() Dim p If n = 0 Then Else For Each item In ListView1.Items x = item.SubItems(2).Text For Each proc As Process In processes If proc.Id.ToString = x Then p = 1 Exit For Else p = 0 End If Next If p = 0 Then item.remove() End If Next End If End Function Function dofirst() Me.getprocess() Timer1.Enabled = True End Function Private Sub RefreshToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshToolStripMenuItem.Click getprocess() End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick getprocess() 'realtime End Sub Private Sub KillProcessToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles KillProcessToolStripMenuItem.Click On Error Resume Next Dim n = ListView1.SelectedItems.Count Dim x If n = 0 Then Else For Each item In ListView1.SelectedItems x = item.SubItems(2).Text() Dim p As Process = Process.GetProcessById(x) If p Is Nothing Then Return If Not p.CloseMainWindow() Then p.Kill() p.WaitForExit() p.Close() item.remove() Next End If getprocess() End Sub Private Sub RepeatedKillToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RepeatedKillToolStripMenuItem.Click On Error Resume Next Dim n = ListView1.SelectedItems.Count Dim x If n = 0 Then Else For Each item In ListView1.SelectedItems x = item.SubItems(0).Text() Form1.ListView4.Items.Add(x) item.remove() Next End If End Sub End Class
pratheeshrussell/Autorun-Processor
Autorun Processor/Form9.vb
Visual Basic
mit
6,241
'//////////////////////////////////////////////////////////////////////// ' Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved. ' ' This file is part of Aspose.Words. The source code in this file ' is only intended as a supplement to the documentation, and is provided ' "as is", without warranty of any kind, either expressed or implied. '//////////////////////////////////////////////////////////////////////// Imports Microsoft.VisualBasic Imports System Imports System.IO Imports System.Reflection Imports Aspose.Words Imports Aspose.Words.Saving Public Class SaveAsMultipageTiff Public Shared Sub Run() ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir_RenderingAndPrinting() ' Open the document. Dim doc As New Document(dataDir & "TestFile Multipage TIFF.doc") ' Save the document as multipage TIFF. doc.Save(dataDir & "TestFile Multipage TIFF.doc Out.tiff") 'Create an ImageSaveOptions object to pass to the Save method Dim options As New ImageSaveOptions(SaveFormat.Tiff) options.PageIndex = 0 options.PageCount = 2 options.TiffCompression = TiffCompression.Ccitt4 options.Resolution = 160 doc.Save(dataDir & "TestFileWithOptions Out.tiff", options) Console.WriteLine(vbNewLine & "Document saved as multi-page TIFF successfully." & vbNewLine & "File saved at " + dataDir + "TestFileWithOptions Out.tiff") End Sub End Class
dtscal/Aspose_Words_NET
Examples/VisualBasic/Rendering-Printing/SaveAsMultipageTiff.vb
Visual Basic
mit
1,511
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.17929 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("serial_communication.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
mmgreenhacker/CodeFinal
serial communication/serial communication/My Project/Resources.Designer.vb
Visual Basic
mit
2,726
Public Class Lists Private token As OauthTokens Friend Sub New(ByVal t As OauthTokens) token = t End Sub ''' <summary> ''' Return the UserListObjectList of selected ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function List(Optional ByVal parameter As RequestParam = Nothing) As Task(Of ResponseObject(Of ListObjectList)) Return Await Task.Run(Function() token.Lists.List(parameter)) End Function ''' <summary> ''' Get statuses of selected list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Statuses(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of StatusObjectList)) Return Await Task.Run(Function() token.Lists.Statuses(parameter)) End Function ''' <summary> ''' Delete selected member of the list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function MembersDestroy(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of String)) Return Await Task.Run(Function() token.Lists.MembersDestroy(parameter)) End Function ''' <summary> ''' Show the Memberships of the user ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Memberships(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObjectWithCursorList)) Return Await Task.Run(Function() token.Lists.Memberships(parameter)) End Function ''' <summary> ''' Show the Ownerships of the user ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function OwnerShips(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObjectWithCursorList)) Return Await Task.Run(Function() token.Lists.OwnerShips(parameter)) End Function ''' <summary> ''' Get subscribers ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Subscribers(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of UserObjectListWithCursor)) Return Await Task.Run(Function() token.Lists.Subscribers(parameter)) End Function ''' <summary> ''' Make a subscriber ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function SubscribersCreate(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.SubscribersCreate(parameter)) End Function ''' <summary> ''' If the user is subscriber, will return userobject ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function SubscribersShow(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of UserObject)) Return Await Task.Run(Function() token.Lists.SubscribersShow(parameter)) End Function ''' <summary> ''' Unread the list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function SubscribersDestroy(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.SubscribersDestroy(parameter)) End Function ''' <summary> ''' Add members to the selected list ''' </summary> ''' <param name="ScreenNames">ScreenNames</param> ''' <param name="parameter">Parameters</param> Public Async Function MembersCreateAll(ByVal ScreenNames As String(), ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.MembersCreateAll(ScreenNames, parameter)) End Function ''' <summary> ''' Add members to the selected list ''' </summary> ''' <param name="Ids">Ids</param> ''' <param name="parameter">Parameters</param> Public Async Function MembersCreateAll(ByVal Ids As Decimal(), ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.MembersCreateAll(Ids, parameter)) End Function ''' <summary> ''' Destroy members from the selected list ''' </summary> ''' <param name="ScreenNames">ScreenNames</param> ''' <param name="parameter">Parameters</param> Public Async Function MembersDestroyAll(ByVal ScreenNames As String(), ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.MembersDestroyAll(ScreenNames, parameter)) End Function ''' <summary> ''' Destroy members from the selected list ''' </summary> ''' <param name="Ids">Ids</param> ''' <param name="parameter">Parameters</param> Public Async Function MembersDestroyAll(ByVal Ids As Decimal(), ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.MembersDestroyAll(Ids, parameter)) End Function ''' <summary> ''' If selected user is a member of the list, will return UserObject ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function MembersShow(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of UserObject)) Return Await Task.Run(Function() token.Lists.MembersShow(parameter)) End Function ''' <summary> ''' Get members of the list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Members(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of UserObjectListWithCursor)) Return Await Task.Run(Function() token.Lists.Members(parameter)) End Function ''' <summary> ''' Add a member to the list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function MembersCreate(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of UserObject)) Return Await Task.Run(Function() token.Lists.MembersCreate(parameter)) End Function ''' <summary> ''' Destroy the selected list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Destroy(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.Destroy(parameter)) End Function ''' <summary> ''' Update the selected list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Update(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.Update(parameter)) End Function ''' <summary> ''' Create the new list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Create(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.Create(parameter)) End Function ''' <summary> ''' Show the selected list ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Show(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObject)) Return Await Task.Run(Function() token.Lists.Show(parameter)) End Function ''' <summary> ''' Show the subscriptions that is reading ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Subscriptions(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of ListObjectWithCursorList)) Return Await Task.Run(Function() token.Lists.Subscriptions(parameter)) End Function End Class
szr2000/FistTwit
FistTwit.Async/Methods/Lists.vb
Visual Basic
mit
7,631
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class QuestRequirements Inherits System.Windows.Forms.Form 'Form esegue l'override del metodo Dispose per pulire l'elenco dei componenti. <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 'Richiesto da Progettazione Windows Form Private components As System.ComponentModel.IContainer 'NOTA: la procedura che segue è richiesta da Progettazione Windows Form 'Può essere modificata in Progettazione Windows Form. 'Non modificarla nell'editor del codice. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(QuestRequirements)) Me.TabControl1 = New System.Windows.Forms.TabControl() Me.tabCreature = New System.Windows.Forms.TabPage() Me.Label17 = New System.Windows.Forms.Label() Me.Label14 = New System.Windows.Forms.Label() Me.Label13 = New System.Windows.Forms.Label() Me.Label9 = New System.Windows.Forms.Label() Me.Label6 = New System.Windows.Forms.Label() Me.txtObj1 = New System.Windows.Forms.TextBox() Me.txtObj2 = New System.Windows.Forms.TextBox() Me.txtObj3 = New System.Windows.Forms.TextBox() Me.txtObj4 = New System.Windows.Forms.TextBox() Me.Label1 = New System.Windows.Forms.Label() Me.Label8 = New System.Windows.Forms.Label() Me.Label11 = New System.Windows.Forms.Label() Me.Label12 = New System.Windows.Forms.Label() Me.numCreatureCount4 = New System.Windows.Forms.NumericUpDown() Me.numCreatureCount3 = New System.Windows.Forms.NumericUpDown() Me.numCreatureCount2 = New System.Windows.Forms.NumericUpDown() Me.numCreatureCount1 = New System.Windows.Forms.NumericUpDown() Me.lblCreatureName4 = New System.Windows.Forms.Label() Me.lblCreatureId4 = New System.Windows.Forms.Label() Me.numCreature4 = New System.Windows.Forms.NumericUpDown() Me.lblCreatureName3 = New System.Windows.Forms.Label() Me.lblCreatureId3 = New System.Windows.Forms.Label() Me.numCreature3 = New System.Windows.Forms.NumericUpDown() Me.lblCreatureName2 = New System.Windows.Forms.Label() Me.lblCreatureId2 = New System.Windows.Forms.Label() Me.numCreature2 = New System.Windows.Forms.NumericUpDown() Me.lblCreatureName1 = New System.Windows.Forms.Label() Me.lblCreatureId1 = New System.Windows.Forms.Label() Me.numCreature1 = New System.Windows.Forms.NumericUpDown() Me.tabItems = New System.Windows.Forms.TabPage() Me.Label10 = New System.Windows.Forms.Label() Me.Label7 = New System.Windows.Forms.Label() Me.Label5 = New System.Windows.Forms.Label() Me.Label4 = New System.Windows.Forms.Label() Me.Label3 = New System.Windows.Forms.Label() Me.Label2 = New System.Windows.Forms.Label() Me.numCount6 = New System.Windows.Forms.NumericUpDown() Me.numCount5 = New System.Windows.Forms.NumericUpDown() Me.numCount4 = New System.Windows.Forms.NumericUpDown() Me.numCount3 = New System.Windows.Forms.NumericUpDown() Me.numCount2 = New System.Windows.Forms.NumericUpDown() Me.numCount1 = New System.Windows.Forms.NumericUpDown() Me.lblItemName6 = New System.Windows.Forms.Label() Me.lblItemName5 = New System.Windows.Forms.Label() Me.lblItemName4 = New System.Windows.Forms.Label() Me.lblItemId6 = New System.Windows.Forms.Label() Me.lblItemId5 = New System.Windows.Forms.Label() Me.lblItemId4 = New System.Windows.Forms.Label() Me.numitemId6 = New System.Windows.Forms.NumericUpDown() Me.numitemId5 = New System.Windows.Forms.NumericUpDown() Me.numItemId4 = New System.Windows.Forms.NumericUpDown() Me.lblItemName3 = New System.Windows.Forms.Label() Me.lblItemId3 = New System.Windows.Forms.Label() Me.numItemId3 = New System.Windows.Forms.NumericUpDown() Me.lblItemName2 = New System.Windows.Forms.Label() Me.lblItemId2 = New System.Windows.Forms.Label() Me.numItemId2 = New System.Windows.Forms.NumericUpDown() Me.lblItemName1 = New System.Windows.Forms.Label() Me.lblItemId1 = New System.Windows.Forms.Label() Me.numItemId1 = New System.Windows.Forms.NumericUpDown() Me.tabFactions = New System.Windows.Forms.TabPage() Me.Label18 = New System.Windows.Forms.Label() Me.lblFactionName2 = New System.Windows.Forms.Label() Me.lblFactionName1 = New System.Windows.Forms.Label() Me.Label15 = New System.Windows.Forms.Label() Me.Label16 = New System.Windows.Forms.Label() Me.numFactionValue2 = New System.Windows.Forms.NumericUpDown() Me.numFactionValue1 = New System.Windows.Forms.NumericUpDown() Me.lblFactionID2 = New System.Windows.Forms.Label() Me.numFaction2 = New System.Windows.Forms.NumericUpDown() Me.lblFactionID1 = New System.Windows.Forms.Label() Me.numFaction1 = New System.Windows.Forms.NumericUpDown() Me.btnCancel = New System.Windows.Forms.Button() Me.btnSave = New System.Windows.Forms.Button() Me.TabControl1.SuspendLayout() Me.tabCreature.SuspendLayout() CType(Me.numCreatureCount4, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCreatureCount3, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCreatureCount2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCreatureCount1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCreature4, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCreature3, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCreature2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCreature1, System.ComponentModel.ISupportInitialize).BeginInit() Me.tabItems.SuspendLayout() CType(Me.numCount6, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCount5, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCount4, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCount3, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCount2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numCount1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numitemId6, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numitemId5, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numItemId4, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numItemId3, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numItemId2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numItemId1, System.ComponentModel.ISupportInitialize).BeginInit() Me.tabFactions.SuspendLayout() CType(Me.numFactionValue2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numFactionValue1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numFaction2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.numFaction1, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'TabControl1 ' Me.TabControl1.Controls.Add(Me.tabCreature) Me.TabControl1.Controls.Add(Me.tabItems) Me.TabControl1.Controls.Add(Me.tabFactions) Me.TabControl1.Location = New System.Drawing.Point(9, 10) Me.TabControl1.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.TabControl1.Name = "TabControl1" Me.TabControl1.SelectedIndex = 0 Me.TabControl1.Size = New System.Drawing.Size(332, 301) Me.TabControl1.TabIndex = 0 ' 'tabCreature ' Me.tabCreature.Controls.Add(Me.Label17) Me.tabCreature.Controls.Add(Me.Label14) Me.tabCreature.Controls.Add(Me.Label13) Me.tabCreature.Controls.Add(Me.Label9) Me.tabCreature.Controls.Add(Me.Label6) Me.tabCreature.Controls.Add(Me.txtObj1) Me.tabCreature.Controls.Add(Me.txtObj2) Me.tabCreature.Controls.Add(Me.txtObj3) Me.tabCreature.Controls.Add(Me.txtObj4) Me.tabCreature.Controls.Add(Me.Label1) Me.tabCreature.Controls.Add(Me.Label8) Me.tabCreature.Controls.Add(Me.Label11) Me.tabCreature.Controls.Add(Me.Label12) Me.tabCreature.Controls.Add(Me.numCreatureCount4) Me.tabCreature.Controls.Add(Me.numCreatureCount3) Me.tabCreature.Controls.Add(Me.numCreatureCount2) Me.tabCreature.Controls.Add(Me.numCreatureCount1) Me.tabCreature.Controls.Add(Me.lblCreatureName4) Me.tabCreature.Controls.Add(Me.lblCreatureId4) Me.tabCreature.Controls.Add(Me.numCreature4) Me.tabCreature.Controls.Add(Me.lblCreatureName3) Me.tabCreature.Controls.Add(Me.lblCreatureId3) Me.tabCreature.Controls.Add(Me.numCreature3) Me.tabCreature.Controls.Add(Me.lblCreatureName2) Me.tabCreature.Controls.Add(Me.lblCreatureId2) Me.tabCreature.Controls.Add(Me.numCreature2) Me.tabCreature.Controls.Add(Me.lblCreatureName1) Me.tabCreature.Controls.Add(Me.lblCreatureId1) Me.tabCreature.Controls.Add(Me.numCreature1) Me.tabCreature.Location = New System.Drawing.Point(4, 22) Me.tabCreature.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.tabCreature.Name = "tabCreature" Me.tabCreature.Padding = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.tabCreature.Size = New System.Drawing.Size(324, 275) Me.tabCreature.TabIndex = 0 Me.tabCreature.Text = "Creature" Me.tabCreature.UseVisualStyleBackColor = True ' 'Label17 ' Me.Label17.AutoSize = True Me.Label17.Location = New System.Drawing.Point(4, 171) Me.Label17.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label17.Name = "Label17" Me.Label17.Size = New System.Drawing.Size(246, 13) Me.Label17.TabIndex = 57 Me.Label17.Text = "Here you can change the standard objective texts:" ' 'Label14 ' Me.Label14.AutoSize = True Me.Label14.Location = New System.Drawing.Point(4, 189) Me.Label14.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label14.Name = "Label14" Me.Label14.Size = New System.Drawing.Size(37, 13) Me.Label14.TabIndex = 56 Me.Label14.Text = "Text1:" ' 'Label13 ' Me.Label13.AutoSize = True Me.Label13.Location = New System.Drawing.Point(4, 212) Me.Label13.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label13.Name = "Label13" Me.Label13.Size = New System.Drawing.Size(37, 13) Me.Label13.TabIndex = 56 Me.Label13.Text = "Text2:" ' 'Label9 ' Me.Label9.AutoSize = True Me.Label9.Location = New System.Drawing.Point(4, 235) Me.Label9.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label9.Name = "Label9" Me.Label9.Size = New System.Drawing.Size(37, 13) Me.Label9.TabIndex = 56 Me.Label9.Text = "Text3:" ' 'Label6 ' Me.Label6.AutoSize = True Me.Label6.Location = New System.Drawing.Point(4, 258) Me.Label6.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label6.Name = "Label6" Me.Label6.Size = New System.Drawing.Size(37, 13) Me.Label6.TabIndex = 56 Me.Label6.Text = "Text4:" ' 'txtObj1 ' Me.txtObj1.Location = New System.Drawing.Point(47, 187) Me.txtObj1.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.txtObj1.Name = "txtObj1" Me.txtObj1.Size = New System.Drawing.Size(263, 20) Me.txtObj1.TabIndex = 55 ' 'txtObj2 ' Me.txtObj2.Location = New System.Drawing.Point(47, 210) Me.txtObj2.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.txtObj2.Name = "txtObj2" Me.txtObj2.Size = New System.Drawing.Size(263, 20) Me.txtObj2.TabIndex = 55 ' 'txtObj3 ' Me.txtObj3.Location = New System.Drawing.Point(47, 232) Me.txtObj3.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.txtObj3.Name = "txtObj3" Me.txtObj3.Size = New System.Drawing.Size(263, 20) Me.txtObj3.TabIndex = 55 ' 'txtObj4 ' Me.txtObj4.Location = New System.Drawing.Point(47, 255) Me.txtObj4.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.txtObj4.Name = "txtObj4" Me.txtObj4.Size = New System.Drawing.Size(263, 20) Me.txtObj4.TabIndex = 55 ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Location = New System.Drawing.Point(258, 131) Me.Label1.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(38, 13) Me.Label1.TabIndex = 51 Me.Label1.Text = "Count:" ' 'Label8 ' Me.Label8.AutoSize = True Me.Label8.Location = New System.Drawing.Point(258, 90) Me.Label8.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label8.Name = "Label8" Me.Label8.Size = New System.Drawing.Size(38, 13) Me.Label8.TabIndex = 52 Me.Label8.Text = "Count:" ' 'Label11 ' Me.Label11.AutoSize = True Me.Label11.Location = New System.Drawing.Point(258, 49) Me.Label11.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label11.Name = "Label11" Me.Label11.Size = New System.Drawing.Size(38, 13) Me.Label11.TabIndex = 53 Me.Label11.Text = "Count:" ' 'Label12 ' Me.Label12.AutoSize = True Me.Label12.Location = New System.Drawing.Point(258, 9) Me.Label12.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label12.Name = "Label12" Me.Label12.Size = New System.Drawing.Size(38, 13) Me.Label12.TabIndex = 54 Me.Label12.Text = "Count:" ' 'numCreatureCount4 ' Me.numCreatureCount4.Location = New System.Drawing.Point(260, 145) Me.numCreatureCount4.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCreatureCount4.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCreatureCount4.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCreatureCount4.Name = "numCreatureCount4" Me.numCreatureCount4.Size = New System.Drawing.Size(49, 20) Me.numCreatureCount4.TabIndex = 48 Me.numCreatureCount4.Tag = "Count" Me.numCreatureCount4.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'numCreatureCount3 ' Me.numCreatureCount3.Location = New System.Drawing.Point(260, 104) Me.numCreatureCount3.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCreatureCount3.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCreatureCount3.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCreatureCount3.Name = "numCreatureCount3" Me.numCreatureCount3.Size = New System.Drawing.Size(49, 20) Me.numCreatureCount3.TabIndex = 47 Me.numCreatureCount3.Tag = "Count" Me.numCreatureCount3.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'numCreatureCount2 ' Me.numCreatureCount2.Location = New System.Drawing.Point(260, 63) Me.numCreatureCount2.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCreatureCount2.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCreatureCount2.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCreatureCount2.Name = "numCreatureCount2" Me.numCreatureCount2.Size = New System.Drawing.Size(49, 20) Me.numCreatureCount2.TabIndex = 49 Me.numCreatureCount2.Tag = "Count" Me.numCreatureCount2.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'numCreatureCount1 ' Me.numCreatureCount1.Location = New System.Drawing.Point(260, 23) Me.numCreatureCount1.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCreatureCount1.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCreatureCount1.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCreatureCount1.Name = "numCreatureCount1" Me.numCreatureCount1.Size = New System.Drawing.Size(49, 20) Me.numCreatureCount1.TabIndex = 50 Me.numCreatureCount1.Tag = "Count" Me.numCreatureCount1.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'lblCreatureName4 ' Me.lblCreatureName4.AutoSize = True Me.lblCreatureName4.Location = New System.Drawing.Point(77, 144) Me.lblCreatureName4.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblCreatureName4.Name = "lblCreatureName4" Me.lblCreatureName4.Size = New System.Drawing.Size(0, 13) Me.lblCreatureName4.TabIndex = 46 ' 'lblCreatureId4 ' Me.lblCreatureId4.AutoSize = True Me.lblCreatureId4.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblCreatureId4.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblCreatureId4.Location = New System.Drawing.Point(4, 124) Me.lblCreatureId4.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblCreatureId4.Name = "lblCreatureId4" Me.lblCreatureId4.Size = New System.Drawing.Size(19, 13) Me.lblCreatureId4.TabIndex = 45 Me.lblCreatureId4.Text = "Id:" ' 'numCreature4 ' Me.numCreature4.Location = New System.Drawing.Point(4, 140) Me.numCreature4.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCreature4.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numCreature4.Name = "numCreature4" Me.numCreature4.Size = New System.Drawing.Size(68, 20) Me.numCreature4.TabIndex = 44 Me.numCreature4.Tag = "Item" ' 'lblCreatureName3 ' Me.lblCreatureName3.AutoSize = True Me.lblCreatureName3.Location = New System.Drawing.Point(77, 103) Me.lblCreatureName3.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblCreatureName3.Name = "lblCreatureName3" Me.lblCreatureName3.Size = New System.Drawing.Size(0, 13) Me.lblCreatureName3.TabIndex = 43 ' 'lblCreatureId3 ' Me.lblCreatureId3.AutoSize = True Me.lblCreatureId3.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblCreatureId3.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblCreatureId3.Location = New System.Drawing.Point(4, 83) Me.lblCreatureId3.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblCreatureId3.Name = "lblCreatureId3" Me.lblCreatureId3.Size = New System.Drawing.Size(19, 13) Me.lblCreatureId3.TabIndex = 42 Me.lblCreatureId3.Text = "Id:" ' 'numCreature3 ' Me.numCreature3.Location = New System.Drawing.Point(4, 99) Me.numCreature3.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCreature3.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numCreature3.Name = "numCreature3" Me.numCreature3.Size = New System.Drawing.Size(68, 20) Me.numCreature3.TabIndex = 41 Me.numCreature3.Tag = "Item" ' 'lblCreatureName2 ' Me.lblCreatureName2.AutoSize = True Me.lblCreatureName2.Location = New System.Drawing.Point(77, 62) Me.lblCreatureName2.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblCreatureName2.Name = "lblCreatureName2" Me.lblCreatureName2.Size = New System.Drawing.Size(0, 13) Me.lblCreatureName2.TabIndex = 40 ' 'lblCreatureId2 ' Me.lblCreatureId2.AutoSize = True Me.lblCreatureId2.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblCreatureId2.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblCreatureId2.Location = New System.Drawing.Point(4, 44) Me.lblCreatureId2.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblCreatureId2.Name = "lblCreatureId2" Me.lblCreatureId2.Size = New System.Drawing.Size(19, 13) Me.lblCreatureId2.TabIndex = 39 Me.lblCreatureId2.Text = "Id:" ' 'numCreature2 ' Me.numCreature2.Location = New System.Drawing.Point(4, 60) Me.numCreature2.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCreature2.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numCreature2.Name = "numCreature2" Me.numCreature2.Size = New System.Drawing.Size(68, 20) Me.numCreature2.TabIndex = 38 Me.numCreature2.Tag = "Item" ' 'lblCreatureName1 ' Me.lblCreatureName1.AutoSize = True Me.lblCreatureName1.Location = New System.Drawing.Point(77, 24) Me.lblCreatureName1.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblCreatureName1.Name = "lblCreatureName1" Me.lblCreatureName1.Size = New System.Drawing.Size(0, 13) Me.lblCreatureName1.TabIndex = 37 ' 'lblCreatureId1 ' Me.lblCreatureId1.AutoSize = True Me.lblCreatureId1.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblCreatureId1.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblCreatureId1.Location = New System.Drawing.Point(4, 6) Me.lblCreatureId1.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblCreatureId1.Name = "lblCreatureId1" Me.lblCreatureId1.Size = New System.Drawing.Size(19, 13) Me.lblCreatureId1.TabIndex = 36 Me.lblCreatureId1.Text = "Id:" ' 'numCreature1 ' Me.numCreature1.Location = New System.Drawing.Point(4, 23) Me.numCreature1.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCreature1.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numCreature1.Name = "numCreature1" Me.numCreature1.Size = New System.Drawing.Size(68, 20) Me.numCreature1.TabIndex = 35 Me.numCreature1.Tag = "Item" ' 'tabItems ' Me.tabItems.Controls.Add(Me.Label10) Me.tabItems.Controls.Add(Me.Label7) Me.tabItems.Controls.Add(Me.Label5) Me.tabItems.Controls.Add(Me.Label4) Me.tabItems.Controls.Add(Me.Label3) Me.tabItems.Controls.Add(Me.Label2) Me.tabItems.Controls.Add(Me.numCount6) Me.tabItems.Controls.Add(Me.numCount5) Me.tabItems.Controls.Add(Me.numCount4) Me.tabItems.Controls.Add(Me.numCount3) Me.tabItems.Controls.Add(Me.numCount2) Me.tabItems.Controls.Add(Me.numCount1) Me.tabItems.Controls.Add(Me.lblItemName6) Me.tabItems.Controls.Add(Me.lblItemName5) Me.tabItems.Controls.Add(Me.lblItemName4) Me.tabItems.Controls.Add(Me.lblItemId6) Me.tabItems.Controls.Add(Me.lblItemId5) Me.tabItems.Controls.Add(Me.lblItemId4) Me.tabItems.Controls.Add(Me.numitemId6) Me.tabItems.Controls.Add(Me.numitemId5) Me.tabItems.Controls.Add(Me.numItemId4) Me.tabItems.Controls.Add(Me.lblItemName3) Me.tabItems.Controls.Add(Me.lblItemId3) Me.tabItems.Controls.Add(Me.numItemId3) Me.tabItems.Controls.Add(Me.lblItemName2) Me.tabItems.Controls.Add(Me.lblItemId2) Me.tabItems.Controls.Add(Me.numItemId2) Me.tabItems.Controls.Add(Me.lblItemName1) Me.tabItems.Controls.Add(Me.lblItemId1) Me.tabItems.Controls.Add(Me.numItemId1) Me.tabItems.Location = New System.Drawing.Point(4, 22) Me.tabItems.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.tabItems.Name = "tabItems" Me.tabItems.Padding = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.tabItems.Size = New System.Drawing.Size(324, 275) Me.tabItems.TabIndex = 1 Me.tabItems.Text = "Items" Me.tabItems.UseVisualStyleBackColor = True ' 'Label10 ' Me.Label10.AutoSize = True Me.Label10.Location = New System.Drawing.Point(258, 212) Me.Label10.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label10.Name = "Label10" Me.Label10.Size = New System.Drawing.Size(38, 13) Me.Label10.TabIndex = 32 Me.Label10.Text = "Count:" ' 'Label7 ' Me.Label7.AutoSize = True Me.Label7.Location = New System.Drawing.Point(258, 171) Me.Label7.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label7.Name = "Label7" Me.Label7.Size = New System.Drawing.Size(38, 13) Me.Label7.TabIndex = 32 Me.Label7.Text = "Count:" ' 'Label5 ' Me.Label5.AutoSize = True Me.Label5.Location = New System.Drawing.Point(258, 128) Me.Label5.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label5.Name = "Label5" Me.Label5.Size = New System.Drawing.Size(38, 13) Me.Label5.TabIndex = 32 Me.Label5.Text = "Count:" ' 'Label4 ' Me.Label4.AutoSize = True Me.Label4.Location = New System.Drawing.Point(258, 87) Me.Label4.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label4.Name = "Label4" Me.Label4.Size = New System.Drawing.Size(38, 13) Me.Label4.TabIndex = 31 Me.Label4.Text = "Count:" ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.Location = New System.Drawing.Point(258, 46) Me.Label3.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(38, 13) Me.Label3.TabIndex = 34 Me.Label3.Text = "Count:" ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Location = New System.Drawing.Point(258, 6) Me.Label2.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(38, 13) Me.Label2.TabIndex = 33 Me.Label2.Text = "Count:" ' 'numCount6 ' Me.numCount6.Location = New System.Drawing.Point(260, 226) Me.numCount6.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCount6.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCount6.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCount6.Name = "numCount6" Me.numCount6.Size = New System.Drawing.Size(49, 20) Me.numCount6.TabIndex = 28 Me.numCount6.Tag = "Count" Me.numCount6.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'numCount5 ' Me.numCount5.Location = New System.Drawing.Point(260, 184) Me.numCount5.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCount5.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCount5.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCount5.Name = "numCount5" Me.numCount5.Size = New System.Drawing.Size(49, 20) Me.numCount5.TabIndex = 28 Me.numCount5.Tag = "Count" Me.numCount5.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'numCount4 ' Me.numCount4.Location = New System.Drawing.Point(260, 141) Me.numCount4.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCount4.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCount4.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCount4.Name = "numCount4" Me.numCount4.Size = New System.Drawing.Size(49, 20) Me.numCount4.TabIndex = 28 Me.numCount4.Tag = "Count" Me.numCount4.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'numCount3 ' Me.numCount3.Location = New System.Drawing.Point(260, 101) Me.numCount3.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCount3.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCount3.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCount3.Name = "numCount3" Me.numCount3.Size = New System.Drawing.Size(49, 20) Me.numCount3.TabIndex = 27 Me.numCount3.Tag = "Count" Me.numCount3.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'numCount2 ' Me.numCount2.Location = New System.Drawing.Point(260, 59) Me.numCount2.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCount2.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCount2.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCount2.Name = "numCount2" Me.numCount2.Size = New System.Drawing.Size(49, 20) Me.numCount2.TabIndex = 30 Me.numCount2.Tag = "Count" Me.numCount2.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'numCount1 ' Me.numCount1.Location = New System.Drawing.Point(260, 20) Me.numCount1.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numCount1.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numCount1.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) Me.numCount1.Name = "numCount1" Me.numCount1.Size = New System.Drawing.Size(49, 20) Me.numCount1.TabIndex = 29 Me.numCount1.Tag = "Count" Me.numCount1.Value = New Decimal(New Integer() {1, 0, 0, 0}) ' 'lblItemName6 ' Me.lblItemName6.AutoSize = True Me.lblItemName6.Location = New System.Drawing.Point(77, 228) Me.lblItemName6.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemName6.Name = "lblItemName6" Me.lblItemName6.Size = New System.Drawing.Size(0, 13) Me.lblItemName6.TabIndex = 26 ' 'lblItemName5 ' Me.lblItemName5.AutoSize = True Me.lblItemName5.Location = New System.Drawing.Point(77, 186) Me.lblItemName5.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemName5.Name = "lblItemName5" Me.lblItemName5.Size = New System.Drawing.Size(0, 13) Me.lblItemName5.TabIndex = 26 ' 'lblItemName4 ' Me.lblItemName4.AutoSize = True Me.lblItemName4.Location = New System.Drawing.Point(77, 143) Me.lblItemName4.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemName4.Name = "lblItemName4" Me.lblItemName4.Size = New System.Drawing.Size(0, 13) Me.lblItemName4.TabIndex = 26 ' 'lblItemId6 ' Me.lblItemId6.AutoSize = True Me.lblItemId6.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblItemId6.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblItemId6.Location = New System.Drawing.Point(4, 210) Me.lblItemId6.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemId6.Name = "lblItemId6" Me.lblItemId6.Size = New System.Drawing.Size(19, 13) Me.lblItemId6.TabIndex = 25 Me.lblItemId6.Text = "Id:" ' 'lblItemId5 ' Me.lblItemId5.AutoSize = True Me.lblItemId5.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblItemId5.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblItemId5.Location = New System.Drawing.Point(4, 168) Me.lblItemId5.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemId5.Name = "lblItemId5" Me.lblItemId5.Size = New System.Drawing.Size(19, 13) Me.lblItemId5.TabIndex = 25 Me.lblItemId5.Text = "Id:" ' 'lblItemId4 ' Me.lblItemId4.AutoSize = True Me.lblItemId4.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblItemId4.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblItemId4.Location = New System.Drawing.Point(4, 125) Me.lblItemId4.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemId4.Name = "lblItemId4" Me.lblItemId4.Size = New System.Drawing.Size(19, 13) Me.lblItemId4.TabIndex = 25 Me.lblItemId4.Text = "Id:" ' 'numitemId6 ' Me.numitemId6.Location = New System.Drawing.Point(4, 226) Me.numitemId6.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numitemId6.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numitemId6.Name = "numitemId6" Me.numitemId6.Size = New System.Drawing.Size(68, 20) Me.numitemId6.TabIndex = 24 Me.numitemId6.Tag = "Item" ' 'numitemId5 ' Me.numitemId5.Location = New System.Drawing.Point(4, 184) Me.numitemId5.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numitemId5.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numitemId5.Name = "numitemId5" Me.numitemId5.Size = New System.Drawing.Size(68, 20) Me.numitemId5.TabIndex = 24 Me.numitemId5.Tag = "Item" ' 'numItemId4 ' Me.numItemId4.Location = New System.Drawing.Point(4, 141) Me.numItemId4.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numItemId4.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numItemId4.Name = "numItemId4" Me.numItemId4.Size = New System.Drawing.Size(68, 20) Me.numItemId4.TabIndex = 24 Me.numItemId4.Tag = "Item" ' 'lblItemName3 ' Me.lblItemName3.AutoSize = True Me.lblItemName3.Location = New System.Drawing.Point(77, 102) Me.lblItemName3.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemName3.Name = "lblItemName3" Me.lblItemName3.Size = New System.Drawing.Size(0, 13) Me.lblItemName3.TabIndex = 23 ' 'lblItemId3 ' Me.lblItemId3.AutoSize = True Me.lblItemId3.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblItemId3.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblItemId3.Location = New System.Drawing.Point(4, 84) Me.lblItemId3.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemId3.Name = "lblItemId3" Me.lblItemId3.Size = New System.Drawing.Size(19, 13) Me.lblItemId3.TabIndex = 22 Me.lblItemId3.Text = "Id:" ' 'numItemId3 ' Me.numItemId3.Location = New System.Drawing.Point(4, 101) Me.numItemId3.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numItemId3.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numItemId3.Name = "numItemId3" Me.numItemId3.Size = New System.Drawing.Size(68, 20) Me.numItemId3.TabIndex = 21 Me.numItemId3.Tag = "Item" ' 'lblItemName2 ' Me.lblItemName2.AutoSize = True Me.lblItemName2.Location = New System.Drawing.Point(77, 61) Me.lblItemName2.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemName2.Name = "lblItemName2" Me.lblItemName2.Size = New System.Drawing.Size(0, 13) Me.lblItemName2.TabIndex = 20 ' 'lblItemId2 ' Me.lblItemId2.AutoSize = True Me.lblItemId2.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblItemId2.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblItemId2.Location = New System.Drawing.Point(4, 43) Me.lblItemId2.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemId2.Name = "lblItemId2" Me.lblItemId2.Size = New System.Drawing.Size(19, 13) Me.lblItemId2.TabIndex = 19 Me.lblItemId2.Text = "Id:" ' 'numItemId2 ' Me.numItemId2.Location = New System.Drawing.Point(4, 59) Me.numItemId2.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numItemId2.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numItemId2.Name = "numItemId2" Me.numItemId2.Size = New System.Drawing.Size(68, 20) Me.numItemId2.TabIndex = 18 Me.numItemId2.Tag = "Item" ' 'lblItemName1 ' Me.lblItemName1.AutoSize = True Me.lblItemName1.Location = New System.Drawing.Point(77, 24) Me.lblItemName1.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemName1.Name = "lblItemName1" Me.lblItemName1.Size = New System.Drawing.Size(0, 13) Me.lblItemName1.TabIndex = 17 ' 'lblItemId1 ' Me.lblItemId1.AutoSize = True Me.lblItemId1.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblItemId1.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblItemId1.Location = New System.Drawing.Point(4, 6) Me.lblItemId1.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblItemId1.Name = "lblItemId1" Me.lblItemId1.Size = New System.Drawing.Size(19, 13) Me.lblItemId1.TabIndex = 16 Me.lblItemId1.Text = "Id:" ' 'numItemId1 ' Me.numItemId1.Location = New System.Drawing.Point(4, 22) Me.numItemId1.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numItemId1.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numItemId1.Name = "numItemId1" Me.numItemId1.Size = New System.Drawing.Size(68, 20) Me.numItemId1.TabIndex = 15 Me.numItemId1.Tag = "Item" ' 'tabFactions ' Me.tabFactions.Controls.Add(Me.Label18) Me.tabFactions.Controls.Add(Me.lblFactionName2) Me.tabFactions.Controls.Add(Me.lblFactionName1) Me.tabFactions.Controls.Add(Me.Label15) Me.tabFactions.Controls.Add(Me.Label16) Me.tabFactions.Controls.Add(Me.numFactionValue2) Me.tabFactions.Controls.Add(Me.numFactionValue1) Me.tabFactions.Controls.Add(Me.lblFactionID2) Me.tabFactions.Controls.Add(Me.numFaction2) Me.tabFactions.Controls.Add(Me.lblFactionID1) Me.tabFactions.Controls.Add(Me.numFaction1) Me.tabFactions.Location = New System.Drawing.Point(4, 22) Me.tabFactions.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.tabFactions.Name = "tabFactions" Me.tabFactions.Size = New System.Drawing.Size(324, 275) Me.tabFactions.TabIndex = 2 Me.tabFactions.Text = "Factions" Me.tabFactions.UseVisualStyleBackColor = True ' 'Label18 ' Me.Label18.AutoSize = True Me.Label18.Location = New System.Drawing.Point(3, 94) Me.Label18.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label18.Name = "Label18" Me.Label18.Size = New System.Drawing.Size(268, 143) Me.Label18.TabIndex = 67 Me.Label18.Text = resources.GetString("Label18.Text") ' 'lblFactionName2 ' Me.lblFactionName2.AutoSize = True Me.lblFactionName2.Location = New System.Drawing.Point(78, 60) Me.lblFactionName2.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblFactionName2.Name = "lblFactionName2" Me.lblFactionName2.Size = New System.Drawing.Size(0, 13) Me.lblFactionName2.TabIndex = 66 ' 'lblFactionName1 ' Me.lblFactionName1.AutoSize = True Me.lblFactionName1.Location = New System.Drawing.Point(78, 23) Me.lblFactionName1.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblFactionName1.Name = "lblFactionName1" Me.lblFactionName1.Size = New System.Drawing.Size(0, 13) Me.lblFactionName1.TabIndex = 65 ' 'Label15 ' Me.Label15.AutoSize = True Me.Label15.Location = New System.Drawing.Point(259, 47) Me.Label15.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label15.Name = "Label15" Me.Label15.Size = New System.Drawing.Size(37, 13) Me.Label15.TabIndex = 63 Me.Label15.Text = "Value:" ' 'Label16 ' Me.Label16.AutoSize = True Me.Label16.Location = New System.Drawing.Point(259, 7) Me.Label16.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.Label16.Name = "Label16" Me.Label16.Size = New System.Drawing.Size(37, 13) Me.Label16.TabIndex = 64 Me.Label16.Text = "Value:" ' 'numFactionValue2 ' Me.numFactionValue2.Location = New System.Drawing.Point(261, 61) Me.numFactionValue2.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numFactionValue2.Maximum = New Decimal(New Integer() {10000, 0, 0, 0}) Me.numFactionValue2.Minimum = New Decimal(New Integer() {100000, 0, 0, -2147483648}) Me.numFactionValue2.Name = "numFactionValue2" Me.numFactionValue2.Size = New System.Drawing.Size(49, 20) Me.numFactionValue2.TabIndex = 61 Me.numFactionValue2.Tag = "Value" ' 'numFactionValue1 ' Me.numFactionValue1.Location = New System.Drawing.Point(261, 21) Me.numFactionValue1.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numFactionValue1.Maximum = New Decimal(New Integer() {100000, 0, 0, 0}) Me.numFactionValue1.Minimum = New Decimal(New Integer() {100000, 0, 0, -2147483648}) Me.numFactionValue1.Name = "numFactionValue1" Me.numFactionValue1.Size = New System.Drawing.Size(49, 20) Me.numFactionValue1.TabIndex = 62 Me.numFactionValue1.Tag = "Value" ' 'lblFactionID2 ' Me.lblFactionID2.AutoSize = True Me.lblFactionID2.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblFactionID2.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblFactionID2.Location = New System.Drawing.Point(5, 42) Me.lblFactionID2.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblFactionID2.Name = "lblFactionID2" Me.lblFactionID2.Size = New System.Drawing.Size(19, 13) Me.lblFactionID2.TabIndex = 60 Me.lblFactionID2.Text = "Id:" ' 'numFaction2 ' Me.numFaction2.Location = New System.Drawing.Point(5, 58) Me.numFaction2.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numFaction2.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numFaction2.Name = "numFaction2" Me.numFaction2.Size = New System.Drawing.Size(68, 20) Me.numFaction2.TabIndex = 59 Me.numFaction2.Tag = "Faction" ' 'lblFactionID1 ' Me.lblFactionID1.AutoSize = True Me.lblFactionID1.Font = New System.Drawing.Font("Microsoft Sans Serif", 7.8!, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblFactionID1.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer)) Me.lblFactionID1.Location = New System.Drawing.Point(5, 5) Me.lblFactionID1.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.lblFactionID1.Name = "lblFactionID1" Me.lblFactionID1.Size = New System.Drawing.Size(19, 13) Me.lblFactionID1.TabIndex = 58 Me.lblFactionID1.Text = "Id:" ' 'numFaction1 ' Me.numFaction1.Location = New System.Drawing.Point(5, 21) Me.numFaction1.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.numFaction1.Maximum = New Decimal(New Integer() {10000000, 0, 0, 0}) Me.numFaction1.Name = "numFaction1" Me.numFaction1.Size = New System.Drawing.Size(68, 20) Me.numFaction1.TabIndex = 57 Me.numFaction1.Tag = "Faction" ' 'btnCancel ' Me.btnCancel.Location = New System.Drawing.Point(278, 316) Me.btnCancel.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.btnCancel.Name = "btnCancel" Me.btnCancel.Size = New System.Drawing.Size(63, 27) Me.btnCancel.TabIndex = 1 Me.btnCancel.Text = "Cancel" Me.btnCancel.UseVisualStyleBackColor = True ' 'btnSave ' Me.btnSave.Location = New System.Drawing.Point(211, 316) Me.btnSave.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.btnSave.Name = "btnSave" Me.btnSave.Size = New System.Drawing.Size(63, 27) Me.btnSave.TabIndex = 1 Me.btnSave.Text = "Save" Me.btnSave.UseVisualStyleBackColor = True ' 'QuestRequirements ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(343, 344) Me.Controls.Add(Me.btnSave) Me.Controls.Add(Me.btnCancel) Me.Controls.Add(Me.TabControl1) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow Me.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.MaximumSize = New System.Drawing.Size(359, 383) Me.MinimumSize = New System.Drawing.Size(359, 383) Me.Name = "QuestRequirements" Me.ShowInTaskbar = False Me.Text = "Quest Requirements" Me.TabControl1.ResumeLayout(False) Me.tabCreature.ResumeLayout(False) Me.tabCreature.PerformLayout() CType(Me.numCreatureCount4, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCreatureCount3, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCreatureCount2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCreatureCount1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCreature4, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCreature3, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCreature2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCreature1, System.ComponentModel.ISupportInitialize).EndInit() Me.tabItems.ResumeLayout(False) Me.tabItems.PerformLayout() CType(Me.numCount6, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCount5, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCount4, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCount3, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCount2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numCount1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numitemId6, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numitemId5, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numItemId4, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numItemId3, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numItemId2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numItemId1, System.ComponentModel.ISupportInitialize).EndInit() Me.tabFactions.ResumeLayout(False) Me.tabFactions.PerformLayout() CType(Me.numFactionValue2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numFactionValue1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numFaction2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.numFaction1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents TabControl1 As System.Windows.Forms.TabControl Friend WithEvents tabCreature As System.Windows.Forms.TabPage Friend WithEvents tabItems As System.Windows.Forms.TabPage Friend WithEvents tabFactions As System.Windows.Forms.TabPage Friend WithEvents btnCancel As System.Windows.Forms.Button Friend WithEvents btnSave As System.Windows.Forms.Button Friend WithEvents Label7 As System.Windows.Forms.Label Friend WithEvents Label5 As System.Windows.Forms.Label Friend WithEvents Label4 As System.Windows.Forms.Label Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents numCount5 As System.Windows.Forms.NumericUpDown Friend WithEvents numCount4 As System.Windows.Forms.NumericUpDown Friend WithEvents numCount3 As System.Windows.Forms.NumericUpDown Friend WithEvents numCount2 As System.Windows.Forms.NumericUpDown Friend WithEvents numCount1 As System.Windows.Forms.NumericUpDown Friend WithEvents lblItemName5 As System.Windows.Forms.Label Friend WithEvents lblItemName4 As System.Windows.Forms.Label Friend WithEvents lblItemId5 As System.Windows.Forms.Label Friend WithEvents lblItemId4 As System.Windows.Forms.Label Friend WithEvents numitemId5 As System.Windows.Forms.NumericUpDown Friend WithEvents numItemId4 As System.Windows.Forms.NumericUpDown Friend WithEvents lblItemName3 As System.Windows.Forms.Label Friend WithEvents lblItemId3 As System.Windows.Forms.Label Friend WithEvents numItemId3 As System.Windows.Forms.NumericUpDown Friend WithEvents lblItemName2 As System.Windows.Forms.Label Friend WithEvents lblItemId2 As System.Windows.Forms.Label Friend WithEvents numItemId2 As System.Windows.Forms.NumericUpDown Friend WithEvents lblItemName1 As System.Windows.Forms.Label Friend WithEvents lblItemId1 As System.Windows.Forms.Label Friend WithEvents numItemId1 As System.Windows.Forms.NumericUpDown Friend WithEvents Label10 As System.Windows.Forms.Label Friend WithEvents numCount6 As System.Windows.Forms.NumericUpDown Friend WithEvents lblItemName6 As System.Windows.Forms.Label Friend WithEvents lblItemId6 As System.Windows.Forms.Label Friend WithEvents numitemId6 As System.Windows.Forms.NumericUpDown Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents Label8 As System.Windows.Forms.Label Friend WithEvents Label11 As System.Windows.Forms.Label Friend WithEvents Label12 As System.Windows.Forms.Label Friend WithEvents numCreatureCount4 As System.Windows.Forms.NumericUpDown Friend WithEvents numCreatureCount3 As System.Windows.Forms.NumericUpDown Friend WithEvents numCreatureCount2 As System.Windows.Forms.NumericUpDown Friend WithEvents numCreatureCount1 As System.Windows.Forms.NumericUpDown Friend WithEvents lblCreatureName4 As System.Windows.Forms.Label Friend WithEvents lblCreatureId4 As System.Windows.Forms.Label Friend WithEvents numCreature4 As System.Windows.Forms.NumericUpDown Friend WithEvents lblCreatureName3 As System.Windows.Forms.Label Friend WithEvents lblCreatureId3 As System.Windows.Forms.Label Friend WithEvents numCreature3 As System.Windows.Forms.NumericUpDown Friend WithEvents lblCreatureName2 As System.Windows.Forms.Label Friend WithEvents lblCreatureId2 As System.Windows.Forms.Label Friend WithEvents numCreature2 As System.Windows.Forms.NumericUpDown Friend WithEvents lblCreatureName1 As System.Windows.Forms.Label Friend WithEvents lblCreatureId1 As System.Windows.Forms.Label Friend WithEvents numCreature1 As System.Windows.Forms.NumericUpDown Friend WithEvents lblFactionName2 As System.Windows.Forms.Label Friend WithEvents lblFactionName1 As System.Windows.Forms.Label Friend WithEvents Label15 As System.Windows.Forms.Label Friend WithEvents Label16 As System.Windows.Forms.Label Friend WithEvents numFactionValue2 As System.Windows.Forms.NumericUpDown Friend WithEvents numFactionValue1 As System.Windows.Forms.NumericUpDown Friend WithEvents lblFactionID2 As System.Windows.Forms.Label Friend WithEvents numFaction2 As System.Windows.Forms.NumericUpDown Friend WithEvents lblFactionID1 As System.Windows.Forms.Label Friend WithEvents numFaction1 As System.Windows.Forms.NumericUpDown Friend WithEvents Label17 As System.Windows.Forms.Label Friend WithEvents Label14 As System.Windows.Forms.Label Friend WithEvents Label13 As System.Windows.Forms.Label Friend WithEvents Label9 As System.Windows.Forms.Label Friend WithEvents Label6 As System.Windows.Forms.Label Friend WithEvents txtObj1 As System.Windows.Forms.TextBox Friend WithEvents txtObj2 As System.Windows.Forms.TextBox Friend WithEvents txtObj3 As System.Windows.Forms.TextBox Friend WithEvents txtObj4 As System.Windows.Forms.TextBox Friend WithEvents Label18 As System.Windows.Forms.Label End Class
Gargarensis/ACS
dialogs/QuestRequirements.Designer.vb
Visual Basic
mit
56,151
' 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 Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests_InternalsVisibleTo Public Shared ReadOnly Property AllCompletionImplementations() As IEnumerable(Of Object()) Get Return TestStateFactory.GetAllCompletionImplementations() End Get End Property <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOtherAssembliesOfSolution(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"ClassLibrary1", "ClassLibrary2", "ClassLibrary3"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOtherAssemblyIfAttributeSuffixIsPresent(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("$$ </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"ClassLibrary1"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsTriggeredWhenDoubleQuoteIsEntered(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo($$ </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendTypeChars(""""c) Await state.AssertCompletionItemsContainAll({"ClassLibrary1"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsEmptyUntilDoubleQuotesAreEntered(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo$$ </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny({"ClassLibrary1"}) state.SendTypeChars("("c) Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny({"ClassLibrary1"}) state.SendTypeChars(""""c) Await state.AssertCompletionItemsContainAll({"ClassLibrary1"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsTriggeredWhenCharacterIsEnteredAfterOpeningDoubleQuote(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendTypeChars("a"c) Await state.AssertCompletionItemsContainAll({"ClassLibrary1"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredWhenCharacterIsEnteredThatIsNotRightBesideTheOpeniningDoubleQuote(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("a$$")] </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendTypeChars("b"c) Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredWhenDoubleQuoteIsEnteredAtStartOfFile(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs">$$ </Document> </Project> </Workspace>) Await state.AssertNoCompletionSession() state.SendTypeChars("a"c) Await state.AssertCompletionItemsDoNotContainAny({"ClassLibrary1"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredByArrayElementAccess(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"><![CDATA[ namespace A { public class C { public void M() { var d = new System.Collections.Generic.Dictionary<string, string>(); var v = d$$; } } } ]]> </Document> </Project> </Workspace>) Dim AssertNoCompletionAndCompletionDoesNotContainClassLibrary1 As Func(Of Task) = Async Function() Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.AssertSessionIsNothingOrNoCompletionItemLike("ClassLibrary1") End Function Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() state.SendTypeChars("["c) Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() state.SendTypeChars(""""c) Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() End Using End Function Private Async Function AssertCompletionListHasItems(completionImplementation As CompletionImplementation, code As String, hasItems As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; <%= code %> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() If hasItems Then Await state.AssertCompletionItemsContainAll({"ClassLibrary1"}) Else Await state.AssertNoCompletionSession End If End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_AfterSingleDoubleQuoteAndClosing(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(""$$)]", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_AfterText(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(""Test$$)]", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfCursorIsInSecondParameter(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(""Test"", ""$$", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfCursorIsClosingDoubleQuote1(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(""Test""$$", False) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfCursorIsClosingDoubleQuote2(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(""""$$", False) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamedParameterIsPresent(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(""$$, AllInternalsVisible = true)]", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamedParameterAndNamedPositionalParametersArePresent(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(assemblyName: ""$$, AllInternalsVisible = true)]", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfNumberIsEntered(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(1$$2)]", False) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfNotInternalsVisibleToAttribute(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: AssemblyVersion(""$$"")]", False) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributeIsPresent1(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: AssemblyVersion(""1.0.0.0""), InternalsVisibleTo(""$$", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributeIsPresent2(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, "[assembly: InternalsVisibleTo(""$$""), AssemblyVersion(""1.0.0.0"")]", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributesAreAhead(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, " [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: InternalsVisibleTo(""$$", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributesAreFollowing(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, " [assembly: InternalsVisibleTo(""$$ [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: AssemblyCompany(""Test"")]", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamespaceIsFollowing(completionImplementation As CompletionImplementation) As Task Await AssertCompletionListHasItems(completionImplementation, " [assembly: InternalsVisibleTo(""$$ namespace A { public class A { } }", True) End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionHasItemsIfInteralVisibleToIsReferencedByTypeAlias(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute; [assembly: IVT("$$ </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"ClassLibrary1"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionDoesNotContainCurrentAssembly(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny({"TestAssembly"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionInsertsAssemblyNameOnCommit(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1"")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionInsertsPublicKeyOnCommit(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %>/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsPublicKeyIfKeyIsSpecifiedByAttribute(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %>/> <Document> [assembly: System.Reflection.AssemblyKeyFile("<%= SigningTestHelpers.PublicKeyFile.Replace("\", "\\") %>")] </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsPublicKeyIfDelayedSigningIsEnabled(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %> DelaySign="True"/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionListIsEmptyIfAttributeIsNotTheBCLAttribute(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: Test.InternalsVisibleTo("$$")] namespace Test { [System.AttributeUsage(System.AttributeTargets.Assembly)] public sealed class InternalsVisibleToAttribute: System.Attribute { public InternalsVisibleToAttribute(string ignore) { } } } </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVT(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary1")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary2")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny({"ClassLibrary1", "ClassLibrary2"}) Await state.AssertCompletionItemsContainAll({"ClassLibrary3"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTIfAssemblyNameIsAConstant(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <MetadataReferenceFromSource Language="C#" CommonReferences="true"> <Document FilePath="ReferencedDocument.cs"> namespace A { public static class Constants { public const string AssemblyName1 = "ClassLibrary1"; } } </Document> </MetadataReferenceFromSource> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(A.Constants.AssemblyName1)] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary2")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny({"ClassLibrary1", "ClassLibrary2"}) Await state.AssertCompletionItemsContainAll({"ClassLibrary3"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTForDifferentSyntax(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary4"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary5"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary6"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary7"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary8"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary9"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> // Code comment using System.Runtime.CompilerServices; using System.Reflection; using IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute; // Code comment [assembly: InternalsVisibleTo("ClassLibrary1", AllInternalsVisible = true)] [assembly: InternalsVisibleTo(assemblyName: "ClassLibrary2", AllInternalsVisible = true)] [assembly: AssemblyVersion("1.0.0.0"), InternalsVisibleTo("ClassLibrary3")] [assembly: InternalsVisibleTo("ClassLibrary4"), AssemblyCopyright("Copyright")] [assembly: AssemblyDescription("Description")] [assembly: InternalsVisibleTo("ClassLibrary5")] [assembly: InternalsVisibleTo("ClassLibrary6, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")] [assembly: InternalsVisibleTo("ClassLibrary" + "7")] [assembly: IVT("ClassLibrary8")] [assembly: InternalsVisibleTo("$$ namespace A { public class A { } } </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny({"ClassLibrary1", "ClassLibrary2", "ClassLibrary3", "ClassLibrary4", "ClassLibrary5", "ClassLibrary6", "ClassLibrary7", "ClassLibrary8"}) Await state.AssertCompletionItemsContainAll({"ClassLibrary9"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTWithSyntaxError(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("ClassLibrary" + 1)] // Not a constant [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>) state.SendInvokeCompletionList() ' ClassLibrary1 must be listed because the existing attribute argument can't be resolved to a constant. Await state.AssertCompletionItemsContainAll({"ClassLibrary1"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTWithMoreThanOneDocument(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="OtherDocument.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("ClassLibrary1")] [assembly: AssemblyDescription("Description")] </Document> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny({"ClassLibrary1"}) Await state.AssertCompletionItemsContainAll({"ClassLibrary2"}) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIgnoresUnsupportedProjectTypes(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="NoCompilation" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_1(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted.Assem$$bly")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name"")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_2(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted.Assem$$bly </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_3(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(" Dotted.Assem$$bly ")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name"")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_4(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted1.Dotted2.Assem$$bly.Dotted")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3"")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_Verbatim_1(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Dotted1.Dotted2.Assem$$bly.Dotted")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@""Dotted1.Dotted2.Assembly.Dotted3"")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_Verbatim_2(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Dotted1.Dotted2.Assem$$bly </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_EscapeSequence_1(completionImplementation As CompletionImplementation) As Task ' Escaped double quotes are not handled properly: The selection is expanded from the cursor position until ' a double quote or new line is reached. But because double quotes are not allowed in this context this ' case is rare enough to ignore. Supporting it would require more complicated code that was reverted in ' https://github.com/dotnet/roslyn/pull/29447/commits/e7a852a7e83fffe1f25a8dee0aaec68f67fcc1d8 Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("\"Dotted1.Dotted2.Assem$$bly\"")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""\""Dotted1.Dotted2.Assembly.Dotted3"""")]") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEnded(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted1.Dotted2.Assem$$bly.Dotted4 </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_AndPublicKey_OpenEnded(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Company.Asse$$mbly, PublicKey=123 </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_AndPublicKey_LineBreakExampleFromMSDN(completionImplementation As CompletionImplementation) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$Friend1, PublicKey=002400000480000094" + "0000000602000000240000525341310004000" + "001000100bf8c25fcd44838d87e245ab35bf7" + "3ba2615707feea295709559b3de903fb95a93" + "3d2729967c3184a97d7b84c7547cd87e435b5" + "6bdf8621bcb62b59c00c88bd83aa62c4fcdd4" + "712da72eec2533dc00f8529c3a0bbb4103282" + "f0d894d5f34e9f0103c473dce9f4b457a5dee" + "fd8f920d8681ed6dfcb0a81e96bd9b176525a" + "26e0b3")] </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3"" +") state.AssertMatchesTextStartingAtLine(2, " ""0000000602000000240000525341310004000"" +") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEndedStringFollowedByEOF(completionImplementation As CompletionImplementation) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Friend1$$</Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEndedStringFollowedByNewLines(completionImplementation As CompletionImplementation) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace(completionImplementation, <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"><![CDATA[ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Friend1$$ ]]> </Document> </Project> </Workspace>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") state.AssertMatchesTextStartingAtLine(2, "") End Using End Function End Class End Namespace
aelij/roslyn
src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_InternalsVisibleTo.vb
Visual Basic
apache-2.0
54,603
Partial Public Class Xml2 Implements Yahoo.Samples.Common.ISample ''' <summary> ''' Gets the sample description. ''' </summary> Public ReadOnly Property Description() As String Implements Common.ISample.Description Get Return "Shows a simple example on using XmlDocument" End Get End Property ''' <summary> ''' Gets the sample name. ''' </summary> Public ReadOnly Property Name() As String Implements Common.ISample.Name Get Return "VB.NET: XmlDocument" End Get End Property ''' <summary> ''' Gets the sample source filename. ''' </summary> Public ReadOnly Property SourceFile() As String Implements Common.ISample.SourceFile Get Return "Xml2Sample.vb" End Get End Property End Class
smallsharptools/SmallSharpToolsDotNet
YahooPack/ThirdParty/Yahoo Developer Center/VBSamples/Xml2.vb
Visual Basic
apache-2.0
754
' 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.ExpressionEvaluator Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation Imports System.Reflection Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class ResultsViewTests Inherits VisualBasicResultProviderTestBase <Fact> Public Sub IEnumerableExplicitImplementation() Const source = "Imports System.Collections Class C Implements IEnumerable Private e As IEnumerable Sub New(e As IEnumerable) Me.e = e End Sub Private Function F() As IEnumerator Implements IEnumerable.GetEnumerator Return e.GetEnumerator() End Function End Class" Dim assembly = GetAssembly(source) Dim assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly) Using ReflectionUtilities.LoadAssemblies(assemblies) Dim runtime = New DkmClrRuntimeInstance(assemblies) Dim type = assembly.GetType("C") Dim value = CreateDkmClrValue( value:=type.Instantiate(New Integer() {1, 2}), type:=runtime.GetType(CType(type, TypeImpl))) Dim result = FormatResult("o", value) Verify(result, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult( "e", "{Length=2}", "System.Collections.IEnumerable {Integer()}", "o.e", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)) children = GetChildren(children(1)) Verify(children, EvalResult("(0)", "1", "Object {Integer}", "New System.Linq.SystemCore_EnumerableDebugView(o).Items(0)"), EvalResult("(1)", "2", "Object {Integer}", "New System.Linq.SystemCore_EnumerableDebugView(o).Items(1)")) End Using End Sub <Fact> Public Sub IEnumerableOfTExplicitImplementation() Const source = "Imports System.Collections Imports System.Collections.Generic Class C(Of T) Implements IEnumerable(Of T) Private e As IEnumerable(Of T) Sub New(e As IEnumerable(Of T)) Me.e = e End Sub Private Function F() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator Return e.GetEnumerator() End Function Private Function G() As IEnumerator Implements IEnumerable.GetEnumerator Return e.GetEnumerator() End Function End Class" Dim assembly = GetAssembly(source) Dim assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly) Using ReflectionUtilities.LoadAssemblies(assemblies) Dim runtime = New DkmClrRuntimeInstance(assemblies) Dim type = assembly.GetType("C`1").MakeGenericType(GetType(Integer)) Dim value = CreateDkmClrValue( value:=type.Instantiate(New Integer() {1, 2}), type:=runtime.GetType(CType(type, TypeImpl))) Dim result = FormatResult("o", value) Verify(result, EvalResult("o", "{C(Of Integer)}", "C(Of Integer)", "o", DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult( "e", "{Length=2}", "System.Collections.Generic.IEnumerable(Of Integer) {Integer()}", "o.e", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)) children = GetChildren(children(1)) Verify(children, EvalResult("(0)", "1", "Integer", "New System.Linq.SystemCore_EnumerableDebugView(Of Integer)(o).Items(0)"), EvalResult("(1)", "2", "Integer", "New System.Linq.SystemCore_EnumerableDebugView(Of Integer)(o).Items(1)")) End Using End Sub <WorkItem(1043746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1043746")> <Fact> Public Sub GetProxyPropertyValueError() Const source = "Imports System.Collections Class C Implements IEnumerable Private Iterator Function F() As IEnumerator Implements IEnumerable.GetEnumerator Yield 1 End Function End Class" Dim runtime As DkmClrRuntimeInstance = Nothing Dim getMemberValue As GetMemberValueDelegate = Function(v, m) If(m = "Items", CreateErrorValue(runtime.GetType(GetType(Object)).MakeArrayType(), String.Format("Unable to evaluate '{0}'", m)), Nothing) runtime = New DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue:=getMemberValue) Using runtime.Load() Dim type = runtime.GetType("C") Dim value = type.Instantiate() Dim result = FormatResult("o", value) Verify(result, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)) children = GetChildren(children(0)) Verify(children, EvalFailedResult("Error", "Unable to evaluate 'Items'", flags:=DkmEvaluationResultFlags.None)) End Using End Sub <Fact> Public Sub NoSideEffects() Const source = "Imports System.Collections Class C Implements IEnumerable Private e As IEnumerable Sub New(e As IEnumerable) Me.e = e End Sub Private Function F() As IEnumerator Implements IEnumerable.GetEnumerator Return e.GetEnumerator() End Function End Class" Dim assembly = GetAssembly(source) Dim assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly) Using ReflectionUtilities.LoadAssemblies(assemblies) Dim runtime = New DkmClrRuntimeInstance(assemblies) Dim type = assembly.GetType("C") Dim value = CreateDkmClrValue( value:=type.Instantiate(New Integer() {1, 2}), type:=runtime.GetType(CType(type, TypeImpl))) Dim inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.NoSideEffects) Dim result = FormatResult("o", value, inspectionContext:=inspectionContext) Verify(result, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result, inspectionContext:=inspectionContext) Verify(children, EvalResult( "e", "{Length=2}", "System.Collections.IEnumerable {Integer()}", "o.e", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite)) End Using End Sub End Class End Namespace
abock/roslyn
src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ResultsViewTests.vb
Visual Basic
mit
8,751
' Copyright (c) 2015 ZZZ Projects. All rights reserved ' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) ' Website: http://www.zzzprojects.com/ ' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 ' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library Imports System.Linq Public Module Extensions_495 ''' <summary> ''' A string extension method that extracts the letter described by @this. ''' </summary> ''' <param name="this">The @this to act on.</param> ''' <returns>The extracted letter.</returns> <System.Runtime.CompilerServices.Extension> _ Public Function ExtractLetter(this As String) As String Return New String(this.ToCharArray().Where(Function(x) [Char].IsLetter(x)).ToArray()) End Function End Module
huoxudong125/Z.ExtensionMethods
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.String/String.ExtractLetter.vb
Visual Basic
mit
860
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyDescription("")> <Assembly: CLSCompliant(True)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("54BF601C-DC2F-46E8-ADB7-5C505F725076")>
EIDSS/EIDSS-Legacy
EIDSS v6/vb/EIDSS/EIDSS_ClientAgent/AssemblyInfo.vb
Visual Basic
bsd-2-clause
543
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class EnumMemberDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of EnumMemberDeclarationSyntax) Protected Overrides Sub CollectBlockSpans(enumMemberDeclaration As EnumMemberDeclarationSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(enumMemberDeclaration, spans, optionProvider) End Sub End Class End Namespace
AmadeusW/roslyn
src/Features/VisualBasic/Portable/Structure/Providers/EnumMemberDeclarationStructureProvider.vb
Visual Basic
apache-2.0
1,082
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class NoPIATests Inherits ExpressionCompilerTestBase <Fact> Public Sub ExplicitEmbeddedType() Const source = "Imports System.Runtime.InteropServices <TypeIdentifier> <Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9D9"")> Public Interface I Function F() As Object End Interface Class C Sub M() Dim o As I = Nothing End Sub End Class" Dim comp = CreateCompilationWithMscorlib( {source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me", errorMessage, testData, DebuggerDiagnosticFormatter.Instance) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldarg.0 IL_0001: ret }") End Sub) End Sub End Class End Namespace
mmitche/roslyn
src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/NoPIATests.vb
Visual Basic
apache-2.0
1,758
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Partial Class BoundBinaryConditionalExpression #If DEBUG Then Private Sub Validate() ValidateConstantValue() If ConvertedTestExpression Is Nothing Then Debug.Assert(TestExpressionPlaceholder Is Nothing) ElseIf ConvertedTestExpression.Kind <> BoundKind.Conversion Then Debug.Assert(HasErrors) Debug.Assert(ConvertedTestExpression.Kind = BoundKind.BadExpression) End If If Not HasErrors Then TestExpression.AssertRValue() ElseExpression.AssertRValue() Debug.Assert(ElseExpression.IsNothingLiteral() OrElse (TestExpression.IsConstant AndAlso Not TestExpression.ConstantValueOpt.IsNothing) OrElse Type.IsSameTypeIgnoringAll(ElseExpression.Type)) If ConvertedTestExpression IsNot Nothing Then ConvertedTestExpression.AssertRValue() Debug.Assert(Type.IsSameTypeIgnoringAll(ConvertedTestExpression.Type)) If TestExpressionPlaceholder IsNot Nothing Then Debug.Assert(TestExpressionPlaceholder.Type.IsSameTypeIgnoringAll(TestExpression.Type.GetNullableUnderlyingTypeOrSelf())) End If Else If Not Type.IsSameTypeIgnoringAll(TestExpression.Type.GetNullableUnderlyingTypeOrSelf()) Then Dim conversion As ConversionKind = Conversions.ClassifyDirectCastConversion(TestExpression.Type, Type, Nothing) Debug.Assert(Conversions.IsWideningConversion(conversion) AndAlso Conversions.IsCLRPredefinedConversion(conversion)) End If End If End If End Sub #End If End Class End Namespace
OmarTawfik/roslyn
src/Compilers/VisualBasic/Portable/BoundTree/BoundBinaryConditionalExpression.vb
Visual Basic
apache-2.0
2,217
Imports System Imports System.Collections.Generic Imports System.IO Imports System.Linq Imports System.Runtime.Serialization Imports System.Text Imports System.Threading.Tasks Imports Windows.ApplicationModel Imports Windows.Storage Imports Windows.Storage.Streams Imports Windows.UI.Xaml Imports Windows.UI.Xaml.Controls Namespace Global.SDKTemplate.Common ''' <summary> ''' SuspensionManager captures global session state to simplify process lifetime management ''' for an application. Note that session state will be automatically cleared under a variety ''' of conditions and should only be used to store information that would be convenient to ''' carry across sessions, but that should be discarded when an application crashes or is ''' upgraded. ''' </summary> Friend NotInheritable Class SuspensionManager Private Shared _sessionState As Dictionary(Of String, Object) = New Dictionary(Of String, Object)() Private Shared _knownTypes As List(Of Type) = New List(Of Type)() Private Const sessionStateFilename As String = "_sessionState.xml" Public Shared ReadOnly Property SessionState As Dictionary(Of String, Object) Get Return _sessionState End Get End Property Public Shared ReadOnly Property KnownTypes As List(Of Type) Get Return _knownTypes End Get End Property ''' <summary> ''' Save the current <see cref="SessionState"/> . Any <see cref="Frame"/> instances ''' registered with <see cref="RegisterFrame"/> will also preserve their current ''' navigation stack, which in turn gives their active <see cref="Page"/> an opportunity ''' to save its state. ''' </summary> ''' <returns>An asynchronous task that reflects when session state has been saved.</returns> Public Shared Async Function SaveAsync() As Task Try For Each weakFrameReference In _registeredFrames Dim frame As Frame = Nothing If weakFrameReference.TryGetTarget(frame) Then SaveFrameNavigationState(frame) End If Next ' Serialize the session state synchronously to avoid asynchronous access to shared ' state Dim sessionData As MemoryStream = New MemoryStream() Dim serializer As DataContractSerializer = New DataContractSerializer(GetType(Dictionary(Of String, Object)), _knownTypes) serializer.WriteObject(sessionData, _sessionState) ' Get an output stream for the SessionState file and write the state asynchronously Dim file As StorageFile = Await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting) Using fileStream As Stream = Await file.OpenStreamForWriteAsync() sessionData.Seek(0, SeekOrigin.Begin) Await sessionData.CopyToAsync(fileStream) End Using Catch e As Exception Throw New SuspensionManagerException(e) End Try End Function ''' <summary> ''' Restores previously saved <see cref="SessionState"/> . Any <see cref="Frame"/> instances ''' registered with <see cref="RegisterFrame"/> will also restore their prior navigation ''' state, which in turn gives their active <see cref="Page"/> an opportunity restore its ''' state. ''' </summary> ''' <param name="sessionBaseKey">An optional key that identifies the type of session. ''' This can be used to distinguish between multiple application launch scenarios.</param> ''' <returns>An asynchronous task that reflects when session state has been read. The ''' content of <see cref="SessionState"/> should not be relied upon until this task ''' completes.</returns> Public Shared Async Function RestoreAsync(Optional sessionBaseKey As String = Nothing) As Task _sessionState = New Dictionary(Of String, [Object])() Try ' Get the input stream for the SessionState file Dim file As StorageFile = Await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename) Using inStream As IInputStream = Await file.OpenSequentialReadAsync() ' Deserialize the Session State Dim serializer As DataContractSerializer = New DataContractSerializer(GetType(Dictionary(Of String, Object)), _knownTypes) _sessionState = CType(serializer.ReadObject(inStream.AsStreamForRead()), Dictionary(Of String, Object)) End Using For Each weakFrameReference In _registeredFrames Dim frame As Frame = Nothing If weakFrameReference.TryGetTarget(frame) AndAlso CType(frame.GetValue(FrameSessionBaseKeyProperty), String) = sessionBaseKey Then frame.ClearValue(FrameSessionStateProperty) RestoreFrameNavigationState(frame) End If Next Catch e As Exception Throw New SuspensionManagerException(e) End Try End Function Private Shared FrameSessionStateKeyProperty As DependencyProperty = DependencyProperty.RegisterAttached("_FrameSessionStateKey", GetType(String), GetType(SuspensionManager), Nothing) Private Shared FrameSessionBaseKeyProperty As DependencyProperty = DependencyProperty.RegisterAttached("_FrameSessionBaseKeyParams", GetType(String), GetType(SuspensionManager), Nothing) Private Shared FrameSessionStateProperty As DependencyProperty = DependencyProperty.RegisterAttached("_FrameSessionState", GetType(Dictionary(Of String, [Object])), GetType(SuspensionManager), Nothing) Private Shared _registeredFrames As List(Of WeakReference(Of Frame)) = New List(Of WeakReference(Of Frame))() ''' <summary> ''' Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to ''' and restored from <see cref="SessionState"/> . Frames should be registered once ''' immediately after creation if they will participate in session state management. Upon ''' registration if state has already been restored for the specified key ''' the navigation history will immediately be restored. Subsequent invocations of ''' <see cref="RestoreAsync"/> will also restore navigation history. ''' </summary> ''' <param name="frame">An instance whose navigation history should be managed by ''' <see cref="SuspensionManager"/></param> ''' <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to ''' store navigation-related information.</param> ''' <param name="sessionBaseKey">An optional key that identifies the type of session. ''' This can be used to distinguish between multiple application launch scenarios.</param> Public Shared Sub RegisterFrame(frame As Frame, sessionStateKey As String, Optional sessionBaseKey As String = Nothing) If frame.GetValue(FrameSessionStateKeyProperty) IsNot Nothing Then Throw New InvalidOperationException("Frames can only be registered to one session state key") End If If frame.GetValue(FrameSessionStateProperty) IsNot Nothing Then Throw New InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all") End If If Not String.IsNullOrEmpty(sessionBaseKey) Then frame.SetValue(FrameSessionBaseKeyProperty, sessionBaseKey) sessionStateKey = sessionBaseKey & "_" & sessionStateKey End If frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey) _registeredFrames.Add(New WeakReference(Of Frame)(frame)) RestoreFrameNavigationState(frame) End Sub ''' <summary> ''' Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/> ''' from <see cref="SessionState"/> . Any navigation state previously captured will be ''' removed. ''' </summary> ''' <param name="frame">An instance whose navigation history should no longer be ''' managed.</param> Public Shared Sub UnregisterFrame(frame As Frame) SessionState.Remove(CType(frame.GetValue(FrameSessionStateKeyProperty), String)) _registeredFrames.RemoveAll(Function(weakFrameReference) Dim testFrame As Frame = Nothing Return Not weakFrameReference.TryGetTarget(testFrame) OrElse testFrame Is frame End Function) End Sub ''' <summary> ''' Provides storage for session state associated with the specified <see cref="Frame"/> . ''' Frames that have been previously registered with <see cref="RegisterFrame"/> have ''' their session state saved and restored automatically as a part of the global ''' <see cref="SessionState"/> . Frames that are not registered have transient state ''' that can still be useful when restoring pages that have been discarded from the ''' navigation cache. ''' </summary> ''' <remarks>Apps may choose to rely on <see cref="NavigationHelper"/> to manage ''' page-specific state instead of working with frame session state directly.</remarks> ''' <param name="frame">The instance for which session state is desired.</param> ''' <returns>A collection of state subject to the same serialization mechanism as ''' <see cref="SessionState"/> .</returns> Public Shared Function SessionStateForFrame(frame As Frame) As Dictionary(Of String, [Object]) Dim frameState = CType(frame.GetValue(FrameSessionStateProperty), Dictionary(Of String, [Object])) If frameState Is Nothing Then Dim frameSessionKey = CType(frame.GetValue(FrameSessionStateKeyProperty), String) If frameSessionKey IsNot Nothing Then If Not _sessionState.ContainsKey(frameSessionKey) Then _sessionState(frameSessionKey) = New Dictionary(Of String, [Object])() End If frameState = CType(_sessionState(frameSessionKey), Dictionary(Of String, [Object])) Else frameState = New Dictionary(Of String, [Object])() End If frame.SetValue(FrameSessionStateProperty, frameState) End If Return frameState End Function Private Shared Sub RestoreFrameNavigationState(frame As Frame) Dim frameState = SessionStateForFrame(frame) If frameState.ContainsKey("Navigation") Then frame.SetNavigationState(CType(frameState("Navigation"), String)) End If End Sub Private Shared Sub SaveFrameNavigationState(frame As Frame) Dim frameState = SessionStateForFrame(frame) frameState("Navigation") = frame.GetNavigationState() End Sub End Class Public Class SuspensionManagerException Inherits Exception Public Sub New() End Sub Public Sub New(e As Exception) MyBase.New("SuspensionManager failed", e) End Sub End Class End Namespace
japf/Windows-universal-samples
Samples/ApplicationData/vb/SuspensionManager.vb
Visual Basic
mit
11,841
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("PredefinedCastExpressionSignatureHelpProvider", LanguageNames.VisualBasic)> Friend Partial Class PredefinedCastExpressionSignatureHelpProvider Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of PredefinedCastExpressionSyntax) Protected Overrides Function GetIntrinsicOperatorDocumentation(node As PredefinedCastExpressionSyntax, document As Document, cancellationToken As CancellationToken) As IEnumerable(Of AbstractIntrinsicOperatorDocumentation) Return SpecializedCollections.SingletonEnumerable(New PredefinedCastExpressionDocumentation(node.Keyword.Kind, document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken))) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsChildToken(Of PredefinedCastExpressionSyntax)(Function(ce) ce.OpenParenToken) End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As PredefinedCastExpressionSyntax, token As SyntaxToken) As Boolean Return node.Keyword <> token AndAlso node.CloseParenToken <> token End Function End Class End Namespace
cybernet14/roslyn
src/EditorFeatures/VisualBasic/SignatureHelp/PredefinedCastExpressionSignatureHelpProvider.vb
Visual Basic
apache-2.0
1,910
Option Infer On Imports System Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim assemblyDocument As SolidEdgeAssembly.AssemblyDocument = Nothing Dim occurrences As SolidEdgeAssembly.Occurrences = Nothing Dim occurrence As SolidEdgeAssembly.Occurrence = Nothing Dim faceStyle As SolidEdgeFramework.FaceStyle = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) assemblyDocument = TryCast(application.ActiveDocument, SolidEdgeAssembly.AssemblyDocument) If assemblyDocument IsNot Nothing Then occurrences = assemblyDocument.Occurrences For i As Integer = 1 To occurrences.Count occurrence = occurrences.Item(1) Dim isForeign = occurrence.IsForeign Next i End If Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeAssembly.Occurrence.IsForeign.vb
Visual Basic
mit
1,575
Imports System.Data Partial Class rCDiario_CContable 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 lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden Dim loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine(" SELECT Comprobantes.Documento, ") loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Cue, ") loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Mon_Deb, ") loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Mon_Hab, ") loComandoSeleccionar.AppendLine(" DATEPART(yyyy,Renglones_Comprobantes.Fec_Ini) AS Anno, ") loComandoSeleccionar.AppendLine(" DATEPART(mm,Renglones_Comprobantes.Fec_Ini) AS Mes ") loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes01 ") loComandoSeleccionar.AppendLine(" FROM Comprobantes, ") loComandoSeleccionar.AppendLine(" Renglones_Comprobantes ") loComandoSeleccionar.AppendLine(" WHERE Comprobantes.Documento = Renglones_Comprobantes.Documento ") loComandoSeleccionar.AppendLine(" And Comprobantes.Documento Between " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" And " & lcParametro0Hasta) loComandoSeleccionar.AppendLine(" And Comprobantes.Fec_Ini Between " & lcParametro1Desde) loComandoSeleccionar.AppendLine(" And " & lcParametro1Hasta) loComandoSeleccionar.AppendLine(" And Renglones_Comprobantes.Cod_Mon Between " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" And " & lcParametro2Hasta) loComandoSeleccionar.AppendLine(" And YEAR(Renglones_Comprobantes.Fec_Ini) = YEAR(Comprobantes.Fec_Ini) ") loComandoSeleccionar.AppendLine(" And MONTH(Renglones_Comprobantes.Fec_Ini) = MONTH(Comprobantes.Fec_Ini) ") loComandoSeleccionar.AppendLine(" SELECT Documento, ") loComandoSeleccionar.AppendLine(" Cod_Cue, ") loComandoSeleccionar.AppendLine(" SUM(Mon_Deb) AS Mon_Deb, ") loComandoSeleccionar.AppendLine(" SUM(Mon_Hab) AS Mon_Hab, ") loComandoSeleccionar.AppendLine(" Anno, ") loComandoSeleccionar.AppendLine(" Mes ") loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes02 ") loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes01 ") loComandoSeleccionar.AppendLine(" GROUP BY Anno, ") loComandoSeleccionar.AppendLine(" Mes, ") loComandoSeleccionar.AppendLine(" Documento, ") loComandoSeleccionar.AppendLine(" Cod_Cue ") loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes02.*, ") loComandoSeleccionar.AppendLine(" Comprobantes.Resumen, ") loComandoSeleccionar.AppendLine(" Comprobantes.Tipo, ") loComandoSeleccionar.AppendLine(" Comprobantes.Fec_Ini, ") loComandoSeleccionar.AppendLine(" Comprobantes.Origen, ") loComandoSeleccionar.AppendLine(" Comprobantes.Integracion, ") loComandoSeleccionar.AppendLine(" Comprobantes.Status, ") loComandoSeleccionar.AppendLine(" Comprobantes.Notas ") loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes03 ") loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes02, Comprobantes ") loComandoSeleccionar.AppendLine(" WHERE #tmpComprobantes02.Documento = Comprobantes.Documento ") loComandoSeleccionar.AppendLine(" And #tmpComprobantes02.Anno = YEAR(Comprobantes.Fec_Ini) ") loComandoSeleccionar.AppendLine(" And #tmpComprobantes02.Mes = MONTH(Comprobantes.Fec_Ini) ") loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes03.*, ") loComandoSeleccionar.AppendLine(" Cuentas_Contables.Nom_Cue AS Nom_Cue ") loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes04 ") loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes03 LEFT JOIN Cuentas_Contables ") loComandoSeleccionar.AppendLine(" ON #tmpComprobantes03.Cod_Cue = Cuentas_Contables.Cod_Cue ") loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes04.* ") loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes04 ") 'loComandoSeleccionar.AppendLine(" ORDER BY Fec_Ini, Documento, Cod_Cue ") loComandoSeleccionar.AppendLine("ORDER BY Fec_Ini, Documento, " & lcOrdenamiento) 'Me.Response.Clear() 'Me.Response.ContentType="text/plain" 'Me.Response.Write(loComandoSeleccionar.ToString()) 'Me.Response.Flush() 'Me.Response.End() 'Return Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rCDiario_CContable", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrCDiario_CContable.ReportSource = loObjetoReporte Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload Try loObjetoReporte.Close() Catch loExcepcion As Exception End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo '-------------------------------------------------------------------------------------------' ' JJD: 23/02/09: Codigo inicial '-------------------------------------------------------------------------------------------' ' CMS: 17/08/09: Metodo de ordenamiento '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
Reportes - Contabilidad/rCDiario_CContable.aspx.vb
Visual Basic
mit
8,058
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class ProcessManager 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.components = New System.ComponentModel.Container() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(ProcessManager)) Me.ProcessListView = New StormRat.AeroListView() Me.ProcessNameColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.PIDColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.CPUColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.WindowTitleColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.FunctionMenuStrip = New System.Windows.Forms.ContextMenuStrip(Me.components) Me.RefreshToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ResumeToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.SuspendToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.KillToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ProcessImageList = New System.Windows.Forms.ImageList(Me.components) Me.FunctionMenuStrip.SuspendLayout() Me.SuspendLayout() ' 'ProcessListView ' Me.ProcessListView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.ProcessListView.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ProcessNameColumnHeader, Me.PIDColumnHeader, Me.CPUColumnHeader, Me.WindowTitleColumnHeader}) Me.ProcessListView.ContextMenuStrip = Me.FunctionMenuStrip Me.ProcessListView.FullRowSelect = True Me.ProcessListView.Location = New System.Drawing.Point(12, 12) Me.ProcessListView.Name = "ProcessListView" Me.ProcessListView.Size = New System.Drawing.Size(370, 352) Me.ProcessListView.SmallImageList = Me.ProcessImageList Me.ProcessListView.TabIndex = 0 Me.ProcessListView.UseCompatibleStateImageBehavior = False Me.ProcessListView.View = System.Windows.Forms.View.Details ' 'ProcessNameColumnHeader ' Me.ProcessNameColumnHeader.Text = "Process Name" Me.ProcessNameColumnHeader.Width = 100 ' 'PIDColumnHeader ' Me.PIDColumnHeader.Text = "PID" ' 'CPUColumnHeader ' Me.CPUColumnHeader.Text = "CPU" ' 'WindowTitleColumnHeader ' Me.WindowTitleColumnHeader.Text = "Window Title" Me.WindowTitleColumnHeader.Width = 131 ' 'FunctionMenuStrip ' Me.FunctionMenuStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.RefreshToolStripMenuItem, Me.ResumeToolStripMenuItem, Me.SuspendToolStripMenuItem, Me.KillToolStripMenuItem}) Me.FunctionMenuStrip.Name = "FunctionMenuStrip" Me.FunctionMenuStrip.Size = New System.Drawing.Size(120, 92) ' 'RefreshToolStripMenuItem ' Me.RefreshToolStripMenuItem.Image = CType(resources.GetObject("RefreshToolStripMenuItem.Image"), System.Drawing.Image) Me.RefreshToolStripMenuItem.Name = "RefreshToolStripMenuItem" Me.RefreshToolStripMenuItem.Size = New System.Drawing.Size(119, 22) Me.RefreshToolStripMenuItem.Text = "Refresh" ' 'ResumeToolStripMenuItem ' Me.ResumeToolStripMenuItem.Image = CType(resources.GetObject("ResumeToolStripMenuItem.Image"), System.Drawing.Image) Me.ResumeToolStripMenuItem.Name = "ResumeToolStripMenuItem" Me.ResumeToolStripMenuItem.Size = New System.Drawing.Size(119, 22) Me.ResumeToolStripMenuItem.Text = "Resume" ' 'SuspendToolStripMenuItem ' Me.SuspendToolStripMenuItem.Image = CType(resources.GetObject("SuspendToolStripMenuItem.Image"), System.Drawing.Image) Me.SuspendToolStripMenuItem.Name = "SuspendToolStripMenuItem" Me.SuspendToolStripMenuItem.Size = New System.Drawing.Size(119, 22) Me.SuspendToolStripMenuItem.Text = "Suspend" ' 'KillToolStripMenuItem ' Me.KillToolStripMenuItem.Image = CType(resources.GetObject("KillToolStripMenuItem.Image"), System.Drawing.Image) Me.KillToolStripMenuItem.Name = "KillToolStripMenuItem" Me.KillToolStripMenuItem.Size = New System.Drawing.Size(119, 22) Me.KillToolStripMenuItem.Text = "Kill" ' 'ProcessImageList ' Me.ProcessImageList.ImageStream = CType(resources.GetObject("ProcessImageList.ImageStream"), System.Windows.Forms.ImageListStreamer) Me.ProcessImageList.TransparentColor = System.Drawing.Color.Transparent Me.ProcessImageList.Images.SetKeyName(0, "application_xp.png") ' 'ProcessManager ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(394, 376) Me.Controls.Add(Me.ProcessListView) Me.Font = New System.Drawing.Font("Segoe UI", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "ProcessManager" Me.ShowIcon = False Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.FunctionMenuStrip.ResumeLayout(False) Me.ResumeLayout(False) End Sub Friend WithEvents ProcessListView As StormRat.AeroListView Friend WithEvents ProcessNameColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents PIDColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents CPUColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents WindowTitleColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents FunctionMenuStrip As System.Windows.Forms.ContextMenuStrip Friend WithEvents RefreshToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ResumeToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents SuspendToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents KillToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ProcessImageList As System.Windows.Forms.ImageList End Class
Retrobyte/StormRat
StormRat/ProcessManager.Designer.vb
Visual Basic
mit
7,472
'------------------------------------------------------------------------------ ' <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_Project '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("Creative.Banner.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
sharpninja/WorldBankBBS
Banner/My Project/Resources.Designer.vb
Visual Basic
mit
2,704
Option Infer On Imports System Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim partDocument As SolidEdgePart.PartDocument = Nothing Dim models As SolidEdgePart.Models = Nothing Dim model As SolidEdgePart.Model = Nothing Dim body As SolidEdgeGeometry.Body = Nothing Dim faces As SolidEdgeGeometry.Faces = Nothing Dim face As SolidEdgeGeometry.Face = Nothing Dim plane As SolidEdgeGeometry.Plane = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument) If partDocument IsNot Nothing Then models = partDocument.Models model = models.Item(1) body = CType(model.Body, SolidEdgeGeometry.Body) Dim FaceType = SolidEdgeGeometry.FeatureTopologyQueryTypeConstants.igQueryPlane faces = CType(body.Faces(FaceType), SolidEdgeGeometry.Faces) If faces.Count > 0 Then face = CType(faces.Item(1), SolidEdgeGeometry.Face) plane = CType(face.Geometry, SolidEdgeGeometry.Plane) Dim RootPoint = Array.CreateInstance(GetType(Double), 0) Dim NormalVector = Array.CreateInstance(GetType(Double), 0) plane.GetPlaneData(RootPoint, NormalVector) End If End If Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeGeometry.Plane.GetPlaneData.vb
Visual Basic
mit
2,217
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Main 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(Main)) Me.Button1 = New System.Windows.Forms.Button() Me.Button2 = New System.Windows.Forms.Button() Me.Button3 = New System.Windows.Forms.Button() Me.Button4 = New System.Windows.Forms.Button() Me.MenuStrip1 = New System.Windows.Forms.MenuStrip() Me.VenteToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.FacturesToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.FacturesImpayeesToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator6 = New System.Windows.Forms.ToolStripSeparator() Me.FacturesClientToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.RapportsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.JournalDeCaisseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator() Me.JournalDeVenteToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator5 = New System.Windows.Forms.ToolStripSeparator() Me.MouvementsDeCaisseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.JournalDeMouvementDeCaisseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator7 = New System.Windows.Forms.ToolStripSeparator() Me.NouveauToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator17 = New System.Windows.Forms.ToolStripSeparator() Me.DetteClientsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.StocksToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripMenuItem1 = New System.Windows.Forms.ToolStripMenuItem() Me.ParProduitToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ParEnregitrementToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.HistoriqueDesStocksToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator2 = New System.Windows.Forms.ToolStripSeparator() Me.EnregistreUnStockToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator4 = New System.Windows.Forms.ToolStripSeparator() Me.ModifierLeStockToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.RapportsToolStripMenuItem1 = New System.Windows.Forms.ToolStripMenuItem() Me.ListeDesClientsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator8 = New System.Windows.Forms.ToolStripSeparator() Me.NouveauClientToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.LesProduitsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ListeDesProduitsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator10 = New System.Windows.Forms.ToolStripSeparator() Me.NouveauProduitToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.RapportsToolStripMenuItem2 = New System.Windows.Forms.ToolStripMenuItem() Me.RapportDeStockToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator13 = New System.Windows.Forms.ToolStripSeparator() Me.ClassementClientsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator14 = New System.Windows.Forms.ToolStripSeparator() Me.RapportDeVenteToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator15 = New System.Windows.Forms.ToolStripSeparator() Me.DashboardToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ApplicationToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.FermerLaSessionToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.QuitterToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator3 = New System.Windows.Forms.ToolStripSeparator() Me.FinDeJournerToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator11 = New System.Windows.Forms.ToolStripSeparator() Me.ParametresToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.FinancesToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.TypeDesMouvementsDeCaisseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator9 = New System.Windows.Forms.ToolStripSeparator() Me.EtablissementToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator12 = New System.Windows.Forms.ToolStripSeparator() Me.UtilisateursToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripSeparator18 = New System.Windows.Forms.ToolStripSeparator() Me.AProposToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.PanelContainer = New System.Windows.Forms.Panel() Me.ProgressBar1 = New System.Windows.Forms.ProgressBar() Me.PictureBox2 = New System.Windows.Forms.PictureBox() Me.PictureBox1 = New System.Windows.Forms.PictureBox() Me.Label2 = New System.Windows.Forms.Label() Me.LabelLogo = New HG.UI.TransparentLabel() Me.labelUser = New System.Windows.Forms.Label() Me.Button8 = New System.Windows.Forms.Button() Me.Button7 = New System.Windows.Forms.Button() Me.Button6 = New System.Windows.Forms.Button() Me.Button5 = New System.Windows.Forms.Button() Me.TimerLabel = New System.Windows.Forms.Timer(Me.components) Me.SidePanel = New System.Windows.Forms.Panel() Me.TabControl1 = New System.Windows.Forms.TabControl() Me.TabPage1 = New System.Windows.Forms.TabPage() Me.ListProduits = New System.Windows.Forms.ListView() Me.ColumnHeader1 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.ColumnHeader2 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.ColumnHeader3 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.TabPage2 = New System.Windows.Forms.TabPage() Me.ListProduitBouch = New System.Windows.Forms.ListView() Me.ColumnHeader4 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.ColumnHeader5 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.ColumnHeader6 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.Label1 = New System.Windows.Forms.Label() Me.LabelDate = New System.Windows.Forms.Label() Me.LabelHeure = New System.Windows.Forms.Label() Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components) Me.bgWorker = New System.ComponentModel.BackgroundWorker() Me.MenuStrip1.SuspendLayout() Me.PanelContainer.SuspendLayout() CType(Me.PictureBox2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit() Me.SidePanel.SuspendLayout() Me.TabControl1.SuspendLayout() Me.TabPage1.SuspendLayout() Me.TabPage2.SuspendLayout() Me.SuspendLayout() ' 'Button1 ' Me.Button1.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Button1.Cursor = System.Windows.Forms.Cursors.Hand Me.Button1.FlatAppearance.BorderSize = 0 Me.Button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button1.Location = New System.Drawing.Point(70, 139) Me.Button1.Margin = New System.Windows.Forms.Padding(4) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(270, 138) Me.Button1.TabIndex = 0 Me.Button1.Text = "VENTE" Me.Button1.UseVisualStyleBackColor = False ' 'Button2 ' Me.Button2.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Button2.Cursor = System.Windows.Forms.Cursors.Hand Me.Button2.FlatAppearance.BorderSize = 0 Me.Button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button2.Location = New System.Drawing.Point(353, 139) Me.Button2.Margin = New System.Windows.Forms.Padding(4) Me.Button2.Name = "Button2" Me.Button2.Size = New System.Drawing.Size(270, 138) Me.Button2.TabIndex = 0 Me.Button2.Text = "LES PRODUITS" Me.Button2.UseVisualStyleBackColor = False ' 'Button3 ' Me.Button3.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Button3.Cursor = System.Windows.Forms.Cursors.Hand Me.Button3.FlatAppearance.BorderSize = 0 Me.Button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button3.Location = New System.Drawing.Point(637, 139) Me.Button3.Margin = New System.Windows.Forms.Padding(4) Me.Button3.Name = "Button3" Me.Button3.Size = New System.Drawing.Size(270, 138) Me.Button3.TabIndex = 1 Me.Button3.Text = "LES FACTURES" Me.Button3.UseVisualStyleBackColor = False ' 'Button4 ' Me.Button4.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Button4.Cursor = System.Windows.Forms.Cursors.Hand Me.Button4.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer)) Me.Button4.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button4.ForeColor = System.Drawing.Color.FromArgb(CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer)) Me.Button4.Image = CType(resources.GetObject("Button4.Image"), System.Drawing.Image) Me.Button4.Location = New System.Drawing.Point(70, 310) Me.Button4.Margin = New System.Windows.Forms.Padding(4) Me.Button4.Name = "Button4" Me.Button4.Size = New System.Drawing.Size(270, 138) Me.Button4.TabIndex = 2 Me.Button4.Text = "GERER LE STOCK" Me.Button4.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText Me.Button4.UseVisualStyleBackColor = False ' 'MenuStrip1 ' Me.MenuStrip1.Font = New System.Drawing.Font("Segoe Print", 9.0!) Me.MenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.VenteToolStripMenuItem, Me.FacturesToolStripMenuItem, Me.RapportsToolStripMenuItem, Me.StocksToolStripMenuItem, Me.RapportsToolStripMenuItem1, Me.LesProduitsToolStripMenuItem, Me.RapportsToolStripMenuItem2, Me.ApplicationToolStripMenuItem}) Me.MenuStrip1.Location = New System.Drawing.Point(0, 0) Me.MenuStrip1.Name = "MenuStrip1" Me.MenuStrip1.Padding = New System.Windows.Forms.Padding(9, 3, 0, 3) Me.MenuStrip1.Size = New System.Drawing.Size(1276, 31) Me.MenuStrip1.TabIndex = 4 Me.MenuStrip1.Text = "MenuStrip1" ' 'VenteToolStripMenuItem ' Me.VenteToolStripMenuItem.Name = "VenteToolStripMenuItem" Me.VenteToolStripMenuItem.ShortcutKeyDisplayString = "V" Me.VenteToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.V), System.Windows.Forms.Keys) Me.VenteToolStripMenuItem.Size = New System.Drawing.Size(57, 25) Me.VenteToolStripMenuItem.Text = "Vente" ' 'FacturesToolStripMenuItem ' Me.FacturesToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FacturesImpayeesToolStripMenuItem, Me.ToolStripSeparator6, Me.FacturesClientToolStripMenuItem}) Me.FacturesToolStripMenuItem.Image = CType(resources.GetObject("FacturesToolStripMenuItem.Image"), System.Drawing.Image) Me.FacturesToolStripMenuItem.Name = "FacturesToolStripMenuItem" Me.FacturesToolStripMenuItem.Size = New System.Drawing.Size(88, 25) Me.FacturesToolStripMenuItem.Text = "Factures" ' 'FacturesImpayeesToolStripMenuItem ' Me.FacturesImpayeesToolStripMenuItem.Name = "FacturesImpayeesToolStripMenuItem" Me.FacturesImpayeesToolStripMenuItem.Size = New System.Drawing.Size(183, 26) Me.FacturesImpayeesToolStripMenuItem.Text = "Factures impayés" ' 'ToolStripSeparator6 ' Me.ToolStripSeparator6.Name = "ToolStripSeparator6" Me.ToolStripSeparator6.Size = New System.Drawing.Size(180, 6) ' 'FacturesClientToolStripMenuItem ' Me.FacturesClientToolStripMenuItem.Name = "FacturesClientToolStripMenuItem" Me.FacturesClientToolStripMenuItem.Size = New System.Drawing.Size(183, 26) Me.FacturesClientToolStripMenuItem.Text = "Factures client" ' 'RapportsToolStripMenuItem ' Me.RapportsToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.JournalDeCaisseToolStripMenuItem, Me.ToolStripSeparator1, Me.JournalDeVenteToolStripMenuItem, Me.ToolStripSeparator5, Me.MouvementsDeCaisseToolStripMenuItem, Me.ToolStripSeparator17, Me.DetteClientsToolStripMenuItem}) Me.RapportsToolStripMenuItem.Image = Global.HG.My.Resources.Resources.money Me.RapportsToolStripMenuItem.Name = "RapportsToolStripMenuItem" Me.RapportsToolStripMenuItem.Size = New System.Drawing.Size(88, 25) Me.RapportsToolStripMenuItem.Text = "Finances" ' 'JournalDeCaisseToolStripMenuItem ' Me.JournalDeCaisseToolStripMenuItem.Image = CType(resources.GetObject("JournalDeCaisseToolStripMenuItem.Image"), System.Drawing.Image) Me.JournalDeCaisseToolStripMenuItem.Name = "JournalDeCaisseToolStripMenuItem" Me.JournalDeCaisseToolStripMenuItem.Size = New System.Drawing.Size(211, 26) Me.JournalDeCaisseToolStripMenuItem.Text = "Journal de caisse" ' 'ToolStripSeparator1 ' Me.ToolStripSeparator1.Name = "ToolStripSeparator1" Me.ToolStripSeparator1.Size = New System.Drawing.Size(208, 6) ' 'JournalDeVenteToolStripMenuItem ' Me.JournalDeVenteToolStripMenuItem.Image = CType(resources.GetObject("JournalDeVenteToolStripMenuItem.Image"), System.Drawing.Image) Me.JournalDeVenteToolStripMenuItem.Name = "JournalDeVenteToolStripMenuItem" Me.JournalDeVenteToolStripMenuItem.Size = New System.Drawing.Size(211, 26) Me.JournalDeVenteToolStripMenuItem.Text = "Journal de vente" ' 'ToolStripSeparator5 ' Me.ToolStripSeparator5.Name = "ToolStripSeparator5" Me.ToolStripSeparator5.Size = New System.Drawing.Size(208, 6) ' 'MouvementsDeCaisseToolStripMenuItem ' Me.MouvementsDeCaisseToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.JournalDeMouvementDeCaisseToolStripMenuItem, Me.ToolStripSeparator7, Me.NouveauToolStripMenuItem}) Me.MouvementsDeCaisseToolStripMenuItem.Image = CType(resources.GetObject("MouvementsDeCaisseToolStripMenuItem.Image"), System.Drawing.Image) Me.MouvementsDeCaisseToolStripMenuItem.Name = "MouvementsDeCaisseToolStripMenuItem" Me.MouvementsDeCaisseToolStripMenuItem.Size = New System.Drawing.Size(211, 26) Me.MouvementsDeCaisseToolStripMenuItem.Text = "Mouvements de caisse" ' 'JournalDeMouvementDeCaisseToolStripMenuItem ' Me.JournalDeMouvementDeCaisseToolStripMenuItem.Image = CType(resources.GetObject("JournalDeMouvementDeCaisseToolStripMenuItem.Image"), System.Drawing.Image) Me.JournalDeMouvementDeCaisseToolStripMenuItem.Name = "JournalDeMouvementDeCaisseToolStripMenuItem" Me.JournalDeMouvementDeCaisseToolStripMenuItem.Size = New System.Drawing.Size(286, 26) Me.JournalDeMouvementDeCaisseToolStripMenuItem.Text = "Journal des mouvements de caisse" ' 'ToolStripSeparator7 ' Me.ToolStripSeparator7.Name = "ToolStripSeparator7" Me.ToolStripSeparator7.Size = New System.Drawing.Size(283, 6) ' 'NouveauToolStripMenuItem ' Me.NouveauToolStripMenuItem.Image = CType(resources.GetObject("NouveauToolStripMenuItem.Image"), System.Drawing.Image) Me.NouveauToolStripMenuItem.Name = "NouveauToolStripMenuItem" Me.NouveauToolStripMenuItem.Size = New System.Drawing.Size(286, 26) Me.NouveauToolStripMenuItem.Text = "Nouveau" ' 'ToolStripSeparator17 ' Me.ToolStripSeparator17.Name = "ToolStripSeparator17" Me.ToolStripSeparator17.Size = New System.Drawing.Size(208, 6) ' 'DetteClientsToolStripMenuItem ' Me.DetteClientsToolStripMenuItem.Name = "DetteClientsToolStripMenuItem" Me.DetteClientsToolStripMenuItem.Size = New System.Drawing.Size(211, 26) Me.DetteClientsToolStripMenuItem.Text = "Dette Clients" ' 'StocksToolStripMenuItem ' Me.StocksToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripMenuItem1, Me.HistoriqueDesStocksToolStripMenuItem, Me.ToolStripSeparator2, Me.EnregistreUnStockToolStripMenuItem, Me.ToolStripSeparator4, Me.ModifierLeStockToolStripMenuItem}) Me.StocksToolStripMenuItem.Image = CType(resources.GetObject("StocksToolStripMenuItem.Image"), System.Drawing.Image) Me.StocksToolStripMenuItem.Name = "StocksToolStripMenuItem" Me.StocksToolStripMenuItem.Size = New System.Drawing.Size(77, 25) Me.StocksToolStripMenuItem.Text = "Stocks" ' 'ToolStripMenuItem1 ' Me.ToolStripMenuItem1.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ParProduitToolStripMenuItem, Me.ParEnregitrementToolStripMenuItem}) Me.ToolStripMenuItem1.Image = CType(resources.GetObject("ToolStripMenuItem1.Image"), System.Drawing.Image) Me.ToolStripMenuItem1.Name = "ToolStripMenuItem1" Me.ToolStripMenuItem1.Size = New System.Drawing.Size(239, 26) Me.ToolStripMenuItem1.Text = "Rapport detailler de stock" ' 'ParProduitToolStripMenuItem ' Me.ParProduitToolStripMenuItem.Name = "ParProduitToolStripMenuItem" Me.ParProduitToolStripMenuItem.Size = New System.Drawing.Size(192, 26) Me.ParProduitToolStripMenuItem.Text = "Par produit" ' 'ParEnregitrementToolStripMenuItem ' Me.ParEnregitrementToolStripMenuItem.Name = "ParEnregitrementToolStripMenuItem" Me.ParEnregitrementToolStripMenuItem.Size = New System.Drawing.Size(192, 26) Me.ParEnregitrementToolStripMenuItem.Text = "Par enregitrement" ' 'HistoriqueDesStocksToolStripMenuItem ' Me.HistoriqueDesStocksToolStripMenuItem.Image = CType(resources.GetObject("HistoriqueDesStocksToolStripMenuItem.Image"), System.Drawing.Image) Me.HistoriqueDesStocksToolStripMenuItem.Name = "HistoriqueDesStocksToolStripMenuItem" Me.HistoriqueDesStocksToolStripMenuItem.Size = New System.Drawing.Size(239, 26) Me.HistoriqueDesStocksToolStripMenuItem.Text = "Etat de stock actuelle" ' 'ToolStripSeparator2 ' Me.ToolStripSeparator2.Name = "ToolStripSeparator2" Me.ToolStripSeparator2.Size = New System.Drawing.Size(236, 6) ' 'EnregistreUnStockToolStripMenuItem ' Me.EnregistreUnStockToolStripMenuItem.Image = CType(resources.GetObject("EnregistreUnStockToolStripMenuItem.Image"), System.Drawing.Image) Me.EnregistreUnStockToolStripMenuItem.Name = "EnregistreUnStockToolStripMenuItem" Me.EnregistreUnStockToolStripMenuItem.Size = New System.Drawing.Size(239, 26) Me.EnregistreUnStockToolStripMenuItem.Text = "Enregistré un stock" ' 'ToolStripSeparator4 ' Me.ToolStripSeparator4.Name = "ToolStripSeparator4" Me.ToolStripSeparator4.Size = New System.Drawing.Size(236, 6) Me.ToolStripSeparator4.Visible = False ' 'ModifierLeStockToolStripMenuItem ' Me.ModifierLeStockToolStripMenuItem.Name = "ModifierLeStockToolStripMenuItem" Me.ModifierLeStockToolStripMenuItem.Size = New System.Drawing.Size(239, 26) Me.ModifierLeStockToolStripMenuItem.Text = "Editer le stock" Me.ModifierLeStockToolStripMenuItem.Visible = False ' 'RapportsToolStripMenuItem1 ' Me.RapportsToolStripMenuItem1.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ListeDesClientsToolStripMenuItem, Me.ToolStripSeparator8, Me.NouveauClientToolStripMenuItem}) Me.RapportsToolStripMenuItem1.Image = CType(resources.GetObject("RapportsToolStripMenuItem1.Image"), System.Drawing.Image) Me.RapportsToolStripMenuItem1.Name = "RapportsToolStripMenuItem1" Me.RapportsToolStripMenuItem1.Size = New System.Drawing.Size(77, 25) Me.RapportsToolStripMenuItem1.Text = "Clients" ' 'ListeDesClientsToolStripMenuItem ' Me.ListeDesClientsToolStripMenuItem.Image = CType(resources.GetObject("ListeDesClientsToolStripMenuItem.Image"), System.Drawing.Image) Me.ListeDesClientsToolStripMenuItem.Name = "ListeDesClientsToolStripMenuItem" Me.ListeDesClientsToolStripMenuItem.Size = New System.Drawing.Size(174, 26) Me.ListeDesClientsToolStripMenuItem.Text = "Liste des clients" ' 'ToolStripSeparator8 ' Me.ToolStripSeparator8.Name = "ToolStripSeparator8" Me.ToolStripSeparator8.Size = New System.Drawing.Size(171, 6) ' 'NouveauClientToolStripMenuItem ' Me.NouveauClientToolStripMenuItem.Image = CType(resources.GetObject("NouveauClientToolStripMenuItem.Image"), System.Drawing.Image) Me.NouveauClientToolStripMenuItem.Name = "NouveauClientToolStripMenuItem" Me.NouveauClientToolStripMenuItem.Size = New System.Drawing.Size(174, 26) Me.NouveauClientToolStripMenuItem.Text = "Nouveau client" ' 'LesProduitsToolStripMenuItem ' Me.LesProduitsToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ListeDesProduitsToolStripMenuItem, Me.ToolStripSeparator10, Me.NouveauProduitToolStripMenuItem}) Me.LesProduitsToolStripMenuItem.Name = "LesProduitsToolStripMenuItem" Me.LesProduitsToolStripMenuItem.Size = New System.Drawing.Size(96, 25) Me.LesProduitsToolStripMenuItem.Text = "Les produits" ' 'ListeDesProduitsToolStripMenuItem ' Me.ListeDesProduitsToolStripMenuItem.Image = CType(resources.GetObject("ListeDesProduitsToolStripMenuItem.Image"), System.Drawing.Image) Me.ListeDesProduitsToolStripMenuItem.Name = "ListeDesProduitsToolStripMenuItem" Me.ListeDesProduitsToolStripMenuItem.Size = New System.Drawing.Size(187, 26) Me.ListeDesProduitsToolStripMenuItem.Text = "Liste des produits" ' 'ToolStripSeparator10 ' Me.ToolStripSeparator10.Name = "ToolStripSeparator10" Me.ToolStripSeparator10.Size = New System.Drawing.Size(184, 6) ' 'NouveauProduitToolStripMenuItem ' Me.NouveauProduitToolStripMenuItem.Image = CType(resources.GetObject("NouveauProduitToolStripMenuItem.Image"), System.Drawing.Image) Me.NouveauProduitToolStripMenuItem.Name = "NouveauProduitToolStripMenuItem" Me.NouveauProduitToolStripMenuItem.Size = New System.Drawing.Size(187, 26) Me.NouveauProduitToolStripMenuItem.Text = "Nouveau produit" ' 'RapportsToolStripMenuItem2 ' Me.RapportsToolStripMenuItem2.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.RapportDeStockToolStripMenuItem, Me.ToolStripSeparator13, Me.ClassementClientsToolStripMenuItem, Me.ToolStripSeparator14, Me.RapportDeVenteToolStripMenuItem, Me.ToolStripSeparator15, Me.DashboardToolStripMenuItem}) Me.RapportsToolStripMenuItem2.Name = "RapportsToolStripMenuItem2" Me.RapportsToolStripMenuItem2.Size = New System.Drawing.Size(78, 25) Me.RapportsToolStripMenuItem2.Text = "Rapports" ' 'RapportDeStockToolStripMenuItem ' Me.RapportDeStockToolStripMenuItem.Name = "RapportDeStockToolStripMenuItem" Me.RapportDeStockToolStripMenuItem.Size = New System.Drawing.Size(188, 26) Me.RapportDeStockToolStripMenuItem.Text = "Rapport de stock" ' 'ToolStripSeparator13 ' Me.ToolStripSeparator13.Name = "ToolStripSeparator13" Me.ToolStripSeparator13.Size = New System.Drawing.Size(185, 6) ' 'ClassementClientsToolStripMenuItem ' Me.ClassementClientsToolStripMenuItem.Name = "ClassementClientsToolStripMenuItem" Me.ClassementClientsToolStripMenuItem.Size = New System.Drawing.Size(188, 26) Me.ClassementClientsToolStripMenuItem.Text = "Classement clients" ' 'ToolStripSeparator14 ' Me.ToolStripSeparator14.Name = "ToolStripSeparator14" Me.ToolStripSeparator14.Size = New System.Drawing.Size(185, 6) ' 'RapportDeVenteToolStripMenuItem ' Me.RapportDeVenteToolStripMenuItem.Name = "RapportDeVenteToolStripMenuItem" Me.RapportDeVenteToolStripMenuItem.Size = New System.Drawing.Size(188, 26) Me.RapportDeVenteToolStripMenuItem.Text = "Rapport de vente" ' 'ToolStripSeparator15 ' Me.ToolStripSeparator15.Name = "ToolStripSeparator15" Me.ToolStripSeparator15.Size = New System.Drawing.Size(185, 6) ' 'DashboardToolStripMenuItem ' Me.DashboardToolStripMenuItem.Name = "DashboardToolStripMenuItem" Me.DashboardToolStripMenuItem.Size = New System.Drawing.Size(188, 26) Me.DashboardToolStripMenuItem.Text = "Tableau de bord" ' 'ApplicationToolStripMenuItem ' Me.ApplicationToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FermerLaSessionToolStripMenuItem, Me.QuitterToolStripMenuItem, Me.ToolStripSeparator3, Me.FinDeJournerToolStripMenuItem, Me.ToolStripSeparator11, Me.ParametresToolStripMenuItem, Me.ToolStripSeparator18, Me.AProposToolStripMenuItem}) Me.ApplicationToolStripMenuItem.Image = CType(resources.GetObject("ApplicationToolStripMenuItem.Image"), System.Drawing.Image) Me.ApplicationToolStripMenuItem.Name = "ApplicationToolStripMenuItem" Me.ApplicationToolStripMenuItem.Size = New System.Drawing.Size(106, 25) Me.ApplicationToolStripMenuItem.Text = "Application" ' 'FermerLaSessionToolStripMenuItem ' Me.FermerLaSessionToolStripMenuItem.Image = CType(resources.GetObject("FermerLaSessionToolStripMenuItem.Image"), System.Drawing.Image) Me.FermerLaSessionToolStripMenuItem.Name = "FermerLaSessionToolStripMenuItem" Me.FermerLaSessionToolStripMenuItem.Size = New System.Drawing.Size(182, 26) Me.FermerLaSessionToolStripMenuItem.Text = "Fermer la session" ' 'QuitterToolStripMenuItem ' Me.QuitterToolStripMenuItem.Image = CType(resources.GetObject("QuitterToolStripMenuItem.Image"), System.Drawing.Image) Me.QuitterToolStripMenuItem.Name = "QuitterToolStripMenuItem" Me.QuitterToolStripMenuItem.Size = New System.Drawing.Size(182, 26) Me.QuitterToolStripMenuItem.Text = "Quitter" ' 'ToolStripSeparator3 ' Me.ToolStripSeparator3.Name = "ToolStripSeparator3" Me.ToolStripSeparator3.Size = New System.Drawing.Size(179, 6) ' 'FinDeJournerToolStripMenuItem ' Me.FinDeJournerToolStripMenuItem.Name = "FinDeJournerToolStripMenuItem" Me.FinDeJournerToolStripMenuItem.Size = New System.Drawing.Size(182, 26) Me.FinDeJournerToolStripMenuItem.Text = "Fin de journer" ' 'ToolStripSeparator11 ' Me.ToolStripSeparator11.Name = "ToolStripSeparator11" Me.ToolStripSeparator11.Size = New System.Drawing.Size(179, 6) ' 'ParametresToolStripMenuItem ' Me.ParametresToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FinancesToolStripMenuItem, Me.ToolStripSeparator9, Me.EtablissementToolStripMenuItem, Me.ToolStripSeparator12, Me.UtilisateursToolStripMenuItem}) Me.ParametresToolStripMenuItem.Image = CType(resources.GetObject("ParametresToolStripMenuItem.Image"), System.Drawing.Image) Me.ParametresToolStripMenuItem.Name = "ParametresToolStripMenuItem" Me.ParametresToolStripMenuItem.Size = New System.Drawing.Size(182, 26) Me.ParametresToolStripMenuItem.Text = "Parametres" ' 'FinancesToolStripMenuItem ' Me.FinancesToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.TypeDesMouvementsDeCaisseToolStripMenuItem}) Me.FinancesToolStripMenuItem.Name = "FinancesToolStripMenuItem" Me.FinancesToolStripMenuItem.Size = New System.Drawing.Size(162, 26) Me.FinancesToolStripMenuItem.Text = "Finances" ' 'TypeDesMouvementsDeCaisseToolStripMenuItem ' Me.TypeDesMouvementsDeCaisseToolStripMenuItem.Name = "TypeDesMouvementsDeCaisseToolStripMenuItem" Me.TypeDesMouvementsDeCaisseToolStripMenuItem.Size = New System.Drawing.Size(265, 26) Me.TypeDesMouvementsDeCaisseToolStripMenuItem.Text = "Types de mouvement de caisse" ' 'ToolStripSeparator9 ' Me.ToolStripSeparator9.Name = "ToolStripSeparator9" Me.ToolStripSeparator9.Size = New System.Drawing.Size(159, 6) ' 'EtablissementToolStripMenuItem ' Me.EtablissementToolStripMenuItem.Name = "EtablissementToolStripMenuItem" Me.EtablissementToolStripMenuItem.Size = New System.Drawing.Size(162, 26) Me.EtablissementToolStripMenuItem.Text = "Etablissement" ' 'ToolStripSeparator12 ' Me.ToolStripSeparator12.Name = "ToolStripSeparator12" Me.ToolStripSeparator12.Size = New System.Drawing.Size(159, 6) ' 'UtilisateursToolStripMenuItem ' Me.UtilisateursToolStripMenuItem.Image = CType(resources.GetObject("UtilisateursToolStripMenuItem.Image"), System.Drawing.Image) Me.UtilisateursToolStripMenuItem.Name = "UtilisateursToolStripMenuItem" Me.UtilisateursToolStripMenuItem.Size = New System.Drawing.Size(162, 26) Me.UtilisateursToolStripMenuItem.Text = "Utilisateurs" ' 'ToolStripSeparator18 ' Me.ToolStripSeparator18.Name = "ToolStripSeparator18" Me.ToolStripSeparator18.Size = New System.Drawing.Size(179, 6) ' 'AProposToolStripMenuItem ' Me.AProposToolStripMenuItem.Image = CType(resources.GetObject("AProposToolStripMenuItem.Image"), System.Drawing.Image) Me.AProposToolStripMenuItem.Name = "AProposToolStripMenuItem" Me.AProposToolStripMenuItem.Size = New System.Drawing.Size(182, 26) Me.AProposToolStripMenuItem.Text = "A propos" ' 'PanelContainer ' Me.PanelContainer.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.PanelContainer.BackColor = System.Drawing.Color.Transparent Me.PanelContainer.Controls.Add(Me.ProgressBar1) Me.PanelContainer.Controls.Add(Me.PictureBox2) Me.PanelContainer.Controls.Add(Me.PictureBox1) Me.PanelContainer.Controls.Add(Me.Label2) Me.PanelContainer.Controls.Add(Me.LabelLogo) Me.PanelContainer.Controls.Add(Me.labelUser) Me.PanelContainer.Controls.Add(Me.Button1) Me.PanelContainer.Controls.Add(Me.Button2) Me.PanelContainer.Controls.Add(Me.Button8) Me.PanelContainer.Controls.Add(Me.Button7) Me.PanelContainer.Controls.Add(Me.Button6) Me.PanelContainer.Controls.Add(Me.Button5) Me.PanelContainer.Controls.Add(Me.Button4) Me.PanelContainer.Controls.Add(Me.Button3) Me.PanelContainer.Location = New System.Drawing.Point(292, 30) Me.PanelContainer.Name = "PanelContainer" Me.PanelContainer.Size = New System.Drawing.Size(1068, 711) Me.PanelContainer.TabIndex = 5 ' 'ProgressBar1 ' Me.ProgressBar1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.ProgressBar1.Location = New System.Drawing.Point(656, 644) Me.ProgressBar1.Name = "ProgressBar1" Me.ProgressBar1.Size = New System.Drawing.Size(270, 23) Me.ProgressBar1.TabIndex = 7 ' 'PictureBox2 ' Me.PictureBox2.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.PictureBox2.Cursor = System.Windows.Forms.Cursors.Hand Me.PictureBox2.Image = CType(resources.GetObject("PictureBox2.Image"), System.Drawing.Image) Me.PictureBox2.Location = New System.Drawing.Point(866, 24) Me.PictureBox2.Name = "PictureBox2" Me.PictureBox2.Size = New System.Drawing.Size(49, 50) Me.PictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.PictureBox2.TabIndex = 6 Me.PictureBox2.TabStop = False Me.ToolTip1.SetToolTip(Me.PictureBox2, "Fermer la session") ' 'PictureBox1 ' Me.PictureBox1.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.PictureBox1.Cursor = System.Windows.Forms.Cursors.Hand Me.PictureBox1.Image = CType(resources.GetObject("PictureBox1.Image"), System.Drawing.Image) Me.PictureBox1.Location = New System.Drawing.Point(921, 24) Me.PictureBox1.Name = "PictureBox1" Me.PictureBox1.Size = New System.Drawing.Size(49, 50) Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.PictureBox1.TabIndex = 6 Me.PictureBox1.TabStop = False Me.ToolTip1.SetToolTip(Me.PictureBox1, "Quitter l'application") ' 'Label2 ' Me.Label2.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.Label2.AutoSize = True Me.Label2.BackColor = System.Drawing.Color.Transparent Me.Label2.Font = New System.Drawing.Font("Baskerville Old Face", 12.0!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label2.ForeColor = System.Drawing.Color.White Me.Label2.Location = New System.Drawing.Point(539, 101) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(86, 18) Me.Label2.TabIndex = 1 Me.Label2.Text = "Utilisateur : " Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'LabelLogo ' Me.LabelLogo.AutoSize = True Me.LabelLogo.Font = New System.Drawing.Font("Agency FB", 50.0!, System.Drawing.FontStyle.Bold) Me.LabelLogo.ForeColor = System.Drawing.Color.White Me.LabelLogo.Location = New System.Drawing.Point(5, 7) Me.LabelLogo.Name = "LabelLogo" Me.LabelLogo.Size = New System.Drawing.Size(608, 80) Me.LabelLogo.TabIndex = 5 Me.LabelLogo.Text = "HG Group Agro & Business" ' 'labelUser ' Me.labelUser.BackColor = System.Drawing.Color.Transparent Me.labelUser.Font = New System.Drawing.Font("Baskerville Old Face", 24.0!, CType((System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Italic), System.Drawing.FontStyle), System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.labelUser.ForeColor = System.Drawing.Color.White Me.labelUser.Location = New System.Drawing.Point(619, 87) Me.labelUser.Name = "labelUser" Me.labelUser.Size = New System.Drawing.Size(130, 36) Me.labelUser.TabIndex = 0 Me.labelUser.Text = "Admin" ' 'Button8 ' Me.Button8.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Button8.Cursor = System.Windows.Forms.Cursors.Hand Me.Button8.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer)) Me.Button8.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button8.ForeColor = System.Drawing.Color.FromArgb(CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer)) Me.Button8.Image = CType(resources.GetObject("Button8.Image"), System.Drawing.Image) Me.Button8.Location = New System.Drawing.Point(353, 475) Me.Button8.Margin = New System.Windows.Forms.Padding(4) Me.Button8.Name = "Button8" Me.Button8.Size = New System.Drawing.Size(270, 138) Me.Button8.TabIndex = 2 Me.Button8.Text = "UTILISATEURS" Me.Button8.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText Me.Button8.UseVisualStyleBackColor = False ' 'Button7 ' Me.Button7.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Button7.Cursor = System.Windows.Forms.Cursors.Hand Me.Button7.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer)) Me.Button7.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button7.ForeColor = System.Drawing.Color.FromArgb(CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer)) Me.Button7.Image = CType(resources.GetObject("Button7.Image"), System.Drawing.Image) Me.Button7.Location = New System.Drawing.Point(70, 475) Me.Button7.Margin = New System.Windows.Forms.Padding(4) Me.Button7.Name = "Button7" Me.Button7.Size = New System.Drawing.Size(270, 138) Me.Button7.TabIndex = 2 Me.Button7.Text = "FERMERTURE" Me.Button7.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText Me.Button7.UseVisualStyleBackColor = False ' 'Button6 ' Me.Button6.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Button6.Cursor = System.Windows.Forms.Cursors.Hand Me.Button6.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer)) Me.Button6.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button6.ForeColor = System.Drawing.Color.FromArgb(CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer)) Me.Button6.Image = CType(resources.GetObject("Button6.Image"), System.Drawing.Image) Me.Button6.Location = New System.Drawing.Point(637, 310) Me.Button6.Margin = New System.Windows.Forms.Padding(4) Me.Button6.Name = "Button6" Me.Button6.Size = New System.Drawing.Size(270, 138) Me.Button6.TabIndex = 2 Me.Button6.Text = "JOURNAL DES VENTES" Me.Button6.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText Me.Button6.UseVisualStyleBackColor = False ' 'Button5 ' Me.Button5.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(252, Byte), Integer), CType(CType(253, Byte), Integer), CType(CType(255, Byte), Integer)) Me.Button5.Cursor = System.Windows.Forms.Cursors.Hand Me.Button5.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer), CType(CType(153, Byte), Integer)) Me.Button5.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button5.ForeColor = System.Drawing.Color.FromArgb(CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer)) Me.Button5.Image = CType(resources.GetObject("Button5.Image"), System.Drawing.Image) Me.Button5.Location = New System.Drawing.Point(353, 310) Me.Button5.Margin = New System.Windows.Forms.Padding(4) Me.Button5.Name = "Button5" Me.Button5.Size = New System.Drawing.Size(270, 138) Me.Button5.TabIndex = 2 Me.Button5.Text = "JOURNAL DE CAISSE" Me.Button5.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText Me.Button5.UseVisualStyleBackColor = False ' 'TimerLabel ' Me.TimerLabel.Interval = 1000 ' 'SidePanel ' Me.SidePanel.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles) Me.SidePanel.BackColor = System.Drawing.Color.FromArgb(CType(CType(80, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer)) Me.SidePanel.Controls.Add(Me.TabControl1) Me.SidePanel.Controls.Add(Me.Label1) Me.SidePanel.Controls.Add(Me.LabelDate) Me.SidePanel.Controls.Add(Me.LabelHeure) Me.SidePanel.Location = New System.Drawing.Point(0, 30) Me.SidePanel.Name = "SidePanel" Me.SidePanel.Size = New System.Drawing.Size(291, 711) Me.SidePanel.TabIndex = 6 ' 'TabControl1 ' Me.TabControl1.Controls.Add(Me.TabPage1) Me.TabControl1.Controls.Add(Me.TabPage2) Me.TabControl1.Location = New System.Drawing.Point(-6, 166) Me.TabControl1.Name = "TabControl1" Me.TabControl1.SelectedIndex = 0 Me.TabControl1.Size = New System.Drawing.Size(309, 467) Me.TabControl1.TabIndex = 8 ' 'TabPage1 ' Me.TabPage1.Controls.Add(Me.ListProduits) Me.TabPage1.Location = New System.Drawing.Point(4, 31) Me.TabPage1.Name = "TabPage1" Me.TabPage1.Padding = New System.Windows.Forms.Padding(3) Me.TabPage1.Size = New System.Drawing.Size(301, 432) Me.TabPage1.TabIndex = 0 Me.TabPage1.Text = "CHAMBRE FROIDE" Me.TabPage1.UseVisualStyleBackColor = True ' 'ListProduits ' Me.ListProduits.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ColumnHeader1, Me.ColumnHeader2, Me.ColumnHeader3}) Me.ListProduits.Dock = System.Windows.Forms.DockStyle.Fill Me.ListProduits.GridLines = True Me.ListProduits.Location = New System.Drawing.Point(3, 3) Me.ListProduits.Name = "ListProduits" Me.ListProduits.Size = New System.Drawing.Size(295, 426) Me.ListProduits.TabIndex = 7 Me.ListProduits.UseCompatibleStateImageBehavior = False Me.ListProduits.View = System.Windows.Forms.View.Details ' 'ColumnHeader1 ' Me.ColumnHeader1.Text = "id" Me.ColumnHeader1.Width = 0 ' 'ColumnHeader2 ' Me.ColumnHeader2.Text = "Nom du produit" Me.ColumnHeader2.Width = 228 ' 'ColumnHeader3 ' Me.ColumnHeader3.Text = "Qte" ' 'TabPage2 ' Me.TabPage2.Controls.Add(Me.ListProduitBouch) Me.TabPage2.Location = New System.Drawing.Point(4, 31) Me.TabPage2.Name = "TabPage2" Me.TabPage2.Padding = New System.Windows.Forms.Padding(3) Me.TabPage2.Size = New System.Drawing.Size(301, 432) Me.TabPage2.TabIndex = 1 Me.TabPage2.Text = "BOUCHERIE" Me.TabPage2.UseVisualStyleBackColor = True ' 'ListProduitBouch ' Me.ListProduitBouch.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ColumnHeader4, Me.ColumnHeader5, Me.ColumnHeader6}) Me.ListProduitBouch.Dock = System.Windows.Forms.DockStyle.Fill Me.ListProduitBouch.GridLines = True Me.ListProduitBouch.Location = New System.Drawing.Point(3, 3) Me.ListProduitBouch.Name = "ListProduitBouch" Me.ListProduitBouch.Size = New System.Drawing.Size(295, 426) Me.ListProduitBouch.TabIndex = 8 Me.ListProduitBouch.UseCompatibleStateImageBehavior = False Me.ListProduitBouch.View = System.Windows.Forms.View.Details ' 'ColumnHeader4 ' Me.ColumnHeader4.Text = "id" Me.ColumnHeader4.Width = 0 ' 'ColumnHeader5 ' Me.ColumnHeader5.Text = "Nom du produit" Me.ColumnHeader5.Width = 228 ' 'ColumnHeader6 ' Me.ColumnHeader6.Text = "Qte" ' 'Label1 ' Me.Label1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.Label1.BackColor = System.Drawing.Color.Transparent Me.Label1.Font = New System.Drawing.Font("Baskerville Old Face", 12.0!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label1.ForeColor = System.Drawing.Color.White Me.Label1.Location = New System.Drawing.Point(-4, 141) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(292, 26) Me.Label1.TabIndex = 1 Me.Label1.Text = "Produits a cours de stock" Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'LabelDate ' Me.LabelDate.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.LabelDate.BackColor = System.Drawing.Color.Transparent Me.LabelDate.Font = New System.Drawing.Font("Baskerville Old Face", 12.0!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.LabelDate.ForeColor = System.Drawing.Color.White Me.LabelDate.Location = New System.Drawing.Point(-4, 97) Me.LabelDate.Name = "LabelDate" Me.LabelDate.Size = New System.Drawing.Size(292, 26) Me.LabelDate.TabIndex = 1 Me.LabelDate.Text = "16 Septembre 2016" Me.LabelDate.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'LabelHeure ' Me.LabelHeure.AutoSize = True Me.LabelHeure.BackColor = System.Drawing.Color.Transparent Me.LabelHeure.Font = New System.Drawing.Font("Baskerville Old Face", 48.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.LabelHeure.ForeColor = System.Drawing.Color.White Me.LabelHeure.Location = New System.Drawing.Point(25, 24) Me.LabelHeure.Name = "LabelHeure" Me.LabelHeure.Size = New System.Drawing.Size(250, 73) Me.LabelHeure.TabIndex = 0 Me.LabelHeure.Text = "00:00:00" ' 'ToolTip1 ' Me.ToolTip1.IsBalloon = True ' 'bgWorker ' Me.bgWorker.WorkerReportsProgress = True ' 'Main ' Me.AutoScaleDimensions = New System.Drawing.SizeF(9.0!, 22.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.White Me.BackgroundImage = Global.HG.My.Resources.Resources.background Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.ClientSize = New System.Drawing.Size(1276, 742) Me.Controls.Add(Me.SidePanel) Me.Controls.Add(Me.PanelContainer) Me.Controls.Add(Me.MenuStrip1) Me.DoubleBuffered = True Me.Font = New System.Drawing.Font("Open Sans", 12.0!) Me.ForeColor = System.Drawing.Color.FromArgb(CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer), CType(CType(17, Byte), Integer)) Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MainMenuStrip = Me.MenuStrip1 Me.Margin = New System.Windows.Forms.Padding(4) Me.Name = "Main" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Fenetre principale" Me.WindowState = System.Windows.Forms.FormWindowState.Maximized Me.MenuStrip1.ResumeLayout(False) Me.MenuStrip1.PerformLayout() Me.PanelContainer.ResumeLayout(False) Me.PanelContainer.PerformLayout() CType(Me.PictureBox2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit() Me.SidePanel.ResumeLayout(False) Me.SidePanel.PerformLayout() Me.TabControl1.ResumeLayout(False) Me.TabPage1.ResumeLayout(False) Me.TabPage2.ResumeLayout(False) Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents Button2 As System.Windows.Forms.Button Friend WithEvents Button3 As System.Windows.Forms.Button Friend WithEvents Button4 As System.Windows.Forms.Button Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip Friend WithEvents PanelContainer As System.Windows.Forms.Panel Friend WithEvents TimerLabel As System.Windows.Forms.Timer Friend WithEvents LabelLogo As HG.UI.TransparentLabel Friend WithEvents Button5 As System.Windows.Forms.Button Friend WithEvents SidePanel As System.Windows.Forms.Panel Friend WithEvents LabelHeure As System.Windows.Forms.Label Friend WithEvents LabelDate As System.Windows.Forms.Label Friend WithEvents Button6 As System.Windows.Forms.Button Friend WithEvents VenteToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents FacturesToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents RapportsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents JournalDeCaisseToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator1 As System.Windows.Forms.ToolStripSeparator Friend WithEvents JournalDeVenteToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents StocksToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents HistoriqueDesStocksToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator2 As System.Windows.Forms.ToolStripSeparator Friend WithEvents EnregistreUnStockToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents RapportsToolStripMenuItem1 As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ApplicationToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents FermerLaSessionToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents QuitterToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator3 As System.Windows.Forms.ToolStripSeparator Friend WithEvents ParametresToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents labelUser As System.Windows.Forms.Label Friend WithEvents Button7 As System.Windows.Forms.Button Friend WithEvents Button8 As System.Windows.Forms.Button Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox Friend WithEvents PictureBox2 As System.Windows.Forms.PictureBox Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip Friend WithEvents ToolStripSeparator5 As System.Windows.Forms.ToolStripSeparator Friend WithEvents MouvementsDeCaisseToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripMenuItem1 As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ParProduitToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ParEnregitrementToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator4 As System.Windows.Forms.ToolStripSeparator Friend WithEvents ModifierLeStockToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents FacturesImpayeesToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents JournalDeMouvementDeCaisseToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator7 As System.Windows.Forms.ToolStripSeparator Friend WithEvents NouveauToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ListeDesClientsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator8 As System.Windows.Forms.ToolStripSeparator Friend WithEvents NouveauClientToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents FinancesToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents TypeDesMouvementsDeCaisseToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator9 As System.Windows.Forms.ToolStripSeparator Friend WithEvents EtablissementToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents ListProduits As System.Windows.Forms.ListView Friend WithEvents ColumnHeader1 As System.Windows.Forms.ColumnHeader Friend WithEvents ColumnHeader2 As System.Windows.Forms.ColumnHeader Friend WithEvents ColumnHeader3 As System.Windows.Forms.ColumnHeader Friend WithEvents LesProduitsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ListeDesProduitsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator10 As System.Windows.Forms.ToolStripSeparator Friend WithEvents NouveauProduitToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents UtilisateursToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents FinDeJournerToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator11 As System.Windows.Forms.ToolStripSeparator Friend WithEvents ToolStripSeparator12 As System.Windows.Forms.ToolStripSeparator Friend WithEvents TabControl1 As System.Windows.Forms.TabControl Friend WithEvents TabPage1 As System.Windows.Forms.TabPage Friend WithEvents TabPage2 As System.Windows.Forms.TabPage Friend WithEvents ListProduitBouch As System.Windows.Forms.ListView Friend WithEvents ColumnHeader4 As System.Windows.Forms.ColumnHeader Friend WithEvents ColumnHeader5 As System.Windows.Forms.ColumnHeader Friend WithEvents ColumnHeader6 As System.Windows.Forms.ColumnHeader Friend WithEvents ToolStripSeparator6 As System.Windows.Forms.ToolStripSeparator Friend WithEvents FacturesClientToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents bgWorker As System.ComponentModel.BackgroundWorker Friend WithEvents RapportsToolStripMenuItem2 As System.Windows.Forms.ToolStripMenuItem Friend WithEvents RapportDeStockToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator13 As System.Windows.Forms.ToolStripSeparator Friend WithEvents ClassementClientsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator14 As System.Windows.Forms.ToolStripSeparator Friend WithEvents RapportDeVenteToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator15 As System.Windows.Forms.ToolStripSeparator Friend WithEvents DashboardToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar Friend WithEvents ToolStripSeparator17 As System.Windows.Forms.ToolStripSeparator Friend WithEvents DetteClientsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripSeparator18 As System.Windows.Forms.ToolStripSeparator Friend WithEvents AProposToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem End Class
lepresk/HG
HG/Main.Designer.vb
Visual Basic
mit
59,225
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Runtime.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Enum Feature AutoProperties LineContinuation StatementLambdas CoContraVariance CollectionInitializers SubLambdas ArrayLiterals AsyncExpressions Iterators GlobalNamespace NullPropagatingOperator NameOfExpressions InterpolatedStrings ReadonlyAutoProperties RegionsEverywhere MultilineStringLiterals CObjInAttributeArguments LineContinuationComments TypeOfIsNot YearFirstDateLiterals WarningDirectives PartialModules PartialInterfaces ImplementingReadonlyOrWriteonlyPropertyWithReadwrite DigitSeparators BinaryLiterals Tuples IOperation InferredTupleNames LeadingDigitSeparator NonTrailingNamedArguments End Enum Friend Module FeatureExtensions <Extension> Friend Function GetFeatureFlag(feature As Feature) As String Select Case feature Case feature.IOperation Return "IOperation" Case Else Return Nothing End Select End Function <Extension> Friend Function GetLanguageVersion(feature As Feature) As LanguageVersion Select Case feature Case Feature.AutoProperties, Feature.LineContinuation, Feature.StatementLambdas, Feature.CoContraVariance, Feature.CollectionInitializers, Feature.SubLambdas, Feature.ArrayLiterals Return LanguageVersion.VisualBasic10 Case Feature.AsyncExpressions, Feature.Iterators, Feature.GlobalNamespace Return LanguageVersion.VisualBasic11 Case Feature.NullPropagatingOperator, Feature.NameOfExpressions, Feature.InterpolatedStrings, Feature.ReadonlyAutoProperties, Feature.RegionsEverywhere, Feature.MultilineStringLiterals, Feature.CObjInAttributeArguments, Feature.LineContinuationComments, Feature.TypeOfIsNot, Feature.YearFirstDateLiterals, Feature.WarningDirectives, Feature.PartialModules, Feature.PartialInterfaces, Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Return LanguageVersion.VisualBasic14 Case Feature.Tuples, Feature.BinaryLiterals, Feature.DigitSeparators Return LanguageVersion.VisualBasic15 Case Feature.InferredTupleNames Return LanguageVersion.VisualBasic15_3 Case Feature.LeadingDigitSeparator, Feature.NonTrailingNamedArguments Return LanguageVersion.VisualBasic15_5 Case Else Throw ExceptionUtilities.UnexpectedValue(feature) End Select End Function <Extension> Friend Function GetResourceId(feature As Feature) As ERRID Select Case feature Case Feature.AutoProperties Return ERRID.FEATURE_AutoProperties Case Feature.ReadonlyAutoProperties Return ERRID.FEATURE_ReadonlyAutoProperties Case Feature.LineContinuation Return ERRID.FEATURE_LineContinuation Case Feature.StatementLambdas Return ERRID.FEATURE_StatementLambdas Case Feature.CoContraVariance Return ERRID.FEATURE_CoContraVariance Case Feature.CollectionInitializers Return ERRID.FEATURE_CollectionInitializers Case Feature.SubLambdas Return ERRID.FEATURE_SubLambdas Case Feature.ArrayLiterals Return ERRID.FEATURE_ArrayLiterals Case Feature.AsyncExpressions Return ERRID.FEATURE_AsyncExpressions Case Feature.Iterators Return ERRID.FEATURE_Iterators Case Feature.GlobalNamespace Return ERRID.FEATURE_GlobalNamespace Case Feature.NullPropagatingOperator Return ERRID.FEATURE_NullPropagatingOperator Case Feature.NameOfExpressions Return ERRID.FEATURE_NameOfExpressions Case Feature.RegionsEverywhere Return ERRID.FEATURE_RegionsEverywhere Case Feature.MultilineStringLiterals Return ERRID.FEATURE_MultilineStringLiterals Case Feature.CObjInAttributeArguments Return ERRID.FEATURE_CObjInAttributeArguments Case Feature.LineContinuationComments Return ERRID.FEATURE_LineContinuationComments Case Feature.TypeOfIsNot Return ERRID.FEATURE_TypeOfIsNot Case Feature.YearFirstDateLiterals Return ERRID.FEATURE_YearFirstDateLiterals Case Feature.WarningDirectives Return ERRID.FEATURE_WarningDirectives Case Feature.PartialModules Return ERRID.FEATURE_PartialModules Case Feature.PartialInterfaces Return ERRID.FEATURE_PartialInterfaces Case Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Return ERRID.FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Case Feature.DigitSeparators Return ERRID.FEATURE_DigitSeparators Case Feature.BinaryLiterals Return ERRID.FEATURE_BinaryLiterals Case Feature.Tuples Return ERRID.FEATURE_Tuples Case Feature.IOperation Return ERRID.FEATURE_IOperation Case Feature.LeadingDigitSeparator Return ERRID.FEATURE_LeadingDigitSeparator Case Else Throw ExceptionUtilities.UnexpectedValue(feature) End Select End Function End Module End Namespace
TyOverby/roslyn
src/Compilers/VisualBasic/Portable/Parser/ParserFeature.vb
Visual Basic
apache-2.0
6,882
' 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 Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class WithBlockSemanticModelTests Inherits FlowTestBase #Region "Symbol / Type Info" <Fact> Public Sub WithAliasedStaticField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports Alias1 = ClassWithField Class ClassWithField Public Shared field1 As String = "a" End Class Module WithAliasedStaticField Sub Main() With Alias1.field1 'BIND:"Alias1.field1" Dim newString = .Replace("a", "b") End With End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim withExpression = DirectCast(tree.GetCompilationUnitRoot().DescendantNodes().Where(Function(n) n.Kind = SyntaxKind.SimpleMemberAccessExpression).First(), MemberAccessExpressionSyntax) Assert.Equal("Alias1", model.GetAliasInfo(DirectCast(withExpression.Expression, IdentifierNameSyntax)).ToDisplayString()) Assert.False(model.GetConstantValue(withExpression).HasValue) Dim typeInfo = model.GetTypeInfo(withExpression) Assert.Equal("String", typeInfo.Type.ToDisplayString()) Assert.Equal("String", typeInfo.ConvertedType.ToDisplayString()) Dim conv = model.GetConversion(withExpression) Assert.Equal(ConversionKind.Identity, conv.Kind) Dim symbolInfo = model.GetSymbolInfo(withExpression) Assert.Equal("Public Shared field1 As String", symbolInfo.Symbol.ToDisplayString()) Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(0, model.GetMemberGroup(withExpression).Length) End Sub <Fact> Public Sub WithDeclaresAnonymousLocalSymbolAndTypeInfo() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module WithDeclaresAnonymousLocalSymbolAndTypeInfo Sub Main() With New With {.A = 1, .B = "2"} 'BIND:"New With {.A = 1, .B = "2"}" .A = .B End With End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AnonymousObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Alias) Assert.False(semanticInfo.ConstantValue.HasValue) Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.Type.ToDisplayString()) Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.ConvertedType.ToDisplayString()) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Public Sub New(A As Integer, B As String)", semanticInfo.Symbol.ToDisplayString()) ' should get constructor for anonymous type Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) End Sub <Fact(), WorkItem(544083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544083")> Public Sub WithSpeculativeSymbolInfo() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C1 Property Property1 As Integer Property Property2 As String End Class Module Module1 Sub Main() Dim x As New C1() With x Dim f = Function() .Property1 'BINDHERE End With End Sub End Module </file> </compilation>) Dim semanticModel = GetSemanticModel(compilation, "a.vb") Dim position = compilation.SyntaxTrees.Single().ToString().IndexOf("'BINDHERE", StringComparison.Ordinal) Dim expr = SyntaxFactory.ParseExpression(".property2") Dim speculativeTypeInfo = semanticModel.GetSpeculativeTypeInfo(position, expr, SpeculativeBindingOption.BindAsExpression) Assert.Equal("String", speculativeTypeInfo.ConvertedType.ToDisplayString()) Dim conv = semanticModel.GetSpeculativeConversion(position, expr, SpeculativeBindingOption.BindAsExpression) Assert.Equal(ConversionKind.Identity, conv.Kind) Assert.Equal("String", speculativeTypeInfo.Type.ToDisplayString()) Dim speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, SyntaxFactory.ParseExpression(".property2"), SpeculativeBindingOption.BindAsExpression) Assert.Equal("Public Property Property2 As String", speculativeSymbolInfo.Symbol.ToDisplayString()) Assert.Equal(SymbolKind.Property, speculativeSymbolInfo.Symbol.Kind) End Sub #End Region #Region "FlowAnalysis" <Fact> Public Sub UseWithVariableInNestedLambda() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Class C1 Property Property1 As Integer End Class Module Module1 Sub Main() Dim x As New C1() With x Dim f = Function() [|Return .Property1|] End Function End With End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Dim dataFlowResults = analysis.Item2 Assert.Empty(dataFlowResults.VariablesDeclared) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Empty(dataFlowResults.DataFlowsIn) Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Empty(dataFlowResults.ReadInside) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Empty(dataFlowResults.WrittenInside) Assert.Equal("x, f", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) Assert.Empty(controlFlowResults.EntryPoints) Assert.False(controlFlowResults.EndPointIsReachable) Assert.True(controlFlowResults.StartPointIsReachable) Assert.Equal(1, controlFlowResults.ExitPoints.Count) End Sub <Fact> Public Sub WithDeclaresAnonymousLocalDataFlow() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Module WithDeclaresAnonymousLocal Sub Main() With New With {.A = 1, .B = "2"} [|.A = .B|] End With End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Dim dataFlowResults = analysis.Item2 Assert.Empty(dataFlowResults.VariablesDeclared) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Empty(dataFlowResults.DataFlowsIn) ' assume anonymous locals don't show Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Empty(dataFlowResults.ReadInside) ' assume anonymous locals don't show Assert.Empty(dataFlowResults.ReadOutside) Assert.Empty(dataFlowResults.WrittenInside) Assert.Empty(dataFlowResults.WrittenOutside) ' assume anonymous locals don't show Assert.Empty(controlFlowResults.ExitPoints) Assert.Empty(controlFlowResults.EntryPoints) Assert.True(controlFlowResults.EndPointIsReachable) Assert.True(controlFlowResults.StartPointIsReachable) End Sub <Fact> Public Sub EmptyWith() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As Object() [|With x End With|] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Dim dataFlowResults = analysis.Item2 Assert.Empty(dataFlowResults.VariablesDeclared) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Empty(dataFlowResults.ReadOutside) Assert.Empty(dataFlowResults.WrittenInside) Assert.Empty(dataFlowResults.WrittenOutside) Assert.Empty(controlFlowResults.ExitPoints) Assert.Empty(controlFlowResults.EntryPoints) Assert.True(controlFlowResults.EndPointIsReachable) Assert.True(controlFlowResults.StartPointIsReachable) End Sub #End Region <Fact, WorkItem(2662, "https://github.com/dotnet/roslyn/issues/2662")> Public Sub Issue2662() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module Program Sub Main(args As String()) End Sub Private Sub AddCustomer() Dim theCustomer As New Customer With theCustomer .Name = "Abc" .URL = "http://www.microsoft.com/" .City = "Redmond" .Print(.Name) End With End Sub <Extension()> Public Sub Print(ByVal cust As Customer, str As String) Console.WriteLine(str) End Sub Public Class Customer Public Property Name As String Public Property City As String Public Property URL As String Public Property Comments As New List(Of String) End Class End Module ]]></file> </compilation>, {SystemCoreRef}) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim withBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of WithBlockSyntax)().Single() Dim name = withBlock.Statements(3).DescendantNodes().OfType(Of IdentifierNameSyntax).Where(Function(i) i.Identifier.ValueText = "Name").Single() model.GetAliasInfo(name) Dim result2 = model.AnalyzeDataFlow(withBlock, withBlock) Assert.True(result2.Succeeded) model = compilation.GetSemanticModel(tree) model.GetAliasInfo(name) Assert.Equal("theCustomer As Program.Customer", model.GetSymbolInfo(withBlock.WithStatement.Expression).Symbol.ToTestDisplayString()) End Sub <Fact> <WorkItem(187910, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=187910&_a=edit")> Public Sub Bug187910() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class ClassWithField Public field1 As String = "a" End Class Class WithAliasedStaticField Sub Test(parameter as ClassWithField) With parameter System.Console.WriteLine(.field1) End With End Sub End Class </file> </compilation>) Dim compilationB = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="b.vb"> Class WithAliasedStaticField1 Sub Test(parameter as ClassWithField) With parameter System.Console.WriteLine(.field1) End With End Sub End Class </file> </compilation>) compilation.AssertTheseDiagnostics() Dim treeA = compilation.SyntaxTrees.Single() Dim modelA = compilation.GetSemanticModel(treeA) Dim parameter = treeA.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "parameter").First() Assert.Equal("Sub WithAliasedStaticField.Test(parameter As ClassWithField)", modelA.GetEnclosingSymbol(parameter.SpanStart).ToTestDisplayString()) Dim treeB = compilationB.SyntaxTrees.Single() Dim withBlockB = treeB.GetCompilationUnitRoot().DescendantNodes().OfType(Of WithBlockSyntax)().Single() Dim modelAB As SemanticModel = Nothing Assert.True(modelA.TryGetSpeculativeSemanticModel(parameter.Parent.Parent.SpanStart, withBlockB, modelAB)) Assert.Equal("Sub WithAliasedStaticField.Test(parameter As ClassWithField)", modelAB.GetEnclosingSymbol(withBlockB.WithStatement.Expression.SpanStart).ToTestDisplayString()) End Sub <Fact> <WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")> Public Sub WithTargetAsArgument_01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class Base End Class Class Derived Inherits Base Public Function Contains(node As Base) As Boolean Return True End Function End Class Module Ext Sub M(vbNode As Derived) With vbNode If .Contains(vbNode) Then End If End With End Sub End Module </file> </compilation>) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray() Dim symbolInfo1 = model.GetSymbolInfo(nodes(0)) Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind) Dim symbolInfo2 = model.GetSymbolInfo(nodes(1)) Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind) Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol) End Sub <Fact> <WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")> Public Sub WithTargetAsArgument_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class Base End Class Class Derived Inherits Base End Class Module Ext <System.Runtime.CompilerServices.Extension()> Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode Return Nothing End Function Sub M(vbNode As Derived) With vbNode If .GetCurrent(vbNode) Is Nothing Then End If End With End Sub End Module ]]></file> </compilation>, additionalRefs:={SystemCoreRef}) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray() Dim symbolInfo1 = model.GetSymbolInfo(nodes(0)) Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind) Dim symbolInfo2 = model.GetSymbolInfo(nodes(1)) Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind) Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol) End Sub <Fact> <WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")> Public Sub WithTargetAsArgument_03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class Base End Class Class Derived Inherits Base Public Function Contains(node As Base) As Boolean Return True End Function End Class Module Ext <System.Runtime.CompilerServices.Extension()> Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode Return Nothing End Function Sub M(vbNode As Derived) With vbNode If .GetCurrent(vbNode) Is Nothing Then End If If .Contains(vbNode) Then End If End With End Sub End Module ]]></file> </compilation>, additionalRefs:={SystemCoreRef}) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray() Dim symbolInfo1 = model.GetSymbolInfo(nodes(0)) Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind) Dim symbolInfo2 = model.GetSymbolInfo(nodes(1)) Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind) Dim symbolInfo3 = model.GetSymbolInfo(nodes(2)) Assert.Equal("vbNode As Derived", symbolInfo3.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, symbolInfo3.Symbol.Kind) Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol) Assert.Same(symbolInfo1.Symbol, symbolInfo3.Symbol) End Sub <Fact> <WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")> Public Sub WithTargetAsArgument_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class Base End Class Class Derived Inherits Base End Class Module Ext <System.Runtime.CompilerServices.Extension()> Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode Return Nothing End Function readonly property vbNode As Derived Get return nothing End Get End Property Sub M() With vbNode If .GetCurrent(vbNode) Is Nothing Then End If End With End Sub End Module ]]></file> </compilation>, additionalRefs:={SystemCoreRef}) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray() Dim symbolInfo1 = model.GetSymbolInfo(nodes(0)) Assert.Equal("ReadOnly Property Ext.vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, symbolInfo1.Symbol.Kind) Dim symbolInfo2 = model.GetSymbolInfo(nodes(1)) Assert.Equal("ReadOnly Property Ext.vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, symbolInfo2.Symbol.Kind) Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol) End Sub End Class End Namespace
abock/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockSemanticModelTests.vb
Visual Basic
mit
19,856
'*******************************************************************************************' ' ' ' Download Free Evaluation Version From: https://bytescout.com/download/web-installer ' ' ' ' Also available as Web API! Get free API Key https://app.pdf.co/signup ' ' ' ' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. ' ' https://www.bytescout.com ' ' https://www.pdf.co ' '*******************************************************************************************' Imports System.Collections.Generic Imports System.Diagnostics Imports System.IO Imports System.Text Imports Bytescout.Spreadsheet Imports Bytescout.Spreadsheet.MSODrawing Namespace AddImages Class Program Friend Shared Sub Main(args As String()) ' Create spreadsheet Dim doc As New Spreadsheet() ' Add worksheet Dim worksheet As Worksheet = doc.Worksheets.Add() ' Put an image to "C3" cell Dim shape As PictureShape = worksheet.Pictures.Add(2, 2, "image1.jpg") ' Make the picture "floating". It will be not moved if you move or resize the "C3" cell shape.PlacementType = Placement.FreeFloating ' Make the picture brighter shape.Brightness = 0.8F ' Put second image to "K11" cell shape = worksheet.Pictures.Add(10, 10, "image2.jpg") ' Make the picture bound to the cell. It will be moved alonf with the "K11" cell shape.PlacementType = Placement.Move ' Crop 10% from left and right side of the image shape.CropFromLeft = 0.1F shape.CropFromRight = 0.1F ' Delete output file if exists If File.Exists("output.xls") Then File.Delete("output.xls") End If ' Save document doc.SaveAs("output.xls") ' Close spreadsheet doc.Close() ' Open generated XLS document in default application Process.Start("output.xls") doc.Dispose() End Sub End Class End Namespace
bytescout/ByteScout-SDK-SourceCode
Spreadsheet SDK/VB.NET/Add Images Advanced/Program.vb
Visual Basic
apache-2.0
2,349
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Organizing Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Organizing <[UseExportProvider]> Public MustInherit Class AbstractOrganizerTests Protected Async Function CheckAsync(initial As XElement, final As XElement) As System.Threading.Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic(initial.NormalizedValue) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Dim newRoot = Await (Await OrganizingService.OrganizeAsync(document)).GetSyntaxRootAsync() Assert.Equal(final.NormalizedValue, newRoot.ToFullString()) End Using End Function End Class End Namespace
abock/roslyn
src/EditorFeatures/VisualBasicTest/Organizing/AbstractOrganizerTests.vb
Visual Basic
mit
1,129
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Text.RegularExpressions Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports System.Reflection Namespace Microsoft.CodeAnalysis.VisualBasic ' This portion of the binder converts an ExpressionSyntax into a BoundExpression Partial Friend Class Binder ' !!! PLEASE KEEP BindExpression FUNCTION AT THE TOP !!! Public Function BindExpression( node As ExpressionSyntax, diagnostics As DiagnosticBag ) As BoundExpression Return BindExpression(node, False, False, False, diagnostics) End Function ''' <summary> ''' The dispatcher method that handles syntax nodes for all stand-alone expressions. ''' </summary> Public Function BindExpression( node As ExpressionSyntax, isInvocationOrAddressOf As Boolean, isOperandOfConditionalBranch As Boolean, eventContext As Boolean, diagnostics As DiagnosticBag ) As BoundExpression If IsEarlyAttributeBinder AndAlso Not EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node, Me) Then Return BadExpression(node, ErrorTypeSymbol.UnknownResultType) End If Select Case node.Kind Case SyntaxKind.MeExpression Return BindMeExpression(DirectCast(node, MeExpressionSyntax), diagnostics) Case SyntaxKind.MyBaseExpression Return BindMyBaseExpression(DirectCast(node, MyBaseExpressionSyntax), diagnostics) Case SyntaxKind.MyClassExpression Return BindMyClassExpression(DirectCast(node, MyClassExpressionSyntax), diagnostics) Case SyntaxKind.IdentifierName, SyntaxKind.GenericName Return BindSimpleName(DirectCast(node, SimpleNameSyntax), isInvocationOrAddressOf, diagnostics) Case SyntaxKind.PredefinedType, SyntaxKind.NullableType Return BindNamespaceOrTypeExpression(DirectCast(node, TypeSyntax), diagnostics) Case SyntaxKind.SimpleMemberAccessExpression Return BindMemberAccess(DirectCast(node, MemberAccessExpressionSyntax), eventContext, diagnostics:=diagnostics) Case SyntaxKind.DictionaryAccessExpression Return BindDictionaryAccess(DirectCast(node, MemberAccessExpressionSyntax), diagnostics) Case SyntaxKind.InvocationExpression Return BindInvocationExpression(DirectCast(node, InvocationExpressionSyntax), diagnostics) Case SyntaxKind.CollectionInitializer Return BindArrayLiteralExpression(DirectCast(node, CollectionInitializerSyntax), diagnostics) Case SyntaxKind.AnonymousObjectCreationExpression Return BindAnonymousObjectCreationExpression(DirectCast(node, AnonymousObjectCreationExpressionSyntax), diagnostics) Case SyntaxKind.ArrayCreationExpression Return BindArrayCreationExpression(DirectCast(node, ArrayCreationExpressionSyntax), diagnostics) Case SyntaxKind.ObjectCreationExpression Return BindObjectCreationExpression(DirectCast(node, ObjectCreationExpressionSyntax), diagnostics) Case SyntaxKind.NumericLiteralExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.CharacterLiteralExpression, SyntaxKind.TrueLiteralExpression, SyntaxKind.FalseLiteralExpression, SyntaxKind.NothingLiteralExpression, SyntaxKind.DateLiteralExpression Return BindLiteralConstant(DirectCast(node, LiteralExpressionSyntax), diagnostics) Case SyntaxKind.ParenthesizedExpression ' Parenthesis tokens are ignored, and operand is bound in the context of ' parent expression. ' Dev10 allows parenthesized type expressions, let's bind as a general expression first. Dim operand As BoundExpression = BindExpression(DirectCast(node, ParenthesizedExpressionSyntax).Expression, False, False, eventContext, diagnostics) If operand.Kind = BoundKind.TypeExpression Then Dim asType = DirectCast(operand, BoundTypeExpression) Return New BoundTypeExpression(node, asType.UnevaluatedReceiverOpt, asType.AliasOpt, operand.Type, operand.HasErrors) ElseIf operand.Kind = BoundKind.ArrayLiteral Then ' Convert the array literal to its inferred array type, reporting warnings/errors if necessary. ' It would have been nice to put this reclassification in ReclassifyAsValue, however, that is called in too many situations. We only ' want to reclassify the array literal this early when it is within parentheses. Dim arrayLiteral = DirectCast(operand, BoundArrayLiteral) Dim reclassified = ReclassifyArrayLiteralExpression(SyntaxKind.CTypeKeyword, arrayLiteral.Syntax, ConversionKind.Widening, False, arrayLiteral, arrayLiteral.InferredType, diagnostics) Return New BoundParenthesized(node, reclassified, reclassified.Type) Else Return New BoundParenthesized(node, operand, operand.Type) End If Case SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.NotExpression Return BindUnaryOperator(DirectCast(node, UnaryExpressionSyntax), diagnostics) Case SyntaxKind.AddExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.LikeExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.OrExpression, SyntaxKind.OrElseExpression, SyntaxKind.AndExpression, SyntaxKind.AndAlsoExpression Return BindBinaryOperator(DirectCast(node, BinaryExpressionSyntax), isOperandOfConditionalBranch, diagnostics) Case SyntaxKind.IsExpression, SyntaxKind.IsNotExpression Return BindIsExpression(DirectCast(node, BinaryExpressionSyntax), diagnostics) Case SyntaxKind.GetTypeExpression Return BindGetTypeExpression(DirectCast(node, GetTypeExpressionSyntax), diagnostics) Case SyntaxKind.NameOfExpression Return BindNameOfExpression(DirectCast(node, NameOfExpressionSyntax), diagnostics) Case SyntaxKind.AddressOfExpression Return BindAddressOfExpression(node, diagnostics) Case SyntaxKind.CTypeExpression, SyntaxKind.TryCastExpression, SyntaxKind.DirectCastExpression Return BindCastExpression(DirectCast(node, CastExpressionSyntax), diagnostics) Case SyntaxKind.PredefinedCastExpression Return BindPredefinedCastExpression(DirectCast(node, PredefinedCastExpressionSyntax), diagnostics) Case SyntaxKind.TypeOfIsExpression, SyntaxKind.TypeOfIsNotExpression Return BindTypeOfExpression(DirectCast(node, TypeOfExpressionSyntax), diagnostics) Case SyntaxKind.BinaryConditionalExpression Return BindBinaryConditionalExpression(DirectCast(node, BinaryConditionalExpressionSyntax), diagnostics) Case SyntaxKind.TernaryConditionalExpression Return BindTernaryConditionalExpression(DirectCast(node, TernaryConditionalExpressionSyntax), diagnostics) Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return BindLambdaExpression(DirectCast(node, LambdaExpressionSyntax), diagnostics) Case SyntaxKind.GlobalName Return New BoundNamespaceExpression(node, Nothing, Compilation.GlobalNamespace) Case SyntaxKind.QueryExpression Return BindQueryExpression(DirectCast(node, QueryExpressionSyntax), diagnostics) Case SyntaxKind.GroupAggregation Return BindGroupAggregationExpression(DirectCast(node, GroupAggregationSyntax), diagnostics) Case SyntaxKind.FunctionAggregation Return BindFunctionAggregationExpression(DirectCast(node, FunctionAggregationSyntax), diagnostics) Case SyntaxKind.NextLabel, SyntaxKind.NumericLabel, SyntaxKind.IdentifierLabel Return BindLabel(DirectCast(node, LabelSyntax), diagnostics) Case SyntaxKind.QualifiedName ' This code is not used during method body binding, but it might be used by SemanticModel for erroneous cases. Return BindQualifiedName(DirectCast(node, QualifiedNameSyntax), diagnostics) Case SyntaxKind.GetXmlNamespaceExpression Return BindGetXmlNamespace(DirectCast(node, GetXmlNamespaceExpressionSyntax), diagnostics) Case SyntaxKind.XmlComment Return BindXmlComment(DirectCast(node, XmlCommentSyntax), rootInfoOpt:=Nothing, diagnostics:=diagnostics) Case SyntaxKind.XmlDocument Return BindXmlDocument(DirectCast(node, XmlDocumentSyntax), diagnostics) Case SyntaxKind.XmlProcessingInstruction Return BindXmlProcessingInstruction(DirectCast(node, XmlProcessingInstructionSyntax), diagnostics) Case SyntaxKind.XmlEmptyElement Return BindXmlEmptyElement(DirectCast(node, XmlEmptyElementSyntax), rootInfoOpt:=Nothing, diagnostics:=diagnostics) Case SyntaxKind.XmlElement Return BindXmlElement(DirectCast(node, XmlElementSyntax), rootInfoOpt:=Nothing, diagnostics:=diagnostics) Case SyntaxKind.XmlEmbeddedExpression ' This case handles embedded expressions that are outside of XML ' literals (error cases). The parser will have reported BC31172 ' already, so no error is reported here. (Valid uses of embedded ' expressions are handled explicitly in BindXmlElement, etc.) Return BindXmlEmbeddedExpression(DirectCast(node, XmlEmbeddedExpressionSyntax), diagnostics:=diagnostics) Case SyntaxKind.XmlCDataSection Return BindXmlCData(DirectCast(node, XmlCDataSectionSyntax), rootInfoOpt:=Nothing, diagnostics:=diagnostics) Case SyntaxKind.XmlElementAccessExpression Return BindXmlElementAccess(DirectCast(node, XmlMemberAccessExpressionSyntax), diagnostics) Case SyntaxKind.XmlAttributeAccessExpression Return BindXmlAttributeAccess(DirectCast(node, XmlMemberAccessExpressionSyntax), diagnostics) Case SyntaxKind.XmlDescendantAccessExpression Return BindXmlDescendantAccess(DirectCast(node, XmlMemberAccessExpressionSyntax), diagnostics) Case SyntaxKind.AwaitExpression Return BindAwait(DirectCast(node, AwaitExpressionSyntax), diagnostics) Case SyntaxKind.ConditionalAccessExpression Return BindConditionalAccessExpression(DirectCast(node, ConditionalAccessExpressionSyntax), diagnostics) Case SyntaxKind.InterpolatedStringExpression Return BindInterpolatedStringExpression(DirectCast(node, InterpolatedStringExpressionSyntax), diagnostics) Case Else ' e.g. SyntaxKind.MidExpression is handled elsewhere ' NOTE: There were too many "else" cases to justify listing them explicitly and throwing on ' anything unexpected. Debug.Assert(node.ContainsDiagnostics, String.Format("Unexpected {0} syntax does not have diagnostics", node.Kind)) Return BadExpression(node, ImmutableArray(Of BoundNode).Empty, ErrorTypeSymbol.UnknownResultType) End Select End Function ''' <summary> ''' Create a BoundBadExpression node for the given syntax node. No symbols or bound nodes are associated with it. ''' </summary> Protected Shared Function BadExpression(node As VisualBasicSyntaxNode, resultType As TypeSymbol) As BoundBadExpression Return New BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundNode).Empty, resultType, hasErrors:=True) End Function ''' <summary> ''' Create a BoundBadExpression node for the given child-expression, which is preserved as a sub-expression. ''' No ResultKind is associated ''' </summary> Private Shared Function BadExpression(node As VisualBasicSyntaxNode, expr As BoundNode, resultType As TypeSymbol) As BoundBadExpression Return New BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(Of BoundNode)(expr), resultType, hasErrors:=True) End Function ''' <summary> ''' Create a BoundBadExpression node for the given child-expression, which is preserved as a sub-expression. ''' A ResultKind explains why the node is bad. ''' </summary> Private Shared Function BadExpression(node As VisualBasicSyntaxNode, expr As BoundNode, resultKind As LookupResultKind, resultType As TypeSymbol) As BoundBadExpression Return New BoundBadExpression(node, resultKind, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(Of BoundNode)(expr), resultType, hasErrors:=True) End Function ''' <summary> ''' Create a BoundBadExpression node for the given child expression, which is preserved as a sub-expression. Symbols ''' associated with the child node are not given a result kind. ''' </summary> Private Shared Function BadExpression(node As VisualBasicSyntaxNode, exprs As ImmutableArray(Of BoundNode), resultType As TypeSymbol) As BoundBadExpression Return New BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, exprs, resultType, hasErrors:=True) End Function Private Shared Function BadExpression(expr As BoundExpression) As BoundBadExpression Return BadExpression(LookupResultKind.Empty, expr) End Function ' Use this for a bad expression with no known type, and a single child whose type and syntax is preserved as the type of the bad expression. Private Shared Function BadExpression(resultKind As LookupResultKind, wrappedExpression As BoundExpression) As BoundBadExpression Dim wrappedBadExpression As BoundBadExpression = TryCast(wrappedExpression, BoundBadExpression) If wrappedBadExpression IsNot Nothing Then Return New BoundBadExpression(wrappedBadExpression.Syntax, resultKind, wrappedBadExpression.Symbols, wrappedBadExpression.ChildBoundNodes, wrappedBadExpression.Type, hasErrors:=True) Else Return New BoundBadExpression(wrappedExpression.Syntax, resultKind, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(Of BoundNode)(wrappedExpression), wrappedExpression.Type, hasErrors:=True) End If End Function Public Function BindNamespaceOrTypeExpression(node As TypeSyntax, diagnostics As DiagnosticBag) As BoundExpression Dim symbol = Me.BindNamespaceOrTypeOrAliasSyntax(node, diagnostics) Dim [alias] = TryCast(symbol, AliasSymbol) If [alias] IsNot Nothing Then symbol = [alias].Target ' check for use site errors ReportUseSiteError(diagnostics, node, symbol) End If Dim [type] = TryCast(symbol, TypeSymbol) If [type] IsNot Nothing Then Return New BoundTypeExpression(node, Nothing, [alias], [type]) End If Dim ns = TryCast(symbol, NamespaceSymbol) If ns IsNot Nothing Then Return New BoundNamespaceExpression(node, Nothing, [alias], ns) End If ' BindNamespaceOrTypeSyntax should always return a type or a namespace (might be an error type). Throw ExceptionUtilities.Unreachable End Function Public Function BindNamespaceOrTypeOrExpressionSyntaxForSemanticModel(node As ExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression If (node.Kind = SyntaxKind.PredefinedType) OrElse (((TypeOf node Is NameSyntax) OrElse node.Kind = SyntaxKind.ArrayType) AndAlso SyntaxFacts.IsInNamespaceOrTypeContext(node)) Then Dim result As BoundExpression = Me.BindNamespaceOrTypeExpression(DirectCast(node, TypeSyntax), diagnostics) ' Deal with the case of a namespace group. We may need to bind more in order to see if the ambiguity can be resolved. If node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.QualifiedName AndAlso DirectCast(node.Parent, QualifiedNameSyntax).Left Is node AndAlso result.Kind = BoundKind.NamespaceExpression Then Dim namespaceExpr = DirectCast(result, BoundNamespaceExpression) If namespaceExpr.NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup Then Dim boundParent As BoundExpression = BindNamespaceOrTypeOrExpressionSyntaxForSemanticModel(DirectCast(node.Parent, QualifiedNameSyntax), New DiagnosticBag()) Dim symbols = ArrayBuilder(Of Symbol).GetInstance() BindNamespaceOrTypeSyntaxForSemanticModelGetExpressionSymbols(boundParent, symbols) If symbols.Count = 0 Then ' If we didn't get anything, let's bind normally and see if any symbol comes out. boundParent = BindExpression(DirectCast(node.Parent, QualifiedNameSyntax), New DiagnosticBag()) BindNamespaceOrTypeSyntaxForSemanticModelGetExpressionSymbols(boundParent, symbols) End If result = AdjustReceiverNamespace(namespaceExpr, symbols) symbols.Free() End If End If Return result Else Return Me.BindExpression(node, isInvocationOrAddressOf:=SyntaxFacts.IsInvocationOrAddressOfOperand(node), diagnostics:=diagnostics, isOperandOfConditionalBranch:=False, eventContext:=False) End If End Function Private Shared Sub BindNamespaceOrTypeSyntaxForSemanticModelGetExpressionSymbols(expression As BoundExpression, symbols As ArrayBuilder(Of Symbol)) expression.GetExpressionSymbols(symbols) If symbols.Count = 1 AndAlso symbols(0).Kind = SymbolKind.ErrorType Then Dim errorType = DirectCast(symbols(0), ErrorTypeSymbol) symbols.Clear() Dim diagnosticInfo = TryCast(errorType.ErrorInfo, IDiagnosticInfoWithSymbols) If diagnosticInfo IsNot Nothing Then diagnosticInfo.GetAssociatedSymbols(symbols) End If End If End Sub ''' <summary> ''' This function is only needed for SemanticModel to perform binding for erroneous cases. ''' </summary> Private Function BindQualifiedName(name As QualifiedNameSyntax, diagnostics As DiagnosticBag) As BoundExpression Return Me.BindMemberAccess(name, BindExpression(name.Left, diagnostics), name.Right, eventContext:=False, diagnostics:=diagnostics) End Function Private Function BindGetTypeExpression(node As GetTypeExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression ' Create a special binder that allows unbound types Dim getTypeBinder = New GetTypeBinder(node.Type, Me) ' GetType is more permissive on what is considered a valid type. ' for example it allows modules, System.Void or open generic types. 'returns either a type, an alias that refers to a type, or an error type Dim typeOrAlias As Symbol = TypeBinder.BindTypeOrAliasSyntax(node.Type, getTypeBinder, diagnostics, suppressUseSiteError:=False, inGetTypeContext:=True, resolvingBaseType:=False) Dim aliasSym As AliasSymbol = TryCast(typeOrAlias, AliasSymbol) Dim typeSym As TypeSymbol = DirectCast(If(aliasSym IsNot Nothing, aliasSym.Target, typeOrAlias), TypeSymbol) Dim typeExpression = New BoundTypeExpression(node.Type, Nothing, aliasSym, typeSym, typeSym.IsErrorType()) ' System.Void() is not allowed for VB. If typeSym.IsArrayType AndAlso DirectCast(typeSym, ArrayTypeSymbol).ElementType.SpecialType = SpecialType.System_Void Then ReportDiagnostic(diagnostics, node.Type, ErrorFactory.ErrorInfo(ERRID.ERR_VoidArrayDisallowed)) End If Return New BoundGetType(node, typeExpression, GetWellKnownType(WellKnownType.System_Type, node, diagnostics)) End Function Private Function BindNameOfExpression(node As NameOfExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression ' Suppress diagnostics if argument has syntax errors If node.Argument.HasErrors Then diagnostics = New DiagnosticBag() End If Dim value As String = Nothing Select Case node.Argument.Kind Case SyntaxKind.SimpleMemberAccessExpression value = DirectCast(node.Argument, MemberAccessExpressionSyntax).Name.Identifier.ValueText Case SyntaxKind.IdentifierName, SyntaxKind.GenericName value = DirectCast(node.Argument, SimpleNameSyntax).Identifier.ValueText Case Else ' Must be a syntax error Debug.Assert(node.Argument.HasErrors) End Select ' Bind the argument Dim argument As BoundExpression = BindExpression(node.Argument, diagnostics) Select Case argument.Kind Case BoundKind.MethodGroup Dim group = DirectCast(argument, BoundMethodGroup) If group.ResultKind = LookupResultKind.Inaccessible Then ReportDiagnostic(diagnostics, If(node.Argument.Kind = SyntaxKind.SimpleMemberAccessExpression, DirectCast(node.Argument, MemberAccessExpressionSyntax).Name, node.Argument), GetInaccessibleErrorInfo(group.Methods.First, useSiteDiagnostics:=Nothing)) ElseIf group.ResultKind = LookupResultKind.Good AndAlso group.TypeArgumentsOpt IsNot Nothing ReportDiagnostic(diagnostics, group.TypeArgumentsOpt.Syntax, ERRID.ERR_MethodTypeArgsUnexpected) End If Case BoundKind.PropertyGroup Dim group = DirectCast(argument, BoundPropertyGroup) If group.ResultKind = LookupResultKind.Inaccessible Then ReportDiagnostic(diagnostics, If(node.Argument.Kind = SyntaxKind.SimpleMemberAccessExpression, DirectCast(node.Argument, MemberAccessExpressionSyntax).Name, node.Argument), GetInaccessibleErrorInfo(group.Properties.First, useSiteDiagnostics:=Nothing)) End If End Select Return New BoundNameOfOperator(node, argument, ConstantValue.Create(value), GetSpecialType(SpecialType.System_String, node, diagnostics)) End Function Private Sub VerifyNameOfLookupResult(container As NamespaceOrTypeSymbol, member As SimpleNameSyntax, lookupResult As LookupResult, diagnostics As DiagnosticBag) If lookupResult.HasDiagnostic Then ' Ambiguous result is Ok If Not lookupResult.IsAmbiguous Then ReportDiagnostic(diagnostics, member, lookupResult.Diagnostic) End If ElseIf lookupResult.HasSymbol Then Debug.Assert(lookupResult.IsGood) ElseIf container IsNot Nothing ReportDiagnostic(diagnostics, member, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, member.Identifier.ValueText, container)) Else ReportDiagnostic(diagnostics, member, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotDeclared1, member.Identifier.ValueText)) End If End Sub Private Function BindTypeOfExpression(node As TypeOfExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression Dim operand = BindRValue(node.Expression, diagnostics, isOperandOfConditionalBranch:=False) Dim operandType = operand.Type Dim operatorIsIsNot = (node.Kind = SyntaxKind.TypeOfIsNotExpression) Dim targetSymbol As Symbol = BindTypeOrAliasSyntax(node.Type, diagnostics) Dim targetType = DirectCast(If(TryCast(targetSymbol, TypeSymbol), DirectCast(targetSymbol, AliasSymbol).Target), TypeSymbol) Dim resultType As TypeSymbol = GetSpecialType(SpecialType.System_Boolean, node, diagnostics) If operand.HasErrors OrElse operandType.IsErrorType() OrElse targetType.IsErrorType() Then ' If operand is bad or either the source or target types have errors, bail out preventing more cascading errors. Return New BoundTypeOf(node, operand, operatorIsIsNot, targetType, resultType) End If If Not operandType.IsReferenceType AndAlso Not operandType.IsTypeParameter() Then ReportDiagnostic(diagnostics, node.Expression, ERRID.ERR_TypeOfRequiresReferenceType1, operandType) Else Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim convKind As ConversionKind = Conversions.ClassifyTryCastConversion(operandType, targetType, useSiteDiagnostics) If diagnostics.Add(node, useSiteDiagnostics) Then ' Suppress any additional diagnostics diagnostics = New DiagnosticBag() ElseIf Not Conversions.ConversionExists(convKind) Then ReportDiagnostic(diagnostics, node, ERRID.ERR_TypeOfExprAlwaysFalse2, operandType, targetType) End If End If If operandType.IsTypeParameter() Then operand = ApplyImplicitConversion(node, GetSpecialType(SpecialType.System_Object, node.Expression, diagnostics), operand, diagnostics) End If Return New BoundTypeOf(node, operand, operatorIsIsNot, targetType, resultType) End Function ''' <summary> ''' BindValue evaluates the node and returns a BoundExpression. BindValue snaps expressions to values. For now that means that method groups ''' become invocations. ''' </summary> Friend Function BindValue( node As ExpressionSyntax, diagnostics As DiagnosticBag, Optional isOperandOfConditionalBranch As Boolean = False ) As BoundExpression Dim expr = BindExpression(node, diagnostics:=diagnostics, isOperandOfConditionalBranch:=isOperandOfConditionalBranch, isInvocationOrAddressOf:=False, eventContext:=False) Return MakeValue(expr, diagnostics) End Function Private Function AdjustReceiverTypeOrValue(receiver As BoundExpression, node As VisualBasicSyntaxNode, isShared As Boolean, diagnostics As DiagnosticBag, ByRef resolvedTypeOrValueExpression As BoundExpression) As BoundExpression Dim unused As QualificationKind Return AdjustReceiverTypeOrValue(receiver, node, isShared, True, diagnostics, unused, resolvedTypeOrValueExpression) End Function Private Function AdjustReceiverTypeOrValue(receiver As BoundExpression, node As VisualBasicSyntaxNode, isShared As Boolean, diagnostics As DiagnosticBag, ByRef qualKind As QualificationKind) As BoundExpression Dim unused As BoundExpression = Nothing Return AdjustReceiverTypeOrValue(receiver, node, isShared, False, diagnostics, qualKind, unused) End Function ''' <summary> ''' Adjusts receiver of a call or a member access. ''' * will turn Unknown property access into Get property access ''' * will turn TypeOrValueExpression into a value expression ''' </summary> Private Function AdjustReceiverTypeOrValue(receiver As BoundExpression, node As VisualBasicSyntaxNode, isShared As Boolean, clearIfShared As Boolean, diagnostics As DiagnosticBag, ByRef qualKind As QualificationKind, ByRef resolvedTypeOrValueExpression As BoundExpression) As BoundExpression If receiver Is Nothing Then Return receiver End If If isShared Then If receiver.Kind = BoundKind.TypeOrValueExpression Then Dim typeOrValue = DirectCast(receiver, BoundTypeOrValueExpression) diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics) receiver = typeOrValue.Data.TypeExpression qualKind = QualificationKind.QualifiedViaTypeName resolvedTypeOrValueExpression = receiver End If If clearIfShared Then receiver = Nothing End If Else If receiver.Kind = BoundKind.TypeOrValueExpression Then Dim typeOrValue = DirectCast(receiver, BoundTypeOrValueExpression) diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics) receiver = MakeValue(typeOrValue.Data.ValueExpression, diagnostics) qualKind = QualificationKind.QualifiedViaValue resolvedTypeOrValueExpression = receiver End If receiver = AdjustReceiverValue(receiver, node, diagnostics) End If Return receiver End Function ''' <summary> ''' Adjusts receiver of a call or a member access if the receiver is an ''' ambiguous BoundTypeOrValueExpression. This can only happen if the ''' receiver is the LHS of a member access expression in which the ''' RHS cannot be resolved (i.e. the RHS is an error or a late-bound ''' invocation/access). ''' </summary> Private Function AdjustReceiverAmbiguousTypeOrValue(receiver As BoundExpression, diagnostics As DiagnosticBag) As BoundExpression If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeOrValueExpression Then Dim typeOrValue = DirectCast(receiver, BoundTypeOrValueExpression) diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics) receiver = typeOrValue.Data.ValueExpression End If Return receiver End Function Private Function AdjustReceiverAmbiguousTypeOrValue(ByRef group As BoundMethodOrPropertyGroup, diagnostics As DiagnosticBag) As BoundExpression Debug.Assert(group IsNot Nothing) Dim receiver = group.ReceiverOpt If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeOrValueExpression Then receiver = AdjustReceiverAmbiguousTypeOrValue(receiver, diagnostics) Select Case group.Kind Case BoundKind.MethodGroup Dim methodGroup = DirectCast(group, BoundMethodGroup) group = methodGroup.Update(methodGroup.TypeArgumentsOpt, methodGroup.Methods, methodGroup.PendingExtensionMethodsOpt, methodGroup.ResultKind, receiver, methodGroup.QualificationKind) Case BoundKind.PropertyGroup Dim propertyGroup = DirectCast(group, BoundPropertyGroup) group = propertyGroup.Update(propertyGroup.Properties, propertyGroup.ResultKind, receiver, propertyGroup.QualificationKind) Case Else Throw ExceptionUtilities.UnexpectedValue(group.Kind) End Select End If Return receiver End Function ''' <summary> ''' Adjusts receiver of a call or a member access if it is a value ''' * will turn Unknown property access into Get property access ''' </summary> Private Function AdjustReceiverValue(receiver As BoundExpression, node As VisualBasicSyntaxNode, diagnostics As DiagnosticBag) As BoundExpression If Not receiver.IsValue() Then receiver = MakeValue(receiver, diagnostics) End If If Not receiver.IsLValue AndAlso Not receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If Dim type = receiver.Type If type Is Nothing OrElse type.IsErrorType() Then Return BadExpression(node, receiver, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType) End If Return receiver End Function Friend Function ReclassifyAsValue( expr As BoundExpression, diagnostics As DiagnosticBag ) As BoundExpression If expr.HasErrors Then Return expr End If Select Case expr.Kind Case BoundKind.Parenthesized If Not expr.IsNothingLiteral() Then Return MakeRValue(expr, diagnostics) End If Case BoundKind.MethodGroup, BoundKind.PropertyGroup Dim group = DirectCast(expr, BoundMethodOrPropertyGroup) If IsGroupOfConstructors(group) Then ' cannot reclassify a constructor call ReportDiagnostic(diagnostics, group.Syntax, ERRID.ERR_InvalidConstructorCall) Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) Else expr = BindInvocationExpression(expr.Syntax, expr.Syntax, ExtractTypeCharacter(expr.Syntax), group, s_noArguments, Nothing, diagnostics, callerInfoOpt:=expr.Syntax) End If Case BoundKind.TypeExpression ' Try default instance property through DefaultInstanceAlias Dim instance As BoundExpression = TryDefaultInstanceProperty(DirectCast(expr, BoundTypeExpression), diagnostics) If instance Is Nothing Then Dim type = expr.Type ReportDiagnostic(diagnostics, expr.Syntax, GetTypeNotExpressionErrorId(type), type) Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If expr = instance Case BoundKind.EventAccess ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_CannotCallEvent1, DirectCast(expr, BoundEventAccess).EventSymbol) Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) Case BoundKind.NamespaceExpression ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_NamespaceNotExpression1, DirectCast(expr, BoundNamespaceExpression).NamespaceSymbol) Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) Case BoundKind.Label ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_VoidValue, DirectCast(expr, BoundLabel).Label.Name) Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End Select Debug.Assert(expr.IsValue) Return expr End Function Friend Overridable ReadOnly Property IsDefaultInstancePropertyAllowed As Boolean Get Return m_containingBinder.IsDefaultInstancePropertyAllowed End Get End Property Friend Overridable ReadOnly Property SuppressCallerInfo As Boolean Get Return m_containingBinder.SuppressCallerInfo End Get End Property Friend Function TryDefaultInstanceProperty(typeExpr As BoundTypeExpression, diagnosticsBagFor_ERR_CantReferToMyGroupInsideGroupType1 As DiagnosticBag) As BoundExpression If Not IsDefaultInstancePropertyAllowed Then Return Nothing End If ' See Semantics::CheckForDefaultInstanceProperty. Dim type As TypeSymbol = typeExpr.Type If type.IsErrorType() OrElse SourceModule IsNot type.ContainingModule OrElse type.TypeKind <> TypeKind.Class Then Return Nothing End If Dim classType = DirectCast(type, NamedTypeSymbol) If classType.IsGenericType Then Return Nothing End If Dim prop As SynthesizedMyGroupCollectionPropertySymbol = SourceModule.GetMyGroupCollectionPropertyWithDefaultInstanceAlias(classType) If prop Is Nothing Then Return Nothing End If Debug.Assert(prop.Type Is classType) ' Lets try to parse and bind an expression of the following form: ' <DefaultInstanceAlias>.<MyGroupCollectionProperty name> ' If any error happens, return Nothing without reporting any diagnostics. ' Note, native compiler doesn't escape DefaultInstanceAlias if it is a reserved keyword. Dim codeToParse As String = "Class DefaultInstanceAlias" & vbCrLf & "Function DefaultInstanceAlias()" & vbCrLf & "Return " & prop.DefaultInstanceAlias & "." & prop.Name & vbCrLf & "End Function" & vbCrLf & "End Class" & vbCrLf ' It looks like Dev11 ignores project level conditional compilation here, which makes sense since expression cannot contain #If directives. Dim tree = VisualBasicSyntaxTree.ParseText(codeToParse) Dim root As CompilationUnitSyntax = tree.GetCompilationUnitRoot() Dim hasErrors As Boolean = False For Each diag As Diagnostic In tree.GetDiagnostics(root) Dim cdiag = TryCast(diag, DiagnosticWithInfo) Debug.Assert(cdiag Is Nothing OrElse Not cdiag.HasLazyInfo, "If we decide to allow lazy syntax diagnostics, we'll have to check all call sites of SyntaxTree.GetDiagnostics") If diag.Severity = DiagnosticSeverity.Error Then Return Nothing End If Next Dim classBlock = DirectCast(root.Members(0), ClassBlockSyntax) Dim functionBlock = DirectCast(classBlock.Members(0), MethodBlockSyntax) ' We expect there to be only one statement, which is [Return] statement. If functionBlock.Statements.Count > 1 Then Return Nothing End If Dim ret = DirectCast(functionBlock.Statements(0), ReturnStatementSyntax) Dim exprDiagnostics = DiagnosticBag.GetInstance() Dim result As BoundExpression = (New DefaultInstancePropertyBinder(Me)).BindValue(ret.Expression, exprDiagnostics) If result.HasErrors OrElse exprDiagnostics.HasAnyErrors() Then exprDiagnostics.Free() Return Nothing End If exprDiagnostics.Free() ' if the default inst expression cannot be correctly bound to an instance of the same type as the class ' ignore it. If result.Type IsNot classType Then Return Nothing End If If diagnosticsBagFor_ERR_CantReferToMyGroupInsideGroupType1 IsNot Nothing AndAlso ContainingType Is classType AndAlso Not ContainingMember.IsShared Then ReportDiagnostic(diagnosticsBagFor_ERR_CantReferToMyGroupInsideGroupType1, typeExpr.Syntax, ERRID.ERR_CantReferToMyGroupInsideGroupType1, classType) End If ' We need to change syntax node for the result to match typeExpr's syntax node. ' This will allow SemanticModel to report the node as a default instance access rather than ' as a type reference. Select Case result.Kind Case BoundKind.PropertyAccess Dim access = DirectCast(result, BoundPropertyAccess) result = New BoundPropertyAccess(typeExpr.Syntax, access.PropertySymbol, access.PropertyGroupOpt, access.AccessKind, access.IsWriteable, access.ReceiverOpt, access.Arguments, access.Type, access.HasErrors) Case BoundKind.FieldAccess Dim access = DirectCast(result, BoundFieldAccess) result = New BoundFieldAccess(typeExpr.Syntax, access.ReceiverOpt, access.FieldSymbol, access.IsLValue, access.SuppressVirtualCalls, access.ConstantsInProgressOpt, access.Type, access.HasErrors) Case BoundKind.Call Dim [call] = DirectCast(result, BoundCall) result = New BoundCall(typeExpr.Syntax, [call].Method, [call].MethodGroupOpt, [call].ReceiverOpt, [call].Arguments, [call].ConstantValueOpt, [call].SuppressObjectClone, [call].Type, [call].HasErrors) Case Else Throw ExceptionUtilities.UnexpectedValue(result.Kind) End Select Return result End Function Private Class DefaultInstancePropertyBinder Inherits Binder Public Sub New(containingBinder As Binder) MyBase.New(containingBinder) End Sub Public Overrides ReadOnly Property ImplicitVariableDeclarationAllowed As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsDefaultInstancePropertyAllowed As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property SuppressCallerInfo As Boolean Get Return True End Get End Property End Class Private Function GetTypeNotExpressionErrorId(type As TypeSymbol) As ERRID Select Case type.TypeKind Case TypeKind.Class Return ERRID.ERR_ClassNotExpression1 Case TypeKind.Interface Return ERRID.ERR_InterfaceNotExpression1 Case TypeKind.Enum Return ERRID.ERR_EnumNotExpression1 Case TypeKind.Structure Return ERRID.ERR_StructureNotExpression1 ' TODO Modules?? Case Else Return ERRID.ERR_TypeNotExpression1 End Select End Function Private Function MakeValue( expr As BoundExpression, diagnostics As DiagnosticBag ) As BoundExpression If expr.Kind = BoundKind.Parenthesized Then If Not expr.IsNothingLiteral() Then Dim parenthesized = DirectCast(expr, BoundParenthesized) Dim enclosed As BoundExpression = MakeValue(parenthesized.Expression, diagnostics) Return parenthesized.Update(enclosed, enclosed.Type) End If ElseIf expr.Kind = BoundKind.ConditionalAccess AndAlso expr.Type Is Nothing Then Dim conditionalAccess = DirectCast(expr, BoundConditionalAccess) Dim access As BoundExpression = Me.MakeRValue(conditionalAccess.AccessExpression, diagnostics) Dim resultType As TypeSymbol = access.Type If Not resultType.IsErrorType() Then If resultType.IsValueType Then If Not resultType.IsNullableType() Then resultType = GetSpecialType(SpecialType.System_Nullable_T, expr.Syntax, diagnostics).Construct(resultType) End If ElseIf Not resultType.IsReferenceType Then ' Access cannot have unconstrained generic type ReportDiagnostic(diagnostics, access.Syntax, ERRID.ERR_CannotBeMadeNullable1, resultType) resultType = ErrorTypeSymbol.UnknownResultType End If End If Return conditionalAccess.Update(conditionalAccess.Receiver, conditionalAccess.Placeholder, access, resultType) End If expr = ReclassifyAsValue(expr, diagnostics) If expr.HasErrors Then If Not expr.IsValue OrElse expr.Type Is Nothing OrElse expr.Type.IsVoidType Then Return BadExpression(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated() Else Return expr End If End If Dim exprType = expr.Type Dim syntax = expr.Syntax If Not expr.IsValue() OrElse (exprType IsNot Nothing AndAlso exprType.SpecialType = SpecialType.System_Void) Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_VoidValue) Return BadExpression(syntax, expr, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType) ElseIf expr.Kind = BoundKind.PropertyAccess Then Dim propertyAccess = DirectCast(expr, BoundPropertyAccess) Select Case propertyAccess.AccessKind Case PropertyAccessKind.Set ReportDiagnostic(diagnostics, syntax, ERRID.ERR_VoidValue) Return BadExpression(syntax, expr, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType) Case PropertyAccessKind.Unknown Dim hasError = True Dim propertySymbol = propertyAccess.PropertySymbol If Not propertySymbol.IsReadable Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoGetProperty1, CustomSymbolDisplayFormatter.ShortErrorName(propertySymbol)) Else Dim getMethod = propertySymbol.GetMostDerivedGetMethod() Debug.Assert(getMethod IsNot Nothing) If Not ReportUseSiteError(diagnostics, syntax, getMethod) Then Dim accessThroughType = GetAccessThroughType(propertyAccess.ReceiverOpt) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing If IsAccessible(getMethod, useSiteDiagnostics, accessThroughType) OrElse Not IsAccessible(propertySymbol, useSiteDiagnostics, accessThroughType) Then hasError = False Else ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoAccessibleGet, CustomSymbolDisplayFormatter.ShortErrorName(propertySymbol)) End If diagnostics.Add(syntax, useSiteDiagnostics) End If End If If hasError Then Return BadExpression(syntax, expr, LookupResultKind.NotAValue, propertySymbol.Type) End If End Select ElseIf expr.IsLateBound() Then If (expr.GetLateBoundAccessKind() And (LateBoundAccessKind.Set Or LateBoundAccessKind.Call)) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_VoidValue) Return BadExpression(syntax, expr, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType) End If ElseIf expr.Kind = BoundKind.AddressOfOperator Then Return expr End If Return expr End Function Private Function GetAccessThroughType(receiverOpt As BoundExpression) As TypeSymbol If receiverOpt Is Nothing OrElse receiverOpt.Kind = BoundKind.MyBaseReference Then ' NOTE: If we are accessing the symbol via MyBase reference we may ' assume the access is being performed via 'Me' Return ContainingType Else Debug.Assert(receiverOpt.Type IsNot Nothing) Return receiverOpt.Type End If End Function ''' <summary> ''' BindRValue evaluates the node and returns a BoundExpression. ''' It ensures that the expression is a value that can be used on the right hand side of an assignment. ''' If not, it reports an error. ''' ''' Note that this function will reclassify all expressions to have their "default" type, i.e. ''' Anonymous Delegate for a lambda, default array type for an array literal, will report an error ''' for an AddressOf, etc. So, if you are in a context where there is a known target type for the ''' expression, do not use this function. Instead, use BindValue followed by ''' ApplyImplicitConversion/ApplyConversion. ''' </summary> Private Function BindRValue( node As ExpressionSyntax, diagnostics As DiagnosticBag, Optional isOperandOfConditionalBranch As Boolean = False ) As BoundExpression Dim expr = BindExpression(node, diagnostics:=diagnostics, isOperandOfConditionalBranch:=isOperandOfConditionalBranch, isInvocationOrAddressOf:=False, eventContext:=False) Return MakeRValue(expr, diagnostics) End Function Friend Function MakeRValue( expr As BoundExpression, diagnostics As DiagnosticBag ) As BoundExpression If expr.Kind = BoundKind.Parenthesized AndAlso Not expr.IsNothingLiteral() Then Dim parenthesized = DirectCast(expr, BoundParenthesized) Dim enclosed As BoundExpression = MakeRValue(parenthesized.Expression, diagnostics) Return parenthesized.Update(enclosed, enclosed.Type) ElseIf expr.Kind = BoundKind.XmlMemberAccess Then Dim memberAccess = DirectCast(expr, BoundXmlMemberAccess) Dim enclosed = MakeRValue(memberAccess.MemberAccess, diagnostics) Return memberAccess.Update(enclosed) End If expr = MakeValue(expr, diagnostics) If expr.HasErrors Then Return expr.MakeRValue() End If Debug.Assert(expr.IsValue()) Dim exprType = expr.Type If exprType Is Nothing Then Return ReclassifyExpression(expr, diagnostics) End If ' Transform LValue to RValue. If expr.IsLValue Then expr = expr.MakeRValue() ElseIf expr.Kind = BoundKind.PropertyAccess Then Dim propertyAccess = DirectCast(expr, BoundPropertyAccess) Dim getMethod = propertyAccess.PropertySymbol.GetMostDerivedGetMethod() Debug.Assert(getMethod IsNot Nothing) ReportDiagnosticsIfObsolete(diagnostics, getMethod, expr.Syntax) Select Case propertyAccess.AccessKind Case PropertyAccessKind.Get ' Nothing to do. Case PropertyAccessKind.Unknown Debug.Assert(propertyAccess.PropertySymbol.IsReadable) WarnOnRecursiveAccess(propertyAccess, PropertyAccessKind.Get, diagnostics) expr = propertyAccess.SetAccessKind(PropertyAccessKind.Get) Case Else Throw ExceptionUtilities.UnexpectedValue(propertyAccess.AccessKind) End Select ElseIf expr.IsLateBound() Then Select Case expr.GetLateBoundAccessKind() Case LateBoundAccessKind.Get ' Nothing to do. Case LateBoundAccessKind.Unknown expr = expr.SetLateBoundAccessKind(LateBoundAccessKind.Get) Case Else Throw ExceptionUtilities.UnexpectedValue(expr.GetLateBoundAccessKind()) End Select End If Return expr End Function Private Function MakeRValueAndIgnoreDiagnostics( expr As BoundExpression ) As BoundExpression Dim ignoreErrors = DiagnosticBag.GetInstance() expr = MakeRValue(expr, ignoreErrors) ignoreErrors.Free() Return expr End Function Friend Function ReclassifyExpression( expr As BoundExpression, diagnostics As DiagnosticBag ) As BoundExpression If expr.IsNothingLiteral() Then ' This is a Nothing literal without a type. ' Reclassify as Object. Return New BoundConversion(expr.Syntax, expr, ConversionKind.WideningNothingLiteral, False, False, expr.ConstantValueOpt, GetSpecialType(SpecialType.System_Object, expr.Syntax, diagnostics), Nothing) End If Select Case expr.Kind Case BoundKind.Parenthesized ' Reclassify enclosed expression. Dim parenthesized = DirectCast(expr, BoundParenthesized) Dim enclosed As BoundExpression = ReclassifyExpression(parenthesized.Expression, diagnostics) Return parenthesized.Update(enclosed, enclosed.Type) Case BoundKind.UnboundLambda Return ReclassifyUnboundLambdaExpression(DirectCast(expr, UnboundLambda), diagnostics) Case BoundKind.AddressOfOperator Dim address = DirectCast(expr, BoundAddressOfOperator) If address.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then If address.MethodGroup.Methods.Length = 1 Then ReportDiagnostic(diagnostics, address.MethodGroup.Syntax, GetInaccessibleErrorInfo(address.MethodGroup.Methods(0), useSiteDiagnostics:=Nothing)) Else ReportDiagnostic(diagnostics, address.MethodGroup.Syntax, ERRID.ERR_NoViableOverloadCandidates1, address.MethodGroup.Methods(0).Name) End If Else Debug.Assert(address.MethodGroup.ResultKind = LookupResultKind.Good) End If ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_VoidValue) Return BadExpression(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType) Case BoundKind.ArrayLiteral Return ReclassifyArrayLiteralExpression(DirectCast(expr, BoundArrayLiteral), diagnostics) Case Else 'TODO: We need to do other expression reclassifications here. ' For now, we simply report an error. ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_VoidValue) Return BadExpression(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType) End Select End Function Private Function ReclassifyArrayLiteralExpression(conversionSemantics As SyntaxKind, tree As VisualBasicSyntaxNode, conv As ConversionKind, isExplicit As Boolean, arrayLiteral As BoundArrayLiteral, destination As TypeSymbol, diagnostics As DiagnosticBag) As BoundExpression Debug.Assert((conv And ConversionKind.UserDefined) = 0) Debug.Assert(Not (TypeOf destination Is ArrayLiteralTypeSymbol)) 'An array literal should never be reclassified as an array literal. If Conversions.NoConversion(conv) AndAlso (conv And ConversionKind.FailedDueToArrayLiteralElementConversion) = 0 Then If Not arrayLiteral.HasDominantType Then ' When there is a conversion error and there isn't a dominant type, report "error BC36717: Cannot infer an element type. ' Specifying the type of the array might correct this error." instead of the specific conversion error because the inferred ' type used in classification was just a guess. ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_ArrayInitNoType) Else ReportNoConversionError(arrayLiteral.Syntax, arrayLiteral.InferredType, destination, diagnostics, Nothing) End If Dim ignoredDiagnostics = DiagnosticBag.GetInstance ' Because we've already reported a no conversion error, ignore any diagnostics in ApplyImplicitConversion Dim argument As BoundExpression = ApplyImplicitConversion(arrayLiteral.Syntax, arrayLiteral.InferredType, arrayLiteral, ignoredDiagnostics) ignoredDiagnostics.Free() If conversionSemantics = SyntaxKind.CTypeKeyword Then argument = New BoundConversion(tree, argument, conv, False, isExplicit, destination) ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then argument = New BoundDirectCast(tree, argument, conv, destination) ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then argument = New BoundTryCast(tree, argument, conv, destination) Else Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End If Return argument End If ' This code must be kept in sync with Conversions.ClassifyArrayLiteralConversion Dim sourceType = arrayLiteral.InferredType Dim targetType = TryCast(destination, NamedTypeSymbol) Dim originalTargetType = If(targetType IsNot Nothing, targetType.OriginalDefinition, Nothing) Dim targetArrayType As ArrayTypeSymbol = TryCast(destination, ArrayTypeSymbol) Dim targetElementType As TypeSymbol = Nothing If targetArrayType IsNot Nothing AndAlso (sourceType.Rank = targetArrayType.Rank OrElse arrayLiteral.IsEmptyArrayLiteral) Then targetElementType = targetArrayType.ElementType sourceType = targetArrayType ElseIf (sourceType.Rank = 1 OrElse arrayLiteral.IsEmptyArrayLiteral) AndAlso originalTargetType IsNot Nothing AndAlso (originalTargetType.SpecialType = SpecialType.System_Collections_Generic_IEnumerable_T OrElse originalTargetType.SpecialType = SpecialType.System_Collections_Generic_IList_T OrElse originalTargetType.SpecialType = SpecialType.System_Collections_Generic_ICollection_T OrElse originalTargetType.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse originalTargetType.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyCollection_T) Then targetElementType = targetType.TypeArgumentsNoUseSiteDiagnostics(0) sourceType = ArrayTypeSymbol.CreateVBArray(targetElementType, Nothing, 1, Compilation) Else ' Use the inferred type targetArrayType = sourceType targetElementType = sourceType.ElementType End If ReportArrayLiteralDiagnostics(arrayLiteral, targetArrayType, diagnostics) Dim arrayInitialization As BoundArrayInitialization Dim bounds As ImmutableArray(Of BoundExpression) If arrayLiteral.IsEmptyArrayLiteral Then Dim knownSizes(sourceType.Rank - 1) As DimensionSize arrayInitialization = ReclassifyEmptyArrayInitialization(arrayLiteral, sourceType.Rank) bounds = CreateArrayBounds(arrayLiteral.Syntax, knownSizes, diagnostics) Else arrayInitialization = ReclassifyArrayInitialization(arrayLiteral.Initializer, targetElementType, diagnostics) bounds = arrayLiteral.Bounds End If ' Mark as compiler generated so that semantic model does not select the array initialization bound node. ' The array initialization node is not a real expression and lacks a type. arrayInitialization.SetWasCompilerGenerated() Debug.Assert(Not Conversions.IsIdentityConversion(conv)) Dim arrayCreation = New BoundArrayCreation(arrayLiteral.Syntax, bounds, arrayInitialization, arrayLiteral, conv, sourceType) If conversionSemantics = SyntaxKind.CTypeKeyword Then Return ApplyConversion(tree, destination, arrayCreation, isExplicit, diagnostics) Else Dim expr As BoundExpression = arrayCreation ' Apply char() to string conversion before directcast/trycast conv = Conversions.ClassifyStringConversion(sourceType, destination) If Conversions.IsWideningConversion(conv) Then expr = CreatePredefinedConversion(arrayLiteral.Syntax, arrayCreation, conv, isExplicit, destination, diagnostics) End If If conversionSemantics = SyntaxKind.DirectCastKeyword Then Return ApplyDirectCastConversion(tree, expr, destination, diagnostics) ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then Return ApplyTryCastConversion(tree, expr, destination, diagnostics) Else Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End If End If End Function Private Sub ReportArrayLiteralDiagnostics(arrayLiteral As BoundArrayLiteral, targetArrayType As ArrayTypeSymbol, diagnostics As DiagnosticBag) If targetArrayType Is arrayLiteral.InferredType Then ' Note, array type symbols do not preserve identity. If the target array is the same as the inferred array then we ' assume that the target has inferred its type from the array literal. ReportArrayLiteralInferredTypeDiagnostics(arrayLiteral, diagnostics) End If End Sub Private Sub ReportArrayLiteralInferredTypeDiagnostics(arrayLiteral As BoundArrayLiteral, diagnostics As DiagnosticBag) Dim targetElementType = arrayLiteral.InferredType.ElementType If targetElementType.IsRestrictedType Then ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_RestrictedType1, targetElementType) ElseIf Not arrayLiteral.HasDominantType Then ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_ArrayInitNoType) Else ' Possibly warn or report an error depending on the value of option strict Select Case OptionStrict Case VisualBasic.OptionStrict.On If arrayLiteral.NumberOfCandidates = 0 Then ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_ArrayInitNoTypeObjectDisallowed) ElseIf arrayLiteral.NumberOfCandidates > 1 Then ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_ArrayInitTooManyTypesObjectDisallowed) End If Case VisualBasic.OptionStrict.Custom If arrayLiteral.NumberOfCandidates = 0 Then ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectAssumed1, ErrorFactory.ErrorInfo(ERRID.WRN_ArrayInitNoTypeObjectAssumed))) ElseIf arrayLiteral.NumberOfCandidates > 1 Then ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectAssumed1, ErrorFactory.ErrorInfo(ERRID.WRN_ArrayInitTooManyTypesObjectAssumed))) End If End Select End If End Sub Private Function ReclassifyArrayInitialization(arrayInitialization As BoundArrayInitialization, elementType As TypeSymbol, diagnostics As DiagnosticBag) As BoundArrayInitialization Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance ' Apply implicit conversion to the elements. For Each expr In arrayInitialization.Initializers If expr.Kind = BoundKind.ArrayInitialization Then expr = ReclassifyArrayInitialization(DirectCast(expr, BoundArrayInitialization), elementType, diagnostics) Else expr = ApplyImplicitConversion(expr.Syntax, elementType, expr, diagnostics) End If initializers.Add(expr) Next arrayInitialization = New BoundArrayInitialization(arrayInitialization.Syntax, initializers.ToImmutableAndFree, Nothing) Return arrayInitialization End Function Private Function ReclassifyEmptyArrayInitialization(arrayLiteral As BoundArrayLiteral, rank As Integer) As BoundArrayInitialization Dim arrayInitialization As BoundArrayInitialization = arrayLiteral.Initializer If rank = 1 Then Return arrayInitialization End If Dim initializers = ImmutableArray(Of BoundExpression).Empty For i = 1 To rank arrayInitialization = New BoundArrayInitialization(arrayInitialization.Syntax, initializers, Nothing) initializers = ImmutableArray.Create(Of BoundExpression)(arrayInitialization) Next Return arrayInitialization End Function Private Function ReclassifyArrayLiteralExpression( arrayLiteral As BoundArrayLiteral, diagnostics As DiagnosticBag ) As BoundExpression Return ApplyImplicitConversion(arrayLiteral.Syntax, arrayLiteral.InferredType, arrayLiteral, diagnostics) End Function Private Function ReclassifyUnboundLambdaExpression( lambda As UnboundLambda, diagnostics As DiagnosticBag ) As BoundExpression Return ApplyImplicitConversion(lambda.Syntax, lambda.InferredAnonymousDelegate.Key, lambda, diagnostics, isOperandOfConditionalBranch:=False) End Function Private Function BindAssignmentTarget( node As ExpressionSyntax, diagnostics As DiagnosticBag ) As BoundExpression Dim expression = BindExpression(node, diagnostics) Return BindAssignmentTarget(node, expression, diagnostics) End Function Private Function BindAssignmentTarget( node As VisualBasicSyntaxNode, expression As BoundExpression, diagnostics As DiagnosticBag ) As BoundExpression expression = ReclassifyAsValue(expression, diagnostics) If Not IsValidAssignmentTarget(expression) Then If Not expression.HasErrors Then ReportAssignmentToRValue(expression, diagnostics) End If expression = BadExpression(node, expression, LookupResultKind.NotAVariable, ErrorTypeSymbol.UnknownResultType) ElseIf expression.Kind = BoundKind.LateInvocation Then ' Since this is a target of an assignment, it is guaranteed to be an array or a property, ' therefore, arguments will be passed ByVal, let's capture this fact in the tree, ' this will simplify analysis later. Dim invocation = DirectCast(expression, BoundLateInvocation) If Not invocation.ArgumentsOpt.IsEmpty Then Dim newArguments(invocation.ArgumentsOpt.Length - 1) As BoundExpression For i As Integer = 0 To newArguments.Length - 1 newArguments(i) = MakeRValue(invocation.ArgumentsOpt(i), diagnostics) Next expression = invocation.Update(invocation.Member, newArguments.AsImmutableOrNull(), invocation.ArgumentNamesOpt, invocation.AccessKind, invocation.MethodOrPropertyGroupOpt, invocation.Type) End If End If Return expression End Function Friend Shared Function IsValidAssignmentTarget(expression As BoundExpression) As Boolean Select Case expression.Kind Case BoundKind.PropertyAccess Dim propertyAccess = DirectCast(expression, BoundPropertyAccess) Dim [property] = propertyAccess.PropertySymbol Dim receiver = propertyAccess.ReceiverOpt Debug.Assert(propertyAccess.AccessKind <> PropertyAccessKind.Get) Return propertyAccess.AccessKind <> PropertyAccessKind.Get AndAlso ([property].IsShared OrElse receiver Is Nothing OrElse receiver.IsLValue() OrElse receiver.IsMeReference() OrElse receiver.IsMyClassReference() OrElse Not receiver.Type.IsValueType) ' If this logic changes, logic in UseTwiceRewriter.UseTwicePropertyAccess might need to change too. Case BoundKind.XmlMemberAccess Return IsValidAssignmentTarget(DirectCast(expression, BoundXmlMemberAccess).MemberAccess) Case BoundKind.LateInvocation Dim invocation = DirectCast(expression, BoundLateInvocation) Debug.Assert(invocation.AccessKind <> LateBoundAccessKind.Get AndAlso invocation.AccessKind <> LateBoundAccessKind.Call) Return invocation.AccessKind <> LateBoundAccessKind.Get AndAlso invocation.AccessKind <> LateBoundAccessKind.Call Case BoundKind.LateMemberAccess Dim member = DirectCast(expression, BoundLateMemberAccess) Debug.Assert(member.AccessKind <> LateBoundAccessKind.Get AndAlso member.AccessKind <> LateBoundAccessKind.Call) Return member.AccessKind <> LateBoundAccessKind.Get AndAlso member.AccessKind <> LateBoundAccessKind.Call Case Else Return expression.IsLValue() End Select End Function Private Sub ReportAssignmentToRValue(expr As BoundExpression, diagnostics As DiagnosticBag) Dim err As ERRID If expr.IsConstant Then err = ERRID.ERR_CantAssignToConst ElseIf ExpressionRefersToReadonlyVariable(expr) Then err = ERRID.ERR_ReadOnlyAssignment Else err = ERRID.ERR_LValueRequired End If ReportDiagnostic(diagnostics, expr.Syntax, err) End Sub Public Shared Function ExpressionRefersToReadonlyVariable( node As BoundExpression, Optional digThroughProperty As Boolean = True ) As Boolean ' TODO: Check base expressions for properties if digThroughProperty==true. If node.Kind = BoundKind.FieldAccess Then Dim field = DirectCast(node, BoundFieldAccess) If field.FieldSymbol.IsReadOnly Then Return True End If Dim base = field.ReceiverOpt If base IsNot Nothing AndAlso base.IsValue() AndAlso base.Type.IsValueType Then Return ExpressionRefersToReadonlyVariable(base, False) End If ElseIf node.Kind = BoundKind.Local Then Return DirectCast(node, BoundLocal).LocalSymbol.IsReadOnly End If Return False End Function ''' <summary> ''' Determine whether field access should be treated as LValue. ''' </summary> Friend Function IsLValueFieldAccess(field As FieldSymbol, receiver As BoundExpression) As Boolean If field.IsConst Then Return False End If If Not field.IsShared AndAlso receiver IsNot Nothing AndAlso receiver.IsValue() Then Dim receiverType = receiver.Type Debug.Assert(Not receiverType.IsTypeParameter() OrElse receiverType.IsReferenceType, "Member variable access through non-class constrained type param unexpected!!!") ' Dev10 comment: ' Note that this is needed so that we can determine whether the structure ' is not an LValue (eg: RField.m_x = 20 where foo is a readonly field of a ' structure type). In such cases, the structure's field m_x cannot be modified. ' ' This does not apply to type params because for type params we do want to ' allow setting the fields even in such scenarios because only class constrained ' type params have fields and readonly reference typed fields' fields can be ' modified. If Not receiverType.IsTypeParameter() AndAlso receiverType.IsValueType AndAlso Not receiver.IsLValue() AndAlso Not receiver.IsMeReference() AndAlso Not receiver.IsMyClassReference() Then Return False End If End If If Not field.IsReadOnly Then Return True End If Dim containingMethodKind As MethodKind = Me.KindOfContainingMethodAtRunTime() If containingMethodKind = MethodKind.Constructor Then If field.IsShared OrElse Not (receiver IsNot Nothing AndAlso receiver.IsInstanceReference()) Then Return False End If ElseIf containingMethodKind = MethodKind.SharedConstructor Then If Not field.IsShared Then Return False End If Else Return False End If ' We are in constructor, now verify that the field belongs to constructor's type. ' Note, ReadOnly fields accessed in lambda within the constructor are not LValues because the ' lambda in the end will be generated as a separate procedure where the ReadOnly field is not ' an LValue. In this case, containingMember will be a LambdaSymbol rather than a symbol for ' constructor. ' We duplicate a bug in the native compiler for compatibility in non-strict mode Return If(Me.Compilation.FeatureStrictEnabled, Me.ContainingMember.ContainingSymbol Is field.ContainingSymbol, Me.ContainingMember.ContainingSymbol.OriginalDefinition Is field.ContainingSymbol.OriginalDefinition) End Function ''' <summary> ''' Return MethodKind corresponding to the method the code being interpreted is going to end up in. ''' </summary> Private Function KindOfContainingMethodAtRunTime() As MethodKind Dim containingMember = Me.ContainingMember If containingMember IsNot Nothing Then Select Case containingMember.Kind Case SymbolKind.Method ' Binding a method body. Return DirectCast(containingMember, MethodSymbol).MethodKind Case SymbolKind.Field, SymbolKind.Property ' Binding field or property initializer. If containingMember.IsShared Then Return MethodKind.SharedConstructor Else Return MethodKind.Constructor End If Case SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Parameter Exit Select Case Else ' What else can it be? Throw ExceptionUtilities.UnexpectedValue(containingMember.Kind) End Select End If Return MethodKind.Ordinary ' Looks like a good default. End Function Private Function BindTernaryConditionalExpression(node As TernaryConditionalExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression ' bind arguments as values Dim boundConditionArg = BindBooleanExpression(node.Condition, diagnostics) Dim boundWhenTrueArg = BindValue(node.WhenTrue, diagnostics) Dim boundWhenFalseArg = BindValue(node.WhenFalse, diagnostics) Dim hasErrors = boundConditionArg.HasErrors OrElse boundWhenTrueArg.HasErrors OrElse boundWhenFalseArg.HasErrors ' infer dominant type of the resulting expression Dim dominantType As TypeSymbol If boundWhenTrueArg.IsNothingLiteral AndAlso boundWhenFalseArg.IsNothingLiteral Then ' From Dev10: backwards compatibility with Orcas... IF(b,Nothing,Nothing) infers Object with no complaint dominantType = GetSpecialType(SpecialType.System_Object, node, diagnostics) Else Dim numCandidates As Integer = 0 Dim array = ArrayBuilder(Of BoundExpression).GetInstance(2) array.Add(boundWhenTrueArg) array.Add(boundWhenFalseArg) dominantType = InferDominantTypeOfExpressions(node, array, diagnostics, numCandidates) array.Free() ' check the resulting type If Not hasErrors Then hasErrors = GenerateDiagnosticsForDominantTypeInferenceInIfExpression(dominantType, numCandidates, node, diagnostics) End If End If ' Void type will be filtered out in BindValue calls Debug.Assert(dominantType Is Nothing OrElse Not dominantType.IsVoidType()) ' convert arguments to the dominant type if necessary If Not hasErrors OrElse dominantType IsNot Nothing Then boundWhenTrueArg = Me.ApplyImplicitConversion(node.WhenTrue, dominantType, boundWhenTrueArg, diagnostics) boundWhenFalseArg = Me.ApplyImplicitConversion(node.WhenFalse, dominantType, boundWhenFalseArg, diagnostics) hasErrors = hasErrors OrElse boundWhenTrueArg.HasErrors OrElse boundWhenFalseArg.HasErrors Else boundWhenTrueArg = MakeRValueAndIgnoreDiagnostics(boundWhenTrueArg) boundWhenFalseArg = MakeRValueAndIgnoreDiagnostics(boundWhenFalseArg) End If ' check for a constant value Dim constVal As ConstantValue = Nothing If Not hasErrors AndAlso IsConstantAllowingCompileTimeFolding(boundWhenTrueArg) AndAlso IsConstantAllowingCompileTimeFolding(boundWhenFalseArg) AndAlso IsConstantAllowingCompileTimeFolding(boundConditionArg) Then constVal = If(boundConditionArg.ConstantValueOpt.BooleanValue, boundWhenTrueArg.ConstantValueOpt, boundWhenFalseArg.ConstantValueOpt) End If Return New BoundTernaryConditionalExpression(node, boundConditionArg, boundWhenTrueArg, boundWhenFalseArg, constVal, If(dominantType, ErrorTypeSymbol.UnknownResultType), hasErrors:=hasErrors) End Function Private Function IsConstantAllowingCompileTimeFolding(candidate As BoundExpression) As Boolean Return candidate.IsConstant AndAlso Not candidate.ConstantValueOpt.IsBad AndAlso (candidate.IsNothingLiteral OrElse (candidate.Type IsNot Nothing AndAlso candidate.Type.AllowsCompileTimeOperations())) End Function Private Function BindBinaryConditionalExpression(node As BinaryConditionalExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression ' bind arguments Dim boundFirstArg = BindValue(node.FirstExpression, diagnostics) Dim boundSecondArg = BindValue(node.SecondExpression, diagnostics) Dim hasErrors = boundFirstArg.HasErrors OrElse boundSecondArg.HasErrors OrElse node.ContainsDiagnostics ' infer dominant type of the resulting expression Dim dominantType As TypeSymbol If boundFirstArg.IsNothingLiteral AndAlso boundSecondArg.IsNothingLiteral Then ' SPECIAL CASE (Dev10): IF(Nothing,Nothing) yields type System.Object ' NOTE: Reuse System.Object from boundFirstArg or boundSecondArg if exists dominantType = If(boundFirstArg.Type, If(boundSecondArg.Type, GetSpecialType(SpecialType.System_Object, node, diagnostics))) ElseIf boundFirstArg.Type IsNot Nothing AndAlso boundFirstArg.Type.IsNullableType AndAlso boundSecondArg.IsNothingLiteral Then ' SPECIAL CASE (Dev10): IF(Nullable<T>, Nothing) yields type Nullable<T>, whereas IF(Nullable<Int>, Int) yields Int. dominantType = boundFirstArg.Type Else ' calculate dominant type Dim numCandidates As Integer = 0 Dim array = ArrayBuilder(Of BoundExpression).GetInstance(2) If boundFirstArg.Type IsNot Nothing AndAlso boundFirstArg.Type.IsNullableType AndAlso Not (boundSecondArg.Type IsNot Nothing AndAlso boundSecondArg.Type.IsNullableType) Then ' From Dev10: Special case: "nullable lifting": when the first argument has a value of nullable ' data type and the second does not, the first is being converted to underlying type ' create a temp variable Dim underlyingType = boundFirstArg.Type.GetNullableUnderlyingType array.Add(New BoundRValuePlaceholder(node.FirstExpression, underlyingType)) Else array.Add(boundFirstArg) End If array.Add(boundSecondArg) dominantType = InferDominantTypeOfExpressions(node, array, diagnostics, numCandidates) array.Free() ' check the resulting type If Not hasErrors Then hasErrors = GenerateDiagnosticsForDominantTypeInferenceInIfExpression(dominantType, numCandidates, node, diagnostics) End If End If ' check for a constant value If Not hasErrors AndAlso IsConstantAllowingCompileTimeFolding(boundFirstArg) AndAlso IsConstantAllowingCompileTimeFolding(boundSecondArg) AndAlso (boundFirstArg.IsNothingLiteral OrElse boundFirstArg.ConstantValueOpt.IsString) Then Dim constVal As ConstantValue If (boundFirstArg.IsNothingLiteral) Then constVal = boundSecondArg.ConstantValueOpt If Not boundSecondArg.IsNothingLiteral Then dominantType = boundSecondArg.Type Else Debug.Assert(dominantType.IsObjectType) End If Else constVal = boundFirstArg.ConstantValueOpt dominantType = boundFirstArg.Type End If ' return binary conditional expression to be constant-folded later Return AnalyzeConversionAndCreateBinaryConditionalExpression( node, testExpression:=boundFirstArg, elseExpression:=boundSecondArg, constantValueOpt:=constVal, type:=dominantType, hasErrors:=False, diagnostics:=diagnostics) End If ' NOTE: no constant folding after this point ' By this time Void type will be filtered out in BindValue calls, and empty dominant type reported as an error Debug.Assert(hasErrors OrElse (dominantType IsNot Nothing AndAlso Not dominantType.IsVoidType())) ' address some cases of Type being Nothing before making an RValue of it If Not hasErrors AndAlso boundFirstArg.Type Is Nothing Then If boundFirstArg.IsNothingLiteral Then ' leave Nothing literal unchanged Else ' convert lambdas, AddressOf, etc. to dominant type boundFirstArg = Me.ApplyImplicitConversion(node.FirstExpression, dominantType, boundFirstArg, diagnostics) hasErrors = boundFirstArg.HasErrors End If End If ' TODO: Address array initializers, they might need to change type. ' make r-value out of boundFirstArg; this will reclassify property access from Unknown to Get and ' also mark not-nothing expressions without type with errors If boundFirstArg.IsNothingLiteral Then ' Don't do anything for nothing literal ElseIf Not hasErrors Then boundFirstArg = MakeRValue(boundFirstArg, diagnostics) hasErrors = boundFirstArg.HasErrors Else boundFirstArg = MakeRValueAndIgnoreDiagnostics(boundFirstArg) End If ' Type of the first expression should be set by now Debug.Assert(hasErrors OrElse boundFirstArg.IsNothingLiteral OrElse boundFirstArg.Type IsNot Nothing) Dim boundSecondArgWithConversions As BoundExpression = boundSecondArg If Not hasErrors Then boundSecondArgWithConversions = Me.ApplyImplicitConversion(node.SecondExpression, dominantType, boundSecondArg, diagnostics) hasErrors = boundSecondArgWithConversions.HasErrors Else boundSecondArgWithConversions = MakeRValueAndIgnoreDiagnostics(boundSecondArg) End If ' if there are still no errors check the original type of the first argument to be ' of a reference or nullable type, generate IllegalCondTypeInIIF otherwise If Not hasErrors AndAlso Not (boundFirstArg.IsNothingLiteral OrElse boundFirstArg.Type.IsNullableType OrElse boundFirstArg.Type.IsReferenceType) Then ReportDiagnostic(diagnostics, node.FirstExpression, ERRID.ERR_IllegalCondTypeInIIF) hasErrors = True End If Return AnalyzeConversionAndCreateBinaryConditionalExpression( node, testExpression:=boundFirstArg, elseExpression:=boundSecondArgWithConversions, constantValueOpt:=Nothing, type:=If(dominantType, ErrorTypeSymbol.UnknownResultType), hasErrors:=hasErrors, diagnostics:=diagnostics) End Function Private Function AnalyzeConversionAndCreateBinaryConditionalExpression( syntax As VisualBasicSyntaxNode, testExpression As BoundExpression, elseExpression As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol, hasErrors As Boolean, diagnostics As DiagnosticBag, Optional explicitConversion As Boolean = False) As BoundExpression Dim convertedTestExpression As BoundExpression = Nothing Dim placeholder As BoundRValuePlaceholder = Nothing If Not hasErrors Then ' Do we need to apply a placeholder? If Not testExpression.IsConstant Then Debug.Assert(Not testExpression.IsLValue) placeholder = New BoundRValuePlaceholder(testExpression.Syntax, testExpression.Type.GetNullableUnderlyingTypeOrSelf()) End If ' apply a conversion convertedTestExpression = ApplyConversion(testExpression.Syntax, type, If(placeholder, testExpression), explicitConversion, diagnostics) If convertedTestExpression Is If(placeholder, testExpression) Then convertedTestExpression = Nothing placeholder = Nothing End If End If Return New BoundBinaryConditionalExpression(syntax, testExpression:=testExpression, convertedTestExpression:=convertedTestExpression, testExpressionPlaceholder:=placeholder, elseExpression:=elseExpression, constantValueOpt:=constantValueOpt, type:=type, hasErrors:=hasErrors) End Function ''' <summary> Process the result of dominant type inference, generate diagnostics </summary> Private Function GenerateDiagnosticsForDominantTypeInferenceInIfExpression(dominantType As TypeSymbol, numCandidates As Integer, node As ExpressionSyntax, diagnostics As DiagnosticBag) As Boolean Dim hasErrors As Boolean = False If dominantType Is Nothing Then ReportDiagnostic(diagnostics, node, ERRID.ERR_IfNoType) hasErrors = True ElseIf numCandidates = 0 Then ' TODO: Is this reachable? Check and add tests If OptionStrict = VisualBasic.OptionStrict.On Then ReportDiagnostic(diagnostics, node, ERRID.ERR_IfNoTypeObjectDisallowed) hasErrors = True ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectAssumed1, ErrorFactory.ErrorInfo(ERRID.WRN_IfNoTypeObjectAssumed))) End If ElseIf numCandidates > 1 Then If OptionStrict = VisualBasic.OptionStrict.On Then ReportDiagnostic(diagnostics, node, ERRID.ERR_IfTooManyTypesObjectDisallowed) hasErrors = True ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectAssumed1, ErrorFactory.ErrorInfo(ERRID.WRN_IfTooManyTypesObjectAssumed))) End If End If Return hasErrors End Function ''' <summary> ''' True if inside in binding arguments of constructor ''' call with {'Me'/'MyClass'/'MyBase'}.New(...) from another constructor ''' </summary> Protected Overridable ReadOnly Property IsInsideChainedConstructorCallArguments As Boolean Get Return Me.ContainingBinder.IsInsideChainedConstructorCallArguments End Get End Property Private Function IsMeOrMyBaseOrMyClassInSharedContext() As Boolean ' If we are inside an attribute then we are not in an instance context. If Me.BindingLocation = VisualBasic.BindingLocation.Attribute Then Return True End If Dim containingMember = Me.ContainingMember If containingMember IsNot Nothing Then Select Case containingMember.Kind Case SymbolKind.Method, SymbolKind.Property Return containingMember.IsShared OrElse Me.ContainingType.IsModuleType Case SymbolKind.Field Return containingMember.IsShared OrElse Me.ContainingType.IsModuleType OrElse DirectCast(containingMember, FieldSymbol).IsConst End Select End If Return True End Function Private Function CheckMeOrMyBaseOrMyClassInSharedOrDisallowedContext(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean errorId = Nothing ' Any executable statement in a script class can access Me/MyClass/MyBase implicitly but not explicitly. ' No code in a script class is shared. Dim containingType = Me.ContainingType If containingType IsNot Nothing AndAlso containingType.IsScriptClass Then If implicitReference Then Return True Else errorId = ERRID.ERR_KeywordNotAllowedInScript Return False End If End If If IsMeOrMyBaseOrMyClassInSharedContext() Then errorId = If(implicitReference, ERRID.ERR_BadInstanceMemberAccess, If(containingType IsNot Nothing AndAlso containingType.IsModuleType, ERRID.ERR_UseOfKeywordFromModule1, ERRID.ERR_UseOfKeywordNotInInstanceMethod1)) Return False ElseIf IsInsideChainedConstructorCallArguments Then errorId = If(implicitReference, ERRID.ERR_InvalidImplicitMeReference, ERRID.ERR_InvalidMeReference) Return False End If Return True End Function ''' <summary> ''' Can we access MyBase in this location. If False is returned, ''' also returns the error id associated with that. ''' </summary> Private Function CanAccessMyBase(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean errorId = Nothing If Not CheckMeOrMyBaseOrMyClassInSharedOrDisallowedContext(implicitReference, errorId) Then Return False End If If ContainingType.IsStructureType Then errorId = ERRID.ERR_UseOfKeywordFromStructure1 Return False End If ' TODO: Find a test case for ERRID_UseOfKeywordOutsideClass1 Debug.Assert(ContainingType.IsClassType) ' TODO: Check for closures Return True End Function Private Function CanAccessMeOrMyClass(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean errorId = Nothing Return CheckMeOrMyBaseOrMyClassInSharedOrDisallowedContext(implicitReference, errorId) End Function ''' <summary> ''' Can we access Me in this location. If False is returned, ''' also returns the error id associated with that. ''' </summary> Friend Function CanAccessMe(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean errorId = Nothing ' TODO: Find a test case for ERRID_UseOfKeywordOutsideClass1 Return CanAccessMeOrMyClass(implicitReference, errorId) End Function ''' <summary> ''' Can we access MyClass in this location. If False is returned, ''' also returns the error id associated with that. ''' </summary> Private Function CanAccessMyClass(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean errorId = Nothing If Me.ContainingType IsNot Nothing AndAlso Me.ContainingType.IsModuleType Then errorId = ERRID.ERR_MyClassNotInClass Return False End If Return CanAccessMeOrMyClass(implicitReference, errorId) End Function Private Function BindMeExpression(node As MeExpressionSyntax, diagnostics As DiagnosticBag) As BoundMeReference Dim err As ERRID = Nothing If Not CanAccessMe(False, err) Then ReportDiagnostic(diagnostics, node, err, SyntaxFacts.GetText(node.Keyword.Kind)) Return New BoundMeReference(node, If(Me.ContainingType, ErrorTypeSymbol.UnknownResultType), hasErrors:=True) End If Return CreateMeReference(node) End Function ' Create a reference to Me, without error checking. Private Function CreateMeReference(node As VisualBasicSyntaxNode, Optional isSynthetic As Boolean = False) As BoundMeReference Dim containingMethod = TryCast(ContainingMember, MethodSymbol) Dim result = New BoundMeReference(node, If(Me.ContainingType, ErrorTypeSymbol.UnknownResultType)) If isSynthetic Then result.SetWasCompilerGenerated() End If Return result End Function Private Function BindMyBaseExpression(node As MyBaseExpressionSyntax, diagnostics As DiagnosticBag) As BoundMyBaseReference Dim err As ERRID = Nothing If Not CanAccessMyBase(False, err) Then ReportDiagnostic(diagnostics, node, err, SyntaxFacts.GetText(node.Keyword.Kind)) Return New BoundMyBaseReference(node, If(Me.ContainingType IsNot Nothing, Me.ContainingType.BaseTypeNoUseSiteDiagnostics, ErrorTypeSymbol.UnknownResultType), hasErrors:=True) End If Dim containingMethod = TryCast(ContainingMember, MethodSymbol) Return New BoundMyBaseReference(node, If(Me.ContainingType IsNot Nothing, Me.ContainingType.BaseTypeNoUseSiteDiagnostics, ErrorTypeSymbol.UnknownResultType)) End Function Private Function BindMyClassExpression(node As MyClassExpressionSyntax, diagnostics As DiagnosticBag) As BoundMyClassReference Dim err As ERRID = Nothing If Not CanAccessMyClass(False, err) Then ReportDiagnostic(diagnostics, node, err, SyntaxFacts.GetText(node.Keyword.Kind)) Return New BoundMyClassReference(node, If(Me.ContainingType, ErrorTypeSymbol.UnknownResultType), hasErrors:=True) End If Dim containingMethod = TryCast(ContainingMember, MethodSymbol) Return New BoundMyClassReference(node, If(Me.ContainingType, ErrorTypeSymbol.UnknownResultType)) End Function ' Can the given name syntax be an implicit declared variables. Only some syntactic locations are permissible ' for implicitly declared variables. They are disallowed in: ' target of invocation ' LHS of member access ' ' Also, For, For Each, and Catch can implicitly declare a variable, but that implicit declaration has ' different rules that is handled directly in the binding of those statements. Thus, they are disallowed here. ' ' Finally, Dev10 disallows 3 special names: "Null", "Empty", and "Rnd". Private Function CanBeImplicitVariableDeclaration(nameSyntax As SimpleNameSyntax) As Boolean ' Disallow generic names. If nameSyntax.Kind <> SyntaxKind.IdentifierName Then Return False End If Dim parent As VisualBasicSyntaxNode = nameSyntax.Parent If parent IsNot Nothing Then Select Case parent.Kind Case SyntaxKind.SimpleMemberAccessExpression ' intentionally NOT SyntaxKind.DictionaryAccess If DirectCast(parent, MemberAccessExpressionSyntax).Expression Is nameSyntax Then Return False End If Case SyntaxKind.InvocationExpression If DirectCast(parent, InvocationExpressionSyntax).Expression Is nameSyntax Then ' Name is the expression part of an invocation. Return False End If Case SyntaxKind.ConditionalAccessExpression Dim conditionalAccess = DirectCast(parent, ConditionalAccessExpressionSyntax) If conditionalAccess.Expression Is nameSyntax Then Dim leaf As ExpressionSyntax = conditionalAccess.GetLeafAccess() If leaf IsNot Nothing AndAlso (leaf.Kind = SyntaxKind.SimpleMemberAccessExpression OrElse leaf.Kind = SyntaxKind.InvocationExpression) Then Return False End If End If Case SyntaxKind.CatchStatement If DirectCast(parent, CatchStatementSyntax).IdentifierName Is nameSyntax Then Return False End If End Select End If ' Dev10 disallows implicit variable creation for "Null", "Empty", and "RND". Dim name As String = MakeHalfWidthIdentifier(nameSyntax.Identifier.ValueText) If CaseInsensitiveComparison.Equals(name, "Null") OrElse CaseInsensitiveComparison.Equals(name, "Empty") OrElse CaseInsensitiveComparison.Equals(name, "RND") Then Return False End If Return True End Function ' "isInvocationOrAddressOf" indicates that the name is being bound as the left hand side of an invocation ' or the argument of an AddressOf, and the return value variable should not be bound to. Private Function BindSimpleName(node As SimpleNameSyntax, isInvocationOrAddressOf As Boolean, diagnostics As DiagnosticBag, Optional skipLocalsAndParameters As Boolean = False) As BoundExpression Dim name As String Dim typeArguments As TypeArgumentListSyntax #If DEBUG Then If CanBeImplicitVariableDeclaration(node) Then CheckSimpleNameBindingOrder(node) End If #End If If node.Kind = SyntaxKind.GenericName Then Dim genericName = DirectCast(node, GenericNameSyntax) typeArguments = genericName.TypeArgumentList name = genericName.Identifier.ValueText Else Debug.Assert(node.Kind = SyntaxKind.IdentifierName) typeArguments = Nothing name = DirectCast(node, IdentifierNameSyntax).Identifier.ValueText End If If String.IsNullOrEmpty(name) Then ' Empty string must have been a syntax error. ' Just produce a bad expression and get out without producing any new errors. Return BadExpression(node, ErrorTypeSymbol.UnknownResultType) End If Dim options As LookupOptions = LookupOptions.AllMethodsOfAnyArity ' overload resolution filters methods by arity. If isInvocationOrAddressOf Then options = options Or LookupOptions.MustNotBeReturnValueVariable End If If skipLocalsAndParameters Then options = options Or LookupOptions.MustNotBeLocalOrParameter End If ' Handle a case of being able to refer to System.Int32 through System.Integer. ' Same for other intrinsic types with intrinsic name different from emitted name. If node.Kind = SyntaxKind.IdentifierName AndAlso DirectCast(node, IdentifierNameSyntax).Identifier.IsBracketed AndAlso MemberLookup.GetTypeForIntrinsicAlias(name) <> SpecialType.None Then options = options Or LookupOptions.AllowIntrinsicAliases End If Dim arity As Integer = If(typeArguments IsNot Nothing, typeArguments.Arguments.Count, 0) Dim result As LookupResult = LookupResult.GetInstance() Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Me.Lookup(result, name, arity, options, useSiteDiagnostics) diagnostics.Add(node, useSiteDiagnostics) If Not result.IsGoodOrAmbiguous AndAlso Me.ImplicitVariableDeclarationAllowed AndAlso Not Me.AllImplicitVariableDeclarationsAreHandled AndAlso CanBeImplicitVariableDeclaration(node) Then ' Declare an implicit local variable. Dim implicitLocal As LocalSymbol = DeclareImplicitLocalVariable(DirectCast(node, IdentifierNameSyntax), diagnostics) result.SetFrom(implicitLocal) End If If Not result.HasSymbol Then ' Did not find anything with that name. result.Free() ' If the name represents an imported XML namespace prefix, report a specific error. Dim [namespace] As String = Nothing Dim fromImports = False If LookupXmlNamespace(name, ignoreXmlNodes:=True, [namespace]:=[namespace], fromImports:=fromImports) Then Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_XmlPrefixNotExpression, name) End If Dim errorInfo As DiagnosticInfo = Nothing If node.Kind = SyntaxKind.IdentifierName Then Select Case KeywordTable.TokenOfString(name) Case SyntaxKind.AwaitKeyword errorInfo = GetAwaitInNonAsyncError() End Select End If If errorInfo Is Nothing Then 'Check for My and use of VB Embed Runtime usage for different diagnostic If IdentifierComparison.Equals(MissingRuntimeMemberDiagnosticHelper.MyVBNamespace, name) AndAlso Me.Compilation.Options.EmbedVbCoreRuntime Then errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_PlatformDoesntSupport, MissingRuntimeMemberDiagnosticHelper.MyVBNamespace) Else errorInfo = ErrorFactory.ErrorInfo(If(Me.IsInQuery, ERRID.ERR_QueryNameNotDeclared, ERRID.ERR_NameNotDeclared1), name) End If End If Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, errorInfo) End If Dim boundExpr As BoundExpression = BindSimpleName(result, node, options, typeArguments, diagnostics) result.Free() Return boundExpr End Function ''' <summary> ''' Second part of BindSimpleName. ''' It is a separate function so that it could be called directly ''' when we have already looked up for the name. ''' </summary> Private Function BindSimpleName(result As LookupResult, node As VisualBasicSyntaxNode, options As LookupOptions, typeArguments As TypeArgumentListSyntax, diagnostics As DiagnosticBag) As BoundExpression ' An implicit Me is inserted if we found something in the immediate containing type. ' Note that validation of whether Me can actually be used in this case is deferred until after ' overload resolution determines if we are accessing a static or instance member. Dim receiver As BoundExpression = Nothing Dim containingType = Me.ContainingType If containingType IsNot Nothing Then If containingType.IsScriptClass Then Dim memberDeclaringType = result.Symbols(0).ContainingType If memberDeclaringType IsNot Nothing Then receiver = TryBindInteractiveReceiver(node, Me.ContainingMember, containingType, memberDeclaringType) End If End If If receiver Is Nothing Then Dim symbol = result.Symbols(0) If symbol.IsReducedExtensionMethod() OrElse BindSimpleNameIsMemberOfType(symbol, containingType) Then receiver = CreateMeReference(node, isSynthetic:=True) End If End If End If Dim boundExpr As BoundExpression = BindSymbolAccess(node, result, options, receiver, typeArguments, QualificationKind.Unqualified, diagnostics) Return boundExpr End Function Private Shared Function BindSimpleNameIsMemberOfType(member As Symbol, type As NamedTypeSymbol) As Boolean Debug.Assert(type IsNot Nothing) Debug.Assert(member IsNot Nothing) Select Case member.Kind Case SymbolKind.Field, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event Dim container = member.ContainingType If container Is Nothing Then Return False Dim currentType = type Do While currentType IsNot Nothing If container.Equals(currentType) Then Return True End If currentType = currentType.BaseTypeNoUseSiteDiagnostics Loop End Select Return False End Function Private Function TryBindInteractiveReceiver(syntax As VisualBasicSyntaxNode, currentMember As Symbol, currentType As NamedTypeSymbol, memberDeclaringType As NamedTypeSymbol) As BoundExpression If currentType.TypeKind = TypeKind.Submission AndAlso Not currentMember.IsShared Then If memberDeclaringType.TypeKind = TypeKind.Submission Then Return New BoundPreviousSubmissionReference(syntax, currentType, memberDeclaringType) Else ' TODO (tomat): host object binding 'Dim hostObjectType As TypeSymbol = Compilation.GetHostObjectTypeSymbol() 'If hostObjectType IsNot Nothing AndAlso (hostObjectType = memberDeclaringType OrElse hostObjectType.BaseClassesContain(memberDeclaringType)) Then ' Return New BoundHostObjectMemberReference(syntax, hostObjectType) 'End If End If End If Return Nothing End Function Private Function BindMemberAccess(node As MemberAccessExpressionSyntax, eventContext As Boolean, diagnostics As DiagnosticBag) As BoundExpression Dim leftOpt = node.Expression Dim boundLeft As BoundExpression = Nothing Dim rightName As SimpleNameSyntax = node.Name If leftOpt Is Nothing Then ' 11.6 Member Access Expressions: "1. If E is omitted, then the expression from the ' immediately containing With statement is substituted for E and the member access ' is performed. If there is no containing With statement, a compile-time error occurs." ' NOTE: If there are no enclosing anonymous type creation or With statement, the method below will ' report error ERR_BadWithRef; otherwise 'the closest' binder (either AnonymousTypeCreationBinder ' or WithStatementBinder (to be created)) should handle binding of such expression Dim wholeMemberAccessExpressionBound As Boolean = False Dim conditionalAccess As ConditionalAccessExpressionSyntax = node.GetCorrespondingConditionalAccessExpression() If conditionalAccess IsNot Nothing Then boundLeft = GetConditionalAccessReceiver(conditionalAccess) Else boundLeft = Me.TryBindOmittedLeftForMemberAccess(node, diagnostics, Me, wholeMemberAccessExpressionBound) End If If boundLeft Is Nothing Then Debug.Assert(Not wholeMemberAccessExpressionBound) Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_BadWithRef) End If If wholeMemberAccessExpressionBound Then ' In case TryBindOmittedLeftForMemberAccess bound the whole member ' access expression syntax node just return the result Return boundLeft End If Else boundLeft = BindLeftOfPotentialColorColorMemberAccess(node, leftOpt, diagnostics) End If Return Me.BindMemberAccess(node, boundLeft, rightName, eventContext, diagnostics) End Function Private Function BindLeftOfPotentialColorColorMemberAccess(parentNode As MemberAccessExpressionSyntax, leftOpt As ExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression ' handle for Color Color case: ' ' ======= 11.6.1 Identical Type and Member Names ' It is not uncommon to name members using the same name as their type. In that situation, however, ' inconvenient name hiding can occur: ' ' Enum Color ' Red ' Green ' Yellow ' End Enum ' ' Class Test ' ReadOnly Property Color() As Color ' Get ' Return Color.Red ' End Get ' End Property ' ' Shared Function DefaultColor() As Color ' Return Color.Green ' Binds to the instance property! ' End Function ' End Class ' ' In the previous example, the simple name Color in DefaultColor binds to the instance property ' instead of the type. Because an instance member cannot be referenced in a shared member, ' this would normally be an error. ' ' However, a special rule allows access to the type in this case. If the base expression ' of a member access expression is a simple name and binds to a constant, field, property, ' local variable or parameter whose type has the same name, then the base expression can refer ' either to the member or the type. This can never result in ambiguity because the members ' that can be accessed off of either one are the same. ' ' In the case that such a base expression binds to an instance member but the binding occurs ' within a context in which "Me" is not accessible, the expression instead binds to the ' type (if applicable). ' ' If the base expression cannot be successfully disambiguated by the context in which it ' occurs, it binds to the member. This can occur in particular in late-bound calls or ' error conditions. If leftOpt.Kind = SyntaxKind.IdentifierName Then Dim node = DirectCast(leftOpt, SimpleNameSyntax) Dim leftDiagnostics = DiagnosticBag.GetInstance() Dim boundLeft = Me.BindSimpleName(node, False, leftDiagnostics) Dim boundValue = boundLeft Dim propertyDiagnostics As DiagnosticBag = Nothing If boundLeft.Kind = BoundKind.PropertyGroup Then propertyDiagnostics = DiagnosticBag.GetInstance() boundValue = Me.AdjustReceiverValue(boundLeft, node, propertyDiagnostics) End If Dim leftSymbol = boundValue.ExpressionSymbol If leftSymbol IsNot Nothing Then Dim leftType As TypeSymbol Dim isInstanceMember As Boolean Select Case leftSymbol.Kind Case SymbolKind.Field, SymbolKind.Property Debug.Assert(boundValue.Type IsNot Nothing) leftType = boundValue.Type isInstanceMember = Not leftSymbol.IsShared Case SymbolKind.Local, SymbolKind.Parameter, SymbolKind.RangeVariable Debug.Assert(boundValue.Type IsNot Nothing) leftType = boundValue.Type isInstanceMember = False Case Else leftType = Nothing isInstanceMember = False End Select If leftType IsNot Nothing Then Dim leftName = node.Identifier.ValueText If CaseInsensitiveComparison.Equals(leftType.Name, leftName) AndAlso leftType.TypeKind <> TypeKind.TypeParameter Then Dim typeDiagnostics = New DiagnosticBag() Dim boundType = Me.BindNamespaceOrTypeExpression(node, typeDiagnostics) If boundType.Type = leftType Then Dim err As ERRID = Nothing If isInstanceMember AndAlso (Not CanAccessMe(implicitReference:=True, errorId:=err) OrElse Not BindSimpleNameIsMemberOfType(leftSymbol, ContainingType)) Then diagnostics.AddRange(typeDiagnostics) leftDiagnostics.Free() Return boundType End If Dim valueDiagnostics = New DiagnosticBag() valueDiagnostics.AddRangeAndFree(leftDiagnostics) If propertyDiagnostics IsNot Nothing Then valueDiagnostics.AddRangeAndFree(propertyDiagnostics) End If Return New BoundTypeOrValueExpression(leftOpt, New BoundTypeOrValueData(boundValue, valueDiagnostics, boundType, typeDiagnostics), leftType) End If End If End If End If If propertyDiagnostics IsNot Nothing Then propertyDiagnostics.Free() End If diagnostics.AddRangeAndFree(leftDiagnostics) Return boundLeft End If ' Not a Color Color case; just bind the LHS as an expression. If leftOpt.Kind = SyntaxKind.SimpleMemberAccessExpression Then Return BindMemberAccess(DirectCast(leftOpt, MemberAccessExpressionSyntax), eventContext:=False, diagnostics:=diagnostics) Else Return Me.BindExpression(leftOpt, diagnostics) End If End Function ''' <summary> ''' Method binds member access in case when we got hold ''' of a bound node representing the left expression ''' </summary> ''' <remarks> ''' The method is protected, so that it can be called from other ''' binders overriding TryBindMemberAccessWithLeftOmitted ''' </remarks> Protected Function BindMemberAccess(node As VisualBasicSyntaxNode, left As BoundExpression, right As SimpleNameSyntax, eventContext As Boolean, diagnostics As DiagnosticBag) As BoundExpression Debug.Assert(node IsNot Nothing) Debug.Assert(left IsNot Nothing) Debug.Assert(right IsNot Nothing) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing ' Check if 'left' is of type which is a class or struct and 'name' is "New" Dim leftTypeSymbol As TypeSymbol = left.Type If leftTypeSymbol IsNot Nothing AndAlso (right.Kind = SyntaxKind.IdentifierName OrElse right.Kind = SyntaxKind.GenericName) Then ' Get the name syntax token Dim identifier = If(right.Kind = SyntaxKind.IdentifierName, DirectCast(right, IdentifierNameSyntax).Identifier, DirectCast(right, GenericNameSyntax).Identifier) If Not identifier.IsBracketed AndAlso CaseInsensitiveComparison.Equals(identifier.ValueText, SyntaxFacts.GetText(SyntaxKind.NewKeyword)) Then If leftTypeSymbol.IsArrayType() Then ' No instance constructors found. Can't call constructor on an array type. If (left.HasErrors) Then Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType) End If Return Me.ReportDiagnosticAndProduceBadExpression( diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ConstructorNotFound1, leftTypeSymbol), left) End If Dim leftTypeKind As TypeKind = leftTypeSymbol.TypeKind If leftTypeKind = TypeKind.Class OrElse leftTypeKind = TypeKind.Structure OrElse leftTypeKind = TypeKind.Module Then ' Bind to method group representing available instance constructors Dim namedLeftTypeSymbol = DirectCast(leftTypeSymbol, NamedTypeSymbol) Dim accessibleConstructors = GetAccessibleConstructors(namedLeftTypeSymbol, useSiteDiagnostics) diagnostics.Add(node, useSiteDiagnostics) useSiteDiagnostics = Nothing If accessibleConstructors.IsEmpty Then ' No instance constructors found If (left.HasErrors) Then Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType) End If Return Me.ReportDiagnosticAndProduceBadExpression( diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ConstructorNotFound1, namedLeftTypeSymbol), left) Else Dim hasErrors As Boolean = left.HasErrors If Not hasErrors AndAlso right.Kind = SyntaxKind.GenericName Then ' Report error BC30282 ReportDiagnostic(diagnostics, node, ERRID.ERR_InvalidConstructorCall) hasErrors = True End If ' Create a method group consisting of all instance constructors Return New BoundMethodGroup(node, Nothing, accessibleConstructors, LookupResultKind.Good, left, If(left.Kind = BoundKind.TypeExpression, QualificationKind.QualifiedViaTypeName, QualificationKind.QualifiedViaValue), hasErrors) End If End If End If End If Dim type As TypeSymbol Dim rightName As String Dim typeArguments As TypeArgumentListSyntax If right.Kind = SyntaxKind.GenericName Then Dim genericName = DirectCast(right, GenericNameSyntax) typeArguments = genericName.TypeArgumentList rightName = genericName.Identifier.ValueText Else Debug.Assert(right.Kind = SyntaxKind.IdentifierName) typeArguments = Nothing rightName = DirectCast(right, IdentifierNameSyntax).Identifier.ValueText End If Dim rightArity As Integer = If(typeArguments IsNot Nothing, typeArguments.Arguments.Count, 0) Dim lookupResult As LookupResult = LookupResult.GetInstance() Dim options As LookupOptions = LookupOptions.AllMethodsOfAnyArity Try If left.Kind = BoundKind.NamespaceExpression Then If String.IsNullOrEmpty(rightName) Then ' Must have been a syntax error. Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType) End If Dim ns As NamespaceSymbol = DirectCast(left, BoundNamespaceExpression).NamespaceSymbol ' Handle a case of being able to refer to System.Int32 through System.Integer. ' Same for other intrinsic types with intrinsic name different from emitted name. If right.Kind = SyntaxKind.IdentifierName AndAlso node.Kind = SyntaxKind.SimpleMemberAccessExpression Then options = options Or LookupOptions.AllowIntrinsicAliases End If MemberLookup.Lookup(lookupResult, ns, rightName, rightArity, options, Me, useSiteDiagnostics) ' overload resolution filters methods by arity. If lookupResult.HasSymbol Then Return BindSymbolAccess(node, lookupResult, options, left, typeArguments, QualificationKind.QualifiedViaNamespace, diagnostics) Else Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, rightName, ns), left) End If ElseIf left.Kind = BoundKind.TypeExpression Then type = DirectCast(left, BoundTypeExpression).Type If type.TypeKind = TypeKind.TypeParameter Then Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_TypeParamQualifierDisallowed), left) Else If String.IsNullOrEmpty(rightName) Then ' Must have been a syntax error. Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType) End If LookupMember(lookupResult, type, rightName, rightArity, options, useSiteDiagnostics) ' overload resolution filters methods by arity. If lookupResult.HasSymbol Then Return BindSymbolAccess(node, lookupResult, options, left, typeArguments, QualificationKind.QualifiedViaTypeName, diagnostics) Else Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, rightName, type), left) End If End If Else left = AdjustReceiverValue(left, node, diagnostics) type = left.Type If type Is Nothing OrElse type.IsErrorType() Then Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType) End If If String.IsNullOrEmpty(rightName) Then ' Must have been a syntax error. Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType) End If Dim effectiveOptions = If(left.Kind <> BoundKind.MyBaseReference, options, options Or LookupOptions.UseBaseReferenceAccessibility) If eventContext Then effectiveOptions = effectiveOptions Or LookupOptions.EventsOnly End If LookupMember(lookupResult, type, rightName, rightArity, effectiveOptions, useSiteDiagnostics) ' overload resolution filters methods by arity. If lookupResult.HasSymbol Then Return BindSymbolAccess(node, lookupResult, effectiveOptions, left, typeArguments, QualificationKind.QualifiedViaValue, diagnostics) ElseIf (type.IsObjectType AndAlso Not left.IsMyBaseReference) OrElse type.IsExtensibleInterfaceNoUseSiteDiagnostics Then Return BindLateBoundMemberAccess(node, rightName, typeArguments, left, type, diagnostics) ElseIf left.HasErrors Then Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType) Else If type.IsInterfaceType() Then ' In case IsExtensibleInterfaceNoUseSiteDiagnostics above failed because there were bad inherited interfaces. type.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics) End If Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, rightName, type), left) End If End If Finally diagnostics.Add(node, useSiteDiagnostics) lookupResult.Free() End Try End Function ''' <summary> ''' Returns a bound node for left part of member access node with omitted left syntax. ''' In particular it handles member access inside With statement. ''' ''' By default the method delegates the work to it's containing binder or returns Nothing. ''' </summary> ''' <param name="accessingBinder"> ''' Specifies the binder which requests an access to the bound node for omitted left. ''' </param> ''' <param name="wholeMemberAccessExpressionBound"> ''' NOTE: in some cases, like for binding inside anonymous object creation expression, this ''' method returns bound node for the whole expression rather than only for omitted left part. ''' </param> Protected Friend Overridable Function TryBindOmittedLeftForMemberAccess(node As MemberAccessExpressionSyntax, diagnostics As DiagnosticBag, accessingBinder As Binder, <Out> ByRef wholeMemberAccessExpressionBound As Boolean) As BoundExpression Debug.Assert(Me.ContainingBinder IsNot Nothing) Return Me.ContainingBinder.TryBindOmittedLeftForMemberAccess(node, diagnostics, accessingBinder, wholeMemberAccessExpressionBound) End Function Protected Friend Overridable Function TryBindOmittedLeftForXmlMemberAccess(node As XmlMemberAccessExpressionSyntax, diagnostics As DiagnosticBag, accessingBinder As Binder) As BoundExpression Debug.Assert(Me.ContainingBinder IsNot Nothing) Return Me.ContainingBinder.TryBindOmittedLeftForXmlMemberAccess(node, diagnostics, accessingBinder) End Function Private Function IsBindingImplicitlyTypedLocal(symbol As LocalSymbol) As Boolean For Each s In Me.ImplicitlyTypedLocalsBeingBound If s = symbol Then Return True End If Next Return False End Function ''' <summary> ''' Given a localSymbol and a syntaxNode where the symbol is used, safely return the symbol's type. ''' </summary> ''' <param name="localSymbol">The local symbol</param> ''' <param name="node">The syntax node that references the symbol</param> ''' <param name="diagnostics">diagnostic bag if errors are to be reported</param> ''' <returns>Returns the symbol's type or an ErrorTypeSymbol if the local is referenced before its definition or if the symbol is still being bound.</returns> ''' <remarks>This method safely returns a local symbol's type by checking for circular references or references before declaration.</remarks> Private Function GetLocalSymbolType(localSymbol As LocalSymbol, node As VisualBasicSyntaxNode, Optional diagnostics As DiagnosticBag = Nothing) As TypeSymbol Dim localType As TypeSymbol = Nothing ' Check if local symbol is used before it's definition. ' Do span comparison first in order to optimize performance for non-error cases. If node IsNot Nothing AndAlso node.SpanStart < localSymbol.IdentifierToken.SpanStart Then Dim declarationLocation As Location = localSymbol.IdentifierLocation Dim referenceLocation As Location = node.GetLocation() If Not localSymbol.IsImplicitlyDeclared AndAlso declarationLocation.IsInSource AndAlso referenceLocation IsNot Nothing AndAlso referenceLocation.IsInSource AndAlso declarationLocation.SourceTree Is referenceLocation.SourceTree Then localType = LocalSymbol.UseBeforeDeclarationResultType If diagnostics IsNot Nothing Then ReportDiagnostic(diagnostics, node, ERRID.ERR_UseOfLocalBeforeDeclaration1, localSymbol) End If End If ElseIf IsBindingImplicitlyTypedLocal(localSymbol) Then ' We are currently in the process of binding this symbol. ' if constant knows its type, there is no circularity ' Example: ' Const x as Color = x.Red If localSymbol.IsConst AndAlso localSymbol.ConstHasType Then Return localSymbol.Type End If ' NOTE: OptionInfer does not need to be checked before reporting the error ' locals only get to ImplicitlyTypedLocalsBeingBound if we actually infer ' their type, either because Option Infer is On or for other reason, ' we use UnknownResultType for such locals. If diagnostics IsNot Nothing Then If localSymbol.IsConst Then ReportDiagnostic(diagnostics, node, ERRID.ERR_CircularEvaluation1, localSymbol) Else ReportDiagnostic(diagnostics, node, ERRID.ERR_CircularInference1, localSymbol) End If End If localType = ErrorTypeSymbol.UnknownResultType End If If localType Is Nothing Then ' It is safe to get the type from the symbol. localType = localSymbol.Type End If Return localType End Function ' Bind access to a symbol, either qualified (LHS.Symbol) or unqualified (Symbol). This kind of qualification is indicated by qualKind. ' receiver is set to a value expression indicating the receiver that the symbol is being accessed off of. ' lookupResult must refer to one or more symbols. If lookupResult has a diagnostic associated with it, that diagnostic is reported. Private Function BindSymbolAccess(node As VisualBasicSyntaxNode, lookupResult As LookupResult, lookupOptionsUsed As LookupOptions, receiver As BoundExpression, typeArgumentsOpt As TypeArgumentListSyntax, qualKind As QualificationKind, diagnostics As DiagnosticBag) As BoundExpression Debug.Assert(lookupResult.HasSymbol) Dim hasError As Boolean = False ' Is there an ERROR (not a warning). If receiver IsNot Nothing Then hasError = receiver.HasErrors ' don't report subsequent errors if LHS was already an error. ' If receiver is a namespace group, let's check if we can collapse it to a single or more narrow namespace receiver = AdjustReceiverNamespace(lookupResult, receiver) End If Dim reportedLookupError As Boolean = False Dim resultKind As LookupResultKind = lookupResult.Kind If lookupResult.HasDiagnostic AndAlso ((lookupResult.Symbols(0).Kind <> SymbolKind.Method AndAlso lookupResult.Symbols(0).Kind <> SymbolKind.Property) OrElse resultKind <> LookupResultKind.Inaccessible) Then Debug.Assert(resultKind <> LookupResultKind.Good) ' Report the diagnostic with the symbol. Dim di As DiagnosticInfo = lookupResult.Diagnostic If Not hasError Then If typeArgumentsOpt IsNot Nothing AndAlso (lookupResult.Kind = LookupResultKind.WrongArity OrElse lookupResult.Kind = LookupResultKind.WrongArityAndStopLookup) Then ' Arity errors are reported on the type arguments only. ReportDiagnostic(diagnostics, typeArgumentsOpt, di) Else ReportDiagnostic(diagnostics, node, di) End If If di.Severity = DiagnosticSeverity.Error Then hasError = True reportedLookupError = True End If End If ' For non-overloadable symbols (everything but property/method) ' Create a BoundBadExpression to encapsulate all the ' symbols and the result kind. ' The type of the expression is the common type of the symbols, so further Intellisense ' works well if all the symbols are of common type. ' For property/method, we create a BoundMethodGroup/PropertyGroup so that we continue to do overload ' resolution. Dim symbols As ImmutableArray(Of Symbol) If TypeOf di Is AmbiguousSymbolDiagnostic Then ' Lookup had an ambiguity between Imports or Modules. Debug.Assert(lookupResult.Kind = LookupResultKind.Ambiguous) symbols = DirectCast(di, AmbiguousSymbolDiagnostic).AmbiguousSymbols Else symbols = lookupResult.Symbols.ToImmutable() End If Return New BoundBadExpression(node, lookupResult.Kind, symbols, If(receiver IsNot Nothing, ImmutableArray.Create(Of BoundNode)(receiver), ImmutableArray(Of BoundNode).Empty), GetCommonExpressionType(node, symbols, ConstantFieldsInProgress), hasErrors:=True) End If Select Case lookupResult.Symbols(0).Kind ' all symbols in a lookupResult must be of the same kind. Case SymbolKind.Method 'TODO: Deal with errors reported by BindTypeArguments. Should we adjust hasError? Return CreateBoundMethodGroup( node, lookupResult, lookupOptionsUsed, receiver, BindTypeArguments(typeArgumentsOpt, diagnostics), qualKind, hasError) Case SymbolKind.Property ' UNDONE: produce error if type arguments were present. Debug.Assert(lookupResult.Kind = LookupResultKind.Good OrElse lookupResult.Kind = LookupResultKind.Inaccessible) Return New BoundPropertyGroup( node, lookupResult.Symbols.ToDowncastedImmutable(Of PropertySymbol), lookupResult.Kind, receiver, qualKind, hasErrors:=hasError) Case SymbolKind.Event Dim eventSymbol = DirectCast(lookupResult.SingleSymbol, EventSymbol) If eventSymbol.IsShared And qualKind = QualificationKind.Unqualified Then receiver = Nothing End If If Not reportedLookupError Then ReportUseSiteError(diagnostics, node, eventSymbol) End If If Not hasError Then If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeOrValueExpression Then receiver = AdjustReceiverTypeOrValue(receiver, node, isShared:=eventSymbol.IsShared, diagnostics:=diagnostics, qualKind:=qualKind) End If hasError = CheckSharedSymbolAccess(node, eventSymbol.IsShared, receiver, qualKind, diagnostics) End If ReportDiagnosticsIfObsolete(diagnostics, eventSymbol, node) If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If Return New BoundEventAccess( node, receiver, eventSymbol, eventSymbol.Type, hasErrors:=hasError) Case SymbolKind.Field Dim fieldSymbol As FieldSymbol = DirectCast(lookupResult.SingleSymbol, FieldSymbol) If fieldSymbol.IsShared And qualKind = QualificationKind.Unqualified Then receiver = Nothing End If ' TODO: Check if this is a constant field with missing or bad value and report an error. If Not hasError Then If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeOrValueExpression Then receiver = AdjustReceiverTypeOrValue(receiver, node, isShared:=fieldSymbol.IsShared, diagnostics:=diagnostics, qualKind:=qualKind) End If hasError = CheckSharedSymbolAccess(node, fieldSymbol.IsShared, receiver, qualKind, diagnostics) End If If Not reportedLookupError Then If Not ReportUseSiteError(diagnostics, node, fieldSymbol) Then CheckMemberTypeAccessibility(diagnostics, node, fieldSymbol) End If End If ReportDiagnosticsIfObsolete(diagnostics, fieldSymbol, node) ' const fields may need to determine the type because it's inferred ' This is why using .Type was replaced by .GetInferredType to detect cycles. Dim fieldAccessType = fieldSymbol.GetInferredType(ConstantFieldsInProgress) Dim asMemberAccess = TryCast(node, MemberAccessExpressionSyntax) If asMemberAccess IsNot Nothing AndAlso Not fieldAccessType.IsErrorType() Then VerifyTypeCharacterConsistency(asMemberAccess.Name, fieldAccessType.GetEnumUnderlyingTypeOrSelf, diagnostics) End If If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If Return New BoundFieldAccess(node, receiver, fieldSymbol, isLValue:=IsLValueFieldAccess(fieldSymbol, receiver), suppressVirtualCalls:=False, constantsInProgressOpt:=Me.ConstantFieldsInProgress, type:=fieldAccessType, hasErrors:=hasError OrElse fieldAccessType.IsErrorType) Case SymbolKind.Local Dim localSymbol = DirectCast(lookupResult.SingleSymbol, LocalSymbol) If localSymbol.IsFunctionValue Then Dim method = DirectCast(localSymbol.ContainingSymbol, MethodSymbol) If method.IsAsync OrElse method.IsIterator Then ReportDiagnostic(diagnostics, node, ERRID.ERR_BadResumableAccessReturnVariable) Return BadExpression(node, ErrorTypeSymbol.UnknownResultType) End If End If Dim localAccessType As TypeSymbol = GetLocalSymbolType(localSymbol, node, diagnostics) Dim asSimpleName = TryCast(node, SimpleNameSyntax) If asSimpleName IsNot Nothing AndAlso Not localAccessType.IsErrorType() Then VerifyTypeCharacterConsistency(asSimpleName, localAccessType.GetEnumUnderlyingTypeOrSelf, diagnostics) End If If localSymbol.IsFor Then ' lifting iteration variable produces a warning Dim localSymbolContainingSymbol As Symbol = localSymbol.ContainingSymbol If ContainingMember IsNot localSymbolContainingSymbol Then ' Need to go up the chain of containers and see if the last lambda we see ' is a QueryLambda, before we reach local's container. If IsTopMostEnclosingLambdaAQueryLambda(ContainingMember, localSymbolContainingSymbol) Then ReportDiagnostic(diagnostics, node, ERRID.WRN_LiftControlVariableQuery, localSymbol.Name) Else ReportDiagnostic(diagnostics, node, ERRID.WRN_LiftControlVariableLambda, localSymbol.Name) End If End If End If ' Debug.Assert(localSymbol.GetUseSiteErrorInfo() Is Nothing) ' Not true in the debugger. Return New BoundLocal(node, localSymbol, localAccessType, hasErrors:=hasError) Case SymbolKind.RangeVariable Dim rangeVariable = DirectCast(lookupResult.SingleSymbol, RangeVariableSymbol) Debug.Assert(rangeVariable.GetUseSiteErrorInfo() Is Nothing) Return New BoundRangeVariable(node, rangeVariable, rangeVariable.Type, hasErrors:=hasError) Case SymbolKind.Parameter Dim parameterSymbol = DirectCast(lookupResult.SingleSymbol, ParameterSymbol) Dim parameterType = parameterSymbol.Type Dim asSimpleName = TryCast(node, SimpleNameSyntax) If asSimpleName IsNot Nothing AndAlso Not parameterType.IsErrorType() Then VerifyTypeCharacterConsistency(asSimpleName, parameterType.GetEnumUnderlyingTypeOrSelf, diagnostics) End If Debug.Assert(parameterSymbol.GetUseSiteErrorInfo() Is Nothing) Return New BoundParameter(node, parameterSymbol, parameterType, hasErrors:=hasError) Case SymbolKind.NamedType, SymbolKind.ErrorType ' Note: arity already checked by lookup process. ' Bind the type arguments. Dim typeArguments As BoundTypeArguments = Nothing If typeArgumentsOpt IsNot Nothing Then ' Bind the type arguments and report errors in the current context. typeArguments = BindTypeArguments(typeArgumentsOpt, diagnostics) End If ' If I identifies a type, then the result is that type constructed with the given type arguments. ' Construct the type if it is generic! See ConstructAndValidateConstraints(). Dim typeSymbol = TryCast(lookupResult.SingleSymbol, NamedTypeSymbol) If typeSymbol IsNot Nothing AndAlso typeArguments IsNot Nothing Then ' Construct the type and validate constraints. Dim constructedType = ConstructAndValidateConstraints( typeSymbol, typeArguments.Arguments, node, typeArgumentsOpt.Arguments, diagnostics) ' Put the constructed type in. Note that this preserves any error associated with the lookupResult. lookupResult.ReplaceSymbol(constructedType) End If ReportDiagnosticsIfObsolete(diagnostics, typeSymbol, node) If Not hasError Then receiver = AdjustReceiverTypeOrValue(receiver, node, isShared:=True, diagnostics:=diagnostics, qualKind:=qualKind) hasError = CheckSharedSymbolAccess(node, True, receiver, qualKind, diagnostics) End If If Not reportedLookupError Then ReportUseSiteError(diagnostics, node, If(typeSymbol, lookupResult.SingleSymbol)) End If Dim type As TypeSymbol = DirectCast(lookupResult.SingleSymbol, TypeSymbol) Dim asSimpleName = TryCast(node, SimpleNameSyntax) If asSimpleName IsNot Nothing AndAlso Not type.IsErrorType() Then VerifyTypeCharacterConsistency(asSimpleName, type.GetEnumUnderlyingTypeOrSelf, diagnostics) End If Return New BoundTypeExpression(node, receiver, Nothing, type, hasErrors:=hasError) Case SymbolKind.TypeParameter ' Note: arity already checked by lookup process. Debug.Assert(lookupResult.SingleSymbol.GetUseSiteErrorInfo() Is Nothing) Return New BoundTypeExpression(node, DirectCast(lookupResult.SingleSymbol, TypeSymbol), hasErrors:=hasError) Case SymbolKind.Namespace ' Note: arity already checked by lookup process. Debug.Assert(lookupResult.SingleSymbol.GetUseSiteErrorInfo() Is Nothing) Return New BoundNamespaceExpression(node, receiver, DirectCast(lookupResult.SingleSymbol, NamespaceSymbol), hasErrors:=hasError) Case SymbolKind.Alias Dim [alias] = DirectCast(lookupResult.SingleSymbol, AliasSymbol) Debug.Assert([alias].GetUseSiteErrorInfo() Is Nothing) Dim symbol = [alias].Target Select Case symbol.Kind Case SymbolKind.NamedType, SymbolKind.ErrorType If Not reportedLookupError Then ReportUseSiteError(diagnostics, node, symbol) End If Return New BoundTypeExpression(node, Nothing, [alias], DirectCast(symbol, TypeSymbol), hasErrors:=hasError) Case SymbolKind.Namespace Debug.Assert(symbol.GetUseSiteErrorInfo() Is Nothing) Return New BoundNamespaceExpression(node, Nothing, [alias], DirectCast(symbol, NamespaceSymbol), hasErrors:=hasError) Case Else Throw ExceptionUtilities.UnexpectedValue(symbol.Kind) End Select Case Else Throw ExceptionUtilities.UnexpectedValue(lookupResult.Symbols(0).Kind) End Select End Function Private Function AdjustReceiverNamespace(lookupResult As LookupResult, receiver As BoundExpression) As BoundExpression If receiver.Kind = BoundKind.NamespaceExpression Then Dim namespaceReceiver = DirectCast(receiver, BoundNamespaceExpression) If namespaceReceiver.NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup Then Dim symbols As ArrayBuilder(Of Symbol) = lookupResult.Symbols If lookupResult.HasDiagnostic Then Dim di As DiagnosticInfo = lookupResult.Diagnostic If TypeOf di Is AmbiguousSymbolDiagnostic Then ' Lookup had an ambiguity Debug.Assert(lookupResult.Kind = LookupResultKind.Ambiguous) Dim ambiguous As ImmutableArray(Of Symbol) = DirectCast(di, AmbiguousSymbolDiagnostic).AmbiguousSymbols symbols = ArrayBuilder(Of Symbol).GetInstance() symbols.AddRange(ambiguous) End If End If receiver = AdjustReceiverNamespace(namespaceReceiver, symbols) If symbols IsNot lookupResult.Symbols Then symbols.Free() End If End If End If Return receiver End Function Private Function AdjustReceiverNamespace(namespaceReceiver As BoundNamespaceExpression, symbols As ArrayBuilder(Of Symbol)) As BoundNamespaceExpression If symbols.Count > 0 Then Dim namespaces = New SmallDictionary(Of NamespaceSymbol, Boolean)() For Each candidate In symbols If Not AddReceiverNamespaces(namespaces, candidate, Me.Compilation) Then namespaces = Nothing Exit For End If Next If namespaces IsNot Nothing AndAlso namespaces.Count < namespaceReceiver.NamespaceSymbol.ConstituentNamespaces.Length Then Return AdjustReceiverNamespace(namespaceReceiver, DirectCast(namespaceReceiver.NamespaceSymbol, MergedNamespaceSymbol).Shrink(namespaces.Keys)) End If End If Return namespaceReceiver End Function Friend Shared Function AddReceiverNamespaces(namespaces As SmallDictionary(Of NamespaceSymbol, Boolean), candidate As Symbol, compilation As VisualBasicCompilation) As Boolean If candidate.Kind = SymbolKind.Namespace AndAlso DirectCast(candidate, NamespaceSymbol).NamespaceKind = NamespaceKindNamespaceGroup Then For Each constituent In DirectCast(candidate, NamespaceSymbol).ConstituentNamespaces If Not AddContainingNamespaces(namespaces, constituent, compilation) Then Return False End If Next Return True Else Return AddContainingNamespaces(namespaces, candidate, compilation) End If End Function Private Shared Function AddContainingNamespaces(namespaces As SmallDictionary(Of NamespaceSymbol, Boolean), candidate As Symbol, compilation As VisualBasicCompilation) As Boolean If candidate Is Nothing OrElse candidate.Kind = SymbolKind.ErrorType Then Return False End If Dim containingNamespace = candidate.ContainingNamespace If containingNamespace IsNot Nothing Then namespaces(compilation.GetCompilationNamespace(containingNamespace)) = False Else Debug.Assert(containingNamespace IsNot Nothing) ' Should not get here, I believe. Return False End If Return True End Function Private Function AdjustReceiverNamespace(namespaceReceiver As BoundNamespaceExpression, adjustedNamespace As NamespaceSymbol) As BoundNamespaceExpression If adjustedNamespace IsNot namespaceReceiver.NamespaceSymbol Then Dim receiver As BoundExpression = namespaceReceiver.UnevaluatedReceiverOpt If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.NamespaceExpression Then Dim parentNamespace = DirectCast(receiver, BoundNamespaceExpression) If parentNamespace.NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup AndAlso IsNamespaceGroupIncludesButNotEquivalentTo(parentNamespace.NamespaceSymbol, adjustedNamespace.ContainingNamespace) Then receiver = AdjustReceiverNamespace(parentNamespace, adjustedNamespace.ContainingNamespace) End If End If Return namespaceReceiver.Update(receiver, namespaceReceiver.AliasOpt, adjustedNamespace) End If Return namespaceReceiver End Function Private Shared Function IsNamespaceGroupIncludesButNotEquivalentTo(namespaceGroup As NamespaceSymbol, other As NamespaceSymbol) As Boolean Debug.Assert(namespaceGroup.NamespaceKind = NamespaceKindNamespaceGroup) Dim result As Boolean If other.NamespaceKind <> NamespaceKindNamespaceGroup Then result = namespaceGroup.ConstituentNamespaces.Contains(other) Else Dim groupConstituents As ImmutableArray(Of NamespaceSymbol) = namespaceGroup.ConstituentNamespaces Dim otherConstituents As ImmutableArray(Of NamespaceSymbol) = other.ConstituentNamespaces If groupConstituents.Length > otherConstituents.Length Then result = True Dim lookup = New SmallDictionary(Of NamespaceSymbol, Boolean)() For Each item In groupConstituents lookup(item) = False Next For Each item In otherConstituents If Not lookup.TryGetValue(item, Nothing) Then result = False Exit For End If Next Else result = False End If End If Debug.Assert(result) Return result End Function Private Sub CheckMemberTypeAccessibility(diagnostics As DiagnosticBag, node As VisualBasicSyntaxNode, member As Symbol) ' We are not doing this check during lookup due to a performance impact it has on IDE scenarios. ' In any case, an accessible member with inaccessible type is beyond language spec, so we have ' some freedom how to deal with it. Dim memberType As TypeSymbol Select Case member.Kind Case SymbolKind.Method memberType = DirectCast(member, MethodSymbol).ReturnType Exit Select Case SymbolKind.Property memberType = DirectCast(member, PropertySymbol).Type Exit Select Case SymbolKind.Field ' Getting the type of a source field that is a constant can cause infinite ' recursion if that field has an inferred type. Rather than passing in fields ' currently being evaluated to break the recursion, we simply note that inferred ' types can never be inaccessible, so we don't check their types. Dim fieldSym = DirectCast(member, FieldSymbol) If fieldSym.HasDeclaredType Then memberType = fieldSym.Type Else Return End If Case Else ' Somewhat strangely, event types are not checked. Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select If CheckAccessibility(memberType, Nothing, Nothing) <> AccessCheckResult.Accessible Then ReportDiagnostic(diagnostics, node, New BadSymbolDiagnostic(member, ERRID.ERR_InaccessibleReturnTypeOfMember2, CustomSymbolDisplayFormatter.WithContainingType(member))) End If End Sub Public Shared Function IsTopMostEnclosingLambdaAQueryLambda(containingMember As Symbol, stopAtContainer As Symbol) As Boolean Dim topMostEnclosingLambdaIsQueryLambda As Boolean = False ' Need to go up the chain of containers and see if the last lambda we see ' is a QueryLambda, before we reach the stopAtContainer. Dim currentContainer As Symbol = containingMember While currentContainer IsNot Nothing AndAlso currentContainer IsNot stopAtContainer Debug.Assert(currentContainer.IsLambdaMethod OrElse stopAtContainer Is Nothing) If currentContainer.IsLambdaMethod Then topMostEnclosingLambdaIsQueryLambda = currentContainer.IsQueryLambdaMethod Else Exit While End If currentContainer = currentContainer.ContainingSymbol End While Return topMostEnclosingLambdaIsQueryLambda End Function Public Function BindLabel(node As LabelSyntax, diagnostics As DiagnosticBag) As BoundExpression Dim labelName As String = node.LabelToken.ValueText Dim result = LookupResult.GetInstance() Me.Lookup(result, labelName, arity:=0, options:=LookupOptions.LabelsOnly, useSiteDiagnostics:=Nothing) Dim symbol As LabelSymbol = Nothing Dim hasErrors As Boolean = False If result.IsGood AndAlso result.HasSingleSymbol Then symbol = DirectCast(result.Symbols.First(), LabelSymbol) Else If result.HasDiagnostic Then ReportDiagnostic(diagnostics, node, result.Diagnostic) Else ' The label is undefined ReportDiagnostic(diagnostics, node, ERRID.ERR_LabelNotDefined1, labelName) End If hasErrors = True End If result.Free() If symbol Is Nothing Then Return New BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundNode).Empty, Nothing, hasErrors:=True) Else Return New BoundLabel(node, symbol, Nothing, hasErrors:=hasErrors) End If End Function Private Function BindTypeArguments( typeArgumentsOpt As TypeArgumentListSyntax, diagnostics As DiagnosticBag ) As BoundTypeArguments If typeArgumentsOpt Is Nothing Then Return Nothing End If Dim arguments = typeArgumentsOpt.Arguments 'TODO: What should we do if count is 0? Can we get in a situation like this? ' Perhaps for a missing type argument case [Foo(Of )]. Dim boundArguments(arguments.Count - 1) As TypeSymbol For i As Integer = 0 To arguments.Count - 1 Step 1 boundArguments(i) = BindTypeSyntax(arguments(i), diagnostics) Next ' TODO: Should we set HasError flag if any of the BindTypeSyntax calls report errors? Return New BoundTypeArguments(typeArgumentsOpt, boundArguments.AsImmutableOrNull()) End Function ''' <summary> ''' Report diagnostics relating to access shared/nonshared symbols. Returns true if an ERROR (but not a warning) ''' was reported. Also replaces receiver as a type with DefaultPropertyInstance when appropriate. ''' </summary> Private Function CheckSharedSymbolAccess(node As VisualBasicSyntaxNode, isShared As Boolean, <[In], Out> ByRef receiver As BoundExpression, qualKind As QualificationKind, diagnostics As DiagnosticBag) As Boolean If isShared Then If qualKind = QualificationKind.QualifiedViaValue AndAlso receiver IsNot Nothing AndAlso receiver.Kind <> BoundKind.TypeOrValueExpression AndAlso receiver.Kind <> BoundKind.MyBaseReference AndAlso Not receiver.HasErrors Then ' NOTE: Since using MyBase is the only way to call a method from base type ' in some cases, calls with 'MyBase' receiver should not be marked ' with this WRN_SharedMemberThroughInstance; ' WARNING: This differs from DEV10 ' we do not want to report this diagnostic in the case of an initialization of a field/property ' through an object initializer. In that case we will output an error ' "BC30991: Member '{0}' cannot be initialized in an object initializer expression because it is shared." ' instead. If node.Parent Is Nothing OrElse node.Parent.Kind <> SyntaxKind.NamedFieldInitializer Then ReportDiagnostic(diagnostics, node, ERRID.WRN_SharedMemberThroughInstance) End If End If Else If qualKind = QualificationKind.QualifiedViaTypeName OrElse (qualKind = QualificationKind.Unqualified AndAlso receiver Is Nothing) Then If qualKind = QualificationKind.QualifiedViaTypeName AndAlso receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeExpression Then ' Try default instance property through DefaultInstanceAlias Dim instance As BoundExpression = TryDefaultInstanceProperty(DirectCast(receiver, BoundTypeExpression), diagnostics) If instance IsNot Nothing Then receiver = instance Return False End If End If ' We don't have a valid qualifier for this instance method. If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeExpression AndAlso IsReceiverOfNameOfArgument(receiver.Syntax) Then receiver = New BoundTypeAsValueExpression(receiver.Syntax, DirectCast(receiver, BoundTypeExpression), receiver.Type).MakeCompilerGenerated() Return False Else ReportDiagnostic(diagnostics, node, ERRID.ERR_ObjectReferenceNotSupplied) Return True End If End If Dim errorId As ERRID = Nothing If qualKind = QualificationKind.Unqualified AndAlso Not IsNameOfArgument(node) AndAlso Not CanAccessMe(True, errorId) Then ' We can't use implicit Me here. ReportDiagnostic(diagnostics, node, errorId) Return True End If End If Return False End Function Private Shared Function IsReceiverOfNameOfArgument(syntax As VisualBasicSyntaxNode) As Boolean Dim parent = syntax.Parent Return parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso DirectCast(parent, MemberAccessExpressionSyntax).Expression Is syntax AndAlso IsNameOfArgument(parent) End Function Private Shared Function IsNameOfArgument(syntax As VisualBasicSyntaxNode) As Boolean Return syntax.Parent IsNot Nothing AndAlso syntax.Parent.Kind = SyntaxKind.NameOfExpression AndAlso DirectCast(syntax.Parent, NameOfExpressionSyntax).Argument Is syntax End Function ''' <summary> ''' Returns a bound node for left part of dictionary access node with omitted left syntax. ''' In particular it handles dictionary access inside With statement. ''' ''' By default the method delegates the work to it's containing binder or returns Nothing. ''' </summary> Protected Overridable Function TryBindOmittedLeftForDictionaryAccess(node As MemberAccessExpressionSyntax, accessingBinder As Binder, diagnostics As DiagnosticBag) As BoundExpression Debug.Assert(Me.ContainingBinder IsNot Nothing) Return Me.ContainingBinder.TryBindOmittedLeftForDictionaryAccess(node, accessingBinder, diagnostics) End Function Private Function BindDictionaryAccess(node As MemberAccessExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression Dim leftOpt = node.Expression Dim left As BoundExpression If leftOpt Is Nothing Then ' Spec 11.7: "If an exclamation point is specified with no expression, the ' expression from the immediately containing With statement is assumed. ' If there is no containing With statement, a compile-time error occurs." Dim conditionalAccess As ConditionalAccessExpressionSyntax = node.GetCorrespondingConditionalAccessExpression() If conditionalAccess IsNot Nothing Then left = GetConditionalAccessReceiver(conditionalAccess) Else left = TryBindOmittedLeftForDictionaryAccess(node, Me, diagnostics) End If If left Is Nothing Then ' Didn't find binder that can handle member access with omitted left part Return BadExpression( node, ImmutableArray.Create(Of BoundNode)( ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_BadWithRef), New BoundLiteral( node.Name, ConstantValue.Create(node.Name.Identifier.ValueText), GetSpecialType(SpecialType.System_String, node.Name, diagnostics))), ErrorTypeSymbol.UnknownResultType) End If Else left = Me.BindExpression(leftOpt, diagnostics) End If If Not left.IsLValue AndAlso left.Kind <> BoundKind.LateMemberAccess Then left = MakeRValue(left, diagnostics) Debug.Assert(left IsNot Nothing) End If Dim type = left.Type Debug.Assert(type IsNot Nothing) If Not type.IsErrorType() Then If type.SpecialType = SpecialType.System_Object OrElse type.IsExtensibleInterfaceNoUseSiteDiagnostics() Then Dim name = node.Name Dim arg = New BoundLiteral(name, ConstantValue.Create(node.Name.Identifier.ValueText), GetSpecialType(SpecialType.System_String, name, diagnostics)) Dim boundArguments = ImmutableArray.Create(Of BoundExpression)(arg) Return BindLateBoundInvocation(node, Nothing, left, boundArguments, Nothing, diagnostics) End If If type.IsInterfaceType Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing ' In case IsExtensibleInterfaceNoUseSiteDiagnostics above failed because there were bad inherited interfaces. type.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics) diagnostics.Add(node, useSiteDiagnostics) End If Dim defaultPropertyGroup As BoundExpression = BindDefaultPropertyGroup(node, left, diagnostics) Debug.Assert(defaultPropertyGroup Is Nothing OrElse defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup OrElse defaultPropertyGroup.HasErrors) ' Dev10 limits Dictionary access to properties. If defaultPropertyGroup IsNot Nothing AndAlso defaultPropertyGroup.Kind = BoundKind.PropertyGroup Then Dim name = node.Name Dim arg = New BoundLiteral(name, ConstantValue.Create(node.Name.Identifier.ValueText), GetSpecialType(SpecialType.System_String, name, diagnostics)) Return BindInvocationExpression( node, left.Syntax, TypeCharacter.None, DirectCast(defaultPropertyGroup, BoundPropertyGroup), boundArguments:=ImmutableArray.Create(Of BoundExpression)(arg), argumentNames:=Nothing, diagnostics:=diagnostics, isDefaultMemberAccess:=True, callerInfoOpt:=node) ElseIf defaultPropertyGroup Is Nothing OrElse Not defaultPropertyGroup.HasErrors Then Select Case type.TypeKind Case TypeKind.Array, TypeKind.Enum ReportQualNotObjectRecord(left, diagnostics) Case TypeKind.Class If type.SpecialType = SpecialType.System_Array Then ReportDefaultMemberNotProperty(left, diagnostics) Else ReportNoDefaultProperty(left, diagnostics) End If Case TypeKind.TypeParameter, TypeKind.Interface ReportNoDefaultProperty(left, diagnostics) Case TypeKind.Structure If type.IsIntrinsicValueType() Then ReportQualNotObjectRecord(left, diagnostics) Else ReportNoDefaultProperty(left, diagnostics) End If Case Else ReportDefaultMemberNotProperty(left, diagnostics) End Select End If End If Return BadExpression( node, ImmutableArray.Create(Of BoundNode)( left, New BoundLiteral( node.Name, ConstantValue.Create(node.Name.Identifier.ValueText), GetSpecialType(SpecialType.System_String, node.Name, diagnostics))), ErrorTypeSymbol.UnknownResultType) End Function Private Sub ReportNoDefaultProperty(expr As BoundExpression, diagnostics As DiagnosticBag) Dim type = expr.Type Dim syntax = expr.Syntax Select Case type.TypeKind Case TypeKind.Class ' "Class '{0}' cannot be indexed because it has no default property." ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoDefaultNotExtend1, type) Case TypeKind.Structure ' "Structure '{0}' cannot be indexed because it has no default property." ReportDiagnostic(diagnostics, syntax, ERRID.ERR_StructureNoDefault1, type) Case TypeKind.Error ' We should have reported an error elsewhere. Case Else ' "'{0}' cannot be indexed because it has no default property." ReportDiagnostic(diagnostics, syntax, ERRID.ERR_InterfaceNoDefault1, type) End Select End Sub Private Sub ReportQualNotObjectRecord(expr As BoundExpression, diagnostics As DiagnosticBag) ' "'!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'." ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_QualNotObjectRecord1, expr.Type) End Sub Private Sub ReportDefaultMemberNotProperty(expr As BoundExpression, diagnostics As DiagnosticBag) ' "Default member '{0}' is not a property." ' Note: The error argument is the expression type ' rather than the expression text used in Dev10. ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_DefaultMemberNotProperty1, expr.Type) End Sub Private Function GenerateBadExpression(node As InvocationExpressionSyntax, target As BoundExpression, boundArguments As ImmutableArray(Of BoundExpression)) As BoundExpression Dim children = ArrayBuilder(Of BoundNode).GetInstance() children.Add(target) children.AddRange(boundArguments) Return BadExpression(node, children.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType) End Function Private Sub VerifyTypeCharacterConsistency(nodeOrToken As SyntaxNodeOrToken, type As TypeSymbol, typeChar As TypeCharacter, diagnostics As DiagnosticBag) Dim typeCharacterString As String = Nothing Dim specialType As SpecialType = GetSpecialTypeForTypeCharacter(typeChar, typeCharacterString) If specialType <> Microsoft.CodeAnalysis.SpecialType.None Then If type.IsArrayType() Then type = DirectCast(type, ArrayTypeSymbol).ElementType End If type = type.GetNullableUnderlyingTypeOrSelf() If type.SpecialType <> specialType Then ReportDiagnostic(diagnostics, nodeOrToken, ERRID.ERR_TypecharNoMatch2, typeCharacterString, type) End If End If End Sub Private Sub VerifyTypeCharacterConsistency(name As SimpleNameSyntax, type As TypeSymbol, diagnostics As DiagnosticBag) Dim typeChar As TypeCharacter = name.Identifier.GetTypeCharacter() If typeChar = TypeCharacter.None Then Return End If Dim typeCharacterString As String = Nothing Dim specialType As SpecialType = GetSpecialTypeForTypeCharacter(typeChar, typeCharacterString) If specialType <> SpecialType.None Then If type.IsArrayType() Then type = DirectCast(type, ArrayTypeSymbol).ElementType End If type = type.GetNullableUnderlyingTypeOrSelf() If type.SpecialType <> specialType Then ReportDiagnostic(diagnostics, name, ERRID.ERR_TypecharNoMatch2, typeCharacterString, type) End If End If End Sub Private Function BindArrayAccess(node As InvocationExpressionSyntax, expr As BoundExpression, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As DiagnosticBag) As BoundExpression Debug.Assert(node IsNot Nothing) Debug.Assert(expr IsNot Nothing) If expr.IsLValue Then expr = expr.MakeRValue() End If Dim builder As ArrayBuilder(Of BoundExpression) = Nothing For i = 0 To boundArguments.Length - 1 Dim index As BoundExpression = boundArguments(i) If builder Is Nothing AndAlso index.IsLValue Then builder = ArrayBuilder(Of BoundExpression).GetInstance() For k = 0 To i - 1 builder.Add(boundArguments(k)) Next End If If builder IsNot Nothing Then builder.Add(index.MakeRValue) End If Next If builder IsNot Nothing Then boundArguments = builder.ToImmutableAndFree() End If Dim exprType = expr.Type If exprType Is Nothing Then Return New BoundArrayAccess(node, expr, boundArguments, Nothing, hasErrors:=True) End If If Not argumentNames.IsDefault AndAlso argumentNames.Length > 0 Then ReportDiagnostic(diagnostics, node, ERRID.ERR_NamedSubscript) End If Dim arrayType As ArrayTypeSymbol = DirectCast(expr.Type, ArrayTypeSymbol) Dim rank As Integer = arrayType.Rank If boundArguments.Length <> arrayType.Rank Then Dim err As ERRID If boundArguments.Length > arrayType.Rank Then err = ERRID.ERR_TooManyIndices Else err = ERRID.ERR_TooFewIndices End If ReportDiagnostic(diagnostics, node.ArgumentList, err, node.ToString()) Return New BoundArrayAccess(node, expr, boundArguments, arrayType.ElementType, hasErrors:=True) End If Dim convertedArguments As BoundExpression() = New BoundExpression(boundArguments.Length - 1) {} Dim int32Type = GetSpecialType(SpecialType.System_Int32, node.ArgumentList, diagnostics) For i = 0 To boundArguments.Length - 1 convertedArguments(i) = ApplyImplicitConversion(boundArguments(i).Syntax, int32Type, boundArguments(i), diagnostics) Next i Return New BoundArrayAccess(node, expr, convertedArguments.AsImmutableOrNull(), arrayType.ElementType) End Function ' Get the common return type of a set of symbols, or error type if no common return type. Used ' in error cases to give a type in ambiguity situations. ' If we can't find a common type, create an error type. If all the types have a common name, ' that name is used as the type of the error type (useful in ambiguous type lookup situations) Private Function GetCommonExpressionType( symbolReference As VisualBasicSyntaxNode, symbols As ImmutableArray(Of Symbol), constantFieldsInProgress As SymbolsInProgress(Of FieldSymbol) ) As TypeSymbol Dim commonType As TypeSymbol = Nothing Dim commonName As String = Nothing Dim noCommonType As Boolean = False Dim noCommonName As Boolean = False Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance() For i As Integer = 0 To symbols.Length - 1 Dim expressionType As TypeSymbol = GetExpressionType(symbolReference, symbols(i), constantFieldsInProgress, diagnostics) If expressionType IsNot Nothing Then If commonType Is Nothing Then commonType = expressionType ElseIf Not noCommonType AndAlso Not commonType.Equals(expressionType) Then noCommonType = True End If If commonName Is Nothing Then commonName = expressionType.Name ElseIf Not noCommonName AndAlso Not CaseInsensitiveComparison.Equals(commonName, expressionType.Name) Then noCommonName = True End If End If Next diagnostics.Free() If noCommonType Then If noCommonName Then Return ErrorTypeSymbol.UnknownResultType Else Return New ExtendedErrorTypeSymbol(Nothing, commonName) End If Else Return commonType End If End Function ' Get the "expression type" of a symbol when used in an expression. Private Function GetExpressionType( symbolReference As VisualBasicSyntaxNode, s As Symbol, constantFieldsInProgress As SymbolsInProgress(Of FieldSymbol), diagnostics As DiagnosticBag ) As TypeSymbol Select Case s.Kind Case SymbolKind.Method Return DirectCast(s, MethodSymbol).ReturnType Case SymbolKind.Field ' const fields may need to determine the type because it's inferred ' This is why using .Type was replaced by .GetInferredType to detect cycles. Return DirectCast(s, FieldSymbol).GetInferredType(constantFieldsInProgress) Case SymbolKind.Property Return DirectCast(s, PropertySymbol).Type Case SymbolKind.Parameter Return DirectCast(s, ParameterSymbol).Type Case SymbolKind.Local Return GetLocalSymbolType(DirectCast(s, LocalSymbol), symbolReference, diagnostics) Case SymbolKind.RangeVariable Return DirectCast(s, RangeVariableSymbol).Type Case Else Dim type = TryCast(s, TypeSymbol) If type IsNot Nothing Then Return type End If End Select Return Nothing End Function ' Given the expression part of a named argument, get the token of it's name. We use this for error reported, and its more efficient ' to calculate it only when needed when reported a diagnostic. Private Shared Function GetNamedArgumentIdentifier(argumentExpression As VisualBasicSyntaxNode) As SyntaxToken Dim parent = TryCast(argumentExpression.Parent, SimpleArgumentSyntax) If parent Is Nothing OrElse Not parent.IsNamed Then Debug.Assert(False, "Did not found a NamedArgumentSyntax where one should have been") Return argumentExpression.GetFirstToken() ' since we use this for error reporting, this gives us something close, anyway. Else Return parent.NameColonEquals.Name.Identifier End If End Function Private Structure DimensionSize Public Enum SizeKind As Byte Unknown Constant NotConstant End Enum Public ReadOnly Kind As SizeKind Public ReadOnly Size As Integer Private Sub New(size As Integer, kind As SizeKind) Me.Size = size Me.Kind = kind End Sub Public Shared Function ConstantSize(size As Integer) As DimensionSize Return New DimensionSize(size, SizeKind.Constant) End Function Public Shared Function VariableSize() As DimensionSize Return New DimensionSize(0, SizeKind.NotConstant) End Function End Structure ''' <summary> ''' Handle ArrayCreationExpressionSyntax ''' new integer(n)(,) {...} ''' new integer() {...} ''' </summary> Private Function BindArrayCreationExpression(node As ArrayCreationExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression ' Bind the type Dim baseType = BindTypeSyntax(node.Type, diagnostics) Dim arrayBoundsOpt = node.ArrayBounds Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing ' Get the resulting array type by applying the array rank specifiers and the array bounds Dim arrayType = CreateArrayOf(baseType, node.RankSpecifiers, arrayBoundsOpt, diagnostics) Dim knownSizes(arrayType.Rank - 1) As DimensionSize ' Bind the bounds. This returns the known sizes of each dimension from the optional bounds boundArguments = BindArrayBounds(arrayBoundsOpt, diagnostics, knownSizes) ' Bind the array initializer. This may update the known sizes for dimensions with initializers but that are missing explicit bounds Dim boundInitializers = BindArrayInitializerList(node.Initializer, arrayType, knownSizes, diagnostics) 'Construct a set of size expressions if we were not given any. If boundArguments.Length = 0 Then boundArguments = CreateArrayBounds(node, knownSizes, diagnostics) End If Return New BoundArrayCreation(node, boundArguments, boundInitializers, arrayType) End Function Private Function BindArrayLiteralExpression(node As CollectionInitializerSyntax, diagnostics As DiagnosticBag) As BoundExpression ' Inspect the collection initializer to determine the literal's rank ' Per 11.1.1, the array literal is reclassified to a value whose type is an array of rank equal to the level of nesting is used. Dim rank = ComputeArrayLiteralRank(node) Dim knownSizes(rank - 1) As DimensionSize Dim hasDominantType As Boolean Dim numberOfCandidates As Integer Dim inferredElementType As TypeSymbol = Nothing Dim arrayInitializer = BindArrayInitializerList(node, knownSizes, hasDominantType, numberOfCandidates, inferredElementType, diagnostics) Dim inferredArrayType = ArrayTypeSymbol.CreateVBArray(inferredElementType, Nothing, knownSizes.Length, Compilation) Dim sizes As ImmutableArray(Of BoundExpression) = CreateArrayBounds(node, knownSizes, diagnostics) Return New BoundArrayLiteral(node, hasDominantType, numberOfCandidates, inferredArrayType, sizes, arrayInitializer, Me) End Function Private Function CreateArrayBounds(node As VisualBasicSyntaxNode, knownSizes() As DimensionSize, diagnostics As DiagnosticBag) As ImmutableArray(Of BoundExpression) Dim rank = knownSizes.Length Dim sizes = New BoundExpression(rank - 1) {} Dim Int32Type = GetSpecialType(SpecialType.System_Int32, node, diagnostics) For i As Integer = 0 To knownSizes.Length - 1 Dim size = knownSizes(i) 'It is possible in error scenarios that some of the bounds were not determined. 'Use default values (0) for those. Dim sizeExpr = New BoundLiteral( node, ConstantValue.Create(size.Size), Int32Type ) sizeExpr.SetWasCompilerGenerated() sizes(i) = sizeExpr Next Return sizes.AsImmutableOrNull End Function Private Function ComputeArrayLiteralRank(node As CollectionInitializerSyntax) As Integer Dim rank As Integer = 1 Do Dim initializers = node.Initializers If initializers.Count = 0 Then Exit Do End If Dim expr = initializers(0) node = TryCast(expr, CollectionInitializerSyntax) If node Is Nothing Then Exit Do End If rank += 1 Loop Return rank End Function ''' <summary> ''' Binds CollectionInitializeSyntax. i.e. { expr, ... } from an ArrayCreationExpressionSyntax ''' </summary> ''' <param name="node">The collection initializer syntax</param> ''' <param name="type">The type of array.</param> ''' <param name="knownSizes">This is in/out. It comes in with sizes from explicit bounds but will be updated based on the number of initializers for dimensions without bounds</param> ''' <param name="diagnostics">Where to put errors</param> Private Function BindArrayInitializerList(node As CollectionInitializerSyntax, type As ArrayTypeSymbol, knownSizes As DimensionSize(), diagnostics As DiagnosticBag) As BoundArrayInitialization Debug.Assert(type IsNot Nothing) Dim result = BindArrayInitializerList(node, type, knownSizes, 1, Nothing, diagnostics) Return result End Function ''' <summary> ''' Binds CollectionInitializeSyntax. i.e. { expr, ... } from an ArrayCreationExpressionSyntax ''' </summary> ''' <param name="node">The collection initializer syntax</param> ''' <param name="knownSizes">This is in/out. It comes in with sizes from explicit bounds but will be updated based on the number of initializers for dimensions without bounds</param> ''' <param name="hasDominantType">When the inferred type is Object() indicates that the dominant type algorithm computed this type.</param> ''' <param name="numberOfCandidates" >The number of candidates found during inference</param> ''' <param name="inferredElementType" >The inferred element type</param> ''' <param name="diagnostics">Where to put errors</param> Private Function BindArrayInitializerList(node As CollectionInitializerSyntax, knownSizes As DimensionSize(), <Out> ByRef hasDominantType As Boolean, <Out> ByRef numberOfCandidates As Integer, <Out> ByRef inferredElementType As TypeSymbol, diagnostics As DiagnosticBag) As BoundArrayInitialization ' Infer the type for this array literal Dim initializers As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance Dim result = BindArrayInitializerList(node, Nothing, knownSizes, 1, initializers, diagnostics) inferredElementType = InferDominantTypeOfExpressions(node, initializers, diagnostics, numberOfCandidates) If inferredElementType Is Nothing Then ' When no dominant type exists, use Object but remember that there wasn't a dominant type. inferredElementType = GetSpecialType(SpecialType.System_Object, node, diagnostics) hasDominantType = False Else hasDominantType = True End If initializers.Free() Return result End Function Private Function BindArrayInitializerList(node As CollectionInitializerSyntax, type As ArrayTypeSymbol, knownSizes As DimensionSize(), dimension As Integer, allInitializers As ArrayBuilder(Of BoundExpression), diagnostics As DiagnosticBag) As BoundArrayInitialization Debug.Assert(type IsNot Nothing OrElse allInitializers IsNot Nothing) Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance Dim arrayInitType As TypeSymbol If dimension = 1 Then ' binding the outer-most initializer list; the result type is the array type being created. arrayInitType = type Else ' binding an inner initializer list; the result type is nothing. arrayInitType = Nothing End If Dim rank As Integer = knownSizes.Length If dimension <> 1 OrElse node.Initializers.Count <> 0 Then Debug.Assert(type Is Nothing OrElse type.Rank = rank) If dimension = rank Then ' We are processing the nth dimension of a rank-n array. We expect ' that these will only be values, not array initializers. Dim elemType As TypeSymbol = If(type IsNot Nothing, type.ElementType, Nothing) For Each expressionSyntax In node.Initializers Dim boundExpression As BoundExpression If expressionSyntax.Kind <> SyntaxKind.CollectionInitializer Then boundExpression = BindValue(expressionSyntax, diagnostics) If elemType IsNot Nothing Then boundExpression = ApplyImplicitConversion(expressionSyntax, elemType, boundExpression, diagnostics) End If Else boundExpression = ReportDiagnosticAndProduceBadExpression(diagnostics, expressionSyntax, ERRID.ERR_ArrayInitializerTooManyDimensions) End If initializers.Add(boundExpression) If allInitializers IsNot Nothing Then allInitializers.Add(boundExpression) End If Next Else ' Inductive case; we'd better have another array initializer For Each expr In node.Initializers Dim init As BoundArrayInitialization = Nothing If expr.Kind = SyntaxKind.CollectionInitializer Then init = Me.BindArrayInitializerList(DirectCast(expr, CollectionInitializerSyntax), type, knownSizes, dimension + 1, allInitializers, diagnostics) Else ReportDiagnostic(diagnostics, expr, ERRID.ERR_ArrayInitializerTooFewDimensions) init = New BoundArrayInitialization(expr, ImmutableArray(Of BoundExpression).Empty, arrayInitType, hasErrors:=True) End If initializers.Add(init) Next End If Dim curSize = knownSizes(dimension - 1) If curSize.Kind = DimensionSize.SizeKind.Unknown Then knownSizes(dimension - 1) = DimensionSize.ConstantSize(initializers.Count) ElseIf curSize.Kind = DimensionSize.SizeKind.NotConstant Then ReportDiagnostic(diagnostics, node, ERRID.ERR_ArrayInitializerForNonConstDim) Return New BoundArrayInitialization(node, initializers.ToImmutableAndFree(), arrayInitType, hasErrors:=True) ElseIf curSize.Size < initializers.Count Then ReportDiagnostic(diagnostics, node, ERRID.ERR_InitializerTooManyElements1, initializers.Count - curSize.Size) Return New BoundArrayInitialization(node, initializers.ToImmutableAndFree(), arrayInitType, hasErrors:=True) ElseIf curSize.Size > initializers.Count Then ReportDiagnostic(diagnostics, node, ERRID.ERR_InitializerTooFewElements1, curSize.Size - initializers.Count) Return New BoundArrayInitialization(node, initializers.ToImmutableAndFree(), arrayInitType, hasErrors:=True) End If End If Return New BoundArrayInitialization(node, initializers.ToImmutableAndFree(), arrayInitType) End Function Private Sub CheckRangeArgumentLowerBound(rangeArgument As RangeArgumentSyntax, diagnostics As DiagnosticBag) Dim lowerBound = BindValue(rangeArgument.LowerBound, diagnostics) ' This check was moved from the parser to the binder. For backwards compatibility with Dev10, the constant must ' be integral. This seems a bit inconsistent because the range argument allows (0 to 5.0) but not (0.0 to 5.0) Dim lowerBoundConstantValueOpt As ConstantValue = lowerBound.ConstantValueOpt If lowerBoundConstantValueOpt Is Nothing OrElse Not lowerBoundConstantValueOpt.IsIntegral OrElse Not lowerBoundConstantValueOpt.IsDefaultValue Then ReportDiagnostic(diagnostics, rangeArgument.LowerBound, ERRID.ERR_OnlyNullLowerBound) End If End Sub ''' <summary> ''' Bind the array bounds and return the sizes for each dimension. ''' </summary> ''' <param name="arrayBoundsOpt">The bounds</param> ''' <param name="diagnostics">Where to put the errors</param> ''' <param name="knownSizes">The bounds if they are constants, if argument is not specified this info is not returned </param> Private Function BindArrayBounds(arrayBoundsOpt As ArgumentListSyntax, diagnostics As DiagnosticBag, Optional knownSizes As DimensionSize() = Nothing, Optional errorOnEmptyBound As Boolean = False) As ImmutableArray(Of BoundExpression) If arrayBoundsOpt Is Nothing Then Return s_noArguments End If Dim arguments As SeparatedSyntaxList(Of ArgumentSyntax) = arrayBoundsOpt.Arguments Dim boundArgumentsBuilder As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance Dim int32Type = GetSpecialType(SpecialType.System_Int32, arrayBoundsOpt, diagnostics) ' check if there is any nonempty array bound ' in such case we will require all other bounds be nonempty For Each argumentSyntax In arguments Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument, SyntaxKind.RangeArgument errorOnEmptyBound = True Exit For End Select Next For i As Integer = 0 To arguments.Count - 1 Dim upperBound As BoundExpression = Nothing Dim upperBoundSyntax As ExpressionSyntax = Nothing Dim argumentSyntax = arguments(i) Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument Dim simpleArgument = DirectCast(argumentSyntax, SimpleArgumentSyntax) If simpleArgument.NameColonEquals IsNot Nothing Then ReportDiagnostic(diagnostics, argumentSyntax, ERRID.ERR_NamedSubscript) End If upperBoundSyntax = simpleArgument.Expression Case SyntaxKind.RangeArgument Dim rangeArgument = DirectCast(argumentSyntax, RangeArgumentSyntax) CheckRangeArgumentLowerBound(rangeArgument, diagnostics) upperBoundSyntax = rangeArgument.UpperBound Case SyntaxKind.OmittedArgument If errorOnEmptyBound Then ReportDiagnostic(diagnostics, argumentSyntax, ERRID.ERR_MissingSubscript) GoTo lElseClause Else Continue For End If Case Else lElseClause: ' TODO - What expression should be generated in this case? Note, the parser already generates a syntax error. ' The syntax is a missing Identifier and not an OmittedArgumentSyntax. upperBound = BadExpression(argumentSyntax, ErrorTypeSymbol.UnknownResultType) End Select If upperBoundSyntax IsNot Nothing Then upperBound = BindValue(upperBoundSyntax, diagnostics) upperBound = ApplyImplicitConversion(upperBoundSyntax, int32Type, upperBound, diagnostics) End If ' Add 1 to the upper bound to get the array size ' Dev10 does not consider checked/unchecked here when folding the addition ' in a case of overflow exception will be thrown at run time Dim upperBoundConstantValueOpt As ConstantValue = upperBound.ConstantValueOpt If upperBoundConstantValueOpt IsNot Nothing AndAlso Not upperBoundConstantValueOpt.IsBad Then ' -1 is a valid value it means 0 - length array ' anything less is invalid. If upperBoundConstantValueOpt.Int32Value < -1 Then ReportDiagnostic(diagnostics, argumentSyntax, ERRID.ERR_NegativeArraySize) End If End If Dim one = New BoundLiteral(argumentSyntax, ConstantValue.Create(1), int32Type) one.SetWasCompilerGenerated() ' Try folding the size. Dim integerOverflow As Boolean = False Dim divideByZero As Boolean = False ' Note: the value may overflow, but we ignore this and use the overflown value. Dim value = OverloadResolution.TryFoldConstantBinaryOperator(BinaryOperatorKind.Add, upperBound, one, int32Type, integerOverflow, divideByZero, Nothing) If knownSizes IsNot Nothing Then If value IsNot Nothing Then knownSizes(i) = DimensionSize.ConstantSize(value.Int32Value) Else knownSizes(i) = DimensionSize.VariableSize End If End If Dim actualSize = New BoundBinaryOperator( argumentSyntax, BinaryOperatorKind.Add, upperBound, one, CheckOverflow, value, int32Type ) actualSize.SetWasCompilerGenerated() boundArgumentsBuilder.Add(actualSize) Next Return boundArgumentsBuilder.ToImmutableAndFree End Function Private Function BindLiteralConstant(node As LiteralExpressionSyntax, diagnostics As DiagnosticBag) As BoundLiteral Dim value = node.Token.Value Dim cv As ConstantValue Dim type As TypeSymbol = Nothing If value Is Nothing Then ' this is for Null cv = ConstantValue.Null Else Debug.Assert(Not value.GetType().GetTypeInfo().IsEnum) Dim specialType As SpecialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value) ' VB literals can't be of type byte, sbyte Debug.Assert(specialType <> SpecialType.None AndAlso specialType <> SpecialType.System_Byte AndAlso specialType <> SpecialType.System_SByte) cv = ConstantValue.Create(value, specialType) type = GetSpecialType(specialType, node, diagnostics) End If Return New BoundLiteral(node, cv, type) End Function Friend Function InferDominantTypeOfExpressions( syntax As VisualBasicSyntaxNode, Expressions As ArrayBuilder(Of BoundExpression), diagnostics As DiagnosticBag, ByRef numCandidates As Integer, Optional ByRef errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other ) As TypeSymbol ' Arguments: "expressions" is a list of expressions from which to infer dominant type ' Output: we might return Nothing / NumCandidates==0 (if we couldn't find a dominant type) ' Or we might return Object / NumCandidates==0 (if we had to assume Object because no dominant type was found) ' Or we might return Object / NumCandidates>=2 (if we had to assume Object because multiple candidates were found) ' Or we might return a real dominant type from one of the candidates / NumCandidates==1 ' In the last case, "winner" is set to one of the expressions who proposed that winning dominant type. ' "Winner" information might be useful if you are calculating the dominant type of "{}" and "{Nothing}" ' and you need to know who the winner is so you can report appropriate warnings on him. ' The dominant type of a list of elements means: ' (1) for each element, attempt to classify it as a value in a context where the target ' type is unknown. So unbound lambdas get classified as anonymous delegates, and array literals get ' classified according to their dominant type (if they have one), and Nothing is ignored, and AddressOf too. ' But skip over empty array literals. ' (2) Consider the types of all elements for which we got a type, and feed these into the dominant-type ' algorithm: if there are multiple candidates such that all other types convert to it through identity/widening, ' then pick the dominant type out of this set. Otherwise, if there is a single all-widening/identity candidate, ' pick this. Otherwise, if there is a single all-widening/identity/narrowing candidate, then pick this. ' (3) Otherwise, if the dominant type algorithm has failed and every element was an empty array literal {} ' then pick Object() and report a warning "Object assumed" ' (4) Otherwise, if every element converts to Object, then pick Object and report a warning "Object assumed". ' (5) Otherwise, there is no dominant type; return Nothing and report an error. numCandidates = 0 Dim count As Integer = 0 Dim countOfEmptyArrays As Integer = 0 ' To detect case (3) Dim anEmptyArray As BoundArrayLiteral = Nothing ' Used for case (3), so we'll return one of them Dim allConvertibleToObject As Boolean = True ' To detect case (4) Dim typeList As New TypeInferenceCollection() For Each expression As BoundExpression In Expressions count += 1 Debug.Assert(expression IsNot Nothing) Debug.Assert(expression.IsValue()) ' Dig through parenthesized. If Not expression.IsNothingLiteral Then expression = expression.GetMostEnclosedParenthesizedExpression() End If Dim expressionKind As BoundKind = expression.Kind Dim expressionType As TypeSymbol = expression.Type If expressionKind = BoundKind.UnboundLambda Then expressionType = DirectCast(expression, UnboundLambda).InferredAnonymousDelegate.Key typeList.AddType(expressionType, RequiredConversion.Any, expression) ElseIf expressionKind = BoundKind.ArrayLiteral Then Dim arrayLiteral = DirectCast(expression, BoundArrayLiteral) ' Empty array literals {} should not be constraints on the dominant type algorithm. ' Array's without a dominant type should not be constraints on the dominant type algorithm. If arrayLiteral.IsEmptyArrayLiteral Then countOfEmptyArrays += 1 anEmptyArray = arrayLiteral ElseIf arrayLiteral.HasDominantType Then expressionType = New ArrayLiteralTypeSymbol(arrayLiteral) typeList.AddType(expressionType, RequiredConversion.Any, expression) End If ElseIf expressionType IsNot Nothing AndAlso Not expressionType.IsVoidType() AndAlso Not (expressionType.IsArrayType() AndAlso DirectCast(expressionType, ArrayTypeSymbol).ElementType.IsVoidType()) Then typeList.AddType(expressionType, RequiredConversion.Any, expression) If expressionType.IsRestrictedType() Then ' this element is a restricted type; not convertible to object allConvertibleToObject = False End If Else ' What else? Debug.Assert(expressionType Is Nothing) If Not expression.IsNothingLiteral Then ' NOTE: Some expressions without type are still convertible to System.Object, example: Nothing literal allConvertibleToObject = False End If ' this will pick up lambdas which couldn't be inferred, and array literals which lacked a dominant type, ' and AddressOf expressions. End If Next ' Here we calculate the dominant type. ' Note: if there were no candidate types in the list, this will fail with errorReason = NoneBest. errorReasons = InferenceErrorReasons.Other Dim results = ArrayBuilder(Of DominantTypeData).GetInstance() Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing typeList.FindDominantType(results, errorReasons, useSiteDiagnostics) If diagnostics.Add(syntax, useSiteDiagnostics) Then ' Suppress additional diagnostics diagnostics = New DiagnosticBag() End If Dim dominantType As TypeSymbol If results.Count = 1 AndAlso errorReasons = InferenceErrorReasons.Other Then ' main case: we succeeded in finding a dominant type Debug.Assert(Not results(0).ResultType.IsVoidType(), "internal logic error: how could void have won the dominant type algorithm?") numCandidates = 1 dominantType = results(0).ResultType ElseIf count = countOfEmptyArrays AndAlso count > 0 Then ' special case: the dominant type of a list of empty arrays is Object(), not Object. Debug.Assert(anEmptyArray IsNot Nothing, "internal logic error: if we got at least one empty array, then AnEmptyArray should not be null") numCandidates = 1 ' Use the inferred Object() from the array literal. ReclassifyArrayLiteral depends on the array identity for correct error reporting ' of inference errors. dominantType = anEmptyArray.InferredType Debug.Assert(dominantType.IsArrayType AndAlso DirectCast(dominantType, ArrayTypeSymbol).Rank = 1 AndAlso DirectCast(dominantType, ArrayTypeSymbol).ElementType.SpecialType = SpecialType.System_Object) ElseIf allConvertibleToObject AndAlso (errorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then ' special case: there were multiple dominant types, so we fall back to Object Debug.Assert(results.Count > 1, "internal logic error: if InferenceErrorReasonsAmbiguous, you'd have expected more than 1 candidate") numCandidates = results.Count dominantType = GetSpecialType(SpecialType.System_Object, syntax, diagnostics) ElseIf allConvertibleToObject Then ' fallback case: we didn't find a dominant type, but can fall back to Object numCandidates = 0 dominantType = GetSpecialType(SpecialType.System_Object, syntax, diagnostics) Else numCandidates = 0 dominantType = Nothing End If ' Ensure that ArrayLiteralType is not returned from the dominant type algorithm Dim arrayLiteralType = TryCast(dominantType, ArrayLiteralTypeSymbol) If arrayLiteralType IsNot Nothing Then dominantType = arrayLiteralType.ArrayLiteral.InferredType End If results.Free() Return dominantType End Function Public Function IsInAsyncContext() As Boolean Return ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(ContainingMember, MethodSymbol).IsAsync End Function Public Function IsInIteratorContext() As Boolean Return ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(ContainingMember, MethodSymbol).IsIterator End Function Private Function BindAwait( node As AwaitExpressionSyntax, diagnostics As DiagnosticBag, Optional bindAsStatement As Boolean = False ) As BoundExpression If IsInQuery Then ReportDiagnostic(diagnostics, node.AwaitKeyword, ERRID.ERR_BadAsyncInQuery) ElseIf Not IsInAsyncContext() Then ReportDiagnostic(diagnostics, node.AwaitKeyword, GetAwaitInNonAsyncError()) End If Dim operand As BoundExpression = BindExpression(node.Expression, diagnostics) Return BindAwait(node, operand, diagnostics, bindAsStatement) End Function Private Function BindAwait( node As VisualBasicSyntaxNode, operand As BoundExpression, diagnostics As DiagnosticBag, bindAsStatement As Boolean ) As BoundExpression ' If the user tries to do "await f()" or "await expr.f()" where f is an async sub, ' then we'll give a more helpful error message... If Not operand.HasErrors AndAlso operand.Type IsNot Nothing AndAlso operand.Type.IsVoidType() AndAlso operand.Kind = BoundKind.Call Then Dim method As MethodSymbol = DirectCast(operand, BoundCall).Method If method.IsSub AndAlso method.IsAsync Then ReportDiagnostic(diagnostics, operand.Syntax, ERRID.ERR_CantAwaitAsyncSub1, method.Name) Return BadExpression(node, operand, ErrorTypeSymbol.UnknownResultType) End If End If operand = MakeRValue(operand, diagnostics) If operand.IsNothingLiteral() Then ReportDiagnostic(diagnostics, node, ERRID.ERR_BadAwaitNothing) Return BadExpression(node, operand, ErrorTypeSymbol.UnknownResultType) ElseIf operand.Type.IsObjectType() Then ' Late-bound pattern. If OptionStrict = OptionStrict.On Then ReportDiagnostic(diagnostics, node, ERRID.ERR_StrictDisallowsLateBinding) Return BadExpression(node, operand, ErrorTypeSymbol.UnknownResultType) ElseIf OptionStrict = OptionStrict.Custom Then ReportDiagnostic(diagnostics, node, ERRID.WRN_LateBindingResolution) End If End If Dim ignoreDiagnostics = DiagnosticBag.GetInstance() ' Will accumulate all ignored diagnostics in case we want to add them Dim allIgnoreDiagnostics = DiagnosticBag.GetInstance() If operand.HasErrors Then ' Disable error reporting going forward. diagnostics = ignoreDiagnostics End If Dim awaitableInstancePlaceholder = New BoundRValuePlaceholder(operand.Syntax, operand.Type).MakeCompilerGenerated() Dim awaiterInstancePlaceholder As BoundLValuePlaceholder = Nothing Dim getAwaiter As BoundExpression = Nothing Dim isCompleted As BoundExpression = Nothing Dim getResult As BoundExpression = Nothing If operand.Type.IsObjectType Then ' Late-bound pattern. getAwaiter = BindLateBoundMemberAccess(node, WellKnownMemberNames.GetAwaiter, Nothing, awaitableInstancePlaceholder, operand.Type, ignoreDiagnostics, suppressLateBindingResolutionDiagnostics:=True).MakeCompilerGenerated() getAwaiter = DirectCast(getAwaiter, BoundLateMemberAccess).SetAccessKind(LateBoundAccessKind.Get) Debug.Assert(getAwaiter.Type.IsObjectType()) awaiterInstancePlaceholder = New BoundLValuePlaceholder(operand.Syntax, getAwaiter.Type).MakeCompilerGenerated() isCompleted = BindLateBoundMemberAccess(node, WellKnownMemberNames.IsCompleted, Nothing, awaiterInstancePlaceholder, awaiterInstancePlaceholder.Type, ignoreDiagnostics, suppressLateBindingResolutionDiagnostics:=True).MakeCompilerGenerated() isCompleted = DirectCast(isCompleted, BoundLateMemberAccess).SetAccessKind(LateBoundAccessKind.Get) Debug.Assert(isCompleted.Type.IsObjectType()) getResult = BindLateBoundMemberAccess(node, WellKnownMemberNames.GetResult, Nothing, awaiterInstancePlaceholder, awaiterInstancePlaceholder.Type, ignoreDiagnostics, suppressLateBindingResolutionDiagnostics:=True).MakeCompilerGenerated() Debug.Assert(getResult.Type.IsObjectType()) getResult = DirectCast(getResult, BoundLateMemberAccess).SetAccessKind(If(bindAsStatement, LateBoundAccessKind.Call, LateBoundAccessKind.Get)) Debug.Assert(operand.Type.IsErrorType() OrElse ignoreDiagnostics.IsEmptyWithoutResolution()) Else Dim lookupResult As LookupResult = LookupResult.GetInstance() Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing ' 11.25 Await Operator ' '1. C contains an accessible instance or extension method named GetAwaiter which has no arguments and which returns some type E; LookupMember(lookupResult, awaitableInstancePlaceholder.Type, WellKnownMemberNames.GetAwaiter, 0, LookupOptions.AllMethodsOfAnyArity, useSiteDiagnostics) Dim methodGroup As BoundMethodGroup = Nothing If lookupResult.Kind = LookupResultKind.Good AndAlso lookupResult.Symbols(0).Kind = SymbolKind.Method Then methodGroup = CreateBoundMethodGroup( node, lookupResult, LookupOptions.Default, awaitableInstancePlaceholder, Nothing, QualificationKind.QualifiedViaValue).MakeCompilerGenerated() ignoreDiagnostics.Clear() getAwaiter = MakeRValue(BindInvocationExpression(node, operand.Syntax, TypeCharacter.None, methodGroup, ImmutableArray(Of BoundExpression).Empty, Nothing, ignoreDiagnostics, callerInfoOpt:=node).MakeCompilerGenerated(), ignoreDiagnostics).MakeCompilerGenerated() ' The result we are looking for is: ' 1) a non-latebound call of an instance (extension method is considered instance) method; ' 2) method doesn't have any parameters, optional parameters should be ruled out; ' 3) method is not a Sub; ' 4) result is not Object. If getAwaiter.HasErrors OrElse DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics) OrElse getAwaiter.Kind <> BoundKind.Call OrElse getAwaiter.Type.IsObjectType() Then getAwaiter = Nothing Else allIgnoreDiagnostics.AddRange(ignoreDiagnostics) Dim method As MethodSymbol = DirectCast(getAwaiter, BoundCall).Method If method.IsShared OrElse method.ParameterCount <> 0 Then getAwaiter = Nothing End If End If Debug.Assert(getAwaiter Is Nothing OrElse Not DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics)) End If If getAwaiter IsNot Nothing AndAlso Not getAwaiter.Type.IsErrorType() Then ' 2. E contains a readable instance property named IsCompleted which takes no arguments and has type Boolean; awaiterInstancePlaceholder = New BoundLValuePlaceholder(operand.Syntax, getAwaiter.Type).MakeCompilerGenerated() lookupResult.Clear() LookupMember(lookupResult, awaiterInstancePlaceholder.Type, WellKnownMemberNames.IsCompleted, 0, LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods, useSiteDiagnostics) If lookupResult.Kind = LookupResultKind.Good AndAlso lookupResult.Symbols(0).Kind = SymbolKind.Property Then Dim propertyGroup = New BoundPropertyGroup(node, lookupResult.Symbols.ToDowncastedImmutable(Of PropertySymbol), lookupResult.Kind, awaiterInstancePlaceholder, QualificationKind.QualifiedViaValue).MakeCompilerGenerated() ignoreDiagnostics.Clear() isCompleted = MakeRValue(BindInvocationExpression(node, operand.Syntax, TypeCharacter.None, propertyGroup, ImmutableArray(Of BoundExpression).Empty, Nothing, ignoreDiagnostics, callerInfoOpt:=node).MakeCompilerGenerated(), ignoreDiagnostics).MakeCompilerGenerated() ' The result we are looking for is: ' 1) a non-latebound get of an instance property; ' 2) property doesn't have any parameters, optional parameters should be ruled out; ' 3) result is Boolean. If isCompleted.HasErrors OrElse DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics) OrElse isCompleted.Kind <> BoundKind.PropertyAccess OrElse Not isCompleted.Type.IsBooleanType() Then isCompleted = Nothing Else allIgnoreDiagnostics.AddRange(ignoreDiagnostics) Debug.Assert(DirectCast(isCompleted, BoundPropertyAccess).AccessKind = PropertyAccessKind.Get) Dim prop As PropertySymbol = DirectCast(isCompleted, BoundPropertyAccess).PropertySymbol If prop.IsShared OrElse prop.ParameterCount <> 0 Then isCompleted = Nothing End If End If Debug.Assert(isCompleted Is Nothing OrElse Not DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics)) End If ' 3. E contains an accessible instance method named GetResult which takes no arguments; lookupResult.Clear() LookupMember(lookupResult, awaiterInstancePlaceholder.Type, WellKnownMemberNames.GetResult, 0, LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods, useSiteDiagnostics) If lookupResult.Kind = LookupResultKind.Good AndAlso lookupResult.Symbols(0).Kind = SymbolKind.Method Then methodGroup = CreateBoundMethodGroup( node, lookupResult, LookupOptions.Default, awaiterInstancePlaceholder, Nothing, QualificationKind.QualifiedViaValue).MakeCompilerGenerated() ignoreDiagnostics.Clear() getResult = BindInvocationExpression(node, operand.Syntax, TypeCharacter.None, methodGroup, ImmutableArray(Of BoundExpression).Empty, Nothing, ignoreDiagnostics, callerInfoOpt:=node).MakeCompilerGenerated() ' The result we are looking for is: ' 1) a non-latebound call of an instance (extension methods ignored) method; ' 2) method doesn't have any parameters, optional parameters should be ruled out; If getResult.HasErrors OrElse DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics) OrElse getResult.Kind <> BoundKind.Call Then getResult = Nothing Else allIgnoreDiagnostics.AddRange(ignoreDiagnostics) Dim method As MethodSymbol = DirectCast(getResult, BoundCall).Method Debug.Assert(Not method.IsReducedExtensionMethod) If method.IsShared OrElse method.ParameterCount <> 0 OrElse (method.IsSub AndAlso method.IsConditional) Then getResult = Nothing End If End If Debug.Assert(getResult Is Nothing OrElse Not DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics)) End If ' 4. E implements either System.Runtime.CompilerServices.INotifyCompletion or ICriticalNotifyCompletion. Dim notifyCompletion As NamedTypeSymbol = GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_INotifyCompletion, node, diagnostics) ' ICriticalNotifyCompletion inherits from INotifyCompletion, so a check for INotifyCompletion is sufficient. If Not notifyCompletion.IsErrorType() AndAlso Not Conversions.IsWideningConversion(Conversions.ClassifyDirectCastConversion(getAwaiter.Type, notifyCompletion, useSiteDiagnostics)) Then ReportDiagnostic(diagnostics, node, ERRID.ERR_DoesntImplementAwaitInterface2, getAwaiter.Type, notifyCompletion) End If End If diagnostics.Add(node, useSiteDiagnostics) lookupResult.Free() End If Dim hasErrors As Boolean = False If getAwaiter Is Nothing Then hasErrors = True ReportDiagnostic(diagnostics, node, ERRID.ERR_BadGetAwaiterMethod1, operand.Type) Debug.Assert(isCompleted Is Nothing AndAlso getResult Is Nothing) getAwaiter = BadExpression(node, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated() ElseIf getAwaiter.Type.IsErrorType() Then hasErrors = True ElseIf isCompleted Is Nothing OrElse getResult Is Nothing Then hasErrors = True ReportDiagnostic(diagnostics, node, ERRID.ERR_BadIsCompletedOnCompletedGetResult2, getAwaiter.Type, operand.Type) End If If awaiterInstancePlaceholder Is Nothing Then Debug.Assert(hasErrors) awaiterInstancePlaceholder = New BoundLValuePlaceholder(node, getAwaiter.Type).MakeCompilerGenerated() End If If isCompleted Is Nothing Then isCompleted = BadExpression(node, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated() End If If getResult Is Nothing Then getResult = BadExpression(node, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated() End If Dim resultType As TypeSymbol If bindAsStatement Then resultType = GetSpecialType(SpecialType.System_Void, node, diagnostics) Else resultType = getResult.Type End If If Not hasErrors Then diagnostics.AddRange(allIgnoreDiagnostics) End If allIgnoreDiagnostics.Free() ignoreDiagnostics.Free() Return New BoundAwaitOperator(node, operand, awaitableInstancePlaceholder, getAwaiter, awaiterInstancePlaceholder, isCompleted, getResult, resultType, hasErrors) End Function Private Shared Function DiagnosticBagHasErrorsOtherThanObsoleteOnes(bag As DiagnosticBag) As Boolean If bag.IsEmptyWithoutResolution Then Return False End If For Each diag In bag.AsEnumerable() If diag.Severity = DiagnosticSeverity.Error Then Select Case diag.Code Case ERRID.ERR_UseOfObsoletePropertyAccessor2, ERRID.ERR_UseOfObsoletePropertyAccessor3, ERRID.ERR_UseOfObsoleteSymbolNoMessage1, ERRID.ERR_UseOfObsoleteSymbol2 ' ignore Case Else Return True End Select End If Next Return False End Function Private Function GetAwaitInNonAsyncError() As DiagnosticInfo If Me.IsInLambda Then Return ErrorFactory.ErrorInfo(ERRID.ERR_BadAwaitInNonAsyncLambda) ElseIf ContainingMember.Kind = SymbolKind.Method Then Dim method = DirectCast(ContainingMember, MethodSymbol) If method.IsSub Then Return ErrorFactory.ErrorInfo(ERRID.ERR_BadAwaitInNonAsyncVoidMethod) Else Return ErrorFactory.ErrorInfo(ERRID.ERR_BadAwaitInNonAsyncMethod, method.ReturnType) End If End If Return ErrorFactory.ErrorInfo(ERRID.ERR_BadAwaitNotInAsyncMethodOrLambda) End Function End Class End Namespace
ValentinRueda/roslyn
src/Compilers/VisualBasic/Portable/Binding/Binder_Expressions.vb
Visual Basic
apache-2.0
244,097
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameter that has undergone type substitution. ''' </summary> Friend MustInherit Class SubstitutedParameterSymbol Inherits ParameterSymbol Private ReadOnly _originalDefinition As ParameterSymbol Public Shared Function CreateMethodParameter(container As SubstitutedMethodSymbol, originalDefinition As ParameterSymbol) As SubstitutedParameterSymbol Return New SubstitutedMethodParameterSymbol(container, originalDefinition) End Function Public Shared Function CreatePropertyParameter(container As SubstitutedPropertySymbol, originalDefinition As ParameterSymbol) As SubstitutedParameterSymbol Return New SubstitutedPropertyParameterSymbol(container, originalDefinition) End Function Protected Sub New(originalDefinition As ParameterSymbol) Debug.Assert(originalDefinition.IsDefinition) _originalDefinition = originalDefinition End Sub Public Overrides ReadOnly Property Name As String Get Return _originalDefinition.Name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return _originalDefinition.MetadataName End Get End Property Public Overrides ReadOnly Property Ordinal As Integer Get Return _originalDefinition.Ordinal End Get End Property Public MustOverride Overrides ReadOnly Property ContainingSymbol As Symbol Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return _originalDefinition.ExplicitDefaultConstantValue(inProgress) End Get End Property Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return _originalDefinition.GetAttributes() End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return _originalDefinition.HasExplicitDefaultValue End Get End Property Public Overrides ReadOnly Property IsOptional As Boolean Get Return _originalDefinition.IsOptional End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get Return _originalDefinition.IsParamArray End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _originalDefinition.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _originalDefinition.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _originalDefinition.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return _originalDefinition.Type.InternalSubstituteTypeParameters(TypeSubstitution).Type End Get End Property Public Overrides ReadOnly Property IsByRef As Boolean Get Return _originalDefinition.IsByRef End Get End Property Friend Overrides ReadOnly Property IsMetadataOut As Boolean Get Return _originalDefinition.IsMetadataOut End Get End Property Friend Overrides ReadOnly Property IsMetadataIn As Boolean Get Return _originalDefinition.IsMetadataIn End Get End Property Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get Return _originalDefinition.MarshallingInformation End Get End Property Friend Overrides ReadOnly Property HasOptionCompare As Boolean Get Return _originalDefinition.HasOptionCompare End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get Return _originalDefinition.IsIDispatchConstant End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get Return _originalDefinition.IsIUnknownConstant End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Return _originalDefinition.IsCallerLineNumber End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Return _originalDefinition.IsCallerMemberName End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Return _originalDefinition.IsCallerFilePath End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.RefCustomModifiers) End Get End Property Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return _originalDefinition.IsExplicitByRef End Get End Property Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.Type, _originalDefinition.CustomModifiers) End Get End Property Public Overrides ReadOnly Property OriginalDefinition As ParameterSymbol Get Return _originalDefinition End Get End Property Protected MustOverride ReadOnly Property TypeSubstitution As TypeSubstitution Public Overrides Function GetHashCode() As Integer Dim _hash As Integer = _originalDefinition.GetHashCode() Return Hash.Combine(ContainingSymbol, _hash) End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, SubstitutedParameterSymbol) If other Is Nothing Then Return False End If If Not _originalDefinition.Equals(other._originalDefinition) Then Return False End If If Not ContainingSymbol.Equals(other.ContainingSymbol) Then Return False End If Return True End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _originalDefinition.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function ''' <summary> ''' Represents a method parameter that has undergone type substitution. ''' </summary> Friend Class SubstitutedMethodParameterSymbol Inherits SubstitutedParameterSymbol Private ReadOnly _container As SubstitutedMethodSymbol Public Sub New(container As SubstitutedMethodSymbol, originalDefinition As ParameterSymbol) MyBase.New(originalDefinition) _container = container End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Protected Overrides ReadOnly Property TypeSubstitution As TypeSubstitution Get Return _container.TypeSubstitution End Get End Property End Class ''' <summary> ''' Represents a property parameter that has undergone type substitution. ''' </summary> Private NotInheritable Class SubstitutedPropertyParameterSymbol Inherits SubstitutedParameterSymbol Private ReadOnly _container As SubstitutedPropertySymbol Public Sub New(container As SubstitutedPropertySymbol, originalDefinition As ParameterSymbol) MyBase.New(originalDefinition) _container = container End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Protected Overrides ReadOnly Property TypeSubstitution As TypeSubstitution Get Return _container.TypeSubstitution End Get End Property End Class End Class End Namespace
shyamnamboodiripad/roslyn
src/Compilers/VisualBasic/Portable/Symbols/SubstitutedParameterSymbol.vb
Visual Basic
apache-2.0
10,053
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Partial Class NamedTypeSymbol Implements ITypeReference Implements ITypeDefinition Implements INamedTypeReference Implements INamedTypeDefinition Implements INamespaceTypeReference Implements INamespaceTypeDefinition Implements INestedTypeReference Implements INestedTypeDefinition Implements IGenericTypeInstanceReference Implements ISpecializedNestedTypeReference Private ReadOnly Property ITypeReferenceIsEnum As Boolean Implements ITypeReference.IsEnum Get Debug.Assert(Not Me.IsAnonymousType) Return Me.TypeKind = TYPEKIND.Enum End Get End Property Private ReadOnly Property ITypeReferenceIsValueType As Boolean Implements ITypeReference.IsValueType Get Debug.Assert(Not Me.IsAnonymousType) Return Me.IsValueType End Get End Property Private Function ITypeReferenceGetResolvedType(context As EmitContext) As ITypeDefinition Implements ITypeReference.GetResolvedType Debug.Assert(Not Me.IsAnonymousType) Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return AsTypeDefinitionImpl(moduleBeingBuilt) End Function Private Function ITypeReferenceTypeCode(context As EmitContext) As Cci.PrimitiveTypeCode Implements ITypeReference.TypeCode Debug.Assert(Not Me.IsAnonymousType) Debug.Assert(Me.IsDefinitionOrDistinct()) If Me.IsDefinition Then Return Me.PrimitiveTypeCode End If Return Cci.PrimitiveTypeCode.NotPrimitive End Function Private ReadOnly Property ITypeReferenceTypeDef As TypeDefinitionHandle Implements ITypeReference.TypeDef Get Debug.Assert(Not Me.IsAnonymousType) Dim peNamedType As PENamedTypeSymbol = TryCast(Me, PENamedTypeSymbol) If peNamedType IsNot Nothing Then Return peNamedType.Handle End If Return Nothing End Get End Property Private ReadOnly Property ITypeReferenceAsGenericMethodParameterReference As IGenericMethodParameterReference Implements ITypeReference.AsGenericMethodParameterReference Get Debug.Assert(Not Me.IsAnonymousType) Return Nothing End Get End Property Private ReadOnly Property ITypeReferenceAsGenericTypeInstanceReference As IGenericTypeInstanceReference Implements ITypeReference.AsGenericTypeInstanceReference Get Debug.Assert(Not Me.IsAnonymousType) Debug.Assert(Me.IsDefinitionOrDistinct()) If Not Me.IsDefinition AndAlso Me.Arity > 0 AndAlso Me.ConstructedFrom IsNot Me Then Return Me End If Return Nothing End Get End Property Private ReadOnly Property ITypeReferenceAsGenericTypeParameterReference As IGenericTypeParameterReference Implements ITypeReference.AsGenericTypeParameterReference Get Debug.Assert(Not Me.IsAnonymousType) Return Nothing End Get End Property Private ReadOnly Property ITypeReferenceAsNamespaceTypeReference As INamespaceTypeReference Implements ITypeReference.AsNamespaceTypeReference Get Debug.Assert(Not Me.IsAnonymousType) Debug.Assert(Me.IsDefinitionOrDistinct()) If Me.IsDefinition AndAlso Me.ContainingType Is Nothing Then Return Me End If Return Nothing End Get End Property Private Function ITypeReferenceAsNamespaceTypeDefinition(context As EmitContext) As INamespaceTypeDefinition Implements ITypeReference.AsNamespaceTypeDefinition Debug.Assert(Not Me.IsAnonymousType) Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Debug.Assert(Me.IsDefinitionOrDistinct()) If Me.ContainingType Is Nothing AndAlso Me.IsDefinition AndAlso Me.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then Return Me End If Return Nothing End Function Private ReadOnly Property ITypeReferenceAsNestedTypeReference As INestedTypeReference Implements ITypeReference.AsNestedTypeReference Get Debug.Assert(Not Me.IsAnonymousType) If Me.ContainingType IsNot Nothing Then Return Me End If Return Nothing End Get End Property Private Function ITypeReferenceAsNestedTypeDefinition(context As EmitContext) As INestedTypeDefinition Implements ITypeReference.AsNestedTypeDefinition Debug.Assert(Not Me.IsAnonymousType) Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return AsNestedTypeDefinitionImpl(moduleBeingBuilt) End Function Private Function AsNestedTypeDefinitionImpl(moduleBeingBuilt As PEModuleBuilder) As INestedTypeDefinition Debug.Assert(Me.IsDefinitionOrDistinct()) If Me.ContainingType IsNot Nothing AndAlso Me.IsDefinition AndAlso Me.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then Return Me End If Return Nothing End Function Private ReadOnly Property ITypeReferenceAsSpecializedNestedTypeReference As ISpecializedNestedTypeReference Implements ITypeReference.AsSpecializedNestedTypeReference Get Debug.Assert(Not Me.IsAnonymousType) Debug.Assert(Me.IsDefinitionOrDistinct()) If Not Me.IsDefinition AndAlso (Me.Arity = 0 OrElse Me.ConstructedFrom Is Me) Then Debug.Assert(Me.ContainingType IsNot Nothing AndAlso Me.ContainingType.IsOrInGenericType()) Return Me End If Return Nothing End Get End Property Private Function ITypeReferenceAsTypeDefinition(context As EmitContext) As ITypeDefinition Implements ITypeReference.AsTypeDefinition Debug.Assert(Not Me.IsAnonymousType) Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return AsTypeDefinitionImpl(moduleBeingBuilt) End Function Private Function AsTypeDefinitionImpl(moduleBeingBuilt As PEModuleBuilder) As ITypeDefinition Debug.Assert(Me.IsDefinitionOrDistinct()) ' Can't be generic instantiation ' must be declared in the module we are building If Me.IsDefinition AndAlso Me.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then Return Me End If Return Nothing End Function Friend NotOverridable Overrides Sub IReferenceDispatch(visitor As MetadataVisitor) ' Implements IReference.Dispatch Debug.Assert(Me.IsDefinitionOrDistinct()) If Not Me.IsDefinition Then If Me.Arity > 0 AndAlso Me.ConstructedFrom IsNot Me Then Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing) visitor.Visit(DirectCast(Me, IGenericTypeInstanceReference)) Else Debug.Assert((DirectCast(Me, ITypeReference)).AsSpecializedNestedTypeReference IsNot Nothing) visitor.Visit(DirectCast(Me, ISpecializedNestedTypeReference)) End If Else Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(visitor.Context.Module, PEModuleBuilder) Dim asDefinition As Boolean = (Me.ContainingModule.Equals(moduleBeingBuilt.SourceModule)) If Me.ContainingType Is Nothing Then If asDefinition Then Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeDefinition(visitor.Context) IsNot Nothing) visitor.Visit(DirectCast(Me, INamespaceTypeDefinition)) Else Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing) visitor.Visit(DirectCast(Me, INamespaceTypeReference)) End If Else If asDefinition Then Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeDefinition(visitor.Context) IsNot Nothing) visitor.Visit(DirectCast(Me, INestedTypeDefinition)) Else Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeReference IsNot Nothing) visitor.Visit(DirectCast(Me, INestedTypeReference)) End If End If End If End Sub Friend NotOverridable Overrides Function IReferenceAsDefinition(context As EmitContext) As IDefinition ' Implements IReference.AsDefinition Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return AsTypeDefinitionImpl(moduleBeingBuilt) End Function Private ReadOnly Property ITypeDefinitionAlignment As UShort Implements ITypeDefinition.Alignment Get CheckDefinitionInvariant() Dim layout = Me.Layout Return CUShort(layout.Alignment) End Get End Property Private Function ITypeDefinitionGetBaseClass(context As EmitContext) As ITypeReference Implements ITypeDefinition.GetBaseClass Debug.Assert(Not Me.IsAnonymousType) Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Debug.Assert((DirectCast(Me, ITypeReference)).AsTypeDefinition(context) IsNot Nothing) Dim baseType As NamedTypeSymbol = Me.BaseTypeNoUseSiteDiagnostics If Me.TypeKind = TypeKind.Submission Then ' although submission semantically doesn't have a base we need to emit one into metadata: Debug.Assert(baseType Is Nothing) baseType = Me.ContainingAssembly.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object) End If If baseType IsNot Nothing Then Return moduleBeingBuilt.Translate(baseType, syntaxNodeOpt:=DirectCast(context.SyntaxNodeOpt, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End If Return Nothing End Function Private ReadOnly Property ITypeDefinitionEvents As IEnumerable(Of IEventDefinition) Implements ITypeDefinition.Events Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return GetEventsToEmit() End Get End Property Friend Overridable Iterator Function GetEventsToEmit() As IEnumerable(Of EventSymbol) CheckDefinitionInvariant() For Each member In Me.GetMembersForCci() If member.Kind = SymbolKind.Event Then Yield DirectCast(member, EventSymbol) End If Next End Function Private Function ITypeDefinitionGetExplicitImplementationOverrides(context As EmitContext) As IEnumerable(Of Cci.MethodImplementation) Implements ITypeDefinition.GetExplicitImplementationOverrides Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() If Me.IsInterface Then Return SpecializedCollections.EmptyEnumerable(Of Cci.MethodImplementation)() End If Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim sourceNamedType = TryCast(Me, SourceNamedTypeSymbol) Dim explicitImplements As ArrayBuilder(Of Cci.MethodImplementation) = ArrayBuilder(Of Cci.MethodImplementation).GetInstance() For Each member In Me.GetMembersForCci() If member.Kind = SymbolKind.Method Then AddExplicitImplementations(context, DirectCast(member, MethodSymbol), explicitImplements, sourceNamedType, moduleBeingBuilt) End If Next Dim syntheticMethods = moduleBeingBuilt.GetSynthesizedMethods(Me) If syntheticMethods IsNot Nothing Then For Each synthetic In syntheticMethods Dim method = TryCast(synthetic, MethodSymbol) If method IsNot Nothing Then AddExplicitImplementations(context, method, explicitImplements, sourceNamedType, moduleBeingBuilt) End If Next End If Return explicitImplements.ToImmutableAndFree() End Function Private Sub AddExplicitImplementations(context As EmitContext, implementingMethod As MethodSymbol, explicitImplements As ArrayBuilder(Of Cci.MethodImplementation), sourceNamedType As SourceNamedTypeSymbol, moduleBeingBuilt As PEModuleBuilder) Debug.Assert(implementingMethod.PartialDefinitionPart Is Nothing) ' must be definition For Each implemented In implementingMethod.ExplicitInterfaceImplementations ' If signature doesn't match, we have created a stub with matching signature that delegates to the implementingMethod. ' The stub will implement the implemented method in metadata. If MethodSignatureComparer.CustomModifiersAndParametersAndReturnTypeSignatureComparer.Equals(implementingMethod, implemented) Then explicitImplements.Add(New Cci.MethodImplementation(implementingMethod, moduleBeingBuilt.TranslateOverriddenMethodReference(implemented, DirectCast(context.SyntaxNodeOpt, VisualBasicSyntaxNode), context.Diagnostics))) End If Next ' Explicit overrides needed in some overriding situations. If OverrideHidingHelper.RequiresExplicitOverride(implementingMethod) Then explicitImplements.Add(New Cci.MethodImplementation(implementingMethod, implementingMethod.OverriddenMethod)) End If If sourceNamedType IsNot Nothing Then Dim comMethod As MethodSymbol = sourceNamedType.GetCorrespondingComClassInterfaceMethod(implementingMethod) If comMethod IsNot Nothing Then explicitImplements.Add(New Cci.MethodImplementation(implementingMethod, comMethod)) End If End If End Sub Private Iterator Function ITypeDefinitionGetFields(context As EmitContext) As IEnumerable(Of IFieldDefinition) Implements ITypeDefinition.GetFields Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() For Each field In Me.GetFieldsToEmit() Yield field Next Dim syntheticFields = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedFields(Me) If syntheticFields IsNot Nothing Then For Each field In syntheticFields Yield field Next End If End Function Friend MustOverride Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol) Private ReadOnly Property ITypeDefinitionGenericParameters As IEnumerable(Of IGenericTypeParameter) Implements ITypeDefinition.GenericParameters Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return Me.TypeParameters End Get End Property Private ReadOnly Property ITypeDefinitionGenericParameterCount As UShort Implements ITypeDefinition.GenericParameterCount Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return GenericParameterCountImpl End Get End Property Private ReadOnly Property GenericParameterCountImpl As UShort Get Return CType(Me.Arity, UShort) End Get End Property Private ReadOnly Property ITypeDefinitionHasDeclarativeSecurity As Boolean Implements ITypeDefinition.HasDeclarativeSecurity Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return Me.HasDeclarativeSecurity End Get End Property ''' <summary> ''' Should return Nothing if there are none. ''' </summary> Friend Overridable Function GetSynthesizedImplements() As IEnumerable(Of NamedTypeSymbol) Return Nothing End Function Private Iterator Function ITypeDefinitionInterfaces(context As EmitContext) As IEnumerable(Of ITypeReference) Implements ITypeDefinition.Interfaces Debug.Assert(Not Me.IsAnonymousType) Debug.Assert((DirectCast(Me, ITypeReference)).AsTypeDefinition(context) IsNot Nothing) Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) For Each [interface] In GetInterfacesToEmit() Yield moduleBeingBuilt.Translate([interface], syntaxNodeOpt:=DirectCast(context.SyntaxNodeOpt, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics, fromImplements:=True) Next End Function Friend Overridable Function GetInterfacesToEmit() As IEnumerable(Of NamedTypeSymbol) Debug.Assert(IsDefinition) Debug.Assert(TypeOf ContainingModule Is SourceModuleSymbol) ' Synthesized implements should go first. Currently they are used only by ' ComClass feature, which depends on the order of implemented interfaces. Dim synthesized As IEnumerable(Of NamedTypeSymbol) = GetSynthesizedImplements() ' If this type implements I, and the base class also implements interface I, and this class ' does not implement all the members of I, then do not emit I as an interface. This prevents ' the CLR from using implicit interface implementation. Dim interfaces = Me.InterfacesNoUseSiteDiagnostics If interfaces.IsEmpty Then Return If(synthesized, SpecializedCollections.EmptyEnumerable(Of NamedTypeSymbol)()) End If Dim base = Me.BaseTypeNoUseSiteDiagnostics Dim result As IEnumerable(Of NamedTypeSymbol) = interfaces.Where(Function(sym As NamedTypeSymbol) As Boolean Return Not (base IsNot Nothing AndAlso base.ImplementsInterface(sym, Nothing) AndAlso Not Me.ImplementsAllMembersOfInterface(sym)) End Function) Return If(synthesized Is Nothing, result, synthesized.Concat(result)) End Function Private ReadOnly Property ITypeDefinitionIsAbstract As Boolean Implements ITypeDefinition.IsAbstract Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return IsMetadataAbstract End Get End Property Friend Overridable ReadOnly Property IsMetadataAbstract As Boolean Get CheckDefinitionInvariant() Return Me.IsMustInherit OrElse Me.IsInterface End Get End Property Private ReadOnly Property ITypeDefinitionIsBeforeFieldInit As Boolean Implements ITypeDefinition.IsBeforeFieldInit Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() ' enums or interfaces or delegates are not BeforeFieldInit Select Case Me.TypeKind Case TypeKind.Enum, TypeKind.Interface, TypeKind.Delegate Return False End Select ' apply the beforefieldinit attribute only if there is an implicitly specified static constructor (e.g. caused by ' a Decimal or DateTime field with an initialization). Dim cctor = Me.SharedConstructors.FirstOrDefault If cctor IsNot Nothing Then Debug.Assert(Me.SharedConstructors.Length = 1) ' NOTE: Partial methods without implementation should be skipped in the ' analysis above, see native compiler: PRBuilder.cpp, 'DWORD PEBuilder::GetTypeDefFlags' If Not cctor.IsImplicitlyDeclared Then ' If there is an explicitly implemented shared constructor, do not look further Return False End If ' if the found constructor contains a generated AddHandler for a method, ' beforefieldinit should not be applied. For Each member In GetMembers() If member.Kind = SymbolKind.Method Then Dim methodSym = DirectCast(member, MethodSymbol) Dim handledEvents = methodSym.HandledEvents If Not handledEvents.IsEmpty Then For Each handledEvent In handledEvents If handledEvent.hookupMethod.MethodKind = MethodKind.SharedConstructor Then Return False End If Next End If End If Next ' cctor is implicit and there are no handles, so the sole purpose of ' the cctor is to initialize some fields. ' Therefore it can be deferred until fields are accessed via "beforefieldinit" Return True End If ' if there is a const field of type Decimal or DateTime, the synthesized shared constructor does not ' appear in the member list. We need to check this separately. Dim sourceNamedType = TryCast(Me, SourceMemberContainerTypeSymbol) If sourceNamedType IsNot Nothing AndAlso Not sourceNamedType.StaticInitializers.IsDefaultOrEmpty Then Return sourceNamedType.AnyInitializerToBeInjectedIntoConstructor(sourceNamedType.StaticInitializers, includingNonMetadataConstants:=True) End If Return False End Get End Property Private ReadOnly Property ITypeDefinitionIsComObject As Boolean Implements ITypeDefinition.IsComObject Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return IsComImport End Get End Property Private ReadOnly Property ITypeDefinitionIsGeneric As Boolean Implements ITypeDefinition.IsGeneric Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return Me.Arity <> 0 End Get End Property Private ReadOnly Property ITypeDefinitionIsInterface As Boolean Implements ITypeDefinition.IsInterface Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return Me.IsInterface End Get End Property Private ReadOnly Property ITypeDefinitionIsRuntimeSpecial As Boolean Implements ITypeDefinition.IsRuntimeSpecial Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return False End Get End Property Private ReadOnly Property ITypeDefinitionIsSerializable As Boolean Implements ITypeDefinition.IsSerializable Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return Me.IsSerializable End Get End Property Private ReadOnly Property ITypeDefinitionIsSpecialName As Boolean Implements ITypeDefinition.IsSpecialName Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return HasSpecialName End Get End Property Private ReadOnly Property ITypeDefinitionIsWindowsRuntimeImport As Boolean Implements ITypeDefinition.IsWindowsRuntimeImport Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return Me.IsWindowsRuntimeImport End Get End Property Private ReadOnly Property ITypeDefinitionIsSealed As Boolean Implements ITypeDefinition.IsSealed Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Return IsMetadataSealed End Get End Property Friend Overridable ReadOnly Property IsMetadataSealed As Boolean Get CheckDefinitionInvariant() If Me.IsNotInheritable Then Return True End If Select Case Me.TypeKind Case TypeKind.Module, TypeKind.Enum, TypeKind.Structure Return True Case Else Return False End Select End Get End Property Private ReadOnly Property ITypeDefinitionLayout As LayoutKind Implements ITypeDefinition.Layout Get Debug.Assert(Not Me.IsAnonymousType) CheckDefinitionInvariant() Return Me.Layout.Kind End Get End Property Friend Overridable Function GetMembersForCci() As ImmutableArray(Of Symbol) Return Me.GetMembers() End Function Private Iterator Function ITypeDefinitionGetMethods(context As EmitContext) As IEnumerable(Of IMethodDefinition) Implements ITypeDefinition.GetMethods Debug.Assert(Not Me.IsAnonymousType) ' Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() For Each method In Me.GetMethodsToEmit() Yield method Next Dim syntheticMethods = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedMethods(Me) If syntheticMethods IsNot Nothing Then For Each method In syntheticMethods Yield method Next End If End Function Friend Overridable Iterator Function GetMethodsToEmit() As IEnumerable(Of MethodSymbol) For Each member In Me.GetMembersForCci() If member.Kind = SymbolKind.Method Then Dim method As MethodSymbol = DirectCast(member, MethodSymbol) ' Don't emit: ' (a) Partial methods without an implementation part ' (b) The default value type constructor - the runtime handles that If Not method.IsPartialWithoutImplementation() AndAlso Not method.IsDefaultValueTypeConstructor() Then Yield method End If End If Next End Function Private Function ITypeDefinitionGetNestedTypes(context As EmitContext) As IEnumerable(Of INestedTypeDefinition) Implements ITypeDefinition.GetNestedTypes Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Dim containingModule = DirectCast(context.Module, PEModuleBuilder) Dim result As IEnumerable(Of INestedTypeDefinition) Dim nestedTypes = Me.GetTypeMembers() ' Ordered. If nestedTypes.Length = 0 Then result = SpecializedCollections.EmptyEnumerable(Of INestedTypeDefinition)() ElseIf Me.IsEmbedded Then ' filter out embedded nested types that are not referenced result = nestedTypes.Where(containingModule.SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager.IsReferencedPredicate) Else result = nestedTypes End If Dim syntheticNested = containingModule.GetSynthesizedTypes(Me) If syntheticNested IsNot Nothing Then result = result.Concat(syntheticNested) End If Return result End Function Private Iterator Function ITypeDefinitionGetProperties(context As EmitContext) As IEnumerable(Of IPropertyDefinition) Implements ITypeDefinition.GetProperties Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() For Each [property] In Me.GetPropertiesToEmit() Debug.Assert([property] IsNot Nothing) Yield [property] Next Dim syntheticProperties = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedProperties(Me) If syntheticProperties IsNot Nothing Then For Each prop In syntheticProperties Yield prop Next End If End Function Friend Overridable Iterator Function GetPropertiesToEmit() As IEnumerable(Of PropertySymbol) CheckDefinitionInvariant() For Each member In Me.GetMembersForCci() If member.Kind = SymbolKind.Property Then Yield DirectCast(member, PropertySymbol) End If Next End Function Private ReadOnly Property ITypeDefinitionSecurityAttributes As IEnumerable(Of SecurityAttribute) Implements ITypeDefinition.SecurityAttributes Get Debug.Assert(Not Me.IsAnonymousType) 'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null); ' can't be generic instantiation ' must be declared in the module we are building CheckDefinitionInvariant() Debug.Assert(Me.HasDeclarativeSecurity) Dim securityAttributes As IEnumerable(Of SecurityAttribute) = Me.GetSecurityInformation() Debug.Assert(securityAttributes IsNot Nothing) Return securityAttributes End Get End Property Private ReadOnly Property ITypeDefinitionSizeOf As UInteger Implements ITypeDefinition.SizeOf Get Debug.Assert(Not Me.IsAnonymousType) CheckDefinitionInvariant() Return CUInt(Me.Layout.Size) End Get End Property Private ReadOnly Property ITypeDefinitionStringFormat As CharSet Implements ITypeDefinition.StringFormat Get Debug.Assert(Not Me.IsAnonymousType) CheckDefinitionInvariant() Return Me.MarshallingCharSet End Get End Property Private ReadOnly Property INamedTypeReferenceGenericParameterCount As UShort Implements INamedTypeReference.GenericParameterCount Get Return GenericParameterCountImpl End Get End Property Private ReadOnly Property INamedTypeReferenceMangleName As Boolean Implements INamedTypeReference.MangleName Get Return MangleName End Get End Property Private ReadOnly Property INamedEntityName As String Implements INamedEntity.Name Get ' CCI automatically adds the arity suffix, so we return Name, not MetadataName here. Return Me.Name End Get End Property Private Function INamespaceTypeReferenceGetUnit(context As EmitContext) As IUnitReference Implements INamespaceTypeReference.GetUnit Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing) Return moduleBeingBuilt.Translate(Me.ContainingModule, context.Diagnostics) End Function Private ReadOnly Property INamespaceTypeReferenceNamespaceName As String Implements INamespaceTypeReference.NamespaceName Get Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing) Return If(Me.GetEmittedNamespaceName(), Me.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) End Get End Property Private ReadOnly Property INamespaceTypeDefinitionIsPublic As Boolean Implements INamespaceTypeDefinition.IsPublic Get 'Debug.Assert(((ITypeReference)this).AsNamespaceTypeDefinition != null); CheckDefinitionInvariant() Return PEModuleBuilder.MemberVisibility(Me) = Cci.TypeMemberVisibility.Public End Get End Property Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As ITypeReference Implements ITypeMemberReference.GetContainingType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeReference IsNot Nothing) Debug.Assert(Me.IsDefinitionOrDistinct()) If Not Me.IsDefinition Then Return moduleBeingBuilt.Translate(Me.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNodeOpt, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End If Return Me.ContainingType End Function Private ReadOnly Property ITypeDefinitionMemberContainingTypeDefinition As ITypeDefinition Implements ITypeDefinitionMember.ContainingTypeDefinition Get 'Debug.Assert(((ITypeReference)this).AsNestedTypeDefinition != null); 'return (ITypeDefinition)moduleBeingBuilt.Translate(this.ContainingType, true); Debug.Assert(Me.ContainingType IsNot Nothing) CheckDefinitionInvariant() Return Me.ContainingType End Get End Property Private ReadOnly Property ITypeDefinitionMemberVisibility As TypeMemberVisibility Implements ITypeDefinitionMember.Visibility Get 'Debug.Assert(((ITypeReference)this).AsNestedTypeDefinition != null); Debug.Assert(Me.ContainingType IsNot Nothing) CheckDefinitionInvariant() Return PEModuleBuilder.MemberVisibility(Me) End Get End Property Private Function IGenericTypeInstanceReferenceGetGenericArguments(context As EmitContext) As ImmutableArray(Of ITypeReference) Implements IGenericTypeInstanceReference.GetGenericArguments Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing) Dim builder = ArrayBuilder(Of ITypeReference).GetInstance() For Each t In Me.TypeArgumentsNoUseSiteDiagnostics builder.Add(moduleBeingBuilt.Translate(t, syntaxNodeOpt:=DirectCast(context.SyntaxNodeOpt, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics)) Next Return builder.ToImmutableAndFree End Function Private ReadOnly Property IGenericTypeInstanceReferenceGenericType As INamedTypeReference Implements IGenericTypeInstanceReference.GenericType Get Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing) Return GenericTypeImpl End Get End Property Private ReadOnly Property GenericTypeImpl As INamedTypeReference Get Return Me.OriginalDefinition End Get End Property Private ReadOnly Property ISpecializedNestedTypeReferenceUnspecializedVersion As INestedTypeReference Implements ISpecializedNestedTypeReference.UnspecializedVersion Get Debug.Assert((DirectCast(Me, ITypeReference)).AsSpecializedNestedTypeReference IsNot Nothing) Dim result = GenericTypeImpl.AsNestedTypeReference Debug.Assert(result IsNot Nothing) Return result End Get End Property End Class End Namespace
droyad/roslyn
src/Compilers/VisualBasic/Portable/Emit/NamedTypeSymbolAdapter.vb
Visual Basic
apache-2.0
41,828
Imports MySql.Data.MySqlClient Public Class formStudentAccount Dim con As New connection 'Mysql Connection used through the Form 'Handles Various KeyPresses on the Form Private Sub formStudentAccount_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown If e.KeyCode = Keys.Escape Then Me.Close() ElseIf e.KeyCode = Keys.F12 Then reload() End If End Sub 'On Form Load Private Sub StudentAccount_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Once Loaded Me.KeyPreview = True 'fill() S_ID.Focus() End Sub 'Refreshes the Form Private Sub reload() Controls.Clear() InitializeComponent() S_ID.Focus() fill() S_ID.Focus() End Sub 'Fills up the DataGrid on Form Load with all the Queries on this Month(irrescpective of any student) Private Sub fill() Try con.connect() Dim query As String = "SELECT student_takes.BILL_ID, student_takes.T_ID, student_takes.S_ID, item.NAME, student_takes.QTY, student_takes.DOR, student_takes.RATE, student_takes.E_ID, student_takes.TAX from student_takes INNER JOIN item ON item.ITEM_ID=student_takes.ITEM_ID where date_format(Date(DOR),'%d-%m-%Y') like '%" + MonthCalendar1.SelectionRange.Start.Month.ToString + "-" + MonthCalendar1.SelectionRange.Start.Year.ToString + "' order by dor desc" 'where date_format(Date(DOR),'%d-%m-%Y') like '%" + MonthCalendar1.SelectionRange.Start.Month.ToString + "-" + MonthCalendar1.SelectionRange.Start.Year.ToString + "' ORDER BY DOR DESC" Dim comm As New MySqlCommand(query, con.conn) Dim dr As MySqlDataReader Dim dt As New DataTable dr = comm.ExecuteReader dt.Load(dr) DataGridView1.DataSource = dt dr.Close() Catch ex As Exception MsgBox("Error Occured ! Please try Again ! ") MsgBox(ex.Message.ToString) Me.Close() End Try S_ID.Focus() End Sub 'Handles the KeyPress on S_ID tb Private Sub S_ID_KeyDown(sender As Object, e As KeyEventArgs) Handles S_ID.KeyDown If e.KeyCode = Keys.Enter Then If S_ID.Text.Length = 5 Then S_ID.Text = "F20" + S_ID.Text + "P" ElseIf S_ID.Text.Length = 6 And (S_ID.Text.Contains("H") Or S_ID.Text.Contains("h")) Then S_ID.Text = S_ID.Text.Substring(0, 1) + "20" + S_ID.Text.Substring(1, 5) + "P" ElseIf S_ID.Text.Length = 6 And (S_ID.Text.Contains("P") Or S_ID.Text.Contains("p")) Then S_ID.Text = S_ID.Text.Substring(0, 1) + "20" + S_ID.Text.Substring(1, 5) + "P" End If Try con.connect() Dim query As String = "SELECT * FROM STUDENT WHERE S_ID = '" + S_ID.Text.ToString + "'" Dim dr As MySqlDataReader Dim comm As New MySqlCommand(query, con.conn) dr = comm.ExecuteReader If dr.Read() Then lblNAME.Text = dr.Item("NAME") lblBHAWAN.Text = dr.Item("BHAWAN") lblROOM.Text = dr.Item("ROOM") lblIDNO.Text = dr.Item("IDNO") calc_Account(S_ID.Text.ToString) fill_appro(S_ID.Text.ToString) S_ID.SelectAll() End If dr.Close() Catch ex As Exception MsgBox("Error ! Please Try Again !123") MsgBox(ex.Message.ToString) reload() End Try End If End Sub 'Calculates the Total Extras for a Given Student for this Month and shows it on the Proper Label Private Sub calc_Account(sid As String) Try con.connect() Dim query As String = "select sum(QTY*(RATE*(1+(TAX/100)))) from student_takes where date_format(Date(DOR),'%d-%m-%Y') like '%" + MonthCalendar1.SelectionRange.Start.Month.ToString + "-" + MonthCalendar1.SelectionRange.Start.Year.ToString + "'" + " and s_id='" + sid.ToString + "'" Dim dr As MySqlDataReader Dim comm As New MySqlCommand(query, con.conn) dr = comm.ExecuteReader If dr.Read() And Not IsDBNull(dr.Item(0)) Then lblStudent_Account.Text = dr.Item(0) ElseIf IsDBNull(dr.Item(0)) Then MsgBox("No Record Found for this Student for this Month!!") End If dr.Close() Catch ex As Exception MsgBox("Error Occured ! Please Try Again!") MsgBox(ex.Message.ToString) reload() End Try End Sub 'Gets all the Transactions for a Given Student for this month and shows it in the DataGrid Private Sub fill_appro(sid As String) Try con.connect() Dim query As String = "SELECT student_takes.BILL_ID, student_takes.T_ID, student_takes.S_ID, item.NAME, student_takes.QTY, student_takes.DOR, student_takes.RATE, student_takes.E_ID, student_takes.TAX from student_takes INNER JOIN item ON item.ITEM_ID=student_takes.ITEM_ID where date_format(Date(DOR),'%d-%m-%Y') like '%" + MonthCalendar1.SelectionRange.Start.Month.ToString + "-" + MonthCalendar1.SelectionRange.Start.Year.ToString + "' " + "and s_id='" + sid.ToString + "'" '"select * from student_takes where date_format(Date(DOR),'%d-%m-%Y') like '%" + MonthCalendar1.SelectionRange.Start.Month.ToString + "-" + MonthCalendar1.SelectionRange.Start.Year.ToString + "'" + "and s_id='" + sid + "'" Dim comm As New MySqlCommand(query, con.conn) Dim dr1 As MySqlDataReader Dim dt As New DataTable dr1 = comm.ExecuteReader If Not IsDBNull(dr1) Then dt.Load(dr1) DataGridView1.DataSource = dt dr1.Close() ElseIf IsDBNull(dr1) Then MsgBox("No Record Found for this Student for this Month!!") End If Catch ex As Exception MsgBox("Error ! Please Try again! ") MsgBox(ex.Message.ToString) reload() End Try End Sub 'Recalculates the Extras total and Refills the datagrid when the Date is Changed Private Sub MonthCalendar1_DateChanged(sender As Object, e As DateRangeEventArgs) Handles MonthCalendar1.DateChanged If S_ID.Text <> "" Then fill_appro(S_ID.Text.ToString) calc_Account(S_ID.Text.ToString) Else fill() End If End Sub End Class
SSMS-Pilani/Mess-Management-System
Mess Management System/formStudentAccount.vb
Visual Basic
mit
6,694
Public Class Main Private Sub pb_gown_MouseHover(sender As Object, e As EventArgs) Handles pb_gown.MouseHover pb_gown.BackgroundImage = CType(My.Resources.ResourceManager.GetObject("gown_hover"), Image) End Sub Private Sub pb_gown_MouseLeave(sender As Object, e As EventArgs) Handles pb_gown.MouseLeave pb_gown.BackgroundImage = CType(My.Resources.ResourceManager.GetObject("gown"), Image) End Sub Private Sub pb_interview_MouseHover(sender As Object, e As EventArgs) Handles pb_interview.MouseHover pb_interview.BackgroundImage = CType(My.Resources.ResourceManager.GetObject("interview_hover"), Image) End Sub Private Sub pb_interview_MouseLeave(sender As Object, e As EventArgs) Handles pb_interview.MouseLeave pb_interview.BackgroundImage = CType(My.Resources.ResourceManager.GetObject("interview"), Image) End Sub Private Sub pb_swimwear_MouseHover(sender As Object, e As EventArgs) Handles pb_swimwear.MouseHover pb_swimwear.BackgroundImage = CType(My.Resources.ResourceManager.GetObject("swimwear_hover"), Image) End Sub Private Sub pb_swimwear_MouseLeave(sender As Object, e As EventArgs) Handles pb_swimwear.MouseLeave pb_swimwear.BackgroundImage = CType(My.Resources.ResourceManager.GetObject("swimwear"), Image) End Sub Private Sub pb_talent_MouseHover(sender As Object, e As EventArgs) Handles pb_talent.MouseHover pb_talent.BackgroundImage = CType(My.Resources.ResourceManager.GetObject("talent_hover"), Image) End Sub Private Sub pb_talent_MouseLeave(sender As Object, e As EventArgs) Handles pb_talent.MouseLeave pb_talent.BackgroundImage = CType(My.Resources.ResourceManager.GetObject("talent"), Image) End Sub Private Sub pb_gown_Click(sender As Object, e As EventArgs) Handles pb_gown.Click If isEnabled("Gown") = True Then lbl_event_id.Text = Functions.getId("SELECT id FROM t_event WHERE name = 'gown'") CandidateList1.lbl_event.Text = "Gown" CandidateList1.Show() Me.Hide() Else ScoreList.populateDGV("SELECT number, image, candidate, score FROM v_gown_overall ORDER BY score DESC") ScoreList.Text = "Gown" ScoreList.Show() End If End Sub Private Sub pb_interview_Click(sender As Object, e As EventArgs) Handles pb_interview.Click If isEnabled("Interview") = True Then lbl_event_id.Text = Functions.getId("SELECT id FROM t_event WHERE name = 'interview'") CandidateList1.lbl_event.Text = "Interview" CandidateList1.Show() Me.Hide() Else ScoreList.populateDGV("SELECT number, image, candidate, score FROM v_interview_overall ORDER BY score DESC") ScoreList.Text = "Interview" ScoreList.Show() End If End Sub Private Sub pb_swimwear_Click(sender As Object, e As EventArgs) Handles pb_swimwear.Click If isEnabled("Swimwear") = True Then lbl_event_id.Text = Functions.getId("SELECT id FROM t_event WHERE name = 'swimwear'") CandidateList1.lbl_event.Text = "Swimwear" CandidateList1.Show() Me.Hide() Else ScoreList.populateDGV("SELECT number, image, candidate, score FROM v_swimwear_overall ORDER BY score DESC") ScoreList.Text = "Swimwear" ScoreList.Show() End If End Sub Private Sub pb_talent_Click(sender As Object, e As EventArgs) Handles pb_talent.Click If isEnabled("Talent") = True Then lbl_event_id.Text = Functions.getId("SELECT id FROM t_event WHERE name = 'talent'") CandidateList1.lbl_event.Text = "Talent" CandidateList1.Show() Me.Hide() Else ScoreList.populateDGV("SELECT number, image, candidate, score FROM v_talent_overall ORDER BY score DESC") ScoreList.Text = "Talent" ScoreList.Show() End If End Sub Private Sub Main_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing Dim sql As String = "UPDATE t_judge SET status = 0 WHERE id = '" & lbl_judge_id.Text & "'" Try Connect.constring.Open() Functions.com.Connection = Connect.constring Functions.com.CommandText = sql Functions.com.ExecuteNonQuery() Catch ex As Exception MsgBox(ex.Message) Finally Connect.constring.Close() Login.Show() End Try End Sub End Class
kmligue/Tabulation-System---Client
Tabulation System - Client/Main.vb
Visual Basic
mit
4,620
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("GtkSharp_Test3")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("GtkSharp_Test3")> <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("c801229d-30bd-4e25-9ba0-293bf4faea0b")> ' 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")>
grbd/GBD.Blog.Examples
Source/GtkSharp3/GtkSharp_AdvForm1_VB/My Project/AssemblyInfo.vb
Visual Basic
mit
1,172
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("Password Generator")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Microsoft")> <Assembly: AssemblyProduct("Password Generator")> <Assembly: AssemblyCopyright("Copyright © Microsoft 2014")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("35ce9f00-8239-4629-882e-ce5b7135749d")> ' 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")>
LagrangianPoint/Pasword-Generartor-Visual-Basic
Password Generator/My Project/AssemblyInfo.vb
Visual Basic
mit
1,207
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmLangList #Region "Windows Form Designer generated code " <System.Diagnostics.DebuggerNonUserCode()> Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() End Sub 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean) If Disposing Then If Not components Is Nothing Then components.Dispose() End If End If MyBase.Dispose(Disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer Public ToolTip1 As System.Windows.Forms.ToolTip Public WithEvents cmdDel As System.Windows.Forms.Button Public WithEvents cmdBOMenu As System.Windows.Forms.Button Public WithEvents cmdImport As System.Windows.Forms.Button Public WithEvents cmdNew As System.Windows.Forms.Button Public WithEvents DataList1 As myDataGridView Public WithEvents txtSearch As System.Windows.Forms.TextBox Public WithEvents cmdExit As System.Windows.Forms.Button Public WithEvents lbl As System.Windows.Forms.Label 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmLangList)) Me.components = New System.ComponentModel.Container() Me.ToolTip1 = New System.Windows.Forms.ToolTip(components) Me.cmdDel = New System.Windows.Forms.Button Me.cmdBOMenu = New System.Windows.Forms.Button Me.cmdImport = New System.Windows.Forms.Button Me.cmdNew = New System.Windows.Forms.Button Me.DataList1 = New myDataGridView Me.txtSearch = New System.Windows.Forms.TextBox Me.cmdExit = New System.Windows.Forms.Button Me.lbl = New System.Windows.Forms.Label Me.SuspendLayout() Me.ToolTip1.Active = True CType(Me.DataList1, System.ComponentModel.ISupportInitialize).BeginInit() Me.BackColor = System.Drawing.Color.FromARGB(224, 224, 224) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.Text = "Select a Language" Me.ClientSize = New System.Drawing.Size(260, 491) Me.Location = New System.Drawing.Point(3, 22) Me.ControlBox = False Me.KeyPreview = True Me.MaximizeBox = False Me.MinimizeBox = False Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Enabled = True Me.Cursor = System.Windows.Forms.Cursors.Default Me.RightToLeft = System.Windows.Forms.RightToLeft.No Me.HelpButton = False Me.WindowState = System.Windows.Forms.FormWindowState.Normal Me.Name = "frmLangList" Me.cmdDel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdDel.Text = "&Delete" Me.cmdDel.Size = New System.Drawing.Size(76, 52) Me.cmdDel.Location = New System.Drawing.Point(91, 376) Me.cmdDel.TabIndex = 7 Me.cmdDel.TabStop = False Me.cmdDel.BackColor = System.Drawing.SystemColors.Control Me.cmdDel.CausesValidation = True Me.cmdDel.Enabled = True Me.cmdDel.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdDel.Cursor = System.Windows.Forms.Cursors.Default Me.cmdDel.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdDel.Name = "cmdDel" Me.cmdBOMenu.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdBOMenu.Text = "&Back Office - Menu" Me.cmdBOMenu.Size = New System.Drawing.Size(137, 52) Me.cmdBOMenu.Location = New System.Drawing.Point(113, 432) Me.cmdBOMenu.TabIndex = 6 Me.cmdBOMenu.TabStop = False Me.cmdBOMenu.BackColor = System.Drawing.SystemColors.Control Me.cmdBOMenu.CausesValidation = True Me.cmdBOMenu.Enabled = True Me.cmdBOMenu.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdBOMenu.Cursor = System.Windows.Forms.Cursors.Default Me.cmdBOMenu.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdBOMenu.Name = "cmdBOMenu" Me.cmdImport.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdImport.Text = "&Import" Me.cmdImport.Size = New System.Drawing.Size(97, 52) Me.cmdImport.Location = New System.Drawing.Point(6, 432) Me.cmdImport.TabIndex = 5 Me.cmdImport.TabStop = False Me.cmdImport.BackColor = System.Drawing.SystemColors.Control Me.cmdImport.CausesValidation = True Me.cmdImport.Enabled = True Me.cmdImport.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdImport.Cursor = System.Windows.Forms.Cursors.Default Me.cmdImport.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdImport.Name = "cmdImport" Me.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdNew.Text = "&New" Me.cmdNew.Size = New System.Drawing.Size(76, 52) Me.cmdNew.Location = New System.Drawing.Point(6, 375) Me.cmdNew.TabIndex = 4 Me.cmdNew.TabStop = False Me.cmdNew.BackColor = System.Drawing.SystemColors.Control Me.cmdNew.CausesValidation = True Me.cmdNew.Enabled = True Me.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdNew.Cursor = System.Windows.Forms.Cursors.Default Me.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdNew.Name = "cmdNew" ''DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) Me.DataList1.Size = New System.Drawing.Size(244, 342) Me.DataList1.Location = New System.Drawing.Point(6, 27) Me.DataList1.TabIndex = 2 Me.DataList1.Name = "DataList1" Me.txtSearch.AutoSize = False Me.txtSearch.Size = New System.Drawing.Size(199, 19) Me.txtSearch.Location = New System.Drawing.Point(51, 3) Me.txtSearch.TabIndex = 1 Me.txtSearch.AcceptsReturn = True Me.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left Me.txtSearch.BackColor = System.Drawing.SystemColors.Window Me.txtSearch.CausesValidation = True Me.txtSearch.Enabled = True Me.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText Me.txtSearch.HideSelection = True Me.txtSearch.ReadOnly = False Me.txtSearch.Maxlength = 0 Me.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam Me.txtSearch.MultiLine = False Me.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No Me.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None Me.txtSearch.TabStop = True Me.txtSearch.Visible = True Me.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.txtSearch.Name = "txtSearch" Me.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdExit.Text = "E&xit" Me.cmdExit.Size = New System.Drawing.Size(76, 52) Me.cmdExit.Location = New System.Drawing.Point(175, 375) Me.cmdExit.TabIndex = 3 Me.cmdExit.TabStop = False Me.cmdExit.BackColor = System.Drawing.SystemColors.Control Me.cmdExit.CausesValidation = True Me.cmdExit.Enabled = True Me.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdExit.Cursor = System.Windows.Forms.Cursors.Default Me.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdExit.Name = "cmdExit" Me.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight Me.lbl.Text = "&Search :" Me.lbl.Size = New System.Drawing.Size(40, 13) Me.lbl.Location = New System.Drawing.Point(8, 6) Me.lbl.TabIndex = 0 Me.lbl.BackColor = System.Drawing.Color.Transparent Me.lbl.Enabled = True Me.lbl.ForeColor = System.Drawing.SystemColors.ControlText Me.lbl.Cursor = System.Windows.Forms.Cursors.Default Me.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No Me.lbl.UseMnemonic = True Me.lbl.Visible = True Me.lbl.AutoSize = True Me.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None Me.lbl.Name = "lbl" Me.Controls.Add(cmdDel) Me.Controls.Add(cmdBOMenu) Me.Controls.Add(cmdImport) Me.Controls.Add(cmdNew) Me.Controls.Add(DataList1) Me.Controls.Add(txtSearch) Me.Controls.Add(cmdExit) Me.Controls.Add(lbl) CType(Me.DataList1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub #End Region End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmLangList.Designer.vb
Visual Basic
mit
8,457
Imports System.Web Imports System.Web.Services Public Class Icon Implements System.Web.IHttpHandler Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest context.Response.ContentType = "image/png" Dim buffer() As Byte = Nothing Try buffer = CType(Test.Resources.Images.ResourceManager.GetObject(context.Request.QueryString("id").ToLower().Replace(".", "")), Byte()) Catch ex As Exception buffer = CType(Test.Resources.Images.ResourceManager.GetObject("error"), Byte()) End Try context.Response.OutputStream.Write(buffer, 0, buffer.Length) End Sub ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class
alekseynemiro/nemiro.oauth.dll
examples/Test/Test.VB.AspWebForms/Icon.ashx.vb
Visual Basic
apache-2.0
772
'Copyright 2019 Esri 'Licensed under the Apache License, Version 2.0 (the "License"); 'you may not use this file except in compliance with the License. 'You may obtain a copy of the License at ' http://www.apache.org/licenses/LICENSE-2.0 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. Imports Microsoft.VisualBasic Imports System Imports System.Data Imports System.Collections Imports System.Runtime.InteropServices Imports ESRI.ArcGIS.esriSystem Imports ESRI.ArcGIS.Geometry Imports ESRI.ArcGIS.Carto Imports ESRI.ArcGIS.ADF ''' <summary> ''' Implementation of interface IMaps which is eventually a collection of Maps ''' </summary> Public Class Maps : Implements IMaps, IDisposable 'class member - using internally an ArrayList to manage the Maps collection Private m_array As ArrayList = Nothing #Region "class constructor" Public Sub New() m_array = New ArrayList() End Sub #End Region #Region "IDisposable Members" ''' <summary> ''' Dispose the collection ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose If Not m_array Is Nothing Then m_array.Clear() m_array = Nothing End If End Sub #End Region #Region "IMaps Members" ''' <summary> ''' Add the given Map to the collection ''' </summary> ''' <param name="Map"></param> Public Sub Add(ByVal Map As ESRI.ArcGIS.Carto.IMap) Implements ESRI.ArcGIS.Carto.IMaps.Add If Map Is Nothing Then Throw New Exception("Maps::Add:" & Constants.vbCrLf & "New Map is mot initialized!") End If m_array.Add(Map) End Sub ''' <summary> ''' Get the number of Maps in the collection ''' </summary> Public ReadOnly Property Count() As Integer Implements ESRI.ArcGIS.Carto.IMaps.Count Get Return m_array.Count End Get End Property ''' <summary> ''' Create a new Map, add it to the collection and return it to the caller ''' </summary> ''' <returns></returns> Public Function Create() As ESRI.ArcGIS.Carto.IMap Implements ESRI.ArcGIS.Carto.IMaps.Create Dim newMap As IMap = New MapClass() m_array.Add(newMap) Return newMap End Function ''' <summary> ''' Return the Map at the given index ''' </summary> ''' <param name="Index"></param> ''' <returns></returns> Public ReadOnly Property Item(ByVal Index As Integer) As ESRI.ArcGIS.Carto.IMap Implements ESRI.ArcGIS.Carto.IMaps.Item Get If Index > m_array.Count OrElse Index < 0 Then Throw New Exception("Maps::Item:" & Constants.vbCrLf & "Index is out of range!") End If Return TryCast(m_array(Index), IMap) End Get End Property ''' <summary> ''' Remove the instance of the given Map ''' </summary> ''' <param name="Map"></param> Public Sub Remove(ByVal Map As ESRI.ArcGIS.Carto.IMap) Implements ESRI.ArcGIS.Carto.IMaps.Remove m_array.Remove(Map) End Sub ''' <summary> ''' Remove the Map at the given index ''' </summary> ''' <param name="Index"></param> Public Sub RemoveAt(ByVal Index As Integer) Implements ESRI.ArcGIS.Carto.IMaps.RemoveAt If Index > m_array.Count OrElse Index < 0 Then Throw New Exception("Maps::RemoveAt:" & Constants.vbCrLf & "Index is out of range!") End If m_array.RemoveAt(Index) End Sub ''' <summary> ''' Reset the Maps array ''' </summary> Public Sub Reset() Implements ESRI.ArcGIS.Carto.IMaps.Reset m_array.Clear() End Sub #End Region End Class
Esri/arcobjects-sdk-community-samples
Net/Controls/MapAndPageLayoutSynchApp/VBNet/Maps.vb
Visual Basic
apache-2.0
3,686
Imports Microsoft.VisualBasic Imports System.Windows.Controls Partial Public Class NavigationActions Inherits UserControl Public Sub New() InitializeComponent() End Sub End Class
Esri/arcgis-samples-silverlight
src/VBNet/ArcGISSilverlightSDK/BehaviorsAndActions/NavigationActions.xaml.vb
Visual Basic
apache-2.0
204
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.PasteTracking Namespace Microsoft.CodeAnalysis.AddMissingImports <UseExportProvider> <Trait(Traits.Feature, Traits.Features.AddMissingImports)> Public Class VisualBasicAddMissingImportsRefactoringProviderTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Dim testWorkspace = DirectCast(workspace, TestWorkspace) Dim pasteTrackingService = testWorkspace.ExportProvider.GetExportedValue(Of PasteTrackingService)() Return New VisualBasicAddMissingImportsRefactoringProvider(pasteTrackingService) End Function Protected Overrides Function CreateWorkspaceFromFile(initialMarkup As String, parameters As TestParameters) As TestWorkspace Dim Workspace = TestWorkspace.CreateVisualBasic(initialMarkup) ' Treat the span being tested as the pasted span Dim hostDocument = Workspace.Documents.First() Dim pastedTextSpan = hostDocument.SelectedSpans.FirstOrDefault() If Not pastedTextSpan.IsEmpty Then Dim PasteTrackingService = Workspace.ExportProvider.GetExportedValue(Of PasteTrackingService)() ' This tests the paste tracking service's resiliancy to failing when multiple pasted spans are ' registered consecutively And that the last registered span wins. PasteTrackingService.RegisterPastedTextSpan(hostDocument.TextBuffer, Nothing) PasteTrackingService.RegisterPastedTextSpan(hostDocument.TextBuffer, pastedTextSpan) End If Return Workspace End Function Private Overloads Function TestInRegularAndScriptAsync( initialMarkup As String, expectedMarkup As String, placeSystemNamespaceFirst As Boolean, separateImportDirectiveGroups As Boolean) As Task Dim options = OptionsSet( SingleOption(GenerationOptions.PlaceSystemNamespaceFirst, placeSystemNamespaceFirst), SingleOption(GenerationOptions.SeparateImportDirectiveGroups, separateImportDirectiveGroups)) Return TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options:=options) End Function <WpfFact> Public Async Function AddMissingImports_NoAction_PasteIsNotMissingImports() As Task Dim code = " Class [|C|] Dim foo As D End Class Namespace A Public Class D End Class End Namespace " Await TestMissingInRegularAndScriptAsync(code) End Function <WpfFact> Public Async Function AddMissingImports_AddImport_PasteContainsSingleMissingImport() As Task Dim code = " Class C Dim foo As [|D|] End Class Namespace A Public Class D End Class End Namespace " Dim expected = " Imports A Class C Dim foo As D End Class Namespace A Public Class D End Class End Namespace " Await TestInRegularAndScriptAsync(code, expected) End Function <WpfFact> Public Async Function AddMissingImports_AddImportsBelowSystem_PlaceSystemFirstPasteContainsMultipleMissingImports() As Task Dim code = " Imports System Class C [|Dim foo As D Dim bar As E|] End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class E End Class End Namespace " Dim expected = " Imports System Imports A Imports B Class C Dim foo As D Dim bar As E End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class E End Class End Namespace " Await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst:=True, separateImportDirectiveGroups:=False) End Function <WpfFact> Public Async Function AddMissingImports_AddImportsAboveSystem_DontPlaceSystemFirstPasteContainsMultipleMissingImports() As Task Dim code = " Imports System Class C [|Dim foo As D Dim bar As E|] End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class E End Class End Namespace " Dim expected = " Imports A Imports B Imports System Class C Dim foo As D Dim bar As E End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class E End Class End Namespace " Await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst:=False, separateImportDirectiveGroups:=False) End Function <WpfFact> Public Async Function AddMissingImports_AddImportsUngrouped_SeparateImportGroupsPasteContainsMultipleMissingImports() As Task ' ' The current fixes for AddImport diagnostics do not consider whether imports should be grouped. ' This test documents this behavior and is a reminder that when the behavior changes ' AddMissingImports is also affected and should be considered. Dim code = " Imports System Class C [|Dim foo As D Dim bar As E|] End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class E End Class End Namespace " Dim expected = " Imports A Imports B Imports System Class C Dim foo As D Dim bar As E End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class E End Class End Namespace " Await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst:=False, separateImportDirectiveGroups:=True) End Function <WpfFact> Public Async Function AddMissingImports_NoAction_NoPastedSpan() As Task Dim code = " Class C Dim foo As D[||] End Class Namespace A Public Class D End Class End Namespace " Await TestMissingInRegularAndScriptAsync(code) End Function <WpfFact> Public Async Function AddMissingImports_NoAction_PasteContainsAmibiguousMissingImport() As Task Dim code = " Class C Dim foo As [|D|] End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class D End Class End Namespace " Await TestMissingInRegularAndScriptAsync(code) End Function <WpfFact> Public Async Function AddMissingImports_PartialFix_PasteContainsFixableAndAmbiguousMissingImports() As Task Dim code = " Imports System Class C [|Dim foo As D Dim bar As E|] End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class D End Class Public Class E End Class End Namespace " Dim expected = " Imports System Imports B Class C Dim foo As D Dim bar As E End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class D End Class Public Class E End Class End Namespace " Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(31768, "https://github.com/dotnet/roslyn/issues/31768")> <WpfFact> Public Async Function AddMissingImports_AddMultipleImports_NoPreviousImports() As Task Dim code = " Class C [|Dim foo As D Dim bar As E|] End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class E End Class End Namespace " Dim expected = " Imports A Imports B Class C Dim foo As D Dim bar As E End Class Namespace A Public Class D End Class End Namespace Namespace B Public Class E End Class End Namespace " Await TestInRegularAndScriptAsync(code, expected, placeSystemNamespaceFirst:=False, separateImportDirectiveGroups:=False) End Function End Class End Namespace
nguerrera/roslyn
src/EditorFeatures/VisualBasicTest/CodeRefactorings/AddMissingImports/VisualBasicAddMissingImportsRefactoringProviderTests.vb
Visual Basic
apache-2.0
8,367
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToBase <[UseExportProvider]> Public Class VisualBasicGoToBaseTests Inherits GoToBaseTestsBase Private Overloads Async Function TestAsync(source As String, Optional shouldSucceed As Boolean = True, Optional metadataDefinitions As String() = Nothing) As Task Await TestAsync(source, LanguageNames.VisualBasic, shouldSucceed, metadataDefinitions) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestEmptyFile() As Task Await TestAsync("$$", shouldSucceed:=False) End Function #Region "Classes And Interfaces" <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithSingleClass() As Task Await TestAsync( "class $$C end class", metadataDefinitions:={"mscorlib:Object"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithAbstractClass() As Task Await TestAsync( "mustinherit class [|C|] end class class $$D inherits C end class", metadataDefinitions:={"mscorlib:Object"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithAbstractClassFromInterface() As Task Await TestAsync( "interface [|I|] end interface mustinherit class [|C|] implements I end class class $$D inherits C end class", metadataDefinitions:={"mscorlib:Object"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithSealedClass() As Task Await TestAsync( "class [|D|] end class NotInheritable class $$C inherits D end class", metadataDefinitions:={"mscorlib:Object"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithEnum() As Task Await TestAsync( "enum $$C end enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithNonAbstractClass() As Task Await TestAsync( "class [|C|] end class class $$D inherits C end class", metadataDefinitions:={"mscorlib:Object"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithSingleClassImplementation() As Task Await TestAsync( "class $$C implements I end class interface [|I|] end interface", metadataDefinitions:={"mscorlib:Object"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithTwoClassImplementations() As Task Await TestAsync( "class $$C implements I end class class D implements I end class interface [|I|] end interface", metadataDefinitions:={"mscorlib:Object"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestClassHierarchyWithParentSiblings() As Task Await TestAsync( "class E inherits D end class class $$D inherits B end class class [|B|] inherits A end class class C inherits A end class class [|A|] implements I2 end class interface [|I2|] inherits I end interface interface I1 inherits I end interface interface [|I|] inherits J1, J2 end interface interface [|J1|] end interface interface [|J2|] end interface", metadataDefinitions:={"mscorlib:Object"}) End Function #End Region #Region "Structures" <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithStruct() As Task Await TestAsync( "structure $$S end structure", metadataDefinitions:={"mscorlib:Object", "mscorlib:ValueType"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithSingleStructImplementation() As Task Await TestAsync( "structure $$S implements I end structure interface [|I|] end interface", metadataDefinitions:={"mscorlib:Object", "mscorlib:ValueType"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestStructWithInterfaceHierarchy() As Task Await TestAsync( "structure $$S implements I2 end interface interface [|I2|] inherits I end interface interface I1 inherits I end interface interface [|I|] inherits J1, J2 end interface interface [|J1|] end interface interface [|J2|] end interface", metadataDefinitions:={"mscorlib:Object", "mscorlib:ValueType"}) End Function #End Region #Region "Methods" <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOneMethodImplementation_01() As Task Await TestAsync( "class C implements I public sub $$M() implements I.M end sub end class interface I sub [|M|]() end interface") End Function Public Async Function TestWithOneMethodImplementation_02() As Task Await TestAsync( "class C implements I public sub M() end sub private sub $$I_M() implements I.M end sub end class interface I sub [|M|]() end interface") End Function Public Async Function TestWithOneMethodImplementation_03() As Task Await TestAsync( "class C implements I public sub $$M() end sub private sub I_M() implements I.M end sub end class interface I sub M() end interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestInterfaceWithOneMethodOverload() As Task Await TestAsync( "interface J inherits I overloads sub $$M() end interface interface I sub M() end interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOneMethodImplementationInStruct() As Task Await TestAsync( "structure S implements I sub $$M() implements I.M end sub end structure interface I sub [|M|]() end interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithTwoMethodImplementations() As Task Await TestAsync( "class C implements I sub $$M() implements I.M end sub end class class D implements I sub M() implements I.M end sub end class interface I sub [|M|]() end interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestOverrideWithOverloads_01() As Task Await TestAsync( "class C inherits D public overrides sub $$M() end sub end class class D public overridable sub [|M|]() end sub public overridable sub M(a as integer) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestOverrideWithOverloads_02() As Task Await TestAsync( "class C inherits D public overrides sub $$M(a as integer) end sub end class class D public overridable sub M() end sub public overridable sub [|M|](a as integer) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestImplementWithOverloads_01() As Task Await TestAsync( "Class C Implements I Public Sub $$M() Implements I.M End Sub Public Sub M(a As Integer) Implements I.M End Sub End Class Interface I Sub [|M|]() Sub M(a As Integer) End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestImplementWithOverloads_02() As Task Await TestAsync( "Class C Implements I Public Sub M() Implements I.M End Sub Public Sub $$M(a As Integer) Implements I.M End Sub End Class Interface I Sub M() Sub [|M|](a As Integer) End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnBaseClass() As Task Await TestAsync( "Class C Implements I Public Overridable Sub [|M|]() Implements I.M End Sub End Class Class D Inherits C Public Overrides Sub $$M() End Sub End Class Interface I Sub [|M|]() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithVirtualMethodHiddenWithInterfaceOnBaseClass() As Task ' We should not find hidden methods ' and methods in interfaces if hidden below but the nested class does not implement the interface. Await TestAsync( "Class C Implements I Public Overridable Sub N() Implements I.M End Sub End Class Class D Inherits C Public Shadows Sub $$N() End Sub End Class Interface I Sub M() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnDerivedClass() As Task Await TestAsync( "Class C Public Overridable Sub [|M|]() End Sub End Class Class D Inherits C Implements I Public Overrides Sub $$M Implements I.M End Sub End Class Interface I Sub [|M|]() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithVirtualMethodHiddenWithInterfaceOnDerivedClass() As Task ' We should not find a hidden method. Await TestAsync( "Class C Public Overridable Sub M|) End Sub End Class Class D Inherits C Implements I Public Shadows Sub $$M Implements I.M End Sub End Class Interface I Sub [|M|]() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithVirtualMethodImplementationAndInterfaceImplementedOnDerivedType() As Task Await TestAsync( "Class C Implements I Public Overridable Sub [|M|]() Implements I.M End Sub End Class Class D Inherits C Implements I Public Overrides Sub $$M() End Sub End Class Interface I Sub [|M|]() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithVirtualMethodHiddenAndInterfaceImplementedOnDerivedType() As Task ' We should not find hidden methods. ' We should not find methods of interfaces not implemented by the method symbol. ' In this example, ' Dim i As I = New D() ' i.M() ' calls the method from C not from D. Await TestAsync( "Class C Implements I Public Overridable Sub M() Implements I.M End Sub End Class Class D Inherits C Implements I Public Shadows Sub $$M() End Sub End Class Interface I Sub M() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithVirtualMethodHiddenAndInterfaceAndMethodImplementedOnDerivedType() As Task ' We should not find hidden methods but should find the interface method. Await TestAsync( "Class C Implements I Public Overridable Sub M() Implements I.M End Sub End Class Class D Inherits C Implements I Public Shadows Sub $$M() Implements I.M End Sub End Class Interface I Sub [|M|]() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithAbstractMethodImplementation() As Task Await TestAsync( "MustInherit Class C Implements I Public MustOverride Sub [|N|]() Implements I.M End Class Class D Inherits C Public Overrides Sub $$N() End Sub End Class Interface I Sub [|M|]() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithSimpleMethod() As Task Await TestAsync( "class C public sub $$M() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOverridableMethodOnBase() As Task Await TestAsync( "class C public overridable sub [|M|]() end sub end class class D inherits C public overrides sub $$M() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOverridableMethodOnImplementation() As Task Await TestAsync( "class C public overridable sub $$M() end sub end class class D inherits C public overrides sub M() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithIntermediateAbstractOverrides() As Task Await TestAsync( "MustInherit Class A Public Overridable Sub [|M|]() End Sub End Class MustInherit Class B Inherits A Public MustOverride Overrides Sub M() End Class NotInheritable Class C1 Inherits B Public Overrides Sub M() End Sub End Class NotInheritable Class C2 Inherits A Public Overrides Sub $$M() MyBase.M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOverloadsOverrdiesAndInterfaceImplementation_01() As Task Await TestAsync( "Class C Implements I Public Overridable Sub [|N|]() Implements I.M End Sub Public Overridable Sub N(i As Integer) Implements I.M End Sub End Class Class D Inherits C Public Overrides Sub $$N() End Sub Public Overrides Sub N(i As Integer) End Sub End Class Interface I Sub [|M|]() Sub M(i As Integer) End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOverloadsOverrdiesAndInterfaceImplementation_02() As Task Await TestAsync( "Class C Implements I Public Overridable Sub N() Implements I.M End Sub Public Overridable Sub [|N|](i As Integer) Implements I.M End Sub End Class Class D Inherits C Public Overrides Sub N() End Sub Public Overrides Sub $$N(i As Integer) End Sub End Class Interface I Sub M() Sub [|M|](i As Integer) End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestOverrideOfMethodFromMetadata() As Task Await TestAsync( "Imports System Class C Public Overrides Function $$ToString() As String Return base.ToString(); End Function End Class ", metadataDefinitions:={"mscorlib:Object.ToString"}) End Function #End Region #Region "Properties and Events" <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOneEventImplementation() As Task Await TestAsync( "Class C Implements I Public Event $$E() Implements I.E End Class Interface I Event [|E|]() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOneEventImplementationInStruct() As Task Await TestAsync( "Structure C Implements I Public Event $$E() Implements I.E End Structure Interface I Event [|E|]() End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOnePropertyImplementation() As Task Await TestAsync( "Class C Implements I Public Property $$P As Integer Implements I.P Get Return 0 End Get Set(value As Integer) End Set End Property End Class Interface I Property [|P|]() As Integer End Interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)> Public Async Function TestWithOnePropertyImplementationInStruct() As Task Await TestAsync( "Structure C Implements I Public Property $$P As Integer Implements I.P Get Return 0 End Get Set(value As Integer) End Set End Property End Structure Interface I Property [|P|]() As Integer End Interface") End Function #End Region End Class End Namespace
abock/roslyn
src/EditorFeatures/Test2/GoToBase/VisuaBasicGoToBaseTests.vb
Visual Basic
mit
17,183
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ <Global.System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726")> _ Partial Class LoginForm1 Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub Friend WithEvents LogoPictureBox As System.Windows.Forms.PictureBox Friend WithEvents UsernameLabel As System.Windows.Forms.Label Friend WithEvents PasswordLabel As System.Windows.Forms.Label Friend WithEvents txtUser As System.Windows.Forms.TextBox Friend WithEvents txtPass As System.Windows.Forms.TextBox Friend WithEvents OK As System.Windows.Forms.Button Friend WithEvents Cancel As System.Windows.Forms.Button '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(LoginForm1)) Me.LogoPictureBox = New System.Windows.Forms.PictureBox Me.UsernameLabel = New System.Windows.Forms.Label Me.PasswordLabel = New System.Windows.Forms.Label Me.txtUser = New System.Windows.Forms.TextBox Me.txtPass = New System.Windows.Forms.TextBox Me.OK = New System.Windows.Forms.Button Me.Cancel = New System.Windows.Forms.Button Me.btnChangeUnmae = New System.Windows.Forms.Button Me.Label1 = New System.Windows.Forms.Label CType(Me.LogoPictureBox, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'LogoPictureBox ' Me.LogoPictureBox.Image = CType(resources.GetObject("LogoPictureBox.Image"), System.Drawing.Image) Me.LogoPictureBox.Location = New System.Drawing.Point(0, 0) Me.LogoPictureBox.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.LogoPictureBox.Name = "LogoPictureBox" Me.LogoPictureBox.Size = New System.Drawing.Size(165, 234) Me.LogoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.LogoPictureBox.TabIndex = 0 Me.LogoPictureBox.TabStop = False ' 'UsernameLabel ' Me.UsernameLabel.Location = New System.Drawing.Point(172, 22) Me.UsernameLabel.Name = "UsernameLabel" Me.UsernameLabel.Size = New System.Drawing.Size(220, 32) Me.UsernameLabel.TabIndex = 0 Me.UsernameLabel.Text = "အမည္" Me.UsernameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft ' 'PasswordLabel ' Me.PasswordLabel.Location = New System.Drawing.Point(172, 101) Me.PasswordLabel.Name = "PasswordLabel" Me.PasswordLabel.Size = New System.Drawing.Size(220, 32) Me.PasswordLabel.TabIndex = 2 Me.PasswordLabel.Text = "စကားဝွက္" Me.PasswordLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft ' 'txtUser ' Me.txtUser.Location = New System.Drawing.Point(174, 50) Me.txtUser.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.txtUser.Name = "txtUser" Me.txtUser.Size = New System.Drawing.Size(220, 25) Me.txtUser.TabIndex = 1 ' 'txtPass ' Me.txtPass.Location = New System.Drawing.Point(174, 129) Me.txtPass.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.txtPass.Name = "txtPass" Me.txtPass.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42) Me.txtPass.Size = New System.Drawing.Size(220, 25) Me.txtPass.TabIndex = 3 ' 'OK ' Me.OK.Location = New System.Drawing.Point(198, 178) Me.OK.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.OK.Name = "OK" Me.OK.Size = New System.Drawing.Size(94, 32) Me.OK.TabIndex = 4 Me.OK.Text = "&OK" ' 'Cancel ' Me.Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.Cancel.Location = New System.Drawing.Point(298, 178) Me.Cancel.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.Cancel.Name = "Cancel" Me.Cancel.Size = New System.Drawing.Size(94, 32) Me.Cancel.TabIndex = 5 Me.Cancel.Text = "&Cancel" ' 'btnChangeUnmae ' Me.btnChangeUnmae.Location = New System.Drawing.Point(400, 50) Me.btnChangeUnmae.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.btnChangeUnmae.Name = "btnChangeUnmae" Me.btnChangeUnmae.Size = New System.Drawing.Size(116, 160) Me.btnChangeUnmae.TabIndex = 6 Me.btnChangeUnmae.Text = "အမည္ႏွင္႔ စကားဝွက္ ေျပာင္းလဲရန္" ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Font = New System.Drawing.Font("Zawgyi-One", 11.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label1.ForeColor = System.Drawing.Color.Blue Me.Label1.Location = New System.Drawing.Point(244, 9) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(272, 25) Me.Label1.TabIndex = 7 Me.Label1.Text = "default အမည္=admin, စကားဝွက္=admin" ' 'LoginForm1 ' Me.AcceptButton = Me.OK Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 18.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.CancelButton = Me.Cancel Me.ClientSize = New System.Drawing.Size(528, 234) Me.Controls.Add(Me.Label1) Me.Controls.Add(Me.btnChangeUnmae) Me.Controls.Add(Me.Cancel) Me.Controls.Add(Me.OK) Me.Controls.Add(Me.txtPass) Me.Controls.Add(Me.txtUser) Me.Controls.Add(Me.PasswordLabel) Me.Controls.Add(Me.UsernameLabel) Me.Controls.Add(Me.LogoPictureBox) Me.Font = New System.Drawing.Font("Zawgyi-One", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "LoginForm1" Me.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Login @ Activation Code 2014" CType(Me.LogoPictureBox, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents btnChangeUnmae As System.Windows.Forms.Button Friend WithEvents Label1 As System.Windows.Forms.Label End Class
mmgreenhacker/CodeFinal
VB/Activation Test Project/CipherCad2011-Source/LoginForm1.Designer.vb
Visual Basic
mit
7,488
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Test.Utilities.EmbeddedLanguages Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Classification <Trait(Traits.Feature, Traits.Features.Classification)> Public Class SemanticClassifierTests Inherits AbstractVisualBasicClassifierTests Protected Overrides Async Function GetClassificationSpansAsync(code As String, span As TextSpan, parseOptions As ParseOptions, testHost As TestHost) As Task(Of ImmutableArray(Of ClassifiedSpan)) Using workspace = CreateWorkspace(code, testHost) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Return Await GetSemanticClassificationsAsync(document, span) End Using End Function <Theory, CombinatorialData> Public Async Function TestTypeName1(testHost As TestHost) As Task Await TestInMethodAsync( className:="C(Of T)", methodName:="M", code:="Dim x As New C(Of Integer)()", testHost, [Class]("C")) End Function <Theory, CombinatorialData> Public Async Function TestImportsType(testHost As TestHost) As Task Await TestAsync("Imports System.Console", testHost, [Namespace]("System"), [Class]("Console")) End Function <Theory, CombinatorialData> Public Async Function TestImportsAlias(testHost As TestHost) As Task Await TestAsync("Imports M = System.Math", testHost, [Class]("M"), [Namespace]("System"), [Class]("Math")) End Function <Theory, CombinatorialData> Public Async Function TestMSCorlibTypes(testHost As TestHost) As Task Dim code = "Imports System Module Program Sub Main(args As String()) Console.WriteLine() End Sub End Module" Await TestAsync(code, testHost, [Namespace]("System"), [Class]("Console"), Method("WriteLine"), [Static]("WriteLine")) End Function <Theory, CombinatorialData> Public Async Function TestConstructedGenericWithInvalidTypeArg(testHost As TestHost) As Task Await TestInMethodAsync( className:="C(Of T)", methodName:="M", code:="Dim x As New C(Of UnknownType)()", testHost:=testHost, [Class]("C")) End Function <Theory, CombinatorialData> Public Async Function TestMethodCall(testHost As TestHost) As Task Await TestInMethodAsync( className:="Program", methodName:="M", code:="Program.Main()", testHost:=testHost, [Class]("Program")) End Function <Theory, CombinatorialData> <WorkItem(538647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538647")> Public Async Function TestRegression4315_VariableNamesClassifiedAsType(testHost As TestHost) As Task Dim code = "Module M Sub S() Dim goo End Sub End Module" Await TestAsync(code, testHost) End Function <Theory, CombinatorialData> <WorkItem(541267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541267")> Public Async Function TestRegression7925_TypeParameterCantCastToMethod(testHost As TestHost) As Task Dim code = "Class C Sub GenericMethod(Of T1)(i As T1) End Sub End Class" Await TestAsync(code, testHost, TypeParameter("T1")) End Function <Theory, CombinatorialData> <WorkItem(541610, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541610")> Public Async Function TestRegression8394_AliasesShouldBeClassified1(testHost As TestHost) As Task Dim code = "Imports S = System.String Class T Dim x As S = ""hello"" End Class" Await TestAsync(code, testHost, [Class]("S"), [Namespace]("System"), [Class]("String"), [Class]("S")) End Function <Theory, CombinatorialData> <WorkItem(541610, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541610")> Public Async Function TestRegression8394_AliasesShouldBeClassified2(testHost As TestHost) As Task Dim code = "Imports D = System.IDisposable Class T Dim x As D = Nothing End Class" Await TestAsync(code, testHost, [Interface]("D"), [Namespace]("System"), [Interface]("IDisposable"), [Interface]("D")) End Function <Theory, CombinatorialData> Public Async Function TestConstructorNew1(testHost As TestHost) As Task Dim code = "Class C Sub New End Sub Sub [New] End Sub Sub New(x) Me.New End Sub End Class" Await TestAsync(code, testHost, Keyword("New")) End Function <Theory, CombinatorialData> Public Async Function TestConstructorNew2(testHost As TestHost) As Task Dim code = "Class B Sub New() End Sub End Class Class C Inherits B Sub New(x As Integer) MyBase.New End Sub End Class" Await TestAsync(code, testHost, [Class]("B"), Keyword("New")) End Function <Theory, CombinatorialData> Public Async Function TestConstructorNew3(testHost As TestHost) As Task Dim code = "Class C Sub New End Sub Sub [New] End Sub Sub New(x) MyClass.New End Sub End Class" Await TestAsync(code, testHost, Keyword("New")) End Function <Theory, CombinatorialData> Public Async Function TestConstructorNew4(testHost As TestHost) As Task Dim code = "Class C Sub New End Sub Sub [New] End Sub Sub New(x) With Me .New End With End Sub End Class" Await TestAsync(code, testHost, Keyword("New")) End Function <Theory, CombinatorialData> Public Async Function TestAlias(testHost As TestHost) As Task Dim code = "Imports E = System.Exception Class C Inherits E End Class" Await TestAsync(code, testHost, [Class]("E"), [Namespace]("System"), [Class]("Exception"), [Class]("E")) End Function <WorkItem(542685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")> <Theory, CombinatorialData> Public Async Function TestOptimisticallyColorFromInDeclaration(testHost As TestHost) As Task Await TestInExpressionAsync("From ", testHost, Keyword("From")) End Function <WorkItem(542685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")> <Theory, CombinatorialData> Public Async Function TestOptimisticallyColorFromInAssignment(testHost As TestHost) As Task Dim code = "Dim q = 3 q = From" Await TestInMethodAsync(code, testHost, Local("q"), Keyword("From")) End Function <WorkItem(542685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")> <Theory, CombinatorialData> Public Async Function TestDontColorThingsOtherThanFromInDeclaration(testHost As TestHost) As Task Await TestInExpressionAsync("Fro ", testHost) End Function <WorkItem(542685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")> <Theory, CombinatorialData> Public Async Function TestDontColorThingsOtherThanFromInAssignment(testHost As TestHost) As Task Dim code = "Dim q = 3 q = Fro " Await TestInMethodAsync(code, testHost, Local("q")) End Function <WorkItem(542685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")> <Theory, CombinatorialData> Public Async Function TestDontColorFromWhenBoundInDeclaration(testHost As TestHost) As Task Dim code = "Dim From = 3 Dim q = From" Await TestInMethodAsync(code, testHost, Local("From")) End Function <Theory, CombinatorialData> <WorkItem(542685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542685")> Public Async Function TestDontColorFromWhenBoundInAssignment(testHost As TestHost) As Task Dim code = "Dim From = 3 Dim q = 3 q = From" Await TestInMethodAsync(code, testHost, Local("q"), Local("From")) End Function <Theory, CombinatorialData> <WorkItem(10507, "DevDiv_Projects/Roslyn")> Public Async Function TestArraysInGetType(testHost As TestHost) As Task Await TestInMethodAsync("GetType(System.Exception()", testHost, [Namespace]("System"), [Class]("Exception")) Await TestInMethodAsync("GetType(System.Exception(,)", testHost, [Namespace]("System"), [Class]("Exception")) End Function <Theory, CombinatorialData> Public Async Function TestNewOfInterface(testHost As TestHost) As Task Await TestInMethodAsync("Dim a = New System.IDisposable()", testHost, [Namespace]("System"), [Interface]("IDisposable")) End Function <WorkItem(543404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543404")> <Theory, CombinatorialData> Public Async Function TestNewOfClassWithNoPublicConstructors(testHost As TestHost) As Task Dim code = "Public Class C1 Private Sub New() End Sub End Class Module Program Sub Main() Dim f As New C1() End Sub End Module" Await TestAsync(code, testHost, [Class]("C1")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestAsyncKeyword1(testHost As TestHost) As Task Dim code = "Class C Sub M() Dim x = Async End Sub End Class" Await TestAsync(code, testHost, Keyword("Async")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestAsyncKeyword2(testHost As TestHost) As Task Dim code = "Class C Sub M() Dim x = Async S End Sub End Class" Await TestAsync(code, testHost, Keyword("Async")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestAsyncKeyword3(testHost As TestHost) As Task Dim code = "Class C Sub M() Dim x = Async Su End Sub End Class" Await TestAsync(code, testHost, Keyword("Async")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestAsyncKeyword4(testHost As TestHost) As Task Dim code = "Class C Async End Class" Await TestAsync(code, testHost, Keyword("Async")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestAsyncKeyword5(testHost As TestHost) As Task Dim code = "Class C Private Async End Class" Await TestAsync(code, testHost, Keyword("Async")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestAsyncKeyword6(testHost As TestHost) As Task Dim code = "Class C Private Async As End Class" Await TestAsync(code, testHost) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestAsyncKeyword7(testHost As TestHost) As Task Dim code = "Class C Private Async = End Class" Await TestAsync(code, testHost) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestIteratorKeyword1(testHost As TestHost) As Task Dim code = "Class C Sub M() Dim x = Iterator End Sub End Class" Await TestAsync(code, testHost, Keyword("Iterator")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestIteratorKeyword2(testHost As TestHost) As Task Dim code = "Class C Sub M() Dim x = Iterator F End Sub End Class" Await TestAsync(code, testHost, Keyword("Iterator")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestIteratorKeyword3(testHost As TestHost) As Task Dim code = "Class C Sub M() Dim x = Iterator Functio End Sub End Class" Await TestAsync(code, testHost, Keyword("Iterator")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestIteratorKeyword4(testHost As TestHost) As Task Dim code = "Class C Iterator End Class" Await TestAsync(code, testHost, Keyword("Iterator")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestIteratorKeyword5(testHost As TestHost) As Task Dim code = "Class C Private Iterator End Class" Await TestAsync(code, testHost, Keyword("Iterator")) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestIteratorKeyword6(testHost As TestHost) As Task Dim code = "Class C Private Iterator As End Class" Await TestAsync(code, testHost) End Function <WorkItem(578145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578145")> <Theory, CombinatorialData> Public Async Function TestIteratorKeyword7(testHost As TestHost) As Task Dim code = "Class C Private Iterator = End Class" Await TestAsync(code, testHost) End Function <Theory, CombinatorialData> Public Async Function TestMyNamespace(testHost As TestHost) As Task Dim code = "Class C Sub M() Dim m = My.Goo End Sub End Class" Await TestAsync(code, testHost, Keyword("My")) End Function <Theory, CombinatorialData> Public Async Function TestAwaitInNonAsyncFunction1(testHost As TestHost) As Task Dim code = "dim m = Await" Await TestInMethodAsync(code, testHost, Keyword("Await")) End Function <Theory, CombinatorialData> Public Async Function TestAwaitInNonAsyncFunction2(testHost As TestHost) As Task Dim code = "sub await() end sub sub test() dim m = Await end sub" Await TestInClassAsync(code, testHost, Method("Await")) End Function <Theory, CombinatorialData> <WorkItem(21524, "https://github.com/dotnet/roslyn/issues/21524")> Public Async Function TestAttribute(testHost As TestHost) As Task Dim code = "Imports System <AttributeUsage()> Class Program End Class" Await TestAsync(code, testHost, [Namespace]("System"), [Class]("AttributeUsage")) End Function <WpfTheory, CombinatorialData> Public Async Function TestRegex1(testHost As TestHost) As Task Await TestAsync( " imports System.Text.RegularExpressions class Program sub Goo() ' language=regex var r = ""$(\b\G\z)|(?<name>sub){0,5}?^"" end sub end class", testHost, [Namespace]("System"), [Namespace]("Text"), [Namespace]("RegularExpressions"), Regex.Anchor("$"), Regex.Grouping("("), Regex.Anchor("\"), Regex.Anchor("b"), Regex.Anchor("\"), Regex.Anchor("G"), Regex.Anchor("\"), Regex.Anchor("z"), Regex.Grouping(")"), Regex.Alternation("|"), Regex.Grouping("("), Regex.Grouping("?"), Regex.Grouping("<"), Regex.Grouping("name"), Regex.Grouping(">"), Regex.Text("sub"), Regex.Grouping(")"), Regex.Quantifier("{"), Regex.Quantifier("0"), Regex.Quantifier(","), Regex.Quantifier("5"), Regex.Quantifier("}"), Regex.Quantifier("?"), Regex.Anchor("^")) End Function <WpfTheory, CombinatorialData> Public Async Function TestRegexStringSyntaxAttribute_Field(testHost As TestHost) As Task Await TestAsync( " imports System.Diagnostics.CodeAnalysis imports System.Text.RegularExpressions class Program <StringSyntax(StringSyntaxAttribute.Regex)> dim field as string sub Goo() [|me.field = ""$(\b\G\z)""|] end sub end class" & EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeVB, testHost, Field("field"), Regex.Anchor("$"), Regex.Grouping("("), Regex.Anchor("\"), Regex.Anchor("b"), Regex.Anchor("\"), Regex.Anchor("G"), Regex.Anchor("\"), Regex.Anchor("z"), Regex.Grouping(")")) End Function <WpfTheory, CombinatorialData> Public Async Function TestRegexStringSyntaxAttribute_Attribute(testHost As TestHost) As Task Await TestAsync( " imports system imports System.Diagnostics.CodeAnalysis imports System.Text.RegularExpressions <AttributeUsage(AttributeTargets.Field)> class RegexTestAttribute inherits Attribute public sub new(<StringSyntax(StringSyntaxAttribute.Regex)> value as string) end sub end class class Program [|<RegexTest(""$(\b\G\z)"")>|] dim field as string end class" & EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeVB, testHost, [Class]("RegexTest"), Regex.Anchor("$"), Regex.Grouping("("), Regex.Anchor("\"), Regex.Anchor("b"), Regex.Anchor("\"), Regex.Anchor("G"), Regex.Anchor("\"), Regex.Anchor("z"), Regex.Grouping(")")) End Function <WpfTheory, CombinatorialData> Public Async Function TestRegexStringSyntaxAttribute_Property(testHost As TestHost) As Task Await TestAsync( " imports System.Diagnostics.CodeAnalysis imports System.Text.RegularExpressions class Program <StringSyntax(StringSyntaxAttribute.Regex)> property prop as string sub Goo() [|me.prop = ""$(\b\G\z)""|] end sub end class" & EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeVB, testHost, [Property]("prop"), Regex.Anchor("$"), Regex.Grouping("("), Regex.Anchor("\"), Regex.Anchor("b"), Regex.Anchor("\"), Regex.Anchor("G"), Regex.Anchor("\"), Regex.Anchor("z"), Regex.Grouping(")")) End Function <WpfTheory, CombinatorialData> Public Async Function TestRegexStringSyntaxAttribute_Sub(testHost As TestHost) As Task Await TestAsync( " imports System.Diagnostics.CodeAnalysis imports System.Text.RegularExpressions class Program sub M(<StringSyntax(StringSyntaxAttribute.Regex)>p as string) end sub sub Goo() [|M(""$(\b\G\z)"")|] end sub end class" & EmbeddedLanguagesTestConstants.StringSyntaxAttributeCodeVB, testHost, Method("M"), Regex.Anchor("$"), Regex.Grouping("("), Regex.Anchor("\"), Regex.Anchor("b"), Regex.Anchor("\"), Regex.Anchor("G"), Regex.Anchor("\"), Regex.Anchor("z"), Regex.Grouping(")")) End Function <Theory, CombinatorialData> Public Async Function TestConstField(testHost As TestHost) As Task Dim code = "Const Number = 42 Dim x As Integer = Number" Await TestInClassAsync(code, testHost, Constant("Number"), [Static]("Number")) End Function <Theory, CombinatorialData> Public Async Function TestConstLocal(testHost As TestHost) As Task Dim code = "Const Number = 42 Dim x As Integer = Number" Await TestInMethodAsync(code, testHost, Constant("Number")) End Function <Theory, CombinatorialData> Public Async Function TestModifiedIdentifiersInLocals(testHost As TestHost) As Task Dim code = "Dim x$ = ""23"" x$ = ""19""" Await TestInMethodAsync(code, testHost, Local("x$")) End Function <Theory, CombinatorialData> Public Async Function TestModifiedIdentifiersInFields(testHost As TestHost) As Task Dim code = "Const x$ = ""23"" Dim y$ = x$" Await TestInClassAsync(code, testHost, Constant("x$"), [Static]("x$")) End Function <Theory, CombinatorialData> Public Async Function TestFunctionNamesWithTypeCharacters(testHost As TestHost) As Task Dim code = "Function x%() x% = 42 End Function" Await TestInClassAsync(code, testHost, Local("x%")) End Function <Theory, CombinatorialData> Public Async Function TestExtensionMethod(testHost As TestHost) As Task Dim code = " Imports System.Runtime.CompilerServices Module M <Extension> Sub Square(ByRef x As Integer) x = x * x End Sub End Module Class C Sub Test() Dim x = 42 x.Square() M.Square(x) End Sub End Class" Await TestAsync(code, testHost, [Namespace]("System"), [Namespace]("Runtime"), [Namespace]("CompilerServices"), [Class]("Extension"), ExtensionMethod("Square"), Parameter("x"), Parameter("x"), Parameter("x"), Local("x"), ExtensionMethod("Square"), [Module]("M"), Method("Square"), [Static]("Square"), Local("x")) End Function <Theory, CombinatorialData> Public Async Function TestSimpleEvent(testHost As TestHost) As Task Dim code = " Event E(x As Integer) Sub M() RaiseEvent E(42) End Sub" Await TestInClassAsync(code, testHost, [Event]("E")) End Function <Theory, CombinatorialData> Public Async Function TestOperators(testHost As TestHost) As Task Dim code = " Public Shared Operator Not(t As Test) As Test Return New Test() End Operator Public Shared Operator +(t1 As Test, t2 As Test) As Integer Return 1 End Operator" Await TestInClassAsync(code, testHost) End Function <Theory, CombinatorialData> Public Async Function TestStringEscape1(testHost As TestHost) As Task Await TestInMethodAsync("dim goo = ""goo""""bar""", testHost, Escape("""""")) End Function <Theory, CombinatorialData> Public Async Function TestStringEscape2(testHost As TestHost) As Task Await TestInMethodAsync("dim goo = $""goo{{1}}bar""", testHost, Escape("{{"), Escape("}}")) End Function <Theory, CombinatorialData> Public Async Function TestStringEscape3(testHost As TestHost) As Task Await TestInMethodAsync("dim goo = $""goo""""{{1}}""""bar""", testHost, Escape(""""""), Escape("{{"), Escape("}}"), Escape("""""")) End Function <Theory, CombinatorialData> Public Async Function TestStringEscape4(testHost As TestHost) As Task Await TestInMethodAsync("dim goo = $""goo""""{1}""""bar""", testHost, Escape(""""""), Escape("""""")) End Function <Theory, CombinatorialData> Public Async Function TestStringEscape5(testHost As TestHost) As Task Await TestInMethodAsync("dim goo = $""{{goo{1}bar}}""", testHost, Escape("{{"), Escape("}}")) End Function <WorkItem(29451, "https://github.com/dotnet/roslyn/issues/29451")> <Theory, CombinatorialData> Public Async Function TestDirectiveStringLiteral(testHost As TestHost) As Task Await TestAsync("#region ""goo""""bar""", testHost, Escape("""""")) End Function <WorkItem(30378, "https://github.com/dotnet/roslyn/issues/30378")> <Theory, CombinatorialData> Public Async Function TestFormatSpecifierInInterpolation(testHost As TestHost) As Task Await TestInMethodAsync("dim goo = $""goo{{1:0000}}bar""", testHost, Escape("{{"), Escape("}}")) End Function <Theory, CombinatorialData> Public Async Function TestLabelName(testHost As TestHost) As Task Dim code = " Sub M() E: GoTo E End Sub" Await TestInClassAsync(code, testHost, [Label]("E")) End Function <WorkItem(29492, "https://github.com/dotnet/roslyn/issues/29492")> <Theory, CombinatorialData> Public Async Function TestOperatorOverloads_BinaryExpression(testHost As TestHost) As Task Dim code = "Class C Public Sub M(a As C) Dim b = 1 + 1 Dim c = a + Me End Sub Public Shared Operator +(a As C, b As C) As C Return New C End Operator End Class" Await TestAsync(code, testHost, [Class]("C"), Parameter("a"), OverloadedOperators.Plus, [Class]("C"), [Class]("C"), [Class]("C"), [Class]("C")) End Function <WorkItem(29492, "https://github.com/dotnet/roslyn/issues/29492")> <Theory, CombinatorialData> Public Async Function TestOperatorOverloads_UnaryExpression(testHost As TestHost) As Task Dim code = "Class C Public Sub M() Dim b = -1 Dim c = -Me End Sub Public Shared Operator -(a As C) As C Return New C End Operator End Class" Await TestAsync(code, testHost, OverloadedOperators.Minus, [Class]("C"), [Class]("C"), [Class]("C")) End Function <Theory, CombinatorialData> Public Async Function TestCatchStatement(testHost As TestHost) As Task Dim code = "Try Catch ex As Exception Throw ex End Try" Await TestInMethodAsync(code, testHost, Local("ex"), [Class]("Exception"), Local("ex")) End Function End Class End Namespace
CyrusNajmabadi/roslyn
src/EditorFeatures/VisualBasicTest/Classification/SemanticClassifierTests.vb
Visual Basic
mit
29,228
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.MoveDeclarationNearReference Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.MoveDeclarationNearReference Public Class MoveDeclarationNearReferenceTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New MoveDeclarationNearReferenceCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestMove1() As Task Await TestInRegularAndScriptAsync( "class C sub M() dim [||]x as integer if true Console.WriteLine(x) end if end sub end class", "class C sub M() if true dim x as integer Console.WriteLine(x) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestMove2() As Task Await TestInRegularAndScriptAsync( "class C sub M() dim [||]x as integer Console.WriteLine() Console.WriteLine(x) end sub end class", "class C sub M() Console.WriteLine() dim x as integer Console.WriteLine(x) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestMove3() As Task Await TestInRegularAndScriptAsync( "class C sub M() dim [||]x as integer Console.WriteLine() if true Console.WriteLine(x) end if if true Console.WriteLine(x) end if end sub end class", "class C sub M() Console.WriteLine() dim x as integer if true Console.WriteLine(x) end if if true Console.WriteLine(x) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestMove4() As Task Await TestInRegularAndScriptAsync( "class C sub M() dim [||]x as integer Console.WriteLine() if true Console.WriteLine(x) end if end sub end class", "class C sub M() Console.WriteLine() if true dim x as integer Console.WriteLine(x) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestAssign1() As Task Await TestInRegularAndScriptAsync( "class C sub M() dim [||]x as integer if true x = 5 Console.WriteLine(x) end if end sub end class", "class C sub M() if true dim x as integer = 5 Console.WriteLine(x) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestAssign2() As Task Await TestInRegularAndScriptAsync( "class C sub M() dim [||]x as integer = 0 if true x = 5 Console.WriteLine(x) end if end sub end class", "class C sub M() if true dim x as integer = 5 Console.WriteLine(x) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestAssign3() As Task Await TestInRegularAndScriptAsync( "class C sub M() dim [||]x = ctype(0, integer) if true x = 5 Console.WriteLine(x) end if end sub end class", "class C sub M() if true dim x = ctype(0, integer) x = 5 Console.WriteLine(x) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestMissing1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M() dim [||]x as integer Console.WriteLine(x) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestMissingWhenReferencedInDeclaration() As Task Await TestMissingInRegularAndScriptAsync( "class Program sub M() dim [||]x as object() = { x } x.ToString() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestMissingWhenInDeclarationGroup() As Task Await TestMissingInRegularAndScriptAsync( "class Program sub M() dim [||]i as integer = 5 dim j as integer = 10 Console.WriteLine(i) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestWarnOnChangingScopes1() As Task Await TestInRegularAndScriptAsync( "imports System.Linq class Program sub M() dim [||]gate = new object() dim x = sub() Console.WriteLine(gate) end sub() end sub end class", "imports System.Linq class Program sub M() dim x = sub() {|Warning:dim gate = new object()|} Console.WriteLine(gate) end sub() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function TestWarnOnChangingScopes2() As Task Await TestAsync( "using System using System.Linq class Program sub M() dim [||]i = 0 for each (v in x) Console.Write(i) i = i + 1 next end sub end class", "using System using System.Linq class Program sub M() for each (v in x) {|Warning:dim i = CInt(0)|} Console.Write(i) i = i + 1 next end sub end class", parseOptions:=Nothing) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)> Public Async Function MissingIfNotInDeclarationSpan() As Task Await TestMissingInRegularAndScriptAsync( "using System using System.Collections.Generic using System.Linq class Program sub M() ' Comment [||]about goo! ' Comment about goo! ' Comment about goo! ' Comment about goo! ' Comment about goo! ' Comment about goo! ' Comment about goo! dim goo = 0 Console.WriteLine() Console.WriteLine(goo) end sub end class") End Function End Class End Namespace
DustinCampbell/roslyn
src/EditorFeatures/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb
Visual Basic
apache-2.0
7,585
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.SigningTestHelpers Partial Public Class InternalsVisibleToAndStrongNameTests Inherits BasicTestBase #Region "Helpers" Public Sub New() SigningTestHelpers.InstallKey() End Sub Private Shared ReadOnly s_keyPairFile As String = SigningTestHelpers.KeyPairFile Private Shared ReadOnly s_publicKeyFile As String = SigningTestHelpers.PublicKeyFile Private Shared ReadOnly s_publicKey As ImmutableArray(Of Byte) = SigningTestHelpers.PublicKey Private Shared Function GetDesktopProviderWithPath(keyFilePath As String) As StrongNameProvider Return New DesktopStrongNameProvider(ImmutableArray.Create(keyFilePath), Nothing, New VirtualizedStrongNameFileSystem()) End Function Private Shared Sub VerifySigned(comp As Compilation, Optional expectedToBeSigned As Boolean = True) Using outStream = comp.EmitToStream() outStream.Position = 0 Dim headers = New PEHeaders(outStream) Assert.Equal(expectedToBeSigned, headers.CorHeader.Flags.HasFlag(CorFlags.StrongNameSigned)) End Using End Sub #End Region #Region "Naming Tests" <Fact> Public Sub PubKeyFromKeyFileAttribute() Dim x = s_keyPairFile Dim s = "<Assembly: System.Reflection.AssemblyKeyFile(""" & x & """)>" & vbCrLf & "Public Class C" & vbCrLf & "End Class" Dim g = Guid.NewGuid() Dim other = VisualBasicCompilation.Create( g.ToString(), {VisualBasicSyntaxTree.ParseText(s)}, {MscorlibRef}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver() Dim keyFileDir = Path.GetDirectoryName(s_keyPairFile) Dim keyFileName = Path.GetFileName(s_keyPairFile) Dim s = "<Assembly: System.Reflection.AssemblyKeyFile(""" & keyFileName & """)>" & vbCrLf & "Public Class C" & vbCrLf & "End Class" Dim syntaxTree = ParseAndVerify(s) ' verify failure with default assembly key file resolver Dim comp = CreateCompilationWithMscorlib40({syntaxTree}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound)) Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty) ' verify success with custom assembly key file resolver with keyFileDir added to search paths comp = VisualBasicCompilation.Create( GetUniqueName(), {syntaxTree}, {MscorlibRef}, TestOptions.ReleaseDll.WithStrongNameProvider(GetDesktopProviderWithPath(keyFileDir))) comp.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver_RelativeToCurrentParent() Dim keyFileDir = Path.GetDirectoryName(s_keyPairFile) Dim keyFileName = Path.GetFileName(s_keyPairFile) Dim s = "<Assembly: System.Reflection.AssemblyKeyFile(""..\" & keyFileName & """)>" & vbCrLf & "Public Class C" & vbCrLf & "End Class" Dim syntaxTree = ParseAndVerify(s) ' verify failure with default assembly key file resolver Dim comp As Compilation = CreateCompilationWithMscorlib40({syntaxTree}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments("..\" & keyFileName, CodeAnalysisResources.FileNotFound)) Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty) ' verify success with custom assembly key file resolver with keyFileDir\TempSubDir added to search paths comp = VisualBasicCompilation.Create( GetUniqueName(), references:={MscorlibRef}, syntaxTrees:={syntaxTree}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(GetDesktopProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, "TempSubDir\")))) comp.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyContainerAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileOptions() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileOptions_ReferenceResolver() Dim keyFileDir = Path.GetDirectoryName(s_keyPairFile) Dim keyFileName = Path.GetFileName(s_keyPairFile) Dim source = <![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> Dim references = {MscorlibRef} Dim syntaxTrees = {ParseAndVerify(source)} ' verify failure with default resolver Dim comp = VisualBasicCompilation.Create( GetUniqueName(), references:=references, syntaxTrees:=syntaxTrees, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(s_defaultDesktopProvider)) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound)) Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty) ' verify success with custom assembly key file resolver with keyFileDir added to search paths comp = VisualBasicCompilation.Create( GetUniqueName(), references:=references, syntaxTrees:=syntaxTrees, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(GetDesktopProviderWithPath(keyFileDir))) comp.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileOptionsJustPublicKey() Dim s = <compilation> <file name="Clavelle.vb"><![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation> Dim other = CreateCompilationWithMscorlib40(s, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) Assert.Empty(other.GetDiagnostics()) Assert.True(ByteSequenceComparer.Equals(TestResources.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileOptionsJustPublicKey_ReferenceResolver() Dim publicKeyFileDir = Path.GetDirectoryName(s_publicKeyFile) Dim publicKeyFileName = Path.GetFileName(s_publicKeyFile) Dim source = <![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> Dim references = {MscorlibRef} Dim syntaxTrees = {ParseAndVerify(source)} ' verify failure with default resolver Dim comp = VisualBasicCompilation.Create( GetUniqueName(), references:=references, syntaxTrees:=syntaxTrees, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) ' error CS7027: Error extracting public key from file 'PublicKeyFile.snk' -- File not found. ' warning CS7033: Delay signing was specified and requires a public key, but no public key was specified comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments(publicKeyFileName, CodeAnalysisResources.FileNotFound), Diagnostic(ERRID.WRN_DelaySignButNoKey)) Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty) ' verify success with custom assembly key file resolver with publicKeyFileDir added to search paths comp = VisualBasicCompilation.Create( GetUniqueName(), references:=references, syntaxTrees:=syntaxTrees, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(True).WithStrongNameProvider(GetDesktopProviderWithPath(publicKeyFileDir))) comp.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFileNotFoundOptions() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseExe.WithCryptoKeyFile("goo").WithStrongNameProvider(s_defaultDesktopProvider)) CompilationUtils.AssertTheseDeclarationDiagnostics(other, <errors> BC36980: Error extracting public key from file 'goo': <%= CodeAnalysisResources.FileNotFound %> </errors>) Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub <Fact> Public Sub KeyFileAttributeEmpty() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyFile("")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub <Fact> Public Sub KeyContainerEmpty() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub <Fact> Public Sub PublicKeyFromOptions_DelaySigned() Dim source = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyDelaySign(True)> Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey)) c.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)) Dim Metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()) Dim identity = Metadata.Module.ReadAssemblyIdentityOrThrow() Assert.True(identity.HasPublicKey) AssertEx.Equal(identity.PublicKey, s_publicKey) Assert.Equal(CorFlags.ILOnly, Metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags) End Sub <Fact> <WorkItem(11427, "https://github.com/dotnet/roslyn/issues/11427")> Public Sub PublicKeyFromOptions_PublicSign() ' attributes are ignored Dim source = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> <assembly: System.Reflection.AssemblyKeyFile("some file")> Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey).WithPublicSign(True)) c.AssertTheseDiagnostics( <expected> BC42379: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. BC42379: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. </expected> ) Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)) Dim Metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()) Dim identity = Metadata.Module.ReadAssemblyIdentityOrThrow() Assert.True(identity.HasPublicKey) AssertEx.Equal(identity.PublicKey, s_publicKey) Assert.Equal(CorFlags.ILOnly Or CorFlags.StrongNameSigned, Metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags) c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseModule.WithCryptoPublicKey(s_publicKey).WithPublicSign(True)) c.AssertTheseDiagnostics( <expected> BC37282: Public signing is not supported for netmodules. </expected> ) c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseModule.WithCryptoKeyFile(s_publicKeyFile).WithPublicSign(True)) c.AssertTheseDiagnostics( <expected> BC37207: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. BC37282: Public signing is not supported for netmodules. </expected> ) Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim source1 = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> <assembly: System.Reflection.AssemblyKeyFile("]]><%= snk.Path %><![CDATA[")> Public Class C End Class ]]> </file> </compilation> c = CreateCompilationWithMscorlib40(source1, options:=TestOptions.ReleaseModule.WithCryptoKeyFile(snk.Path).WithPublicSign(True)) c.AssertTheseDiagnostics( <expected> BC37282: Public signing is not supported for netmodules. </expected> ) End Sub <Fact> Public Sub PublicKeyFromOptions_InvalidCompilationOptions() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll. WithCryptoPublicKey(ImmutableArray.Create(Of Byte)(1, 2, 3)). WithCryptoKeyContainer("roslynTestContainer"). WithCryptoKeyFile("file.snk"). WithStrongNameProvider(s_defaultDesktopProvider)) AssertTheseDiagnostics(c, <error> BC2014: the value '01-02-03' is invalid for option 'CryptoPublicKey' BC2046: Compilation options 'CryptoPublicKey' and 'CryptoKeyContainer' can't both be specified at the same time. BC2046: Compilation options 'CryptoPublicKey' and 'CryptoKeyFile' can't both be specified at the same time. </error>) End Sub <Fact> Public Sub PubKeyFileBogusOptions() Dim tmp = Temp.CreateFile().WriteAllBytes(New Byte() {1, 2, 3, 4}) Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file> <![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(tmp.Path).WithStrongNameProvider(New DesktopStrongNameProvider())) other.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments(tmp.Path, CodeAnalysisResources.InvalidPublicKey)) Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub <Fact> Public Sub PubKeyContainerBogusOptions() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseExe.WithCryptoKeyContainer("goo").WithStrongNameProvider(s_defaultDesktopProvider)) ' CompilationUtils.AssertTheseDeclarationDiagnostics(other, ' <errors> 'BC36981: Error extracting public key from container 'goo': Keyset does not exist (Exception from HRESULT: 0x80090016) ' </errors>) Dim err = other.GetDeclarationDiagnostics().Single() Assert.Equal(ERRID.ERR_PublicKeyContainerFailure, err.Code) Assert.Equal(2, err.Arguments.Count) Assert.Equal("goo", DirectCast(err.Arguments(0), String)) Dim errorText = DirectCast(err.Arguments(1), String) Assert.True( errorText.Contains("HRESULT") AndAlso errorText.Contains("0x80090016")) Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub #End Region #Region "IVT Access checking" <Fact> Public Sub IVTBasicCompilation() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="HasIVTToCompilation"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccess")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim c As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccessButCantHave"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New(o As C) o.Goo() End Sub End Class End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) 'compilation should not succeed, and internals should not be imported. c.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(c, <error> BC30390: 'C.Friend Sub Goo()' is not accessible in this context because it is 'Friend'. o.Goo() ~~~~~ </error>) Dim c2 As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New(o As C) o.Goo() End Sub End Class End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) c2.VerifyDiagnostics() End Sub <Fact> Public Sub IVTBasicMetadata() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="HasIVTToCompilation"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccess")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Dim otherImage = other.EmitToArray() Dim c As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccessButCantHave"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New(o As C) o.Goo() End Sub End Class End Class ]]> </file> </compilation>, {MetadataReference.CreateFromImage(otherImage)}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) 'compilation should not succeed, and internals should not be imported. c.GetDiagnostics() 'gives "is not a member" error because internals were not imported because no IVT was found 'on HasIVTToCompilation that referred to WantsIVTAccessButCantHave CompilationUtils.AssertTheseDiagnostics(c, <error> BC30456: 'Goo' is not a member of 'C'. o.Goo() ~~~~~ </error>) Dim c2 As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New(o As C) o.Goo() End Sub End Class End Class ]]> </file> </compilation>, {MetadataReference.CreateFromImage(otherImage)}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) c2.VerifyDiagnostics() End Sub <Fact> Public Sub SignModuleKeyContainerBogus() Dim c1 As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("bogus")> Public Class A End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultDesktopProvider)) 'shouldn't have an error. The attribute's contents are checked when the module is added. Dim reference = c1.EmitToImageReference() Dim c2 As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( (<compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>), {reference}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) 'BC36981: Error extracting public key from container 'bogus': Keyset does not exist (Exception from HRESULT: 0x80090016) 'c2.VerifyDiagnostics(Diagnostic(ERRID.ERR_PublicKeyContainerFailure).WithArguments("bogus", "Keyset does not exist (Exception from HRESULT: 0x80090016)")) Dim err = c2.GetDiagnostics(CompilationStage.Emit).Single() Assert.Equal(ERRID.ERR_PublicKeyContainerFailure, err.Code) Assert.Equal(2, err.Arguments.Count) Assert.Equal("bogus", DirectCast(err.Arguments(0), String)) Dim errorText = DirectCast(err.Arguments(1), String) Assert.True( errorText.Contains("HRESULT") AndAlso errorText.Contains("0x80090016")) End Sub <Fact> Public Sub SignModuleKeyFileBogus() Dim c1 As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyFile("bogus")> Public Class A End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultDesktopProvider)) 'shouldn't have an error. The attribute's contents are checked when the module is added. Dim reference = c1.EmitToImageReference() Dim c2 As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( (<compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>), {reference}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) c2.VerifyDiagnostics(Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments("bogus", CodeAnalysisResources.FileNotFound)) End Sub <Fact> Public Sub IVTSigned() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Public Class A Private Sub New(o As C) o.Goo() End Sub End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, TestOptions.ReleaseDll.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultDesktopProvider)) Dim unused = requestor.Assembly.Identity requestor.VerifyDiagnostics() End Sub <Fact> Public Sub IVTErrorNotBothSigned_VBtoVB() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Public Class A Private Sub New(o As C) o.Goo() End Sub End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) Dim unused = requestor.Assembly.Identity 'gives "is not accessible" error because internals were imported because IVT was found CompilationUtils.AssertTheseDiagnostics(requestor, <error>BC30389: 'C' is not accessible in this context because it is 'Friend'. Private Sub New(o As C) ~ </error>) End Sub <Fact, WorkItem(781312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781312")> Public Sub Bug781312() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Public Class A Private Sub New(o As C) o.Goo() End Sub End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultDesktopProvider)) Dim unused = requestor.Assembly.Identity CompilationUtils.AssertTheseDiagnostics(requestor, <error></error>) End Sub <Fact> Public Sub IVTErrorNotBothSigned_CStoVB() Dim cSource = "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }" Dim other As CSharp.CSharpCompilation = CSharp.CSharpCompilation.Create( assemblyName:="Paul", syntaxTrees:={CSharp.CSharpSyntaxTree.ParseText(cSource)}, references:={MscorlibRef_v4_0_30316_17626}, options:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Public Class A Private Sub New(o As C) o.Goo() End Sub End Class ]]> </file> </compilation>, {MetadataReference.CreateFromImage(other.EmitToArray())}, TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) Dim unused = requestor.Assembly.Identity 'gives "is not accessible" error because internals were imported because IVT was found CompilationUtils.AssertTheseDiagnostics(requestor, <error>BC30390: 'C.Friend Overloads Sub Goo()' is not accessible in this context because it is 'Friend'. o.Goo() ~~~~~ </error>) End Sub <Fact> Public Sub IVTDeferredSuccess() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C 'causes optimistic granting <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Dim unused = requestor.Assembly.Identity Assert.True(DirectCast(other.Assembly, IAssemblySymbol).GivesAccessTo(requestor.Assembly)) requestor.AssertNoDiagnostics() End Sub <Fact> Public Sub IVTDeferredFailSignMismatch() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Dim unused = requestor.Assembly.Identity CompilationUtils.AssertTheseDiagnostics(requestor, <error>BC36958: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the strong name signing state of the output assembly does not match that of the granting assembly.</error>) End Sub <Fact> Public Sub IVTDeferredFailKeyMismatch() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ 'key is wrong in the first digit <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Dim unused = requestor.Assembly.Identity CompilationUtils.AssertTheseDiagnostics(requestor, <errors>BC36957: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', but the public key of the output assembly does not match that specified by the attribute in the granting assembly.</errors>) End Sub <Fact> Public Sub IVTSuccessThroughIAssembly() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C 'causes optimistic granting <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Assert.True(DirectCast(other.Assembly, IAssemblySymbol).GivesAccessTo(requestor.Assembly)) End Sub <Fact> Public Sub IVTFailSignMismatchThroughIAssembly() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Assert.False(DirectCast(other.Assembly, IAssemblySymbol).GivesAccessTo(requestor.Assembly)) End Sub <WorkItem(820450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820450")> <Fact> Public Sub IVTGivesAccessToUsingDifferentKeys() Dim giver As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Namespace ClassLibrary Friend Class FriendClass Public Sub Goo() End Sub End Class end Namespace ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2).WithStrongNameProvider(s_defaultDesktopProvider)) giver.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Public Class ClassWithFriendMethod Friend Sub Test(A as ClassLibrary.FriendClass) End Sub End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(giver)}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Assert.True(DirectCast(giver.Assembly, IAssemblySymbol).GivesAccessTo(requestor.Assembly)) Assert.Empty(requestor.GetDiagnostics()) End Sub #End Region #Region "IVT instantiations" <Fact> Public Sub IVTHasCulture() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Sam"> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo("WantsIVTAccess, Culture=neutral")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Dim expectedErrors = <error><![CDATA[ BC31534: Friend assembly reference 'WantsIVTAccess, Culture=neutral' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. <Assembly: InternalsVisibleTo("WantsIVTAccess, Culture=neutral")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></error> CompilationUtils.AssertTheseDeclarationDiagnostics(other, expectedErrors) End Sub <Fact> Public Sub IVTNoKey() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Sam"> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo("WantsIVTAccess")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim expectedErrors = <error><![CDATA[ BC31535: Friend assembly reference 'WantsIVTAccess' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations. <Assembly: InternalsVisibleTo("WantsIVTAccess")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></error> CompilationUtils.AssertTheseDeclarationDiagnostics(other, expectedErrors) End Sub #End Region #Region "Signing" <ConditionalFact(GetType(WindowsDesktopOnly))> Public Sub MaxSizeKey() Dim pubKey = TestResources.General.snMaxSizePublicKeyString Const pubKeyToken = "1540923db30520b2" Dim pubKeyTokenBytes As Byte() = {&H15, &H40, &H92, &H3D, &HB3, &H5, &H20, &HB2} Dim comp = CreateCompilation( <compilation> <file name="c.vb"> Imports System Imports System.Runtime.CompilerServices &lt;Assembly:InternalsVisibleTo("MaxSizeComp2, PublicKey=<%= pubKey %>, PublicKeyToken=<%= pubKeyToken %>")&gt; Friend Class C Public Shared Sub M() Console.WriteLine("Called M") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile).WithStrongNameProvider(s_defaultDesktopProvider)) comp.VerifyEmitDiagnostics() Assert.True(comp.IsRealSigned) VerifySigned(comp) Assert.Equal(TestResources.General.snMaxSizePublicKey, comp.Assembly.Identity.PublicKey) Assert.Equal(Of Byte)(pubKeyTokenBytes, comp.Assembly.Identity.PublicKeyToken) Dim src = <compilation name="MaxSizeComp2"> <file name="c.vb"> Class D Public Shared Sub Main() C.M() End Sub End Class </file> </compilation> Dim comp2 = CreateCompilation(src, references:={comp.ToMetadataReference()}, options:=TestOptions.ReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile).WithStrongNameProvider(s_defaultDesktopProvider)) CompileAndVerify(comp2, expectedOutput:="Called M") Assert.Equal(TestResources.General.snMaxSizePublicKey, comp2.Assembly.Identity.PublicKey) Assert.Equal(Of Byte)(pubKeyTokenBytes, comp2.Assembly.Identity.PublicKeyToken) Dim comp3 = CreateCompilation(src, references:={comp.EmitToImageReference()}, options:=TestOptions.ReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile).WithStrongNameProvider(s_defaultDesktopProvider)) CompileAndVerify(comp3, expectedOutput:="Called M") Assert.Equal(TestResources.General.snMaxSizePublicKey, comp3.Assembly.Identity.PublicKey) Assert.Equal(Of Byte)(pubKeyTokenBytes, comp3.Assembly.Identity.PublicKeyToken) End Sub <Fact> Public Sub SignIt() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Sam"> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim peHeaders = New PEHeaders(other.EmitToStream()) Assert.Equal(CorFlags.StrongNameSigned, peHeaders.CorHeader.Flags And CorFlags.StrongNameSigned) End Sub <Fact> Public Sub SignItWithOnlyPublicKey() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Sam"> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithStrongNameProvider(s_defaultDesktopProvider)) Using outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) CompilationUtils.AssertTheseDiagnostics(emitResult.Diagnostics, <errors> BC36961: Key file '<%= s_publicKeyFile %>' is missing the private key needed for signing. </errors>) End Using other = other.WithOptions(TestOptions.ReleaseModule.WithCryptoKeyFile(s_publicKeyFile)) Dim assembly As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="Sam2"> <file name="a.vb"> </file> </compilation>, {other.EmitToImageReference()}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Using outStrm = New MemoryStream() Dim emitResult = assembly.Emit(outStrm) CompilationUtils.AssertTheseDiagnostics(emitResult.Diagnostics, <errors> BC36961: Key file '<%= s_publicKeyFile %>' is missing the private key needed for signing. </errors>) End Using End Sub <Fact> Public Sub DelaySignItWithOnlyPublicKey() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Sam"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDelaySign(True)> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithStrongNameProvider(s_defaultDesktopProvider)) CompileAndVerify(other) End Sub <Fact> Public Sub DelaySignButNoKey() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDelaySign(True)> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) ' Dev11: vbc : warning BC40010: Possible problem detected while building assembly 'VBTestD': Delay signing was requested, but no key was given ' warning BC41008: Use command-line option '/delaysign' or appropriate project settings instead of 'System.Reflection.AssemblyDelaySignAttribute'. CompilationUtils.AssertTheseDiagnostics(emitResult.Diagnostics, <errors>BC40060: Delay signing was specified and requires a public key, but no public key was specified.</errors>) Assert.True(emitResult.Success) End Sub <Fact> Public Sub SignInMemory() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.True(emitResult.Success) Assert.True(ILValidation.IsStreamFullSigned(outStrm)) End Sub <WorkItem(545720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545720")> <WorkItem(530050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530050")> <Fact> Public Sub InvalidAssemblyName() Dim il = <![CDATA[ .assembly extern mscorlib { } .assembly asm1 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 09 2F 5C 3A 2A 3F 27 3C 3E 7C 00 00 ) // .../\:*?'<>|.. } .class private auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } ]]> Dim vb = <compilation> <file name="a.vb"><![CDATA[ Public Class Derived Inherits Base End Class ]]> </file> </compilation> Dim ilRef = CompileIL(il.Value, prependDefaultHeader:=False) Dim comp = CreateCompilationWithMscorlib40AndReferences(vb, {ilRef}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) ' NOTE: dev10 reports ERR_FriendAssemblyNameInvalid, but Roslyn won't (DevDiv #15099). comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_InaccessibleSymbol2, "Base").WithArguments("Base", "Friend")) End Sub <Fact> Public Sub DelaySignWithAssemblySignatureKey() '//Note that this SignatureKey is some random one that I found in the devdiv build. '//It is not related to the other keys we use in these tests. '//In the native compiler, when the AssemblySignatureKey attribute is present, and '//the binary is configured for delay signing, the contents of the assemblySignatureKey attribute '//(rather than the contents of the keyfile or container) are used to compute the size needed to '//reserve in the binary for its signature. Signing using this key is only supported via sn.exe Dim other = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDelaySign(True)> <Assembly: System.Reflection.AssemblySignatureKey("002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3", "a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, TestOptions.ReleaseDll.WithDelaySign(True).WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) ' confirm header has expected SN signature size Dim peHeaders = New PEHeaders(other.EmitToStream()) Assert.Equal(256, peHeaders.CorHeader.StrongNameSignatureDirectory.Size) Assert.Equal(CorFlags.ILOnly, peHeaders.CorHeader.Flags) End Sub ''' <summary> ''' Won't fix (easy to be tested here) ''' </summary> <Fact(), WorkItem(529953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529953"), WorkItem(530112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530112")> Public Sub DeclareAssemblyKeyNameAndFile_BC41008() Dim src = "<Assembly: System.Reflection.AssemblyKeyName(""Key1"")>" & vbCrLf & "<Assembly: System.Reflection.AssemblyKeyFile(""" & s_keyPairFile & """)>" & vbCrLf & "Public Class C" & vbCrLf & "End Class" Dim tree = ParseAndVerify(src) Dim comp = CreateCompilationWithMscorlib40({tree}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) ' Native Compiler: 'warning BC41008: Use command-line option '/keycontainer' or appropriate project settings instead of 'System.Reflection.AssemblyKeyNameAttribute() '. ' <Assembly: System.Reflection.AssemblyKeyName("Key1")> ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'warning BC41008: Use command-line option '/keyfile' or appropriate project settings instead of 'System.Reflection.AssemblyKeyFileAttribute() '. '<Assembly: System.Reflection.AssemblyKeyFile("Key2.snk")> ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ comp.VerifyDiagnostics() ' Diagnostic(ERRID.WRN_UseSwitchInsteadOfAttribute, "System.Reflection.AssemblyKeyName(""Key1""").WithArguments("/keycontainer"), ' Diagnostic(ERRID.WRN_UseSwitchInsteadOfAttribute, "System.Reflection.AssemblyKeyFile(""Key2.snk""").WithArguments("/keyfile")) Dim outStrm = New MemoryStream() Dim emitResult = comp.Emit(outStrm) Assert.True(emitResult.Success) End Sub Private Sub ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( moduleContents As Stream, expectedModuleAttr As AttributeDescription, legacyStrongName As Boolean) ' a module doesn't get signed for real. It should have either a keyfile or keycontainer attribute ' parked on a typeRef named 'AssemblyAttributesGoHere.' When the module is added to an assembly, the ' resulting assembly is signed with the key referred to by the aforementioned attribute. Dim success As EmitResult Dim tempFile = Temp.CreateFile() moduleContents.Position = 0 Using metadata = ModuleMetadata.CreateFromStream(moduleContents) Dim flags = metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags ' confirm file does not claim to be signed Assert.Equal(0, CInt(flags And CorFlags.StrongNameSigned)) Dim token As EntityHandle = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere") Assert.False(token.IsNil) ' could the magic type ref be located? If not then the attribute's not there. Dim attrInfos = metadata.Module.FindTargetAttributes(token, expectedModuleAttr) Assert.Equal(1, attrInfos.Count()) Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class Z End Class ]]> </file> </compilation> Dim snProvider As StrongNameProvider = If(legacyStrongName, s_defaultDesktopProvider, s_defaultPortableProvider) ' now that the module checks out, ensure that adding it to a compilation outputting a dll ' results in a signed assembly. Dim assemblyComp = CreateCompilationWithMscorlib40AndReferences( source, {metadata.GetReference()}, TestOptions.ReleaseDll.WithStrongNameProvider(snProvider)) Using finalStrm = tempFile.Open() success = assemblyComp.Emit(finalStrm) End Using End Using success.Diagnostics.Verify() Assert.True(success.Success) AssertFileIsSigned(tempFile) End Sub Private Shared Sub AssertFileIsSigned(file As TempFile) Using peStream = New FileStream(file.Path, FileMode.Open) Assert.True(ILValidation.IsStreamFullSigned(peStream)) End Using End Sub <Fact> Public Sub SignModuleKeyFileAttr_Legacy() Dim x = s_keyPairFile Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>Assembly: System.Reflection.AssemblyKeyFile("<%= x %>")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultDesktopProvider)) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( other.EmitToStream(), AttributeDescription.AssemblyKeyFileAttribute, legacyStrongName:=True) End Sub <Fact> Public Sub SignModuleKeyContainerAttr() Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( outStrm, AttributeDescription.AssemblyKeyNameAttribute, legacyStrongName:=True) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyContainerCmdLine() Dim source = <compilation> <file name="a.vb"> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( outStrm, AttributeDescription.AssemblyKeyNameAttribute, legacyStrongName:=True) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyContainerCmdLine_1() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class C End Class ]]></file> </compilation> Dim other = CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( outStrm, AttributeDescription.AssemblyKeyNameAttribute, legacyStrongName:=True) End Sub <Fact> Public Sub SignModuleKeyFileAttr() Dim x = s_keyPairFile Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>Assembly: System.Reflection.AssemblyKeyFile("<%= x %>")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultPortableProvider)) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( other.EmitToStream(), AttributeDescription.AssemblyKeyFileAttribute, legacyStrongName:=False) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyContainerCmdLine_2() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("bogus")> Public Class C End Class ]]></file> </compilation> Dim other = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultDesktopProvider)) AssertTheseDiagnostics(other, <expected> BC37207: Attribute 'System.Reflection.AssemblyKeyNameAttribute' given in a source file conflicts with option 'CryptoKeyContainer'. </expected>) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyFileCmdLine_Legacy() Dim source = <compilation> <file name="a.vb"> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( outStrm, AttributeDescription.AssemblyKeyFileAttribute, legacyStrongName:=True) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyFileCmdLine_1_Legacy() Dim x = s_keyPairFile Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>assembly: System.Reflection.AssemblyKeyFile("<%= x %>")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( outStrm, AttributeDescription.AssemblyKeyFileAttribute, legacyStrongName:=True) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyFileCmdLine() Dim source = <compilation> <file name="a.vb"> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultPortableProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( outStrm, AttributeDescription.AssemblyKeyFileAttribute, legacyStrongName:=False) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyFileCmdLine_1() Dim x = s_keyPairFile Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>assembly: System.Reflection.AssemblyKeyFile("<%= x %>")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultPortableProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( outStrm, AttributeDescription.AssemblyKeyFileAttribute, legacyStrongName:=False) End Sub <Fact> Public Sub SignModuleKeyFileCmdLine_2() Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>assembly: System.Reflection.AssemblyKeyFile("bogus")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) AssertTheseDiagnostics(other, <expected> BC37207: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. </expected>) End Sub <Fact> <WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")> Public Sub Bug529779_1() Dim unsigned As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C1 End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Goo() Dim x as New System.Guid() System.Console.WriteLine(x) End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) CompileAndVerify(other.WithReferences({other.References(0), New VisualBasicCompilationReference(unsigned)})).VerifyDiagnostics() CompileAndVerify(other.WithReferences({other.References(0), MetadataReference.CreateFromImage(unsigned.EmitToArray)})).VerifyDiagnostics() End Sub <Fact> <WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")> Public Sub Bug529779_2() Dim unsigned As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="Unsigned"> <file name="a.vb"><![CDATA[ Public Class C1 End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Goo() Dim x as New C1() System.Console.WriteLine(x) End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim comps = {other.WithReferences({other.References(0), New VisualBasicCompilationReference(unsigned)}), other.WithReferences({other.References(0), MetadataReference.CreateFromImage(unsigned.EmitToArray)})} For Each comp In comps Dim outStrm = New MemoryStream() Dim emitResult = comp.Emit(outStrm) ' Dev12 reports an error Assert.True(emitResult.Success) AssertTheseDiagnostics(emitResult.Diagnostics, <expected> BC41997: Referenced assembly 'Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. </expected>) Next End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_1() Dim other As VisualBasicCompilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim peHeaders = New PEHeaders(other.EmitToStream()) Assert.Equal(CorFlags.StrongNameSigned, peHeaders.CorHeader.Flags And CorFlags.StrongNameSigned) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_2() Dim other As VisualBasicCompilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.False(emitResult.Success) AssertTheseDiagnostics(emitResult.Diagnostics, <expected> BC37209: Invalid signature public key specified in AssemblySignatureKeyAttribute. "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_3() Dim other As VisualBasicCompilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.False(emitResult.Success) ' AssertTheseDiagnostics(emitResult.Diagnostics, '<expected> 'BC36980: Error extracting public key from file '<%= KeyPairFile %>': Invalid countersignature specified in AssemblySignatureKeyAttribute. (Exception from HRESULT: 0x80131423) '</expected>) Dim err = emitResult.Diagnostics.Single() Assert.Equal(ERRID.ERR_PublicKeyFileFailure, err.Code) Assert.Equal(2, err.Arguments.Count) Assert.Equal(s_keyPairFile, DirectCast(err.Arguments(0), String)) Dim errorText = DirectCast(err.Arguments(1), String) Assert.True( errorText.Contains("HRESULT") AndAlso errorText.Contains("0x80131423")) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_4() Dim other As VisualBasicCompilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.False(emitResult.Success) AssertTheseDiagnostics(emitResult.Diagnostics, <expected> BC37209: Invalid signature public key specified in AssemblySignatureKeyAttribute. "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_5() Dim other As VisualBasicCompilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) CompileAndVerify(other) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_6() Dim other As VisualBasicCompilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( Nothing, "bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.False(emitResult.Success) AssertTheseDiagnostics(emitResult.Diagnostics, <expected> BC37209: Invalid signature public key specified in AssemblySignatureKeyAttribute. Nothing, ~~~~~~~ </expected>) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_7() Dim other As VisualBasicCompilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Nothing)> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultDesktopProvider)) CompileAndVerify(other) End Sub #End Region Public Sub PublicSignCore(options As VisualBasicCompilationOptions) Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=options) PublicSignCore(compilation) End Sub Public Sub PublicSignCore(compilation As Compilation, Optional assertNoDiagnostics As Boolean = True) Assert.True(compilation.Options.PublicSign) Assert.Null(compilation.Options.DelaySign) Dim stream As New MemoryStream() Dim emitResult = compilation.Emit(stream) Assert.True(emitResult.Success) If assertNoDiagnostics Then Assert.True(emitResult.Diagnostics.IsEmpty) End If stream.Position = 0 Using reader As New PEReader(stream) Assert.True(reader.HasMetadata) Dim flags = reader.PEHeaders.CorHeader.Flags Assert.True(flags.HasFlag(CorFlags.StrongNameSigned)) End Using End Sub <Fact> Public Sub PublicSign_NoKey() Dim options = TestOptions.ReleaseDll.WithPublicSign(True) Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>, options:=options ) AssertTheseDiagnostics(comp, <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified </errors>) Assert.True(comp.Options.PublicSign) Assert.True(comp.Assembly.PublicKey.IsDefaultOrEmpty) End Sub <Fact> Public Sub KeyFileFromAttributes_PublicSign() Dim source = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyKeyFile("test.snk")> Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithPublicSign(True)) AssertTheseDiagnostics(c, <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified BC42379: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. </errors>) Assert.True(c.Options.PublicSign) End Sub <Fact> Public Sub KeyContainerFromAttributes_PublicSign() Dim source = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithPublicSign(True)) AssertTheseDiagnostics(c, <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified BC42379: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. </errors>) Assert.True(c.Options.PublicSign) End Sub <Fact> Public Sub PublicSign_FromKeyFileNoStrongNameProvider() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) PublicSignCore(options) End Sub <Fact> Public Sub PublicSign_FromPublicKeyFileNoStrongNameProvider() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) PublicSignCore(options) End Sub <Fact> Public Sub PublicSign_FromKeyFileAndStrongNameProvider() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey2) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True).WithStrongNameProvider(s_defaultDesktopProvider) PublicSignCore(options) End Sub <Fact> Public Sub PublicSign_FromKeyFileAndNoStrongNameProvider() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey2) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) PublicSignCore(options) End Sub <Fact> Public Sub PublicSign_KeyContainerOnly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation> Dim options = TestOptions.ReleaseDll.WithCryptoKeyContainer("testContainer").WithPublicSign(True) Dim compilation = CreateCompilationWithMscorlib40(source, options:=options) AssertTheseDiagnostics(compilation, <errors> BC2046: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. BC37254: Public sign was specified and requires a public key, but no public key was specified </errors>) End Sub <Fact> Public Sub PublicSign_IgnoreSourceAttributes() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> <Assembly: System.Reflection.AssemblyKeyFile("some file")> Public Class C End Class ]]> </file> </compilation> Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) Dim compilation = CreateCompilationWithMscorlib40(source, options:=options) AssertTheseDiagnostics(compilation, <errors> BC42379: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. BC42379: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. </errors>) PublicSignCore(compilation, assertNoDiagnostics:=False) End Sub <Fact> Public Sub PublicSign_DelaySignAttribute() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDelaySign(True)> Public Class C End Class ]]> </file> </compilation> Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) Dim comp = CreateCompilationWithMscorlib40(source, options:=options) AssertTheseDiagnostics(comp, <errors> BC37207: Attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file conflicts with option 'PublicSign'. </errors>) Assert.True(comp.Options.PublicSign) End Sub <Fact> Public Sub PublicSignAndDelaySign() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True).WithDelaySign(True) Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>, options:=options ) AssertTheseDiagnostics(comp, <errors> BC2046: Compilation options 'PublicSign' and 'DelaySign' can't both be specified at the same time. </errors>) Assert.True(comp.Options.PublicSign) Assert.True(comp.Options.DelaySign) End Sub <Fact> Public Sub PublicSignAndDelaySignFalse() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True).WithDelaySign(False) Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>, options:=options ) AssertTheseDiagnostics(comp) Assert.True(comp.Options.PublicSign) Assert.False(comp.Options.DelaySign) End Sub <Fact, WorkItem(769840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769840")> Public Sub Bug769840() Dim ca = CreateCompilationWithMscorlib40( <compilation name="Bug769840_A"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bug769840_B, PublicKey=0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4")> Friend Class A Public Value As Integer = 3 End Class ]]></file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultDesktopProvider)) CompileAndVerify(ca) Dim cb = CreateCompilationWithMscorlib40AndReferences( <compilation name="Bug769840_B"> <file name="a.vb"><![CDATA[ Friend Class B Public Function GetA() As A Return New A() End Function End Class ]]></file> </compilation>, {New VisualBasicCompilationReference(ca)}, options:=TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultDesktopProvider)) CompileAndVerify(cb, verify:=Verification.Fails).Diagnostics.Verify() End Sub <Fact, WorkItem(1072350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072350")> Public Sub Bug1072350() Dim sourceA As XElement = <compilation name="ClassLibrary2"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("X ")> Friend Class A Friend Shared I As Integer = 42 End Class]]> </file> </compilation> Dim sourceB As XElement = <compilation name="X"> <file name="b.vb"><![CDATA[ Class B Shared Sub Main() System.Console.Write(A.I) End Sub End Class]]> </file> </compilation> Dim ca = CreateCompilationWithMscorlib40(sourceA, options:=TestOptions.ReleaseDll) CompileAndVerify(ca) Dim cb = CreateCompilationWithMscorlib40(sourceB, options:=TestOptions.ReleaseExe, references:={New VisualBasicCompilationReference(ca)}) CompileAndVerify(cb, expectedOutput:="42").Diagnostics.Verify() End Sub <Fact, WorkItem(1072339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072339")> Public Sub Bug1072339() Dim sourceA As XElement = <compilation name="ClassLibrary2"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("x")> Friend Class A Friend Shared I As Integer = 42 End Class]]> </file> </compilation> Dim sourceB As XElement = <compilation name="x"> <file name="b.vb"><![CDATA[ Class B Shared Sub Main() System.Console.Write(A.I) End Sub End Class]]> </file> </compilation> Dim ca = CreateCompilationWithMscorlib40(sourceA, options:=TestOptions.ReleaseDll) CompileAndVerify(ca) Dim cb = CreateCompilationWithMscorlib40(sourceB, options:=TestOptions.ReleaseExe, references:={New VisualBasicCompilationReference(ca)}) CompileAndVerify(cb, expectedOutput:="42").Diagnostics.Verify() End Sub <Fact, WorkItem(1095618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095618")> Public Sub Bug1095618() Dim source As XElement = <compilation name="a"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000")> ]]></file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")").WithArguments("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000").WithLocation(1, 2)) End Sub <Fact> <WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingNullKeyFile() Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoKeyFile:=Nothing) Dim compilation = CreateCompilationWithMscorlib40(String.Empty, options:=options).VerifyEmitDiagnostics() VerifySigned(compilation, expectedToBeSigned:=False) End Sub <Fact> <WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingEmptyKeyFile() Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoKeyFile:=String.Empty) Dim compilation = CreateCompilationWithMscorlib40(String.Empty, options:=options).VerifyEmitDiagnostics() VerifySigned(compilation, expectedToBeSigned:=False) End Sub <Fact> <WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingNullKeyFile_PublicSign() Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoKeyFile:=Nothing, publicSign:=True) Dim compilation = CreateCompilationWithMscorlib40(String.Empty, options:=options) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified </errors>) End Sub <Fact> <WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoKeyFile:=String.Empty, publicSign:=True) Dim compilation = CreateCompilationWithMscorlib40(String.Empty, options:=options) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified </errors>) End Sub End Class
tmeschter/roslyn
src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb
Visual Basic
apache-2.0
91,611
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests Public Class InsideNamespaceDeclaration ''' <summary> ''' Declarations outside of any namespace in the file are considered to be in the project's root namespace ''' </summary> Private Shared Async Function VerifyContainsAsync(ParamArray recommendations As String()) As Task Await VerifyRecommendationsContainAsync(<NamespaceDeclaration>|</NamespaceDeclaration>, recommendations) Await VerifyRecommendationsContainAsync(<File>|</File>, recommendations) Await VerifyRecommendationsContainAsync( <File>Imports System |</File>, recommendations) End Function ''' <summary> ''' Declarations outside of any namespace in the file are considered to be in the project's root namespace ''' </summary> Private Shared Async Function VerifyMissingAsync(ParamArray recommendations As String()) As Task Await VerifyRecommendationsMissingAsync(<NamespaceDeclaration>|</NamespaceDeclaration>, recommendations) Await VerifyRecommendationsMissingAsync(<File>|</File>, recommendations) Await VerifyRecommendationsMissingAsync( <File>Imports System |</File>, recommendations) End Function <WorkItem(530100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530100")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AccessibilityModifiersTest() As Task Await VerifyContainsAsync("Public", "Friend") Await VerifyMissingAsync("Protected", "Private", "Protected Friend") End Function <WorkItem(530100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530100")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function ClassModifiersTest() As Task Await VerifyContainsAsync("MustInherit", "NotInheritable", "Partial") End Function End Class End Namespace
jmarolf/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ModifierKeywordRecommenderTests.InsideNamespaceDeclaration.vb
Visual Basic
mit
2,303
' 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.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend MustInherit Class PlaceholderLocalSymbol Inherits EELocalSymbolBase Private ReadOnly _name As String Friend Sub New(method As MethodSymbol, name As String, type As TypeSymbol) MyBase.New(method, type) _name = name End Sub Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind Get Return LocalDeclarationKind.Variable End Get End Property Friend Overrides ReadOnly Property IdentifierToken As SyntaxToken Get Return Nothing End Get End Property Friend Overrides ReadOnly Property IdentifierLocation As Location Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return NoLocations End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As EELocalSymbolBase ' Pseudo-variables should be rewritten in PlaceholderLocalRewriter ' rather than copied as locals to the target method. Throw ExceptionUtilities.Unreachable End Function Friend MustOverride Overrides ReadOnly Property IsReadOnly As Boolean Friend MustOverride Function RewriteLocal( compilation As VisualBasicCompilation, container As EENamedTypeSymbol, syntax As VisualBasicSyntaxNode, isLValue As Boolean, diagnostics As DiagnosticBag) As BoundExpression Friend Shared Function ConvertToLocalType( compilation As VisualBasicCompilation, expr As BoundExpression, type As TypeSymbol, diagnostics As DiagnosticBag) As BoundExpression Dim syntax = expr.Syntax Dim exprType = expr.Type Dim conversionKind As ConversionKind If type.IsErrorType() Then diagnostics.Add(type.GetUseSiteErrorInfo(), syntax.GetLocation()) conversionKind = Nothing ElseIf exprType.IsErrorType() Then diagnostics.Add(exprType.GetUseSiteErrorInfo(), syntax.GetLocation()) conversionKind = Nothing Else Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim pair = Conversions.ClassifyConversion(exprType, type, useSiteDiagnostics) Debug.Assert(useSiteDiagnostics Is Nothing, "If this happens, please add a test") diagnostics.Add(syntax, useSiteDiagnostics) Debug.Assert(pair.Value Is Nothing) ' Conversion method. conversionKind = pair.Key End If Return New BoundDirectCast( syntax, expr, conversionKind, type, hasErrors:=Not Conversions.ConversionExists(conversionKind)).MakeCompilerGenerated() End Function Friend Shared Function GetIntrinsicMethod(compilation As VisualBasicCompilation, methodName As String) As MethodSymbol Dim type = compilation.GetTypeByMetadataName(ExpressionCompilerConstants.IntrinsicAssemblyTypeMetadataName) Dim members = type.GetMembers(methodName) Debug.Assert(members.Length = 1) Return DirectCast(members(0), MethodSymbol) End Function End Class End Namespace
dsplaisted/roslyn
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/PlaceholderLocalSymbol.vb
Visual Basic
apache-2.0
4,372
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class AliasKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AliasAfterLibNameInSubTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Sub goo Lib "Goo" |</ClassDeclaration>, "Alias") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AliasAfterLibNameInFunctionTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Function goo Lib "Goo" |</ClassDeclaration>, "Alias") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AliasNotAfterLibKeywordTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Sub goo Lib |</ClassDeclaration>, Array.Empty(Of String)()) End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NothingAfterBrokenAliasTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Sub goo Lib "Goo" Alais |</ClassDeclaration>, Array.Empty(Of String)()) End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAliasAfterEolTest() VerifyRecommendationsMissing( <ClassDeclaration>Declare Function goo Lib "Goo" |</ClassDeclaration>, "Alias") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AliasAfterExplicitLineContinuationTest() VerifyRecommendationsAreExactly( <ClassDeclaration>Declare Function goo Lib "Goo" _ |</ClassDeclaration>, "Alias") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AliasAfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsAreExactly( <ClassDeclaration>Declare Function goo Lib "Goo" _ ' Test |</ClassDeclaration>, "Alias") End Sub End Class End Namespace
physhi/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/AliasKeywordRecommenderTests.vb
Visual Basic
apache-2.0
2,612
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "CGS_rCRetencion_ISLRProveedores" '-------------------------------------------------------------------------------------------' Partial Class CGS_rCRetencion_ISLRProveedores 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.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3)) Dim lcParametro4Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4)) Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden Dim loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine("SELECT Cuentas_Pagar.Tip_Ori AS Tipo_Origen,") loComandoSeleccionar.AppendLine(" Cuentas_Pagar.Fec_Ini AS Fecha_Retencion,") loComandoSeleccionar.AppendLine(" Cuentas_Pagar.Doc_Ori AS Numero_Pago,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Cod_Tip AS Tipo_Documento,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Doc_Ori AS Numero_Documento,") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Control AS Control_Documento,") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Factura AS Factura_Documento,") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Fec_Ini AS Fecha_Factura,") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Mon_Net AS Monto_Documento,") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Mon_Abo AS Monto_Abonado,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Bas AS Base_Retencion,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Por_Ret AS Porcentaje_Retenido,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Sus AS Sustraendo_Retenido,") loComandoSeleccionar.AppendLine(" RTRIM(Retenciones.Cod_Ret) + ': ' + Retenciones.Nom_Ret AS Concepto,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Ret AS Monto_Retenido,") loComandoSeleccionar.AppendLine(" Cuentas_Pagar.Cod_Pro AS Cod_Pro,") loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro AS Nom_Pro,") loComandoSeleccionar.AppendLine(" Proveedores.Rif AS Rif,") loComandoSeleccionar.AppendLine(" Proveedores.Nit AS Nit,") loComandoSeleccionar.AppendLine(" Proveedores.Dir_Fis AS Direccion,") loComandoSeleccionar.AppendLine(" " & lcParametro4Desde & " AS Agrupar") loComandoSeleccionar.AppendLine("FROM Cuentas_Pagar") loComandoSeleccionar.AppendLine(" JOIN Pagos ON Pagos.documento = Cuentas_Pagar.Doc_Ori") loComandoSeleccionar.AppendLine(" JOIN Retenciones_Documentos ON Retenciones_Documentos.Documento = Pagos.documento") loComandoSeleccionar.AppendLine(" AND Retenciones_Documentos.doc_des = Cuentas_Pagar.documento") loComandoSeleccionar.AppendLine(" AND Retenciones_Documentos.clase = 'ISLR'") loComandoSeleccionar.AppendLine(" JOIN Renglones_Pagos ON Renglones_Pagos.Documento = Pagos.documento") loComandoSeleccionar.AppendLine(" AND Renglones_Pagos.Doc_Ori = Retenciones_Documentos.Doc_Ori") loComandoSeleccionar.AppendLine(" JOIN Proveedores ON Proveedores.Cod_Pro = Cuentas_Pagar.Cod_Pro") loComandoSeleccionar.AppendLine(" LEFT JOIN Retenciones ON Retenciones.Cod_Ret = Retenciones_Documentos.Cod_Ret") loComandoSeleccionar.AppendLine("WHERE Cuentas_Pagar.Cod_Tip = 'ISLR'") loComandoSeleccionar.AppendLine(" AND (Cuentas_Pagar.Status IN (" & lcParametro3Desde & ")") loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.Status IN (SELECT Documentos.status") loComandoSeleccionar.AppendLine(" FROM cuentas_pagar") loComandoSeleccionar.AppendLine(" JOIN retenciones_documentos ON cuentas_pagar.documento = retenciones_documentos.doc_ori") loComandoSeleccionar.AppendLine(" AND cuentas_pagar.cod_tip = 'FACT'") loComandoSeleccionar.AppendLine(" JOIN cuentas_pagar AS Documentos ON retenciones_documentos.doc_des = Documentos.documento") loComandoSeleccionar.AppendLine(" AND Documentos.cod_tip = 'ISLR'") loComandoSeleccionar.AppendLine(" WHERE cuentas_pagar.factura BETWEEN " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) loComandoSeleccionar.AppendLine(" AND Documentos.doc_ori = retenciones_documentos.documento))") loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.Tip_Ori = 'Pagos'") loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.Fec_Ini BETWEEN " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta) loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.Cod_Pro BETWEEN " & lcParametro1Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta) loComandoSeleccionar.AppendLine(" AND Renglones_Pagos.Factura BETWEEN " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) loComandoSeleccionar.AppendLine("UNION ALL ") loComandoSeleccionar.AppendLine("SELECT Retenciones_Documentos.Tip_Ori AS Tipo_Origen,") loComandoSeleccionar.AppendLine(" Ordenes_Pagos.Fec_Ini AS Fecha_Retencion,") loComandoSeleccionar.AppendLine(" '' AS Numero_Pago,") loComandoSeleccionar.AppendLine(" 'ORD/PAG' AS Tipo_Documento,") loComandoSeleccionar.AppendLine(" Ordenes_Pagos.Documento AS Numero_Documento,") loComandoSeleccionar.AppendLine(" '' AS Control_Documento,") loComandoSeleccionar.AppendLine(" '' AS Factura_Documento,") loComandoSeleccionar.AppendLine(" Ordenes_Pagos.Fec_Ini AS Fecha_Factura,") loComandoSeleccionar.AppendLine(" Ordenes_Pagos.Mon_Net AS Monto_Documento,") loComandoSeleccionar.AppendLine(" Ordenes_Pagos.Mon_Net AS Monto_Abonado,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Bas AS Base_Retencion,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Por_Ret AS Porcentaje_Retenido,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Sus AS Sustraendo_Retenido,") loComandoSeleccionar.AppendLine(" RTRIM(Retenciones.Cod_Ret) + ': ' + Retenciones.Nom_Ret AS Concepto,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Ret AS Monto_Retenido,") loComandoSeleccionar.AppendLine(" Ordenes_Pagos.Cod_Pro AS Cod_Pro,") loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro AS Nom_Pro,") loComandoSeleccionar.AppendLine(" Proveedores.Rif AS Rif,") loComandoSeleccionar.AppendLine(" Proveedores.Nit AS Nit,") loComandoSeleccionar.AppendLine(" Proveedores.Dir_Fis AS Direccion,") loComandoSeleccionar.AppendLine(" " & lcParametro4Desde & " AS Agrupar") loComandoSeleccionar.AppendLine("FROM Retenciones_Documentos") loComandoSeleccionar.AppendLine(" JOIN Ordenes_Pagos ON Ordenes_Pagos.Documento = Retenciones_Documentos.documento") loComandoSeleccionar.AppendLine(" JOIN Proveedores ON Proveedores.Cod_Pro = Ordenes_Pagos.Cod_Pro") loComandoSeleccionar.AppendLine(" LEFT JOIN Retenciones ON Retenciones.Cod_Ret = Retenciones_Documentos.Cod_Ret") loComandoSeleccionar.AppendLine("WHERE Ordenes_Pagos.Status = 'Confirmado'") loComandoSeleccionar.AppendLine(" AND Retenciones_Documentos.Tip_Ori = 'Ordenes_Pagos'") loComandoSeleccionar.AppendLine(" AND Retenciones_Documentos.clase = 'ISLR'") loComandoSeleccionar.AppendLine(" AND Ordenes_Pagos.Fec_Ini BETWEEN " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta) loComandoSeleccionar.AppendLine(" AND Ordenes_Pagos.Cod_Pro BETWEEN " & lcParametro1Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta) loComandoSeleccionar.AppendLine(" AND Ordenes_Pagos.factura BETWEEN " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) loComandoSeleccionar.AppendLine("UNION ALL ") loComandoSeleccionar.AppendLine("SELECT Cuentas_Pagar.Tip_Ori AS Tipo_Origen,") loComandoSeleccionar.AppendLine(" Cuentas_Pagar.Fec_Ini AS Fecha_Retencion,") loComandoSeleccionar.AppendLine(" '' AS Numero_Pago,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Cod_Tip AS Tipo_Documento,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Doc_Ori AS Numero_Documento,") loComandoSeleccionar.AppendLine(" Documentos.Control AS Control_Documento,") loComandoSeleccionar.AppendLine(" Documentos.Factura AS Factura_Documento,") loComandoSeleccionar.AppendLine(" Documentos.Fec_Ini AS Fecha_Factura,") loComandoSeleccionar.AppendLine(" Documentos.Mon_Net AS Monto_Documento,") loComandoSeleccionar.AppendLine(" Documentos.Mon_Net AS Monto_Abonado,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Bas AS Base_Retencion,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Por_Ret AS Porcentaje_Retenido,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Sus AS Sustraendo_Retenido,") loComandoSeleccionar.AppendLine(" RTRIM(Retenciones.Cod_Ret) + ': ' + Retenciones.Nom_Ret AS Concepto,") loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Ret AS Monto_Retenido,") loComandoSeleccionar.AppendLine(" Cuentas_Pagar.Cod_Pro AS Cod_Pro,") loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro AS Nom_Pro,") loComandoSeleccionar.AppendLine(" Proveedores.Rif AS Rif,") loComandoSeleccionar.AppendLine(" Proveedores.Nit AS Nit,") loComandoSeleccionar.AppendLine(" Proveedores.Dir_Fis AS Direccion,") loComandoSeleccionar.AppendLine(" " & lcParametro4Desde & " AS Agrupar") loComandoSeleccionar.AppendLine("FROM Cuentas_Pagar") loComandoSeleccionar.AppendLine(" JOIN Cuentas_Pagar AS Documentos ON Documentos.documento = Cuentas_Pagar.Doc_Ori") loComandoSeleccionar.AppendLine(" AND Documentos.Cod_Tip = Cuentas_Pagar.Cla_Ori") loComandoSeleccionar.AppendLine(" JOIN Retenciones_Documentos ON Retenciones_Documentos.Doc_Des = Cuentas_Pagar.Documento") loComandoSeleccionar.AppendLine(" AND Retenciones_Documentos.Doc_Ori = Cuentas_Pagar.Doc_Ori") loComandoSeleccionar.AppendLine(" JOIN Proveedores ON Proveedores.Cod_Pro = Cuentas_Pagar.Cod_Pro") loComandoSeleccionar.AppendLine(" LEFT JOIN Retenciones ON Retenciones.Cod_Ret = Retenciones_Documentos.Cod_Ret") loComandoSeleccionar.AppendLine("WHERE Cuentas_Pagar.Cod_Tip = 'ISLR'") loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.Status IN (" & lcParametro3Desde & ")") loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.Tip_Ori = 'cuentas_pagar'") loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.Fec_Ini BETWEEN " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta) loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.Cod_Pro BETWEEN " & lcParametro1Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta) loComandoSeleccionar.AppendLine(" AND Documentos.factura BETWEEN " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) 'loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento) 'Me.mEscribirConsulta(loComandoSeleccionar.ToString) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString(), "curReportes") '------------------------------------------------------------------------------------------------------- ' Verificando si el select (tabla nº 0) trae registros '------------------------------------------------------------------------------------------------------- If (laDatosReporte.Tables(0).Rows.Count <= 0) Then Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _ "No se Encontraron Registros para los Parámetros Especificados. ", _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _ "350px", _ "200px") End If loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("CGS_rCRetencion_ISLRProveedores", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrCGS_rCRetencion_ISLRProveedores.ReportSource = loObjetoReporte Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload Try loObjetoReporte.Close() Catch loExcepcion As Exception End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo ' '-------------------------------------------------------------------------------------------' ' RJG: 09/04/15: Codigo inicial, a partir de rCRetencion_ISLRProveedores. ' '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
CGS_rCRetencion_ISLRProveedores.aspx.vb
Visual Basic
mit
16,632
 Imports ServiceStack.ServiceHost <Route("/company/{CompanyID}/forms.json", "GET")> Public Class GetCompanyForms Implements IReturn(Of List(Of CompanyForm)) Public Property CompanyID As Integer End Class
pdstewart/Dss.OnboardingApiClient
src/Requests/GetCompanyForms.vb
Visual Basic
mit
219
Imports PlayerIOClient Public NotInheritable Class WorldPortalPlaceUploadMessage Inherits BlockPlaceUploadMessage Public ReadOnly PortalTarget As String Public Sub New(layer As Layer, x As Integer, y As Integer, block As WorldPortalBlock, portalTarget As String) MyBase.New(layer, x, y, DirectCast(block, Block)) Me.PortalTarget = portalTarget End Sub Friend Overrides Function GetMessage(game As IGame) As Message If IsWorldPortal(Block) Then Dim message As Message = MyBase.GetMessage(game) message.Add(PortalTarget) Return message Else Return MyBase.GetMessage(game) End If End Function Friend Overrides Function SendMessage(client As IClient(Of Player)) As Boolean client.Connection.Send(Me) Return True End Function End Class
TeamEEDev/EECloud
EECloud.API/Messages/Upload/WorldPortalPlaceUploadMessage.vb
Visual Basic
mit
876
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Criteria 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.Panel1 = New System.Windows.Forms.Panel() Me.cb_event = New System.Windows.Forms.ComboBox() Me.txt_score = New System.Windows.Forms.TextBox() Me.txt_description = New System.Windows.Forms.TextBox() Me.Label1 = New System.Windows.Forms.Label() Me.Label4 = New System.Windows.Forms.Label() Me.Label2 = New System.Windows.Forms.Label() Me.dgv_criteria = New System.Windows.Forms.DataGridView() Me.id = New System.Windows.Forms.DataGridViewTextBoxColumn() Me.event_name = New System.Windows.Forms.DataGridViewTextBoxColumn() Me.description = New System.Windows.Forms.DataGridViewTextBoxColumn() Me.score = New System.Windows.Forms.DataGridViewTextBoxColumn() Me.btn_add = New System.Windows.Forms.Button() Me.btn_save = New System.Windows.Forms.Button() Me.btn_update = New System.Windows.Forms.Button() Me.btn_edit = New System.Windows.Forms.Button() Me.btn_delete = New System.Windows.Forms.Button() Me.btn_cancel = New System.Windows.Forms.Button() Me.Panel1.SuspendLayout() CType(Me.dgv_criteria, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'Panel1 ' Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.Panel1.Controls.Add(Me.cb_event) Me.Panel1.Controls.Add(Me.txt_score) Me.Panel1.Controls.Add(Me.txt_description) Me.Panel1.Controls.Add(Me.Label1) Me.Panel1.Controls.Add(Me.Label4) Me.Panel1.Controls.Add(Me.Label2) Me.Panel1.Location = New System.Drawing.Point(12, 12) Me.Panel1.Name = "Panel1" Me.Panel1.Size = New System.Drawing.Size(290, 209) Me.Panel1.TabIndex = 6 ' 'cb_event ' Me.cb_event.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList Me.cb_event.Enabled = False Me.cb_event.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cb_event.FormattingEnabled = True Me.cb_event.Location = New System.Drawing.Point(7, 33) Me.cb_event.Name = "cb_event" Me.cb_event.Size = New System.Drawing.Size(268, 28) Me.cb_event.TabIndex = 3 ' 'txt_score ' Me.txt_score.Enabled = False Me.txt_score.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.txt_score.Location = New System.Drawing.Point(7, 163) Me.txt_score.Name = "txt_score" Me.txt_score.Size = New System.Drawing.Size(268, 26) Me.txt_score.TabIndex = 1 ' 'txt_description ' Me.txt_description.Enabled = False Me.txt_description.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.txt_description.Location = New System.Drawing.Point(7, 99) Me.txt_description.Name = "txt_description" Me.txt_description.Size = New System.Drawing.Size(268, 26) Me.txt_description.TabIndex = 1 ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label1.Location = New System.Drawing.Point(3, 76) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(99, 20) Me.Label1.TabIndex = 0 Me.Label1.Text = "Description:*" ' 'Label4 ' Me.Label4.AutoSize = True Me.Label4.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label4.Location = New System.Drawing.Point(3, 10) Me.Label4.Name = "Label4" Me.Label4.Size = New System.Drawing.Size(60, 20) Me.Label4.TabIndex = 0 Me.Label4.Text = "Event:*" ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label2.Location = New System.Drawing.Point(3, 140) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(61, 20) Me.Label2.TabIndex = 0 Me.Label2.Text = "Score:*" ' 'dgv_criteria ' Me.dgv_criteria.AllowUserToAddRows = False Me.dgv_criteria.AllowUserToDeleteRows = False Me.dgv_criteria.AllowUserToOrderColumns = True Me.dgv_criteria.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize Me.dgv_criteria.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.id, Me.event_name, Me.description, Me.score}) Me.dgv_criteria.Location = New System.Drawing.Point(319, 12) Me.dgv_criteria.Name = "dgv_criteria" Me.dgv_criteria.ReadOnly = True Me.dgv_criteria.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect Me.dgv_criteria.Size = New System.Drawing.Size(677, 483) Me.dgv_criteria.TabIndex = 7 ' 'id ' Me.id.HeaderText = "Id" Me.id.Name = "id" Me.id.ReadOnly = True Me.id.Visible = False ' 'event_name ' Me.event_name.HeaderText = "Event" Me.event_name.Name = "event_name" Me.event_name.ReadOnly = True Me.event_name.Width = 150 ' 'description ' Me.description.HeaderText = "Description" Me.description.Name = "description" Me.description.ReadOnly = True Me.description.Width = 350 ' 'score ' Me.score.HeaderText = "Score" Me.score.Name = "score" Me.score.ReadOnly = True ' 'btn_add ' Me.btn_add.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.btn_add.Location = New System.Drawing.Point(364, 501) Me.btn_add.Name = "btn_add" Me.btn_add.Size = New System.Drawing.Size(93, 40) Me.btn_add.TabIndex = 18 Me.btn_add.Text = "Add" Me.btn_add.UseVisualStyleBackColor = True ' 'btn_save ' Me.btn_save.Enabled = False Me.btn_save.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.btn_save.Location = New System.Drawing.Point(463, 501) Me.btn_save.Name = "btn_save" Me.btn_save.Size = New System.Drawing.Size(93, 40) Me.btn_save.TabIndex = 19 Me.btn_save.Text = "Save" Me.btn_save.UseVisualStyleBackColor = True ' 'btn_update ' Me.btn_update.Enabled = False Me.btn_update.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.btn_update.Location = New System.Drawing.Point(661, 501) Me.btn_update.Name = "btn_update" Me.btn_update.Size = New System.Drawing.Size(93, 40) Me.btn_update.TabIndex = 20 Me.btn_update.Text = "Update" Me.btn_update.UseVisualStyleBackColor = True ' 'btn_edit ' Me.btn_edit.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.btn_edit.Location = New System.Drawing.Point(562, 501) Me.btn_edit.Name = "btn_edit" Me.btn_edit.Size = New System.Drawing.Size(93, 40) Me.btn_edit.TabIndex = 21 Me.btn_edit.Text = "Edit" Me.btn_edit.UseVisualStyleBackColor = True ' 'btn_delete ' Me.btn_delete.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.btn_delete.Location = New System.Drawing.Point(760, 501) Me.btn_delete.Name = "btn_delete" Me.btn_delete.Size = New System.Drawing.Size(93, 40) Me.btn_delete.TabIndex = 22 Me.btn_delete.Text = "Delete" Me.btn_delete.UseVisualStyleBackColor = True ' 'btn_cancel ' Me.btn_cancel.Enabled = False Me.btn_cancel.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.btn_cancel.Location = New System.Drawing.Point(859, 501) Me.btn_cancel.Name = "btn_cancel" Me.btn_cancel.Size = New System.Drawing.Size(93, 40) Me.btn_cancel.TabIndex = 23 Me.btn_cancel.Text = "Cancel" Me.btn_cancel.UseVisualStyleBackColor = True ' 'Criteria ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(1008, 729) Me.Controls.Add(Me.btn_add) Me.Controls.Add(Me.btn_save) Me.Controls.Add(Me.btn_update) Me.Controls.Add(Me.btn_edit) Me.Controls.Add(Me.btn_delete) Me.Controls.Add(Me.btn_cancel) Me.Controls.Add(Me.dgv_criteria) Me.Controls.Add(Me.Panel1) Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "Criteria" Me.ShowIcon = False Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Criteria" Me.Panel1.ResumeLayout(False) Me.Panel1.PerformLayout() CType(Me.dgv_criteria, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents Panel1 As System.Windows.Forms.Panel Friend WithEvents cb_event As System.Windows.Forms.ComboBox Friend WithEvents txt_score As System.Windows.Forms.TextBox Friend WithEvents txt_description As System.Windows.Forms.TextBox Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents Label4 As System.Windows.Forms.Label Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents dgv_criteria As System.Windows.Forms.DataGridView Friend WithEvents btn_add As System.Windows.Forms.Button Friend WithEvents btn_save As System.Windows.Forms.Button Friend WithEvents btn_update As System.Windows.Forms.Button Friend WithEvents btn_edit As System.Windows.Forms.Button Friend WithEvents btn_delete As System.Windows.Forms.Button Friend WithEvents btn_cancel As System.Windows.Forms.Button Friend WithEvents id As System.Windows.Forms.DataGridViewTextBoxColumn Friend WithEvents event_name As System.Windows.Forms.DataGridViewTextBoxColumn Friend WithEvents description As System.Windows.Forms.DataGridViewTextBoxColumn Friend WithEvents score As System.Windows.Forms.DataGridViewTextBoxColumn End Class
kmligue/Tabulation-System---Server
Tabulation System - Server/Criteria.Designer.vb
Visual Basic
mit
12,373
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace RowsAndColumns Partial Public Class MakeRowsColumnsReadOnly '''<summary> '''btnMakeCellReadOnly control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents btnMakeCellReadOnly As Global.System.Web.UI.WebControls.Button '''<summary> '''GridWeb1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents GridWeb1 As Global.Aspose.Cells.GridWeb.GridWeb End Class End Namespace
maria-shahid-aspose/Aspose.Cells-for-.NET
Examples.GridWeb/VisualBasic/RowsAndColumns/MakeRowsColumnsReadOnly.aspx.designer.vb
Visual Basic
mit
1,141
'*******************************************************************************************' ' ' ' Download Free Evaluation Version From: https://bytescout.com/download/web-installer ' ' ' ' Also available as Web API! Get free API Key https://app.pdf.co/signup ' ' ' ' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. ' ' https://www.bytescout.com ' ' https://www.pdf.co ' '*******************************************************************************************' Imports System.IO Imports System.Net Imports System.Threading Imports Newtonsoft.Json Imports Newtonsoft.Json.Linq ' Cloud API asynchronous "PDF To CSV" job example. ' Allows to avoid timeout errors when processing huge or scanned PDF documents. Module Module1 ' The authentication key (API Key). ' Get your own by registering at https://app.pdf.co Const API_KEY As String = "***********************************" ' Direct URL of source PDF file. ' You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/ Const SourceFileUrl As String = "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-to-csv/sample.pdf" ' Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. Const Pages As String = "" ' PDF document password. Leave empty for unprotected documents. Const Password As String = "" ' Destination CSV file name Const DestinationFile As String = ".\result.csv" ' (!) Make asynchronous job Const Async As Boolean = True Sub Main() ' Create standard .NET web client instance Dim webClient As WebClient = New WebClient() ' Set API Key webClient.Headers.Add("x-api-key", API_KEY) ' Set JSON content type webClient.Headers.Add("Content-Type", "application/json") ' Prepare URL for `PDF To CSV` API call Dim url As String = "https://api.pdf.co/v1/pdf/convert/to/csv" ' Prepare requests params as JSON ' See documentation: https : //apidocs.pdf.co Dim parameters As New Dictionary(Of String, Object) parameters.Add("name", Path.GetFileName(DestinationFile)) parameters.Add("password", Password) parameters.Add("pages", Pages) parameters.Add("url", SourceFileUrl) parameters.Add("async", Async) ' Convert dictionary of params to JSON Dim jsonPayload As String = JsonConvert.SerializeObject(parameters) Try ' Execute POST request with JSON payload Dim response As String = webClient.UploadString(url, jsonPayload) ' Parse JSON response Dim json As JObject = JObject.Parse(response) If json("error").ToObject(Of Boolean) = False Then ' Asynchronous job ID Dim jobId As String = json("jobId").ToString() ' URL of generated CSV file that will available after the job completion Dim resultFileUrl As String = json("url").ToString() ' Check the job status in a loop. ' If you don't want to pause the main thread you can rework the code ' to use a separate thread for the status checking and completion. Do Dim status As String = CheckJobStatus(jobId) ' Possible statuses: "working", "failed", "aborted", "success". ' Display timestamp and status (for demo purposes) Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status) If status = "success" Then ' Download CSV file webClient.DownloadFile(resultFileUrl, DestinationFile) Console.WriteLine("Generated CSV file saved as ""{0}"" file.", DestinationFile) Exit Do ElseIf status = "working" Then ' Pause for a few seconds Thread.Sleep(3000) Else Console.WriteLine(status) Exit Do End If Loop Else Console.WriteLine(json("message").ToString()) End If Catch ex As WebException Console.WriteLine(ex.ToString()) End Try webClient.Dispose() Console.WriteLine() Console.WriteLine("Press any key...") Console.ReadKey() End Sub Function CheckJobStatus(jobId As String) As String Using webClient As WebClient = New WebClient() ' Set API Key webClient.Headers.Add("x-api-key", API_KEY) Dim url As String = "https://api.pdf.co/v1/job/check?jobid=" + jobId Dim response As String = webClient.DownloadString(url) Dim json As JObject = JObject.Parse(response) Return Convert.ToString(json("status")) End Using End Function End Module
bytescout/ByteScout-SDK-SourceCode
PDF.co Web API/PDF To CSV API/VB.NET/Convert PDF To CSV From URL Asynchronously/Module1.vb
Visual Basic
apache-2.0
5,082
'*******************************************************************************************' ' ' ' Download Free Evaluation Version From: https://bytescout.com/download/web-installer ' ' ' ' Also available as Web API! Get free API Key https://app.pdf.co/signup ' ' ' ' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. ' ' https://www.bytescout.com ' ' https://www.pdf.co ' '*******************************************************************************************' Imports Bytescout.PDFExtractor Namespace PDF2XML Class Program Shared Sub Main(ByVal args As String()) ' Create Bytescout.PDFExtractor.XMLExtractor instance Dim extractor As New XMLExtractor() extractor.RegistrationName = "demo" extractor.RegistrationKey = "demo" ' Load sample PDF document extractor.LoadDocumentFromFile("sample3.pdf") ' Add the following params to get clean data with word nodes only extractor.DetectNewColumnBySpacesRatio = 0.1 ' this splits all text into words extractor.PreserveFormattingOnTextExtraction = False ' Get rid Of empty nodes extractor.SaveXMLToFile("output.XML") ' Cleanup extractor.Dispose() Console.WriteLine() Console.WriteLine("Data has been extracted to 'output.XML' file.") Console.WriteLine() Console.WriteLine("Press any key...") Console.ReadKey() End Sub End Class End Namespace
bytescout/ByteScout-SDK-SourceCode
PDF Extractor SDK/VB.NET/Get Word Coordinates in XML/Module1.vb
Visual Basic
apache-2.0
2,047
'------------------------------------------------------------------------------ ' <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_Project <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 <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.Lycan.Xml.My_Project.MySettings Get Return Global.Lycan.Xml.My_Project.MySettings.Default End Get End Property End Module End NameSpace
kinetiq/Lycan.NET
Source/Lycan.Xml/My Project/Settings.Designer.vb
Visual Basic
apache-2.0
2,930
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Demos.WPF.VisualBasic.GanttChartDataGrid.TimeConstraints.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
DlhSoftTeam/GanttChartLightLibrary-Demos
GanttChartLightLibraryDemos/Demos/Samples/WPF-VisualBasic/GanttChartDataGrid/TimeConstraints/My Project/Resources.Designer.vb
Visual Basic
mit
2,762
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Collections.ObjectModel Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Binder Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend MustInherit Class SourceParameterSymbol Inherits SourceParameterSymbolBase Implements IAttributeTargetSymbol Private ReadOnly _location As Location Private ReadOnly _name As String Private ReadOnly _type As TypeSymbol Friend Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location) MyBase.New(container, ordinal) _name = name _type = type _location = location End Sub Friend ReadOnly Property Location As Location Get Return _location End Get End Property Public NotOverridable Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend NotOverridable Overrides ReadOnly Property HasOptionCompare As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get ' Ideally we should look for IDispatchConstantAttribute on this source parameter symbol, ' but the native VB compiler respects this attribute only on metadata parameter symbols, we do the same. ' See Devdiv bug #10789 (Handle special processing of object type without a default value per VB Language Spec 11.8.2 Applicable Methods) for details. Return False End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get ' Ideally we should look for IUnknownConstantAttribute on this source parameter symbol, ' but the native VB compiler respects this attribute only on metadata parameter symbols, we do the same. ' See Devdiv bug #10789 (Handle special processing of object type without a default value per VB Language Spec 11.8.2 Applicable Methods) for details. Return False End Get End Property Public NotOverridable Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get If _location IsNot Nothing Then Return ImmutableArray.Create(Of Location)(_location) Else Return ImmutableArray(Of Location).Empty End If End Get End Property Public NotOverridable Overrides ReadOnly Property Type As TypeSymbol Get Return _type End Get End Property Public MustOverride Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Friend MustOverride Overrides ReadOnly Property CountOfCustomModifiersPrecedingByRef As UShort Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If IsImplicitlyDeclared Then Return ImmutableArray(Of SyntaxReference).Empty Else Return GetDeclaringSyntaxReferenceHelper(Of ParameterSyntax)(Me.Locations) End If End Get End Property Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get If Me.ContainingSymbol.IsImplicitlyDeclared Then If TryCast(Me.ContainingSymbol, MethodSymbol)?.MethodKind = MethodKind.DelegateInvoke AndAlso Not Me.ContainingType.AssociatedSymbol?.IsImplicitlyDeclared Then Return False End If Return True End If Return (GetMatchingPropertyParameter() IsNot Nothing) End Get End Property ''' <summary> ''' Is this an accessor parameter that came from the associated property? If so, ''' return it, else return Nothing. ''' </summary> Private Function GetMatchingPropertyParameter() As ParameterSymbol Dim containingMethod = TryCast(ContainingSymbol, MethodSymbol) If containingMethod IsNot Nothing AndAlso containingMethod.IsAccessor() Then Dim containingProperty = TryCast(containingMethod.AssociatedSymbol, PropertySymbol) If containingProperty IsNot Nothing AndAlso Ordinal < containingProperty.ParameterCount Then ' We match a parameter on our containing property. Return containingProperty.Parameters(Ordinal) End If End If Return Nothing End Function #Region "Attributes" ' Attributes on corresponding parameters of partial methods are merged. ' We always create a complex parameter for a partial definition to store potential merged attributes there. ' At the creation time we don't know if the corresponding partial implementation has attributes so we need to always assume it might. ' ' Unlike in C#, where both partial definition and partial implementation have partial syntax and ' hence we create a complex parameter for both of them, in VB partial implementation Sub syntax ' is no different from non-partial Sub. Therefore we can't determine at the creation time whether ' a parameter of a Sub that is not a partial definition might need to store attributes or not. ' ' We therefore need to virtualize the storage for attribute data. Simple parameter of a partial implementation ' uses attribute storage of the corresponding partial definition parameter. ' ' When an implementation parameter is asked for attributes it gets them from the definition parameter: ' 1) If the implementation is a simple parameter it calls GetAttributeBag on the definition. ' 2) If it is a complex parameter it copies the data from the definition using BoundAttributesSource. Friend MustOverride Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) Friend MustOverride Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData Friend MustOverride Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData Friend MustOverride ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Friend NotOverridable Overrides ReadOnly Property HasParamArrayAttribute As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDefaultValueAttribute As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.DefaultParameterValue <> ConstantValue.Unset End Get End Property Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Parameter End Get End Property ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> Public NotOverridable Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData ' Declare methods need to know early what marshalling type are their parameters of to determine ByRef-ness. Dim containingSymbol = Me.ContainingSymbol If containingSymbol.Kind = SymbolKind.Method AndAlso DirectCast(containingSymbol, MethodSymbol).MethodKind = MethodKind.DeclareMethod Then If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.MarshalAsAttribute) Then Dim hasAnyDiagnostics As Boolean = False Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasMarshalAsAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If End If Dim possibleValidParamArrayTarget As Boolean = False Select Case containingSymbol.Kind Case SymbolKind.Property possibleValidParamArrayTarget = True Case SymbolKind.Method Select Case DirectCast(containingSymbol, MethodSymbol).MethodKind Case MethodKind.Conversion, MethodKind.UserDefinedOperator, MethodKind.EventAdd, MethodKind.EventRemove Debug.Assert(Not possibleValidParamArrayTarget) Case Else possibleValidParamArrayTarget = True End Select End Select If possibleValidParamArrayTarget AndAlso VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ParamArrayAttribute) Then Dim hasAnyDiagnostics As Boolean = False Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasParamArrayAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DefaultParameterValueAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DefaultParameterValueAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DecimalConstantAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DecimalConstantAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DateTimeConstantAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DateTimeConstantAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerLineNumberAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerLineNumberAttribute = True ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerFilePathAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerFilePathAttribute = True ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerMemberNameAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerMemberNameAttribute = True End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function ' It is not strictly necessary to decode default value attributes early in VB, ' but it is necessary in C#, so this keeps the implementations consistent. Private Function EarlyDecodeAttributeForDefaultParameterValue(description As AttributeDescription, ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(description.Equals(AttributeDescription.DefaultParameterValueAttribute) OrElse description.Equals(AttributeDescription.DecimalConstantAttribute) OrElse description.Equals(AttributeDescription.DateTimeConstantAttribute)) Dim hasAnyDiagnostics = False Dim attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) Dim value As ConstantValue If attribute.HasErrors Then value = ConstantValue.Bad hasAnyDiagnostics = True Else value = DecodeDefaultParameterValueAttribute(description, attribute) End If Dim paramData = arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData)() If paramData.DefaultParameterValue = ConstantValue.Unset Then paramData.DefaultParameterValue = value End If Return If(hasAnyDiagnostics, Nothing, attribute) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) Debug.Assert(arguments.SymbolPart = AttributeLocation.None) ' Differences from C#: ' ' DefaultParameterValueAttribute ' - emitted as is, not treated as pseudo-custom attribute ' - checked (along with DecimalConstantAttribute and DateTimeConstantAttribute) for consistency with any explicit default value ' ' OptionalAttribute ' - Not used by the language, only syntactically optional parameters or metadata optional parameters are recognized by overload resolution. ' OptionalAttribute is checked for in emit phase. ' ' ParamArrayAttribute ' - emitted as is, no error reported ' - Dev11 incorrectly emits the attribute twice ' ' InAttribute, OutAttribute ' - metadata flag set, no diagnostics reported, don't influence language semantics If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then arguments.Diagnostics.Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If If attrData.IsTargetAttribute(Me, AttributeDescription.DefaultParameterValueAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DefaultParameterValueAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DecimalConstantAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DecimalConstantAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DateTimeConstantAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DateTimeConstantAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.InAttribute) Then arguments.GetOrCreateData(Of CommonParameterWellKnownAttributeData)().HasInAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.OutAttribute) Then arguments.GetOrCreateData(Of CommonParameterWellKnownAttributeData)().HasOutAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.MarshalAsAttribute) Then MarshalAsAttributeDecoder(Of CommonParameterWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation).Decode(arguments, AttributeTargets.Parameter, MessageProvider.Instance) End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Private Sub DecodeDefaultParameterValueAttribute(description As AttributeDescription, ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim attribute = arguments.Attribute Dim diagnostics = arguments.Diagnostics Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Debug.Assert(diagnostics IsNot Nothing) Dim value = DecodeDefaultParameterValueAttribute(description, attribute) If Not value.IsBad Then VerifyParamDefaultValueMatchesAttributeIfAny(value, arguments.AttributeSyntaxOpt, diagnostics) End If End Sub ''' <summary> ''' Verify the default value matches the default value from any earlier attribute ''' (DefaultParameterValueAttribute, DateTimeConstantAttribute or DecimalConstantAttribute). ''' If not, report ERR_ParamDefaultValueDiffersFromAttribute. ''' </summary> Protected Sub VerifyParamDefaultValueMatchesAttributeIfAny(value As ConstantValue, syntax As VisualBasicSyntaxNode, diagnostics As DiagnosticBag) Dim data = GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing Then Dim attrValue = data.DefaultParameterValue If attrValue <> ConstantValue.Unset AndAlso value <> attrValue Then Binder.ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ParamDefaultValueDiffersFromAttribute) End If End If End Sub Private Function DecodeDefaultParameterValueAttribute(description As AttributeDescription, attribute As VisualBasicAttributeData) As ConstantValue Debug.Assert(Not attribute.HasErrors) If description.Equals(AttributeDescription.DefaultParameterValueAttribute) Then Return DecodeDefaultParameterValueAttribute(attribute) ElseIf description.Equals(AttributeDescription.DecimalConstantAttribute) Then Return attribute.DecodeDecimalConstantValue() Else Debug.Assert(description.Equals(AttributeDescription.DateTimeConstantAttribute)) Return attribute.DecodeDateTimeConstantValue() End If End Function Private Function DecodeDefaultParameterValueAttribute(attribute As VisualBasicAttributeData) As ConstantValue Debug.Assert(attribute.CommonConstructorArguments.Length = 1) ' the type of the value is the type of the expression in the attribute Dim arg = attribute.CommonConstructorArguments(0) Dim specialType = If(arg.Kind = TypedConstantKind.Enum, DirectCast(arg.Type, INamedTypeSymbol).EnumUnderlyingType.SpecialType, arg.Type.SpecialType) Dim constantValueDiscriminator = ConstantValue.GetDiscriminator(specialType) If constantValueDiscriminator = ConstantValueTypeDiscriminator.Bad Then If arg.Kind <> TypedConstantKind.Array AndAlso arg.Value Is Nothing AndAlso Type.IsReferenceType Then Return ConstantValue.Null End If Return ConstantValue.Bad End If Return ConstantValue.Create(arg.Value, constantValueDiscriminator) End Function Friend NotOverridable Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get Dim data = GetDecodedWellKnownAttributeData() If data IsNot Nothing Then Return data.MarshallingInformation End If ' Default marshalling for string parameters of Declare methods (ByRef or ByVal) If Type.IsStringType() Then Dim container As Symbol = ContainingSymbol If container.Kind = SymbolKind.Method Then Dim methodSymbol = DirectCast(container, MethodSymbol) If methodSymbol.MethodKind = MethodKind.DeclareMethod Then Dim info As New MarshalPseudoCustomAttributeData() Debug.Assert(IsByRef) If IsExplicitByRef Then Dim pinvoke As DllImportData = methodSymbol.GetDllImportData() Select Case pinvoke.CharacterSet Case Cci.Constants.CharSet_None, CharSet.Ansi info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_AnsiBStr) Case Cci.Constants.CharSet_Auto info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_TBStr) Case CharSet.Unicode info.SetMarshalAsSimpleType(UnmanagedType.BStr) Case Else Throw ExceptionUtilities.UnexpectedValue(pinvoke.CharacterSet) End Select Else info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_VBByRefStr) End If Return info End If End If End If Return Nothing End Get End Property Public NotOverridable Overrides ReadOnly Property IsByRef As Boolean Get If IsExplicitByRef Then Return True End If ' String parameters of Declare methods without explicit MarshalAs attribute are always ByRef, even if they are declared ByVal. If Type.IsStringType() AndAlso ContainingSymbol.Kind = SymbolKind.Method AndAlso DirectCast(ContainingSymbol, MethodSymbol).MethodKind = MethodKind.DeclareMethod Then Dim data = GetEarlyDecodedWellKnownAttributeData() Return data Is Nothing OrElse Not data.HasMarshalAsAttribute End If Return False End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMetadataOut As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasOutAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMetadataIn As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasInAttribute End Get End Property #End Region End Class Friend Enum SourceParameterFlags As Byte [ByVal] = 1 << 0 [ByRef] = 1 << 1 [Optional] = 1 << 2 [ParamArray] = 1 << 3 End Enum End Namespace
vslsnap/roslyn
src/Compilers/VisualBasic/Portable/Symbols/Source/SourceParameterSymbol.vb
Visual Basic
apache-2.0
25,167
' ' DotNetNuke® - http://www.dotnetnuke.com ' Copyright (c) 2002-2014 ' by DotNetNuke Corporation ' ' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ' documentation files (the "Software"), to deal in the Software without restriction, including without limitation ' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and ' to permit persons to whom the Software is furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all copies or substantial portions ' of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. ' Imports System 'Imports System.Configuration Imports System.Web.Compilation Imports System.Reflection Namespace DotNetNuke.UI.Utilities Public Class Reflection #Region "Public Shared Methods" Public Shared Function CreateObject(ByVal TypeName As String, ByVal CacheKey As String) As Object Return CreateObject(TypeName, CacheKey, True) End Function Public Shared Function CreateObject(ByVal TypeName As String, ByVal CacheKey As String, ByVal UseCache As Boolean) As Object ' dynamically create the object Return Activator.CreateInstance(CreateType(TypeName, CacheKey, UseCache)) End Function Public Shared Function CreateObject(Of T)() As T ' dynamically create the object Return Activator.CreateInstance(Of T)() End Function Public Shared Function CreateType(ByVal TypeName As String) As Type Return CreateType(TypeName, "", True, False) End Function Public Shared Function CreateType(ByVal TypeName As String, ByVal IgnoreErrors As Boolean) As Type Return CreateType(TypeName, "", True, IgnoreErrors) End Function Public Shared Function CreateType(ByVal TypeName As String, ByVal CacheKey As String, ByVal UseCache As Boolean) As Type Return CreateType(TypeName, CacheKey, UseCache, False) End Function Public Shared Function CreateType(ByVal TypeName As String, ByVal CacheKey As String, ByVal UseCache As Boolean, ByVal IgnoreErrors As Boolean) As Type If CacheKey = "" Then CacheKey = TypeName End If Dim objType As Type = Nothing ' use the cache for performance If UseCache Then objType = CType(DataCache.GetCache(CacheKey), Type) End If ' is the type in the cache? If objType Is Nothing Then Try ' use reflection to get the type of the class objType = BuildManager.GetType(TypeName, True, True) If UseCache Then ' insert the type into the cache DataCache.SetCache(CacheKey, objType) End If Catch exc As Exception ' could not load the type If Not IgnoreErrors Then 'LogException(exc) Throw exc End If End Try End If Return objType End Function Public Shared Function CreateInstance(ByVal Type As Type) As Object If Not Type Is Nothing Then Return Type.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, Nothing, Nothing, Nothing, Nothing) Else Return Nothing End If End Function Public Shared Function GetProperty(ByVal Type As Type, ByVal PropertyName As String, ByVal Target As Object) As Object If Not Type Is Nothing Then Return Type.InvokeMember(PropertyName, System.Reflection.BindingFlags.GetProperty, Nothing, Target, Nothing) Else Return Nothing End If End Function Public Shared Sub SetProperty(ByVal Type As Type, ByVal PropertyName As String, ByVal Target As Object, ByVal Args() As Object) If Not Type Is Nothing Then Type.InvokeMember(PropertyName, System.Reflection.BindingFlags.SetProperty, Nothing, Target, Args) End If End Sub Public Shared Function InvokeMethod(ByVal Type As Type, ByVal MethodName As String, ByVal Target As Object, ByVal Args() As Object) As Object If Not Type Is Nothing Then 'Can't use this. in case generic method defined, params match and ambiguous match found error 'Dim method As MethodInfo = Type.GetMethod(MethodName, Type.GetTypeArray(Args)) Dim match As Boolean = False Dim method As MethodInfo = Nothing For Each method In Type.GetMethods() If method.Name = MethodName AndAlso method.IsGenericMethod = False AndAlso method.GetParameters().Length = Args.Length Then If ParamsSameType(method.GetParameters(), Args) Then match = True Exit For End If End If Next If match AndAlso Not method Is Nothing Then Return method.Invoke(Target, Args) End If End If Return Nothing End Function Private Shared Function ParamsSameType(ByVal params() As ParameterInfo, ByVal Args() As Object) As Boolean Dim match As Boolean = True For i As Integer = 0 To Args.Length - 1 If params(i).ParameterType.IsAssignableFrom(Args(i).GetType()) = False Then match = False Exit For End If Next Return match End Function Public Shared Function InvokeGenericMethod(Of T)(ByVal Type As Type, ByVal MethodName As String, ByVal Target As Object, ByVal Args() As Object) As T If Not Type Is Nothing Then Dim method As MethodInfo = Nothing For Each method In Type.GetMembers() If method.Name = MethodName AndAlso method.IsGenericMethod Then Exit For Next If Not method Is Nothing Then Dim genMethod As MethodInfo = method.MakeGenericMethod(GetType(T)) Return CType(genMethod.Invoke(Target, Args), T) End If End If Return Nothing End Function #End Region End Class End Namespace
abukres/Dnn.Platform
DNN Platform/DotNetNuke.WebUtility/Reflection.vb
Visual Basic
mit
7,322
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.OnErrorStatements Public Class GoToKeywordRecommenderTests <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GoToAfterOnError() VerifyRecommendationsContain(<MethodBody>On Error |</MethodBody>, "GoTo") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GoToNotAfterOnErrorInLambda() VerifyRecommendationsAreExactly(<MethodBody> Dim x = Sub() On Error | End Sub</MethodBody>, Array.Empty(Of String)()) End Sub End Class End Namespace
VPashkov/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/OnErrorStatements/GoToKeywordRecommenderTests.vb
Visual Basic
apache-2.0
1,085
' 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.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Partial Friend Class EndConstructStatementVisitor Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As AbstractEndConstructResult ' If it's a event with a signature we don't want to spit since it can't be a custom ' event If node.AsClause Is Nothing Then Return Nothing End If If node.CustomKeyword.Kind <> SyntaxKind.CustomKeyword Then Return Nothing End If Dim eventBlock = node.GetAncestor(Of EventBlockSyntax)() ' If we have an End, we don't have to spit If Not eventBlock.EndEventStatement.IsMissing Then Return Nothing End If ' We need to generate our various handlers Dim lines As New List(Of String) lines.AddRange(GenerateAddOrRemoveHandler(node, SyntaxKind.AddHandlerKeyword)) lines.AddRange(GenerateAddOrRemoveHandler(node, SyntaxKind.RemoveHandlerKeyword)) lines.AddRange(GenerateRaiseEventHandler(node)) Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart) lines.Add(aligningWhitespace & "End Event") Return New SpitLinesResult(lines) End Function Private Function GenerateAddOrRemoveHandler(eventStatement As EventStatementSyntax, kind As SyntaxKind) As String() Dim type = _state.SemanticModel.GetTypeInfo(DirectCast(eventStatement.AsClause, SimpleAsClauseSyntax).Type, Me._cancellationToken) Dim position As Integer = eventStatement.SpanStart Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(position) & " " Return {aligningWhitespace & SyntaxFacts.GetText(kind) & "(value As " & type.Type.ToMinimalDisplayString(_state.SemanticModel, position, SymbolDisplayFormats.NameFormat) & ")", "", aligningWhitespace & "End " & SyntaxFacts.GetText(kind)} End Function Private Function GenerateRaiseEventHandler(eventStatement As EventStatementSyntax) As String() Dim type = TryCast(_state.SemanticModel.GetTypeInfo(DirectCast(eventStatement.AsClause, SimpleAsClauseSyntax).Type, Me._cancellationToken).Type, INamedTypeSymbol) Dim signature = "" If type IsNot Nothing AndAlso type.DelegateInvokeMethod IsNot Nothing Then Dim parameterStrings = type.DelegateInvokeMethod.Parameters.Select( Function(p) p.ToMinimalDisplayString(_state.SemanticModel, eventStatement.SpanStart)) signature = String.Join(", ", parameterStrings) End If Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(eventStatement.SpanStart) & " " Return {aligningWhitespace & "RaiseEvent(" & signature & ")", "", aligningWhitespace & "End RaiseEvent"} End Function End Class End Namespace
physhi/roslyn
src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_CustomEvents.vb
Visual Basic
apache-2.0
3,425
' 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.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This is a binder for use when early decoding of well known attributes. The binder will only bind expressions that can appear in an attribute. ''' Its purpose is to allow a symbol to safely decode any attribute without the possibility of any attribute related infinite recursion during binding. ''' If an attribute and its arguments are valid then this binder returns a BoundAttributeExpression otherwise it returns a BadExpression. ''' </summary> Friend NotInheritable Class EarlyWellKnownAttributeBinder Inherits Binder Private ReadOnly _owner As Symbol Friend Sub New(owner As Symbol, containingBinder As Binder) MyBase.New(containingBinder, isEarlyAttributeBinder:=True) Me._owner = owner End Sub Public Overrides ReadOnly Property ContainingMember As Symbol Get Return If(_owner, MyBase.ContainingMember) End Get End Property ' This binder is only used to bind expressions in an attribute context. Public Overrides ReadOnly Property BindingLocation As BindingLocation Get Return BindingLocation.Attribute End Get End Property ' Hide the GetAttribute overload which takes a diagnostic bag. ' This ensures that diagnostics from the early bound attributes are never preserved. Friend Shadows Function GetAttribute(node As AttributeSyntax, boundAttributeType As NamedTypeSymbol, <Out> ByRef generatedDiagnostics As Boolean) As SourceAttributeData Dim diagnostics = DiagnosticBag.GetInstance() Dim earlyAttribute = MyBase.GetAttribute(node, boundAttributeType, diagnostics) generatedDiagnostics = Not diagnostics.IsEmptyWithoutResolution() diagnostics.Free() Return earlyAttribute End Function ''' <summary> ''' Check that the syntax can appear in an attribute argument. ''' </summary> Friend Shared Function CanBeValidAttributeArgument(node As ExpressionSyntax, memberAccessBinder As Binder) As Boolean Debug.Assert(node IsNot Nothing) ' 11.2 Constant Expressions ' 'A constant expression is an expression whose value can be fully evaluated at compile time. The type of a constant expression can be Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Char, Single, Double, Decimal, Date, Boolean, String, Object, or any enumeration type. The following constructs are permitted in constant expressions: ' ' Literals (including Nothing). ' References to constant type members or constant locals. ' References to members of enumeration types. ' Parenthesized subexpressions. ' Coercion expressions, provided the target type is one of the types listed above. Coercions to and from String are an exception to this rule and are only allowed on null values because String conversions are always done in the current culture of the execution environment at run time. Note that constant coercion expressions can only ever use intrinsic conversions. ' The +, – and Not unary operators, provided the operand and result is of a type listed above. ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, provided each operand and result is of a type listed above. ' The conditional operator If, provided each operand and result is of a type listed above. ' The following run-time functions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ' ' In addition, attributes allow array expressions including both array literal and array creation expressions as well as GetType expressions. Select Case node.Kind Case _ SyntaxKind.NumericLiteralExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.CharacterLiteralExpression, SyntaxKind.TrueLiteralExpression, SyntaxKind.FalseLiteralExpression, SyntaxKind.NothingLiteralExpression, SyntaxKind.DateLiteralExpression ' Literals (including Nothing). Return True Case _ SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.GlobalName, SyntaxKind.IdentifierName, SyntaxKind.PredefinedType ' References to constant type members or constant locals. ' References to members of enumeration types. Return True Case SyntaxKind.ParenthesizedExpression ' Parenthesized subexpressions. Return True Case _ SyntaxKind.CTypeExpression, SyntaxKind.TryCastExpression, SyntaxKind.DirectCastExpression, SyntaxKind.PredefinedCastExpression ' Coercion expressions, provided the target type is one of the types listed above. ' Coercions to and from String are an exception to this rule and are only allowed on null values ' because String conversions are always done in the current culture of the execution environment ' at run time. Note that constant coercion expressions can only ever use intrinsic conversions. Return True Case _ SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.NotExpression ' The +, – and Not unary operators, provided the operand and result is of a type listed above. Return True Case _ SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.AndExpression, SyntaxKind.OrExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.AndAlsoExpression, SyntaxKind.OrElseExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, ' provided each operand and result is of a type listed above. Return True Case _ SyntaxKind.BinaryConditionalExpression, SyntaxKind.TernaryConditionalExpression ' The conditional operator If, provided each operand and result is of a type listed above. Return True Case SyntaxKind.InvocationExpression ' The following run-time functions may appear in constant expressions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty Dim memberAccess = TryCast(DirectCast(node, InvocationExpressionSyntax).Expression, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then Dim diagnostics = DiagnosticBag.GetInstance Dim boundExpression = memberAccessBinder.BindExpression(memberAccess, diagnostics) diagnostics.Free() If boundExpression.HasErrors Then Return False End If Dim boundMethodGroup = TryCast(boundExpression, BoundMethodGroup) If boundMethodGroup IsNot Nothing AndAlso boundMethodGroup.Methods.Length = 1 Then Dim method = boundMethodGroup.Methods(0) Dim compilation As VisualBasicCompilation = memberAccessBinder.Compilation If method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32) Then Return True End If End If End If Return False Case SyntaxKind.CollectionInitializer, SyntaxKind.ArrayCreationExpression, SyntaxKind.GetTypeExpression ' These are not constants and are special for attribute expressions. ' SyntaxKind.CollectionInitializer in this case really means ArrayLiteral, i.e.{1, 2, 3}. ' SyntaxKind.ArrayCreationExpression is array creation expression, i.e. new Char {'a'c, 'b'c}. ' SyntaxKind.GetTypeExpression is a GetType expression, i.e. GetType(System.String). Return True Case Else Return False End Select End Function Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions ' When early binding attributes, extension methods should always be ignored. Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.IgnoreExtensionMethods End Function End Class End Namespace
robinsedlaczek/roslyn
src/Compilers/VisualBasic/Portable/Binding/EarlyWellKnownAttributeBinder.vb
Visual Basic
apache-2.0
11,841
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateFromMembers.GenerateEqualsAndGetHashCode Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.GenerateFromMembers.GenerateEqualsAndGetHashCode ' <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCode)> <ExtensionOrder(After:=PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers)> Friend Class GenerateEqualsAndGetHashCodeCodeRefactoringProvider Inherits CodeRefactoringProvider Public Overrides Async Function ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task Dim document = context.Document Dim textSpan = context.Span Dim cancellationToken = context.CancellationToken Dim workspace = document.Project.Solution.Workspace If workspace.Kind = WorkspaceKind.MiscellaneousFiles Then Return End If Dim service = document.GetLanguageService(Of IGenerateEqualsAndGetHashCodeService)() Dim result = Await service.GenerateEqualsAndGetHashCodeAsync(document, textSpan, cancellationToken).ConfigureAwait(False) If Not result.ContainsChanges Then Return End If Dim actions = result.GetCodeRefactoring(cancellationToken).Actions context.RegisterRefactorings(actions) End Function End Class End Namespace
ValentinRueda/roslyn
src/Features/VisualBasic/Portable/CodeRefactorings/GenerateFromMembers/GenerateEqualsAndGetHashCode/GenerateEqualsAndGetHashCodeCodeRefactoringProvider.vb
Visual Basic
apache-2.0
1,683
Imports System.Drawing Public Class ColourRamps Public RampList As New ImageList Public fullRampList As New List(Of fullRamp) Public rampPicker As ComboBox Public Sub init(ByRef theComboBox As ComboBox) RampList.ImageSize = New Size(100, 10) RampList.ColorDepth = ColorDepth.Depth24Bit rampPicker = theComboBox 'get ramp settings file Dim rampFile As String = My.Resources.colourRamps Dim allRamps() As String = rampFile.Split(vbLf) Dim currentRamp() As String Dim currentRampClass As singleRamp Dim currentFullRampClass As fullRamp Dim currentColours() As String 'add random ramp first Dim tempFullRamp As New fullRamp RampList.Images.Add(tempFullRamp.createRandomBitmap) 'cycle through ramps (1 per line) adding each to image list For Each ramp As String In allRamps currentRamp = ramp.Split("|") currentFullRampClass = New fullRamp For i = 0 To currentRamp.Count - 2 currentRampClass = New singleRamp currentColours = currentRamp(i).Split(",") currentRampClass.startColour = Color.FromArgb(currentColours(0), currentColours(1), currentColours(2)) currentColours = currentRamp(i + 1).Split(",") currentRampClass.endColour = Color.FromArgb(currentColours(0), currentColours(1), currentColours(2)) currentFullRampClass.rampList.Add(currentRampClass) currentFullRampClass.createBitmap() Next fullRampList.Add(currentFullRampClass) RampList.Images.Add(currentFullRampClass.rampBitmap) Next 'add images to combobox For i As Int32 = 0 To RampList.Images.Count - 1 theComboBox.Items.Add("Item " & i.ToString) Next theComboBox.DropDownStyle = ComboBoxStyle.DropDownList theComboBox.DrawMode = DrawMode.OwnerDrawVariable theComboBox.ItemHeight = RampList.ImageSize.Height + 4 theComboBox.Width = RampList.ImageSize.Width + 18 theComboBox.MaxDropDownItems = RampList.Images.Count theComboBox.DropDownHeight = 200 AddHandler theComboBox.DrawItem, AddressOf CB_DrawItem End Sub Sub CB_DrawItem(ByVal sender As System.Object, ByVal e As DrawItemEventArgs) If e.Index <> -1 Then e.Graphics.DrawImage(RampList.Images(e.Index), e.Bounds.Left, e.Bounds.Top) End If End Sub End Class Public Class singleRamp Private _startColour As Color Public Property startColour() As Color Get Return _startColour End Get Set(ByVal value As Color) _startColour = value End Set End Property Private _endColour As Color Public Property endColour() As Color Get Return _endColour End Get Set(ByVal value As Color) _endColour = value End Set End Property End Class <Serializable()> _ Public Class fullRamp Public rampList As New List(Of singleRamp) Private _rampbitmap As Bitmap Public Property rampBitmap() As Bitmap Get Return _rampbitmap End Get Set(ByVal value As Bitmap) _rampbitmap = value End Set End Property Sub createBitmap() Dim theRampBitmap As New Bitmap(100, 10) Dim theCol As Color For i = 0 To 99 theCol = getColourByPercent(i + 1) For y As Integer = 0 To 9 theRampBitmap.SetPixel(i, y, theCol) Next Next rampBitmap = theRampBitmap End Sub Function createRandomBitmap() As Bitmap Dim rand As New Random Dim theRampBitmap As New Bitmap(100, 10) Dim theCol As Color For i = 0 To 99 theCol = Color.FromArgb(255, rand.Next(1, 254), rand.Next(1, 254), rand.Next(1, 254)) For y As Integer = 0 To 9 theRampBitmap.SetPixel(i, y, theCol) Next Next Return theRampBitmap End Function Function getColourByPercent(ByVal thePercent As Integer) As Color Dim ColourRampDescNum As Double = (100 / rampList.Count) Dim theRamp As singleRamp = rampList(Math.Floor((thePercent - 0.1) / ColourRampDescNum)) Dim finalPercent As Integer = Math.Floor((thePercent Mod ColourRampDescNum)) * rampList.Count ' If finalPercent = 0 Then Return theRamp.endColour 'Form1.TextBox1.Text = Form1.TextBox1.Text & vbCrLf & finalPercent Return BlendColor(theRamp.endColour, theRamp.startColour, (finalPercent / 100) * 255) End Function Public Shared Function BlendColor(color1 As Color, color2 As Color, ratio As Byte) As Color Dim color2Ratio = 255 - ratio Dim newR = CByte((CInt(color1.R) * ratio + CInt(color2.R) * color2Ratio) / 255) Dim newG = CByte((CInt(color1.G) * ratio + CInt(color2.G) * color2Ratio) / 255) Dim newB = CByte((CInt(color1.B) * ratio + CInt(color2.B) * color2Ratio) / 255) Return Color.FromArgb(newR, newG, newB) End Function End Class
JohnWilcock/OL3Designer
OL3Designer/Functions/ColourRamps.vb
Visual Basic
mit
5,227
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("DetectAdmin")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("DetectAdmin")> <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("bab995c2-e666-4182-b855-b16c443811c9")> ' 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")>
SaturnsVoid/GoBot2
Tools/Sources/DetectAdmin/DetectAdmin/My Project/AssemblyInfo.vb
Visual Basic
mit
1,131
 Partial Class controls_RmbEquipment Inherits Entities.Modules.PortalModuleBase Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init Dim FileName As String = System.IO.Path.GetFileNameWithoutExtension(Me.AppRelativeVirtualPath) If Not (Me.ID Is Nothing) Then 'this will fix it when its placed as a ChildUserControl Me.LocalResourceFile = Me.LocalResourceFile.Replace(Me.ID, FileName) Else ' this will fix it when its dynamically loaded using LoadControl method Me.LocalResourceFile = Me.LocalResourceFile & FileName & ".ascx.resx" Dim Locale = System.Threading.Thread.CurrentThread.CurrentCulture.Name Dim AppLocRes As New System.IO.DirectoryInfo(Me.LocalResourceFile.Replace(FileName & ".ascx.resx", "")) If Locale = PortalSettings.CultureCode Then 'look for portal varient If AppLocRes.GetFiles(FileName & ".ascx.Portal-" & PortalId & ".resx").Count > 0 Then Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", "Portal-" & PortalId & ".resx") End If Else If AppLocRes.GetFiles(FileName & ".ascx." & Locale & ".Portal-" & PortalId & ".resx").Count > 0 Then 'lookFor a CulturePortalVarient Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", Locale & ".Portal-" & PortalId & ".resx") ElseIf AppLocRes.GetFiles(FileName & ".ascx." & Locale & ".resx").Count > 0 Then 'look for a CultureVarient Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", Locale & ".resx") ElseIf AppLocRes.GetFiles(FileName & ".ascx.Portal-" & PortalId & ".resx").Count > 0 Then 'lookFor a PortalVarient Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", "Portal-" & PortalId & ".resx") End If End If End If End Sub Public Sub Initialize(ByVal settings As Hashtable) ttlReceipt.Text = DotNetNuke.Services.Localization.Localization.GetString("lblReceipt.Text", LocalResourceFile) hfNoReceiptLimit.Value = settings("NoReceipt") Dim _LIMIT As String = StaffBrokerFunctions.GetSetting("Currency", PortalId) & settings("NoReceipt") ddlVATReceipt.Items(2).Text = DotNetNuke.Services.Localization.Localization.GetString("NoReceipt.Text", LocalResourceFile).Replace("[LIMIT]", _LIMIT) ttlReceipt.HelpText = DotNetNuke.Services.Localization.Localization.GetString("lblReceipt.Help", LocalResourceFile).Replace("[LIMIT]", _LIMIT) ddlVATReceipt.Items(2).Enabled = (settings("NoReceipt") > 0) If settings("NoReceipt") = 0 And settings("ElectronicReceipts") = False Then ddlVATReceipt.SelectedValue = 1 ReceiptLine.Visible = False Else ReceiptLine.Visible = True End If If settings("VatAttrib") = "True" Then VATLine.Visible = True End If ddlVATReceipt.Items(1).Enabled = settings("ElectronicReceipts") Or ddlVATReceipt.SelectedValue = 2 Try If (Not String.IsNullOrEmpty(settings("DescriptionLength"))) And CInt(settings("DescriptionLength")) > 0 Then tbDesc.Attributes("maxLength") = CInt(settings("DescriptionLength")) If CInt(settings("DescriptionLength")) < 50 Then tbDesc.Columns = CInt(settings("DescriptionLength")) + 3 tbDesc.Width = Nothing End If End If Catch ex As Exception End Try End Sub Public Property ReceiptType() As Integer Get Return ddlVATReceipt.SelectedValue End Get Set(ByVal value As Integer) ddlVATReceipt.SelectedValue = value End Set End Property Public Property Comment() As String Get Return tbDesc.Text End Get Set(ByVal value As String) tbDesc.Text = value End Set End Property Public Property theDate() As Date Get Return CDate(dtDate.Text) End Get Set(ByVal value As Date) If value = Nothing Then dtDate.Text = Today.ToShortDateString Else dtDate.Text = value End If End Set End Property Public Property VAT() As Boolean Get Return cbVAT.Checked End Get Set(ByVal value As Boolean) cbVAT.Checked = value End Set End Property Public Property Amount() As Double Get Return Double.Parse(tbAmount.Text, New CultureInfo("en-US").NumberFormat) End Get Set(ByVal value As Double) tbAmount.Text = value.ToString("n2", New CultureInfo("en-US")) End Set End Property Public Property Taxable() As Boolean Get Return False End Get Set(ByVal value As Boolean) End Set End Property Public Property Spare1() As String ' type Get Return ddlType.SelectedValue End Get Set(ByVal value As String) ddlType.SelectedValue = value End Set End Property Public Property Spare2() As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property Public Property Spare3() As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property Public Property Spare4() As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property Public Property Spare5() As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property Public Property Receipt() As Boolean Get Return ddlVATReceipt.SelectedValue >= 0 End Get Set(ByVal value As Boolean) If value = False Then ddlVATReceipt.SelectedValue = -1 End If End Set End Property Public Property ErrorText() As String Get Return "" End Get Set(ByVal value As String) ErrorLbl.Text = value End Set End Property Public Function ValidateForm(ByVal userId As Integer) As Boolean If tbDesc.Text = "" Then ErrorLbl.Text = DotNetNuke.Services.Localization.Localization.GetString("Description.Error", LocalResourceFile) Return False End If Try Dim theDate As Date = dtDate.Text If theDate > Today Then ErrorLbl.Text = DotNetNuke.Services.Localization.Localization.GetString("OldDate.Error", LocalResourceFile) Return False End If Catch ex As Exception ErrorLbl.Text = DotNetNuke.Services.Localization.Localization.GetString("Date.Error", LocalResourceFile) Return False End Try Try Dim theAmount As Double = Double.Parse(tbAmount.Text, New CultureInfo("en-US").NumberFormat) If Amount <= 0 Then ErrorLbl.Text = DotNetNuke.Services.Localization.Localization.GetString("Amount.Error", LocalResourceFile) Return False End If If ddlVATReceipt.SelectedValue = "-1" And theAmount > CDbl(hfNoReceiptLimit.Value) Then ErrorLbl.Text = DotNetNuke.Services.Localization.Localization.GetString("AmountRec.Error", LocalResourceFile).Replace("[LIMIT]", StaffBrokerFunctions.GetSetting("Currency", PortalId) & hfNoReceiptLimit.Value) ddlVATReceipt.SelectedValue = 1 Return False End If Catch ex As Exception ErrorLbl.Text = DotNetNuke.Services.Localization.Localization.GetString("Amount.Error", LocalResourceFile) Return False End Try ErrorLbl.Text = "" Return True End Function End Class
GlobalTechnology/OpsInABox
DesktopModules/AgapeConnect/StaffRmb/Controls/RmbEquipment.ascx.vb
Visual Basic
mit
8,249
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:2.0.50727.3082 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On '''<summary> '''_Default class. '''</summary> '''<remarks> '''Auto-generated class. '''</remarks> Partial Public Class _Default '''<summary> '''Head1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead '''<summary> '''form1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm '''<summary> '''cbEdit control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents cbEdit As Global.System.Web.UI.WebControls.CheckBox '''<summary> '''VideoPanel1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents VideoPanel1 As Global.VideoPanel.VideoPanel End Class
Micmaz/DTIControls
VideoPanel/VideoPanelTester/VideoPanelTester/Default.aspx.designer.vb
Visual Basic
mit
1,680
Imports ServerMonitor.Core Public Class SqlDataRepository Implements IDataRepository Private _ConnectionString As String Public Sub New(connectionString As String) MyBase.New() Me._ConnectionString = connectionString End Sub Private Function GetConnection() As SqlClient.SqlConnection Dim lConn As SqlClient.SqlConnection = New SqlClient.SqlConnection(_ConnectionString) lConn.Open() Return lConn End Function Public Function GetServerInfo(serverName As String) As IRepositoryResult(Of ServerInfo) Implements IRepository.GetServerInfo Dim lServer As ServerInfo = New ServerInfo Dim lResult As IRepositoryResult(Of ServerInfo) = New RepositoryResult(Of ServerInfo)(lServer) Dim lIDServer As Integer = 0 Using lConnection As SqlClient.SqlConnection = GetConnection() Using lTransaction = lConnection.BeginTransaction Try Using lCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand("dbo.usp_MON_Server_Get", lConnection, lTransaction) lCmd.CommandType = CommandType.StoredProcedure With lCmd.Parameters .Add("@pServerName", SqlDbType.NVarChar, 50) End With With lCmd .Parameters("@pServerName").Value = serverName End With Using lDA As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(lCmd) Using lDT As DataTable = New DataTable lDA.Fill(lDT) If lDT.Rows.Count > 0 Then lIDServer = Integer.Parse(lDT.Rows(0).Item("IDServer").ToString) lServer.Server = lDT.Rows(0).Item("Name").ToString lServer.DomainWorkgroup = lDT.Rows(0).Item("Domain").ToString lServer.ReportDateTime = lDT.Rows(0).Item("UpdateDateTime").ToString End If End Using End Using End Using Using lCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand("dbo.usp_MON_ServerDataAggregate_List_ForServer", lConnection, lTransaction) lCmd.CommandType = CommandType.StoredProcedure With lCmd.Parameters .Add("@pIDServer", SqlDbType.Int) End With With lCmd .Parameters("@pIDServer").Value = lIDServer End With Using lDA As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(lCmd) Using lDT As DataTable = New DataTable lDA.Fill(lDT) For lIndex = 0 To lDT.Rows.Count - 1 Dim lAggregate As RawData = New RawData Dim lName As String = lDT.Rows(lIndex).Item("Name").ToString Dim lDomain As String = lDT.Rows(lIndex).Item("Domain").ToString lAggregate.DataKey = lDT.Rows(lIndex).Item("DataKey").ToString lAggregate.Data = lDT.Rows(lIndex).Item("Data").ToString If lServer.AggregateData Is Nothing Then lServer.AggregateData = New List(Of RawData) lServer.AggregateData.Add(lAggregate) Next End Using End Using End Using Using lCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand("dbo.usp_MON_ServerData_List_ForServer", lConnection, lTransaction) lCmd.CommandType = CommandType.StoredProcedure With lCmd.Parameters .Add("@pIDServer", SqlDbType.Int) End With With lCmd .Parameters("@pIDServer").Value = lIDServer End With Using lDA As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(lCmd) Using lDT As DataTable = New DataTable lDA.Fill(lDT) For lIndex = 0 To lDT.Rows.Count - 1 Dim lData As RawData = New RawData Dim lName As String = lDT.Rows(lIndex).Item("Name").ToString Dim lDomain As String = lDT.Rows(lIndex).Item("Domain").ToString lData.DataKey = lDT.Rows(lIndex).Item("DataKey").ToString lData.Data = lDT.Rows(lIndex).Item("Data").ToString If lServer.Data Is Nothing Then lServer.Data = New List(Of RawData) lServer.Data.Add(lData) Next End Using End Using End Using lTransaction.Commit() Catch ex As Exception lTransaction.Rollback() lResult = New RepositoryResult(Of List(Of ServerInfo))(ex) End Try End Using lConnection.Close() End Using Return lResult End Function Public Function ListServerInfo() As IRepositoryResult(Of List(Of ServerInfo)) Implements IRepository.ListServerInfo Dim lServers = New List(Of ServerInfo) Dim lResult As IRepositoryResult(Of List(Of ServerInfo)) = New RepositoryResult(Of List(Of ServerInfo))(lServers) Using lConnection As SqlClient.SqlConnection = GetConnection() Using lTransaction = lConnection.BeginTransaction Try Using lCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand("dbo.usp_MON_Server_List", lConnection, lTransaction) lCmd.CommandType = CommandType.StoredProcedure Using lDA As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(lCmd) Using lDT As DataTable = New DataTable lDA.Fill(lDT) For lIndex = 0 To lDT.Rows.Count - 1 Dim lServer As ServerInfo = New ServerInfo lServer.Server = lDT.Rows(lIndex).Item("Name").ToString lServer.DomainWorkgroup = lDT.Rows(lIndex).Item("Domain").ToString lServer.ReportDateTime = lDT.Rows(lIndex).Item("UpdateDateTime").ToString lResult.Result.Add(lServer) Next End Using End Using End Using Using lCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand("dbo.usp_MON_ServerDataAggregate_List", lConnection, lTransaction) lCmd.CommandType = CommandType.StoredProcedure Using lDA As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(lCmd) Using lDT As DataTable = New DataTable lDA.Fill(lDT) For lIndex = 0 To lDT.Rows.Count - 1 Dim lAggregate As RawData = New RawData Dim lName As String = lDT.Rows(lIndex).Item("Name").ToString Dim lDomain As String = lDT.Rows(lIndex).Item("Domain").ToString Dim lServer As ServerInfo = lResult.Result.FirstOrDefault(Function(si) si.DomainWorkgroup = lDomain AndAlso si.Server = lName) If lServer IsNot Nothing Then lAggregate.DataKey = lDT.Rows(lIndex).Item("DataKey").ToString lAggregate.Data = lDT.Rows(lIndex).Item("Data").ToString If lServer.AggregateData Is Nothing Then lServer.AggregateData = New List(Of RawData) lServer.AggregateData.Add(lAggregate) End If Next End Using End Using End Using lTransaction.Commit() Catch ex As Exception lTransaction.Rollback() lResult = New RepositoryResult(Of List(Of ServerInfo))(ex) End Try End Using lConnection.Close() End Using Return lResult End Function Public Function UpdateServerInfo(info As ServerInfo, settings As SystemSettings) As IRepositoryResult Implements IRepository.UpdateServerInfo Dim lResult As IRepositoryResult = New RepositoryResult() Using lConnection As SqlClient.SqlConnection = GetConnection() Using lTransaction = lConnection.BeginTransaction Try Using lCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand("dbo.usp_MON_ServerInfo_Write", lConnection, lTransaction) lCmd.CommandType = CommandType.StoredProcedure With lCmd.Parameters .Add("@pServerName", SqlDbType.NVarChar, 50) .Add("@pDomainName", SqlDbType.NVarChar, 100) .Add("@pUpdateDateTime", SqlDbType.DateTimeOffset) .Add("@pDataAggregate", SqlDbType.Structured) .Add("@pData", SqlDbType.Structured) End With With lCmd .Parameters("@pServerName").Value = info.Server .Parameters("@pDomainName").Value = info.DomainWorkgroup .Parameters("@pUpdateDateTime").Value = DateTimeOffset.UtcNow 'Build the server data as Json packets .Parameters("@pDataAggregate").Value = info.AsAggregateDataTable(settings) .Parameters("@pData").Value = info.AsJsonDataTable(settings) End With lCmd.ExecuteNonQuery() End Using lTransaction.Commit() Catch ex As Exception lTransaction.Rollback() lResult = New RepositoryResult(ex) End Try End Using lConnection.Close() End Using Return lResult End Function Public Function GetSystemSettings() As IRepositoryResult(Of SystemSettings) Implements IRepository.GetSystemSettings Dim lSystemSettings As SystemSettings = New SystemSettings Dim lResult As IRepositoryResult(Of SystemSettings) = New RepositoryResult(Of SystemSettings)(lSystemSettings) Using lConnection As SqlClient.SqlConnection = GetConnection() Using lTransaction = lConnection.BeginTransaction Try Using lCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand("dbo.usp_MON_Setting_List", lConnection, lTransaction) Using lDA As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(lCmd) Using lDT As DataTable = New DataTable lDA.Fill(lDT) If lDT.Rows.Count > 0 Then Dim DataKey As String Dim Data As String For lIndex = 0 To lDT.Rows.Count - 1 DataKey = lDT.Rows(lIndex).Item("DataKey").ToString Data = lDT.Rows(lIndex).Item("Data").ToString Select Case DataKey Case "MonitoredService" lSystemSettings.MonitoredServices.Add(Data) Case Else 'drop it on the floor... End Select Next End If End Using End Using End Using lTransaction.Commit() Catch ex As Exception lTransaction.Rollback() lResult = New RepositoryResult(ex) End Try End Using End Using Return lResult End Function End Class
redgumtech/servermonitor
ServerMonitor.Data/DataRepository.vb
Visual Basic
mit
13,313
Imports LiteDB Partial Class AddGig Inherits VerifiedUsersOnly Public Overrides Sub Page_Load(sender As Object, e As EventArgs) MyBase.Page_Load(sender, e) End Sub ''' <summary> ''' This method adds a new gig to the database, based on the submitted form. ''' </summary> ''' <param name="sender">event sender</param> ''' <param name="e">event arguments (not used here)</param> Public Sub Add(sender As Object, e As EventArgs) Handles btnAdd.Click ' TODO finish later... If txtGigName.Text.Length < 2 Then lblError.Text = "You must enter a gig name" lblError.Visible = True Return End If If txtDescription.Text.Length < 2 Then lblError.Text = "You must enter a description" lblError.Visible = True Return End If If txtImages.Text.Length < 2 Then lblError.Text = "You must enter at least 1 image url" lblError.Visible = True Return End If If txtPrice.Text.Length < 2 Then lblError.Text = "You must enter a price" lblError.Visible = True Return End If If txtShortDescription.Text.Length < 2 Then lblError.Text = "You must enter a short description" lblError.Visible = True Return End If Using db = New LiteDatabase(Server.MapPath("~/App_Data/Database.accdb")) Dim gigTbl = db.GetCollection(Of JobProposal)("Proposals") Dim usrTbl = db.GetCollection(Of User)("Users") If Session("UserID") Is Nothing Then lblError.Text = "Login problem" lblError.Visible = True Return End If Dim usr = usrTbl.FindById(New BsonValue(Session("UserID"))) Dim price As Double If Not Double.TryParse(txtPrice.Text, price) Then lblError.Text = "Price must be number-convertible" lblError.Visible = True Return End If Dim entry = New JobProposal With { .Description = txtDescription.Text, .ImageURLs = txtImages.Text.Split(New Char() {"\n", "\r"}, StringSplitOptions.RemoveEmptyEntries), .Offerer = usr.Id, .OffererOrg = Nothing, .Price = price, .Title = txtGigName.Text, .Type = GigType.OfferProduct, .VideoURL = txtVideoURL.Text, .ShortDescription = txtShortDescription.Text } gigTbl.Insert(entry) gigTbl.Update(entry) Response.Redirect("/GigPage.aspx?gig=" & entry.Id) End Using End Sub End Class
yotam180/DeedCoin
AddGig.aspx.vb
Visual Basic
mit
2,808
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class MainFrm Inherits MetroFramework.Forms.MetroForm '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(MainFrm)) Me.MetroPanel1 = New MetroFramework.Controls.MetroPanel() Me.helpbtn = New MetroFramework.Controls.MetroButton() Me.Compress = New MetroFramework.Controls.MetroButton() Me.Browse = New MetroFramework.Controls.MetroButton() Me.OutFile = New MetroFramework.Controls.MetroTextBox() Me.Label2 = New System.Windows.Forms.Label() Me.Import = New MetroFramework.Controls.MetroButton() Me.OrigFile = New MetroFramework.Controls.MetroTextBox() Me.Label1 = New System.Windows.Forms.Label() Me.Label3 = New System.Windows.Forms.Label() Me.Label4 = New System.Windows.Forms.Label() Me.Aboutbtn = New MetroFramework.Controls.MetroButton() Me.MetroPanel3 = New MetroFramework.Controls.MetroPanel() Me.MetroPanel2 = New MetroFramework.Controls.MetroPanel() Me.upperL = New MetroFramework.Controls.MetroCheckBox() Me.i = New MetroFramework.Controls.MetroCheckBox() Me.u = New MetroFramework.Controls.MetroCheckBox() Me.lowerx = New MetroFramework.Controls.MetroCheckBox() Me.m = New MetroFramework.Controls.MetroCheckBox() Me.lowers = New MetroFramework.Controls.MetroCheckBox() Me.b = New MetroFramework.Controls.MetroCheckBox() Me.uppers = New MetroFramework.Controls.MetroCheckBox() Me.r = New MetroFramework.Controls.MetroCheckBox() Me.Log = New System.Windows.Forms.TextBox() Me.Panel1 = New System.Windows.Forms.Panel() Me.MetroPanel1.SuspendLayout() Me.MetroPanel3.SuspendLayout() Me.MetroPanel2.SuspendLayout() Me.Panel1.SuspendLayout() Me.SuspendLayout() ' 'MetroPanel1 ' Me.MetroPanel1.AutoScroll = True Me.MetroPanel1.BorderStyle = MetroFramework.Drawing.MetroBorderStyle.FixedSingle Me.MetroPanel1.Controls.Add(Me.helpbtn) Me.MetroPanel1.Controls.Add(Me.Compress) Me.MetroPanel1.Controls.Add(Me.Browse) Me.MetroPanel1.Controls.Add(Me.OutFile) Me.MetroPanel1.Controls.Add(Me.Label2) Me.MetroPanel1.Controls.Add(Me.Import) Me.MetroPanel1.Controls.Add(Me.OrigFile) Me.MetroPanel1.Controls.Add(Me.Label1) Me.MetroPanel1.HorizontalScrollbar = True Me.MetroPanel1.HorizontalScrollbarBarColor = True Me.MetroPanel1.HorizontalScrollbarHighlightOnWheel = False Me.MetroPanel1.HorizontalScrollbarSize = 10 Me.MetroPanel1.Location = New System.Drawing.Point(13, 63) Me.MetroPanel1.Name = "MetroPanel1" Me.MetroPanel1.Size = New System.Drawing.Size(375, 163) Me.MetroPanel1.Style = MetroFramework.MetroColorStyle.Black Me.MetroPanel1.TabIndex = 0 Me.MetroPanel1.VerticalScrollbar = True Me.MetroPanel1.VerticalScrollbarBarColor = True Me.MetroPanel1.VerticalScrollbarHighlightOnWheel = False Me.MetroPanel1.VerticalScrollbarSize = 10 ' 'helpbtn ' Me.helpbtn.Location = New System.Drawing.Point(9, 129) Me.helpbtn.Name = "helpbtn" Me.helpbtn.Size = New System.Drawing.Size(23, 23) Me.helpbtn.TabIndex = 9 Me.helpbtn.Text = "?" ' 'Compress ' Me.Compress.Location = New System.Drawing.Point(38, 129) Me.Compress.Name = "Compress" Me.Compress.Size = New System.Drawing.Size(325, 23) Me.Compress.Style = MetroFramework.MetroColorStyle.Green Me.Compress.TabIndex = 8 Me.Compress.Text = "Compress" ' 'Browse ' Me.Browse.Location = New System.Drawing.Point(304, 89) Me.Browse.Name = "Browse" Me.Browse.Size = New System.Drawing.Size(59, 23) Me.Browse.TabIndex = 7 Me.Browse.Text = "Browse" ' 'OutFile ' Me.OutFile.Location = New System.Drawing.Point(9, 89) Me.OutFile.Name = "OutFile" Me.OutFile.Size = New System.Drawing.Size(289, 23) Me.OutFile.TabIndex = 6 ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Font = New System.Drawing.Font("Segoe UI", 9.0!) Me.Label2.Location = New System.Drawing.Point(11, 70) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(69, 15) Me.Label2.TabIndex = 5 Me.Label2.Text = "Output File:" ' 'Import ' Me.Import.Location = New System.Drawing.Point(305, 33) Me.Import.Name = "Import" Me.Import.Size = New System.Drawing.Size(59, 23) Me.Import.TabIndex = 4 Me.Import.Text = "Import" ' 'OrigFile ' Me.OrigFile.Location = New System.Drawing.Point(10, 33) Me.OrigFile.Name = "OrigFile" Me.OrigFile.Size = New System.Drawing.Size(289, 23) Me.OrigFile.TabIndex = 3 ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Font = New System.Drawing.Font("Segoe UI", 9.0!) Me.Label1.Location = New System.Drawing.Point(12, 14) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(73, 15) Me.Label1.TabIndex = 2 Me.Label1.Text = "Original File:" ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.Font = New System.Drawing.Font("Segoe UI", 9.0!) Me.Label3.Location = New System.Drawing.Point(3, 11) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(52, 15) Me.Label3.TabIndex = 11 Me.Label3.Text = "Options:" ' 'Label4 ' Me.Label4.AutoSize = True Me.Label4.Font = New System.Drawing.Font("Segoe UI", 9.0!) Me.Label4.Location = New System.Drawing.Point(10, 236) Me.Label4.Name = "Label4" Me.Label4.Size = New System.Drawing.Size(30, 15) Me.Label4.TabIndex = 14 Me.Label4.Text = "Log:" ' 'Aboutbtn ' Me.Aboutbtn.Location = New System.Drawing.Point(138, 0) Me.Aboutbtn.Name = "Aboutbtn" Me.Aboutbtn.Size = New System.Drawing.Size(75, 23) Me.Aboutbtn.TabIndex = 16 Me.Aboutbtn.Text = "About" ' 'MetroPanel3 ' Me.MetroPanel3.Controls.Add(Me.MetroPanel2) Me.MetroPanel3.Controls.Add(Me.Aboutbtn) Me.MetroPanel3.Controls.Add(Me.Label3) Me.MetroPanel3.Dock = System.Windows.Forms.DockStyle.Right Me.MetroPanel3.HorizontalScrollbarBarColor = True Me.MetroPanel3.HorizontalScrollbarHighlightOnWheel = False Me.MetroPanel3.HorizontalScrollbarSize = 10 Me.MetroPanel3.Location = New System.Drawing.Point(399, 60) Me.MetroPanel3.Name = "MetroPanel3" Me.MetroPanel3.Size = New System.Drawing.Size(213, 292) Me.MetroPanel3.TabIndex = 17 Me.MetroPanel3.VerticalScrollbarBarColor = True Me.MetroPanel3.VerticalScrollbarHighlightOnWheel = False Me.MetroPanel3.VerticalScrollbarSize = 10 ' 'MetroPanel2 ' Me.MetroPanel2.BorderStyle = MetroFramework.Drawing.MetroBorderStyle.FixedSingle Me.MetroPanel2.Controls.Add(Me.upperL) Me.MetroPanel2.Controls.Add(Me.i) Me.MetroPanel2.Controls.Add(Me.u) Me.MetroPanel2.Controls.Add(Me.lowerx) Me.MetroPanel2.Controls.Add(Me.m) Me.MetroPanel2.Controls.Add(Me.lowers) Me.MetroPanel2.Controls.Add(Me.b) Me.MetroPanel2.Controls.Add(Me.uppers) Me.MetroPanel2.Controls.Add(Me.r) Me.MetroPanel2.Dock = System.Windows.Forms.DockStyle.Bottom Me.MetroPanel2.HorizontalScrollbarBarColor = True Me.MetroPanel2.HorizontalScrollbarHighlightOnWheel = False Me.MetroPanel2.HorizontalScrollbarSize = 10 Me.MetroPanel2.Location = New System.Drawing.Point(0, 29) Me.MetroPanel2.Name = "MetroPanel2" Me.MetroPanel2.Size = New System.Drawing.Size(213, 263) Me.MetroPanel2.TabIndex = 17 Me.MetroPanel2.VerticalScrollbarBarColor = True Me.MetroPanel2.VerticalScrollbarHighlightOnWheel = False Me.MetroPanel2.VerticalScrollbarSize = 10 ' 'upperL ' Me.upperL.AutoSize = True Me.upperL.BackColor = System.Drawing.Color.Transparent Me.upperL.Location = New System.Drawing.Point(5, 89) Me.upperL.Name = "upperL" Me.upperL.Size = New System.Drawing.Size(95, 15) Me.upperL.Style = MetroFramework.MetroColorStyle.Green Me.upperL.TabIndex = 38 Me.upperL.Text = "Short liscense" Me.upperL.UseVisualStyleBackColor = False ' 'i ' Me.i.AutoSize = True Me.i.BackColor = System.Drawing.Color.Transparent Me.i.Location = New System.Drawing.Point(5, 5) Me.i.Name = "i" Me.i.Size = New System.Drawing.Size(160, 15) Me.i.Style = MetroFramework.MetroColorStyle.Green Me.i.TabIndex = 30 Me.i.Text = "Ignore compression result" Me.i.UseVisualStyleBackColor = False ' 'u ' Me.u.AutoSize = True Me.u.BackColor = System.Drawing.Color.Transparent Me.u.Location = New System.Drawing.Point(5, 111) Me.u.Name = "u" Me.u.Size = New System.Drawing.Size(176, 30) Me.u.Style = MetroFramework.MetroColorStyle.Green Me.u.TabIndex = 34 Me.u.Text = "Do not remove unsupported " & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "architectures (mac osx, -ub)" Me.u.UseVisualStyleBackColor = False ' 'lowerx ' Me.lowerx.AutoSize = True Me.lowerx.BackColor = System.Drawing.Color.Transparent Me.lowerx.Location = New System.Drawing.Point(5, 219) Me.lowerx.Name = "lowerx" Me.lowerx.Size = New System.Drawing.Size(162, 30) Me.lowerx.Style = MetroFramework.MetroColorStyle.Green Me.lowerx.TabIndex = 32 Me.lowerx.Text = "Don't manage exceptions" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "(64 bit PE32+)" Me.lowerx.UseVisualStyleBackColor = False ' 'm ' Me.m.AutoSize = True Me.m.BackColor = System.Drawing.Color.Transparent Me.m.Location = New System.Drawing.Point(5, 47) Me.m.Name = "m" Me.m.Size = New System.Drawing.Size(129, 15) Me.m.Style = MetroFramework.MetroColorStyle.Green Me.m.TabIndex = 35 Me.m.Text = "Force to use LZMAT" Me.m.UseVisualStyleBackColor = False ' 'lowers ' Me.lowers.AutoSize = True Me.lowers.BackColor = System.Drawing.Color.Transparent Me.lowers.Location = New System.Drawing.Point(5, 183) Me.lowers.Name = "lowers" Me.lowers.Size = New System.Drawing.Size(203, 30) Me.lowers.Style = MetroFramework.MetroColorStyle.Green Me.lowers.TabIndex = 37 Me.lowers.Text = "Search the best LZMA parameters " & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "(slower but better)" Me.lowers.UseVisualStyleBackColor = False ' 'b ' Me.b.AutoSize = True Me.b.BackColor = System.Drawing.Color.Transparent Me.b.Location = New System.Drawing.Point(5, 26) Me.b.Name = "b" Me.b.Size = New System.Drawing.Size(118, 15) Me.b.Style = MetroFramework.MetroColorStyle.Green Me.b.TabIndex = 31 Me.b.Text = "Create backup file" Me.b.UseVisualStyleBackColor = False ' 'uppers ' Me.uppers.AutoSize = True Me.uppers.BackColor = System.Drawing.Color.Transparent Me.uppers.Location = New System.Drawing.Point(5, 147) Me.uppers.Name = "uppers" Me.uppers.Size = New System.Drawing.Size(158, 30) Me.uppers.Style = MetroFramework.MetroColorStyle.Green Me.uppers.TabIndex = 33 Me.uppers.Text = "Don't patch strong name " & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "signature (.NET)" Me.uppers.UseVisualStyleBackColor = False ' 'r ' Me.r.AutoSize = True Me.r.BackColor = System.Drawing.Color.Transparent Me.r.Location = New System.Drawing.Point(5, 68) Me.r.Name = "r" Me.r.Size = New System.Drawing.Size(166, 15) Me.r.Style = MetroFramework.MetroColorStyle.Green Me.r.TabIndex = 36 Me.r.Text = "Do not compress resources" Me.r.UseVisualStyleBackColor = False ' 'Log ' Me.Log.AccessibleRole = System.Windows.Forms.AccessibleRole.None Me.Log.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.Log.Enabled = False Me.Log.Font = New System.Drawing.Font("Segoe UI", 8.25!) Me.Log.Location = New System.Drawing.Point(-1, -1) Me.Log.Multiline = True Me.Log.Name = "Log" Me.Log.ReadOnly = True Me.Log.Size = New System.Drawing.Size(375, 100) Me.Log.TabIndex = 15 Me.Log.Text = "" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Matcode comPRESSor for executables" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Copyright (c) 2007-2009, Vitaly Evseenko, M" & _ "ATCODE Software" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Mpress Graphic User Interface" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "by Gerard Balaoro" Me.Log.TextAlign = System.Windows.Forms.HorizontalAlignment.Center ' 'Panel1 ' Me.Panel1.BackColor = System.Drawing.Color.Transparent Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.Panel1.Controls.Add(Me.Log) Me.Panel1.Location = New System.Drawing.Point(13, 252) Me.Panel1.Name = "Panel1" Me.Panel1.Size = New System.Drawing.Size(375, 100) Me.Panel1.TabIndex = 19 ' 'MainFrm ' Me.AutoScaleDimensions = New System.Drawing.SizeF(4.0!, 7.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.AutoValidate = System.Windows.Forms.AutoValidate.EnablePreventFocusChange Me.BorderStyle = MetroFramework.Drawing.MetroBorderStyle.FixedSingle Me.ClientSize = New System.Drawing.Size(625, 363) Me.Controls.Add(Me.Panel1) Me.Controls.Add(Me.MetroPanel3) Me.Controls.Add(Me.Label4) Me.Controls.Add(Me.MetroPanel1) Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 5.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Margin = New System.Windows.Forms.Padding(2) Me.MaximizeBox = False Me.Name = "MainFrm" Me.Padding = New System.Windows.Forms.Padding(13, 60, 13, 11) Me.Resizable = False Me.Style = MetroFramework.MetroColorStyle.Green Me.Text = "Mpress Graphic User Interface" Me.TextAlign = System.Windows.Forms.VisualStyles.HorizontalAlign.Center Me.MetroPanel1.ResumeLayout(False) Me.MetroPanel1.PerformLayout() Me.MetroPanel3.ResumeLayout(False) Me.MetroPanel3.PerformLayout() Me.MetroPanel2.ResumeLayout(False) Me.MetroPanel2.PerformLayout() Me.Panel1.ResumeLayout(False) Me.Panel1.PerformLayout() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents MetroPanel1 As MetroFramework.Controls.MetroPanel Friend WithEvents Browse As MetroFramework.Controls.MetroButton Friend WithEvents OutFile As MetroFramework.Controls.MetroTextBox Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents Import As MetroFramework.Controls.MetroButton Friend WithEvents OrigFile As MetroFramework.Controls.MetroTextBox Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents Compress As MetroFramework.Controls.MetroButton Friend WithEvents Label4 As System.Windows.Forms.Label Friend WithEvents Aboutbtn As MetroFramework.Controls.MetroButton Friend WithEvents helpbtn As MetroFramework.Controls.MetroButton Friend WithEvents MetroPanel3 As MetroFramework.Controls.MetroPanel Friend WithEvents MetroPanel2 As MetroFramework.Controls.MetroPanel Friend WithEvents upperL As MetroFramework.Controls.MetroCheckBox Friend WithEvents i As MetroFramework.Controls.MetroCheckBox Friend WithEvents u As MetroFramework.Controls.MetroCheckBox Friend WithEvents lowerx As MetroFramework.Controls.MetroCheckBox Friend WithEvents m As MetroFramework.Controls.MetroCheckBox Friend WithEvents lowers As MetroFramework.Controls.MetroCheckBox Friend WithEvents b As MetroFramework.Controls.MetroCheckBox Friend WithEvents uppers As MetroFramework.Controls.MetroCheckBox Friend WithEvents r As MetroFramework.Controls.MetroCheckBox Friend WithEvents Log As System.Windows.Forms.TextBox Friend WithEvents Panel1 As System.Windows.Forms.Panel End Class
GerardBalaoro/MpressGUI
MpressGUI/Form1.Designer.vb
Visual Basic
mit
18,549
'------------------------------------------------------------------------------ ' <generado automáticamente> ' Este código fue generado por una herramienta. ' ' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si ' se vuelve a generar el código. ' </generado automáticamente> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Partial Public Class ControlConveMarco '''<summary> '''Control TxtCodigo. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents TxtCodigo As Global.System.Web.UI.WebControls.TextBox '''<summary> '''Control RequiredFieldValidator2. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents RequiredFieldValidator2 As Global.System.Web.UI.WebControls.RequiredFieldValidator '''<summary> '''Control TxtNombre. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents TxtNombre As Global.System.Web.UI.WebControls.TextBox '''<summary> '''Control RequiredFieldValidator1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents RequiredFieldValidator1 As Global.System.Web.UI.WebControls.RequiredFieldValidator '''<summary> '''Control BtnNuevoAdj. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents BtnNuevoAdj As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control GridView1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents GridView1 As Global.System.Web.UI.WebControls.GridView '''<summary> '''Control OdsAdjuntos. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents OdsAdjuntos As Global.System.Web.UI.WebControls.ObjectDataSource '''<summary> '''Control Panel1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents Panel1 As Global.System.Web.UI.WebControls.Panel '''<summary> '''Control UploadButton. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents UploadButton As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control BtnActualizarAdj. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents BtnActualizarAdj As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control BtnAbrirArchivo. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents BtnAbrirArchivo As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control BtnEliminarAdj. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents BtnEliminarAdj As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control CtnCancelarAdj. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents CtnCancelarAdj As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control FileUploadControl. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents FileUploadControl As Global.System.Web.UI.WebControls.FileUpload '''<summary> '''Control TxtDescAdj. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents TxtDescAdj As Global.System.Web.UI.WebControls.TextBox '''<summary> '''Control StatusLabel. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents StatusLabel As Global.System.Web.UI.WebControls.Label '''<summary> '''Control TxtIdAdj. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents TxtIdAdj As Global.System.Web.UI.WebControls.TextBox '''<summary> '''Control RadCodeBlock1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents RadCodeBlock1 As Global.Telerik.Web.UI.RadCodeBlock '''<summary> '''Control CmdGrabar. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents CmdGrabar As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control CmdActualizar. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents CmdActualizar As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control CmdCancelar. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents CmdCancelar As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control TxtIdTabla. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents TxtIdTabla As Global.System.Web.UI.WebControls.TextBox End Class
crackper/SistFoncreagro
SistFoncreagro.WebSite/Monitoreo/Controles/ControlConveMarco.ascx.designer.vb
Visual Basic
mit
8,072
Public Class frmGame End Class
flaxj/Otaku-Break-The-Safe
Otaku Break the Safe/frmGame.vb
Visual Basic
mit
34
Imports Aspose.Cloud Namespace Paragraph Class GetParagraphs Public Shared Sub Run() Dim inputfile As String = "doc-sample.doc" Dim subdirection As String = "Paragraph" ' Upload input file from local directory to Cloud Storage Common.UploadFile(inputfile, subdirection) ' Get a List of Paragraphs from a Word Document Dim wordsParagraphsResponse As WordsParagraphsResponse = Common.WordsService.WordsParagraph.GetParagraphs(inputfile, Common.FOLDER) Console.WriteLine((Convert.ToString(vbLf) & inputfile) + " have " + wordsParagraphsResponse.Paragraphs.ParagraphLinkList.Count + " paragraphs.") End Sub End Class End Namespace
farooqsheikhpk/Aspose_Words_Cloud
Examples/DotNET/SDK/VisualBasic/Paragraph/GetParagraphs.vb
Visual Basic
mit
741
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests_Regex Public Shared ReadOnly Property AllCompletionImplementations() As IEnumerable(Of Object()) Get Return TestStateFactory.GetAllCompletionImplementations() End Get End Property <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex("$$"); } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("\A", inlineDescription:=WorkspacesResources.Regex_start_of_string_only_short) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new Regex(""\\A"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_VerbatimString(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"$$"); } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("\A") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new Regex(@""\A"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCaretPlacement(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"$$"); } } ]]></Document>) state.SendTypeChars("[") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() state.SendDownKey() state.SendDownKey() state.SendDownKey() state.SendDownKey() Await state.AssertSelectedCompletionItem("[^ firstCharacter-lastCharacter ]") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new Regex(@""[^-]"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertLineTextAroundCaret(" var r = new Regex(@""[^", "-]"");") End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackslashBInCharacterClass(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"[$$]"); } } ]]></Document>) state.SendTypeChars("\b") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("\b", description:=WorkspacesResources.Regex_backspace_character_long) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackslashBOutOfCharacterClass(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"$$"); } } ]]></Document>) state.SendTypeChars("\b") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("\b", description:=WorkspacesResources.Regex_word_boundary_long) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function OnlyEscapes(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"$$"); } } ]]></Document>) state.SendTypeChars("\") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() For Each item In state.GetCompletionItems() Assert.StartsWith("\", item.DisplayText) Next state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function OnlyClasses(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"$$"); } } ]]></Document>) state.SendTypeChars("[") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() For Each item In state.GetCompletionItems() Assert.StartsWith("[", item.DisplayText) Next state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function OnlyGroups(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"$$"); } } ]]></Document>) state.SendTypeChars("(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() For Each item In state.GetCompletionItems() Assert.StartsWith("(", item.DisplayText) Next state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestKReferenceOutsideOfCharacterClass(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"$$"); } } ]]></Document>) state.SendTypeChars("\") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Assert.True(state.GetCompletionItems().Any(Function(i) i.DisplayText.StartsWith("\k"))) state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoKReferenceInsideOfCharacterClass(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"[$$]"); } } ]]></Document>) state.SendTypeChars("\") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Assert.False(state.GetCompletionItems().Any(Function(i) i.DisplayText.StartsWith("\k"))) state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCategory(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@"\p$$"); } } ]]></Document>) state.SendTypeChars("{") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Assert.True(state.GetCompletionItems().Any(Function(i) i.DisplayText = "IsGreek")) state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotInInterpolatedString(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex($"$$"); } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotInInterpolatedStringPart(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex($"goo{$$}bar"); } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Dim items = state.GetCompletionItems() Assert.False(items.Any(Function(c) c.DisplayText = "*")) End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotInInterpolatedStringPrefix(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex($"go$$o{0}bar"); } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotInInterpolatedStringSuffix(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex($"goo{0}$$"); } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotInInterpolatedVerbatimString1(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex($@"$$"); } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() End Using End Function <MemberData(NameOf(AllCompletionImplementations))> <WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotInInterpolatedVerbatimString2(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, <Document><![CDATA[ using System.Text.RegularExpressions; class c { void goo() { var r = new Regex(@$"$$"); } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() End Using End Function End Class End Namespace
VSadov/roslyn
src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_Regex.vb
Visual Basic
apache-2.0
15,391