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
|
|---|---|---|---|---|---|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
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.EmailSizer.MySettings
Get
Return Global.EmailSizer.MySettings.Default
End Get
End Property
End Module
End Namespace
|
davidschlachter/outlookquota
|
EmailSizer/My Project/Settings.Designer.vb
|
Visual Basic
|
bsd-2-clause
| 2,806
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Partial Friend Class SymbolCompletionProvider
Inherits AbstractRecommendationServiceBasedCompletionProvider
Protected Overrides Function GetInsertionText(item As CompletionItem, ch As Char) As String
Return CompletionUtilities.GetInsertionTextAtInsertionTime(item, ch)
End Function
Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Return CompletionUtilities.IsDefaultTriggerCharacterOrParen(text, characterPosition, options)
End Function
Protected Overrides Async Function IsSemanticTriggerCharacterAsync(document As Document, characterPosition As Integer, cancellationToken As CancellationToken) As Task(Of Boolean)
If document Is Nothing Then
Return False
End If
Dim result = Await IsTriggerOnDotAsync(document, characterPosition, cancellationToken).ConfigureAwait(False)
If result.HasValue Then
Return result.Value
End If
Return True
End Function
Private Async Function IsTriggerOnDotAsync(document As Document, characterPosition As Integer, cancellationToken As CancellationToken) As Task(Of Boolean?)
Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False)
If text(characterPosition) <> "."c Then
Return Nothing
End If
' don't want to trigger after a number. All other cases after dot are ok.
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim token = root.FindToken(characterPosition)
Return IsValidTriggerToken(token)
End Function
Private Function IsValidTriggerToken(token As SyntaxToken) As Boolean
If token.Kind <> SyntaxKind.DotToken Then
Return False
End If
Dim previousToken = token.GetPreviousToken()
If previousToken.Kind = SyntaxKind.IntegerLiteralToken Then
Return token.Parent.Kind <> SyntaxKind.SimpleMemberAccessExpression OrElse Not DirectCast(token.Parent, MemberAccessExpressionSyntax).Expression.IsKind(SyntaxKind.NumericLiteralExpression)
End If
Return True
End Function
Protected Overrides Function GetDisplayAndInsertionText(symbol As ISymbol, context As SyntaxContext) As ValueTuple(Of String, String)
Return CompletionUtilities.GetDisplayAndInsertionText(symbol, context)
End Function
Protected Overrides Async Function CreateContext(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of SyntaxContext)
Dim semanticModel = Await document.GetSemanticModelForSpanAsync(New TextSpan(position, 0), cancellationToken).ConfigureAwait(False)
Return Await VisualBasicSyntaxContext.CreateContextAsync(document.Project.Solution.Workspace, semanticModel, position, cancellationToken).ConfigureAwait(False)
End Function
Protected Overrides Function GetFilterText(symbol As ISymbol, displayText As String, context As SyntaxContext) As String
' Filter on New if we have a ctor
If symbol.IsConstructor() Then
Return "New"
End If
Return MyBase.GetFilterText(symbol, displayText, context)
End Function
Private Shared cachedRules As Dictionary(Of ValueTuple(Of Boolean, Boolean, Boolean), CompletionItemRules) =
InitCachedRules()
Private Shared Function InitCachedRules() As Dictionary(Of ValueTuple(Of Boolean, Boolean, Boolean), CompletionItemRules)
Dim result = New Dictionary(Of ValueTuple(Of Boolean, Boolean, Boolean), CompletionItemRules)()
For importDirective = 0 To 1
For preselect = 0 To 1
For tuple = 0 To 1
If importDirective = 1 AndAlso tuple = 1 Then
Continue For
End If
Dim context = ValueTuple.Create(importDirective = 1, preselect = 1, tuple = 1)
result(context) = MakeRule(importDirective, preselect, tuple)
Next
Next
Next
Return result
End Function
Private Shared Function MakeRule(importDirective As Integer, preselect As Integer, tuple As Integer) As CompletionItemRules
Return MakeRule(importDirective = 1, preselect = 1, tuple = 1)
End Function
Private Shared Function MakeRule(importDirective As Boolean, preselect As Boolean, tuple As Boolean) As CompletionItemRules
' '(' should not filter the completion list, even though it's in generic items like IList(Of...)
Dim generalBaseline = CompletionItemRules.Default.
WithFilterCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, "("c)).
WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, "("c))
Dim importDirectBasline As CompletionItemRules =
CompletionItemRules.Create(commitCharacterRules:=
ImmutableArray.Create(
CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, "."c)))
Dim rule = If(importDirective, importDirectBasline, generalBaseline)
If preselect Then
rule = rule.WithSelectionBehavior(CompletionItemSelectionBehavior.SoftSelection)
End If
If tuple Then
rule = rule.WithCommitCharacterRule(
CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ":"c))
End If
Return rule
End Function
Protected Overrides Function GetCompletionItemRules(symbols As List(Of ISymbol),
context As SyntaxContext, preselect As Boolean) As CompletionItemRules
Return If(cachedRules(
ValueTuple.Create(context.IsInImportsDirective, preselect, context.IsPossibleTupleContext)),
CompletionItemRules.Default)
End Function
Protected Overrides Function GetCompletionItemRules(symbols As IReadOnlyList(Of ISymbol), context As SyntaxContext) As CompletionItemRules
' Unused
Throw New NotImplementedException
End Function
Protected Overrides Function IsInstrinsic(s As ISymbol) As Boolean
Return If(TryCast(s, ITypeSymbol)?.IsIntrinsicType(), False)
End Function
Protected Overrides ReadOnly Property PreselectedItemSelectionBehavior As CompletionItemSelectionBehavior
Get
Return CompletionItemSelectionBehavior.SoftSelection
End Get
End Property
End Class
End Namespace
|
KevinH-MS/roslyn
|
src/Features/VisualBasic/Portable/Completion/CompletionProviders/SymbolCompletionProvider.vb
|
Visual Basic
|
apache-2.0
| 7,714
|
Imports System.IO
Imports System.Runtime.InteropServices
Module Example
<STAThread()> _
Sub Main()
Dim objApplication As SolidEdgeFramework.Application = Nothing
Dim objPartDocument As SolidEdgePart.PartDocument = Nothing
Dim objStudyOwner As SolidEdgePart.StudyOwner = Nothing
Dim objStudy As SolidEdgePart.Study = Nothing
Dim objThermalStudy As SolidEdgePart.Study = Nothing
Dim objMeshOwner As SolidEdgePart.MeshOwner = Nothing
Dim objLoadOwner As SolidEdgePart.LoadOwner = Nothing
Dim objLoad As SolidEdgePart.Load = Nothing
Dim objModels As SolidEdgePart.Models = Nothing
Dim objModel As SolidEdgePart.Model = Nothing
Dim objModelBody As SolidEdgeGeometry.Body = Nothing
Dim objGeomArray(0) As Object
Dim objFaces As SolidEdgeGeometry.Faces = Nothing
Dim objFaceArray(1) As SolidEdgeGeometry.Face
Dim objExtrudedProtrusions As SolidEdgePart.ExtrudedProtrusions = Nothing
Dim objExtrudedProtrusion As SolidEdgePart.ExtrudedProtrusion = Nothing
Dim estudyType As SolidEdgePart.FEAStudyTypeEnum_Auto
Dim eMeshType As SolidEdgePart.FEAMeshTypeEnum_Auto
Dim dThickness As Double = 0
Dim dwInputOptions As UInteger = 0
Dim ulNumModes As ULong = 7
Dim dFreqlow As Double = 0
Dim dFreqHigh As Double = 1.0
Dim cmdLineOpts As String = ""
Dim nastranKeywordOpts As String = ""
Dim dwResultoptions As UInteger = 0
'Thermal Options
Dim dConvectionExp As Double = 0
Dim dEnclosureAmbientEle As Double = 0
Dim dwThrmlOptions As UInteger = 0
'Thermal Load Options
Dim eLoadType As SolidEdgePart.FEALoadTypeEnum_Auto = SolidEdgePart.FEALoadTypeEnum_Auto.eLoadTypeNone_Auto
Dim dLoadValue As Double = 0.0
Dim dLoadValueAngAccln As Double = 0.0
Dim eLoadSymbDir As SolidEdgePart.LoadSymbDirOptsEnum_Auto = SolidEdgePart.LoadSymbDirOptsEnum_Auto.eLoadDirHeatFlux_Auto
Dim dLoadDirX As Double = 0.0
Dim dLoadDirY As Double = 0.0
Dim dLoadDirZ As Double = 0.0
Dim dLoadPosX As Double = 0.0
Dim dLoadPosY As Double = 0.0
Dim dLoadPosZ As Double = 0.0
Dim unColorSymbol As UInteger = 255
Dim unAngAcclnColorSymbol As UInteger = 8388673
Dim dSpacingFactor As Double = 0.0
Dim dSizeFactor As Double = 0.0
Dim dSteeringWheelLen As Double = 0.0
Dim dwLoadProps As UInteger = 0
Dim dLoadSymSpacing As Double = 0.0
Dim dLoadSymSize As Double = 0.0
Dim dAmbientTemp As Double = 0.0
Dim dSurfEmissivity As Double = 0.0
Dim dSurfAbsoptivity As Double = 0.0
Dim dViewFactor As Double = 0.0
Dim nCavity As Integer = 0
Try
OleMessageFilter.Register()
objApplication = Marshal.GetActiveObject("SolidEdge.Application")
objPartDocument = objApplication.ActiveDocument
' Get Study Owner
objStudyOwner = objPartDocument.StudyOwner
'Add Thermal Study
estudyType = SolidEdgePart.FEAStudyTypeEnum_Auto.eStudyTypeSSHT_Auto
eMeshType = SolidEdgePart.FEAMeshTypeEnum_Auto.eMeshTypeTetrahedral_Auto
objStudyOwner.AddThermalStudy(estudyType,
eMeshType,
dThickness,
dwInputOptions,
ulNumModes,
dFreqlow,
dFreqHigh,
cmdLineOpts,
nastranKeywordOpts,
dwResultoptions,
dwThrmlOptions,
dEnclosureAmbientEle,
dConvectionExp,
objStudy)
objThermalStudy = objStudy
objModels = objPartDocument.Models
objModel = objModels.Item(1)
' Get the study geometries
objModelBody = objModel.Body()
objGeomArray(0) = Nothing
objGeomArray(0) = objModelBody
' Deselect the geometry from study
objThermalStudy.SetGeometries(objGeomArray)
objThermalStudy.GetLoadOwner(objLoadOwner)
'Get Thermal Options
objThermalStudy.GetThermalStudyOptions(dwThrmlOptions, dEnclosureAmbientEle, dConvectionExp)
dEnclosureAmbientEle = 10
dConvectionExp = 3.4
'Set Thermal Options
objThermalStudy.SetThermalStudyOptions(dwThrmlOptions, dEnclosureAmbientEle, dConvectionExp)
' Get Protrusion.
objExtrudedProtrusions = objModel.ExtrudedProtrusions
objExtrudedProtrusion = objExtrudedProtrusions.Item(1)
' Get faces collection
objFaces = objExtrudedProtrusion.Faces(SolidEdgeGeometry.FeatureTopologyQueryTypeConstants.igQueryAll)
objFaceArray(0) = objFaces.Item(0)
'Heat Flux Load Properties
eLoadType = SolidEdgePart.FEALoadTypeEnum_Auto.eLoadTypeSSHTHeatflux_Auto
dLoadValue = 100
dLoadValueAngAccln = 0.0
eLoadSymbDir = SolidEdgePart.LoadSymbDirOptsEnum_Auto.eLoadDirHeatFlux_Auto
dLoadDirX = 0.0
dLoadDirY = 0.0
dLoadDirZ = 1
dLoadPosX = -0.039485373058438106
dLoadPosY = 0.0
dLoadPosZ = 0.034828766147378246
unColorSymbol = 255
unAngAcclnColorSymbol = 8388673
dSpacingFactor = 0.15
dSizeFactor = 0.155
dSteeringWheelLen = 0.0
dwLoadProps = 2304
dLoadSymSpacing = 0.046329513280848368
dLoadSymSize = 0.047873830390209982
dAmbientTemp = 273.15
dSurfEmissivity = 0
dSurfAbsoptivity = 0
dViewFactor = 0
nCavity = 1
'Add Thermal Heat Flux Load
objLoadOwner.AddThermalLoad(objFaceArray,
eLoadType,
dLoadValue,
dLoadValueAngAccln,
eLoadSymbDir,
dLoadDirX,
dLoadDirY,
dLoadDirZ,
dLoadPosX,
dLoadPosY,
dLoadPosZ,
unColorSymbol,
unAngAcclnColorSymbol,
dSpacingFactor,
dSizeFactor,
dSteeringWheelLen,
dwLoadProps,
dLoadSymSpacing,
dLoadSymSize,
dAmbientTemp,
dSurfEmissivity,
dSurfAbsoptivity,
dViewFactor,
nCavity,
objLoad)
'Update Heat Flux Load Value.
objLoad.SetLoadValue(500)
objLoad = Nothing
objFaceArray(0) = Nothing
objFaceArray(0) = objFaces.Item(4)
'Radiation Load Properties
eLoadType = SolidEdgePart.FEALoadTypeEnum_Auto.eLoadTypeSSHTRadiation_Auto
dLoadValue = 100
dLoadValueAngAccln = 0.0
eLoadSymbDir = SolidEdgePart.LoadSymbDirOptsEnum_Auto.eLoadDirNormalToFace_Auto
dLoadDirX = 1
dLoadDirY = 0.0
dLoadDirZ = 0.0
dLoadPosX = -0.04057088227356833
dLoadPosY = 0.022897311677400896
dLoadPosZ = 0.06554422099691215
unColorSymbol = 42495
unAngAcclnColorSymbol = 8388673
dSpacingFactor = 0.15
dSizeFactor = 0.155
dSteeringWheelLen = 0.0
dwLoadProps = 2048
dLoadSymSpacing = 0.046329513280848368
dLoadSymSize = 0.047873830390209982
dAmbientTemp = 315.15
dSurfEmissivity = 0.54
dSurfAbsoptivity = 0.237
dViewFactor = 0.45
nCavity = 1
'Add Thermal Radiation Load
objLoadOwner.AddThermalLoad(objFaceArray,
eLoadType,
dLoadValue,
dLoadValueAngAccln,
eLoadSymbDir,
dLoadDirX,
dLoadDirY,
dLoadDirZ,
dLoadPosX,
dLoadPosY,
dLoadPosZ,
unColorSymbol,
unAngAcclnColorSymbol,
dSpacingFactor,
dSizeFactor,
dSteeringWheelLen,
dwLoadProps,
dLoadSymSpacing,
dLoadSymSize,
dAmbientTemp,
dSurfEmissivity,
dSurfAbsoptivity,
dViewFactor,
nCavity,
objLoad)
'Get Thermal Load Options
objLoad.GetThermalLoadOptions(eLoadType,
dLoadValue,
dLoadValueAngAccln,
eLoadSymbDir,
dLoadDirX,
dLoadDirY,
dLoadDirZ,
dLoadPosX,
dLoadPosY,
dLoadPosZ,
unColorSymbol,
unAngAcclnColorSymbol,
dSpacingFactor,
dSizeFactor,
dSteeringWheelLen,
dwLoadProps,
dLoadSymSpacing,
dLoadSymSize,
dAmbientTemp,
dSurfEmissivity,
dSurfAbsoptivity,
dViewFactor,
nCavity)
dAmbientTemp = 306.15
dSurfAbsoptivity = 0.9
dSurfEmissivity = 0.43
dViewFactor = 0.75
nCavity = 10
'Set Thermal Load Options
objLoad.SetThermalLoadOptions(eLoadType,
dLoadValue,
dLoadValueAngAccln,
eLoadSymbDir,
dLoadDirX,
dLoadDirY,
dLoadDirZ,
dLoadPosX,
dLoadPosY,
dLoadPosY,
unColorSymbol,
unAngAcclnColorSymbol,
dSpacingFactor,
dSizeFactor,
dSteeringWheelLen,
dwLoadProps,
dLoadSymSpacing,
dLoadSymSize,
dAmbientTemp,
dSurfEmissivity,
dSurfAbsoptivity,
dViewFactor,
nCavity)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
OleMessageFilter.Revoke()
End Try
End Sub
End Module
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.LoadOwner.AddThermalLoad.vb
|
Visual Basic
|
mit
| 13,028
|
' 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.Reflection
Public Module Extensions_822
''' <summary>
''' A T extension method that returns all the public methods of the current Type.
''' </summary>
''' <typeparam name="T">Generic type parameter.</typeparam>
''' <param name="this">The @this to act on.</param>
''' <returns>
''' An array of MethodInfo objects representing all the public methods defined for the current Type. or An empty
''' array of type MethodInfo, if no public methods are defined for the current Type.
''' </returns>
<System.Runtime.CompilerServices.Extension> _
Public Function GetMethods(Of T)(this As T) As MethodInfo()
Return this.[GetType]().GetMethods()
End Function
''' <summary>
''' A T extension method that searches for the methods defined for the current Type, using the specified binding
''' constraints.
''' </summary>
''' <typeparam name="T">Generic type parameter.</typeparam>
''' <param name="this">The @this to act on.</param>
''' <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.</param>
''' <returns>
''' An array of MethodInfo objects representing all methods defined for the current Type that match the specified
''' binding constraints. or An empty array of type MethodInfo, if no methods are defined for the current Type, or
''' if none of the defined methods match the binding constraints.
''' </returns>
<System.Runtime.CompilerServices.Extension> _
Public Function GetMethods(Of T)(this As T, bindingAttr As BindingFlags) As MethodInfo()
Return this.[GetType]().GetMethods(bindingAttr)
End Function
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Reflection/System.Object/Object.GetMethods.vb
|
Visual Basic
|
mit
| 2,038
|
' 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.Drawing
Public Module Extensions_746
''' <summary>
''' Translates the specified structure to an HTML string color representation.
''' </summary>
''' <param name="c">The structure to translate.</param>
''' <returns>The string that represents the HTML color.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function ToHtml(c As Color) As [String]
Return ColorTranslator.ToHtml(c)
End Function
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Drawing/System.Drawing.Color/System.Drawing.ColorTranslator/Color.ToHtml.vb
|
Visual Basic
|
mit
| 832
|
' 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.ApiDesignGuidelines.Analyzers
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.ApiDesignGuidelines.VisualBasic.Analyzers
''' <summary>
''' Async002: Async Method Names Should End in Async
''' </summary>
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public NotInheritable Class BasicAsyncMethodNamesShouldEndInAsyncAnalyzer
Inherits AsyncMethodNamesShouldEndInAsyncAnalyzer
End Class
End Namespace
|
bkoelman/roslyn-analyzers
|
src/Microsoft.CodeQuality.Analyzers/VisualBasic/ApiDesignGuidelines/BasicAsyncMethodNamesShouldEndInAsync.vb
|
Visual Basic
|
apache-2.0
| 656
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
Private Function CreateQueryLambdaSymbol(syntaxNode As VisualBasicSyntaxNode,
kind As SynthesizedLambdaKind,
parameters As ImmutableArray(Of BoundLambdaParameterSymbol)) As SynthesizedLambdaSymbol
Debug.Assert(kind.IsQueryLambda)
Return New SynthesizedLambdaSymbol(kind,
syntaxNode,
parameters,
LambdaSymbol.ReturnTypePendingDelegate,
Me)
End Function
Private Shared Function CreateBoundQueryLambda(queryLambdaSymbol As SynthesizedLambdaSymbol,
rangeVariables As ImmutableArray(Of RangeVariableSymbol),
expression As BoundExpression,
exprIsOperandOfConditionalBranch As Boolean) As BoundQueryLambda
Return New BoundQueryLambda(queryLambdaSymbol.Syntax, queryLambdaSymbol, rangeVariables, expression, exprIsOperandOfConditionalBranch)
End Function
Friend Overridable Function BindGroupAggregationExpression(group As GroupAggregationSyntax, diagnostics As DiagnosticBag) As BoundExpression
' Only special query binders that have enough context can bind GroupAggregationSyntax.
' TODO: Do we need to report any diagnostic?
Debug.Assert(False, "Binding out of context is unsupported!")
Return BadExpression(group, ErrorTypeSymbol.UnknownResultType)
End Function
Friend Overridable Function BindFunctionAggregationExpression([function] As FunctionAggregationSyntax, diagnostics As DiagnosticBag) As BoundExpression
' Only special query binders that have enough context can bind FunctionAggregationSyntax.
' TODO: Do we need to report any diagnostic?
Debug.Assert(False, "Binding out of context is unsupported!")
Return BadExpression([function], ErrorTypeSymbol.UnknownResultType)
End Function
''' <summary>
''' Bind a Query Expression.
''' This is the entry point.
''' </summary>
Private Function BindQueryExpression(
query As QueryExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
If query.Clauses.Count < 1 Then
' Syntax error must have been reported
Return BadExpression(query, ErrorTypeSymbol.UnknownResultType)
End If
Dim operators As SyntaxList(Of QueryClauseSyntax).Enumerator = query.Clauses.GetEnumerator()
Dim moveResult = operators.MoveNext()
Debug.Assert(moveResult)
Dim current As QueryClauseSyntax = operators.Current
Select Case current.Kind
Case SyntaxKind.FromClause
Return BindFromQueryExpression(query, operators, diagnostics)
Case SyntaxKind.AggregateClause
Return BindAggregateQueryExpression(query, operators, diagnostics)
Case Else
' Syntax error must have been reported
Return BadExpression(query, ErrorTypeSymbol.UnknownResultType)
End Select
End Function
''' <summary>
''' Given a result of binding of initial set of collection range variables, the source,
''' bind the rest of the operators in the enumerator.
'''
''' There is a special method to bind an operator of each kind, the common thing among them is that
''' all of them take the result we have so far, the source, and return result of an application
''' of one or two following operators.
''' Some of the methods also take operators enumerator in order to be able to do a necessary look-ahead
''' and in some cases even to advance the enumerator themselves.
''' Join and From operators absorb following Select or Let, that is when the process of binding of
''' a single operator actually handles two and advances the enumerator.
''' </summary>
Private Function BindSubsequentQueryOperators(
source As BoundQueryClauseBase,
operators As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundQueryClauseBase
Debug.Assert(source IsNot Nothing)
While operators.MoveNext()
Dim current As QueryClauseSyntax = operators.Current
Select Case current.Kind
Case SyntaxKind.FromClause
' Note, this call can advance [operators] enumerator if it absorbs the following Let or Select.
source = BindFromClause(source, DirectCast(current, FromClauseSyntax), operators, diagnostics)
Case SyntaxKind.SelectClause
source = BindSelectClause(source, DirectCast(current, SelectClauseSyntax), operators, diagnostics)
Case SyntaxKind.LetClause
source = BindLetClause(source, DirectCast(current, LetClauseSyntax), operators, diagnostics)
Case SyntaxKind.WhereClause
source = BindWhereClause(source, DirectCast(current, WhereClauseSyntax), diagnostics)
Case SyntaxKind.SkipWhileClause
source = BindSkipWhileClause(source, DirectCast(current, PartitionWhileClauseSyntax), diagnostics)
Case SyntaxKind.TakeWhileClause
source = BindTakeWhileClause(source, DirectCast(current, PartitionWhileClauseSyntax), diagnostics)
Case SyntaxKind.DistinctClause
source = BindDistinctClause(source, DirectCast(current, DistinctClauseSyntax), diagnostics)
Case SyntaxKind.SkipClause
source = BindSkipClause(source, DirectCast(current, PartitionClauseSyntax), diagnostics)
Case SyntaxKind.TakeClause
source = BindTakeClause(source, DirectCast(current, PartitionClauseSyntax), diagnostics)
Case SyntaxKind.OrderByClause
source = BindOrderByClause(source, DirectCast(current, OrderByClauseSyntax), diagnostics)
Case SyntaxKind.SimpleJoinClause
' Note, this call can advance [operators] enumerator if it absorbs the following Let or Select.
source = BindInnerJoinClause(source, DirectCast(current, SimpleJoinClauseSyntax), Nothing, operators, diagnostics)
Case SyntaxKind.GroupJoinClause
source = BindGroupJoinClause(source, DirectCast(current, GroupJoinClauseSyntax), Nothing, operators, diagnostics)
Case SyntaxKind.GroupByClause
source = BindGroupByClause(source, DirectCast(current, GroupByClauseSyntax), diagnostics)
Case SyntaxKind.AggregateClause
source = BindAggregateClause(source, DirectCast(current, AggregateClauseSyntax), operators, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(current.Kind)
End Select
End While
Return source
End Function
''' <summary>
''' Bind query expression that starts with From keyword, as opposed to the one that starts with Aggregate.
'''
''' From {collection range variables} [{other operators}]
''' </summary>
Private Function BindFromQueryExpression(
query As QueryExpressionSyntax,
operators As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundQueryExpression
' Note, this call can advance [operators] enumerator if it absorbs the following Let or Select.
Dim source As BoundQueryClauseBase = BindFromClause(Nothing, DirectCast(operators.Current, FromClauseSyntax), operators, diagnostics)
source = BindSubsequentQueryOperators(source, operators, diagnostics)
If Not source.Type.IsErrorType() AndAlso source.Kind = BoundKind.QueryableSource AndAlso
DirectCast(source, BoundQueryableSource).Source.Kind = BoundKind.QuerySource Then
' Need to apply implicit Select.
source = BindFinalImplicitSelectClause(source, diagnostics)
End If
Return New BoundQueryExpression(query, source, source.Type)
End Function
''' <summary>
''' Bind query expression that starts with Aggregate keyword, as opposed to the one that starts with From.
'''
''' Aggregate {collection range variables} [{other operators}] Into {aggregation range variables}
'''
''' If Into clause has one item, a single value is produced. If it has multiple items, values are
''' combined into an instance of an Anonymous Type.
''' </summary>
Private Function BindAggregateQueryExpression(
query As QueryExpressionSyntax,
operators As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundQueryExpression
Dim aggregate = DirectCast(operators.Current, AggregateClauseSyntax)
Dim malformedSyntax As Boolean = operators.MoveNext()
Debug.Assert(Not malformedSyntax, "Malformed syntax tree. Parser shouldn't produce a tree like that.")
operators = aggregate.AdditionalQueryOperators.GetEnumerator()
' Note, this call can advance [operators] enumerator if it absorbs the following Let or Select.
Dim source As BoundQueryClauseBase = BindCollectionRangeVariables(aggregate, Nothing, aggregate.Variables, operators, diagnostics)
source = BindSubsequentQueryOperators(source, operators, diagnostics)
Dim aggregationVariables As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = aggregate.AggregationVariables
Dim aggregationVariablesCount As Integer = aggregationVariables.Count
Select Case aggregationVariablesCount
Case 0
Debug.Assert(aggregationVariables.Count > 0, "Malformed syntax tree.")
Dim intoBinder As New IntoClauseDisallowGroupReferenceBinder(Me, source, source.RangeVariables, source.CompoundVariableType, source.RangeVariables)
source = New BoundAggregateClause(aggregate, Nothing, Nothing,
BadExpression(aggregate, source, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated(),
ImmutableArray(Of RangeVariableSymbol).Empty,
ErrorTypeSymbol.UnknownResultType,
ImmutableArray.Create(Of Binder)(intoBinder),
ErrorTypeSymbol.UnknownResultType)
Case 1
' Simple case, one item in the [Into] clause, source is our group.
Dim intoBinder As New IntoClauseDisallowGroupReferenceBinder(Me, source, source.RangeVariables, source.CompoundVariableType, source.RangeVariables)
Dim aggregationSelector As BoundExpression = Nothing
intoBinder.BindAggregationRangeVariable(aggregationVariables(0),
Nothing,
aggregationSelector,
diagnostics)
source = New BoundAggregateClause(aggregate, Nothing, Nothing,
aggregationSelector,
ImmutableArray(Of RangeVariableSymbol).Empty,
aggregationSelector.Type,
ImmutableArray.Create(Of Binder)(intoBinder),
aggregationSelector.Type)
Case Else
' Complex case, need to build an instance of an Anonymous Type.
Dim declaredNames As HashSet(Of String) = CreateSetOfDeclaredNames()
Dim selectors = New BoundExpression(aggregationVariablesCount - 1) {}
Dim fields = New AnonymousTypeField(selectors.Length - 1) {}
Dim groupReference = New BoundRValuePlaceholder(aggregate, source.Type).MakeCompilerGenerated()
Dim intoBinder As New IntoClauseDisallowGroupReferenceBinder(Me, groupReference, source.RangeVariables, source.CompoundVariableType, source.RangeVariables)
For i As Integer = 0 To aggregationVariablesCount - 1
Dim rangeVar As RangeVariableSymbol = intoBinder.BindAggregationRangeVariable(aggregationVariables(i),
declaredNames, selectors(i),
diagnostics)
Debug.Assert(rangeVar IsNot Nothing)
fields(i) = New AnonymousTypeField(rangeVar.Name, rangeVar.Type, rangeVar.Syntax.GetLocation(), isKeyOrByRef:=True)
Next
Dim result As BoundExpression = BindAnonymousObjectCreationExpression(aggregate,
New AnonymousTypeDescriptor(fields.AsImmutableOrNull(),
aggregate.IntoKeyword.GetLocation(),
True),
selectors.AsImmutableOrNull(),
diagnostics).MakeCompilerGenerated()
source = New BoundAggregateClause(aggregate, source, groupReference,
result,
ImmutableArray(Of RangeVariableSymbol).Empty,
result.Type,
ImmutableArray.Create(Of Binder)(intoBinder),
result.Type)
End Select
Debug.Assert(Not source.Binders.IsDefault AndAlso source.Binders.Length = 1 AndAlso source.Binders(0) IsNot Nothing)
Return New BoundQueryExpression(query, source, If(malformedSyntax, ErrorTypeSymbol.UnknownResultType, source.Type), hasErrors:=malformedSyntax)
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Aggregate operator.
'''
''' {Preceding query operators} Aggregate {collection range variables} [{other operators}] Into {aggregation range variables}
'''
''' Depending on how many items we have in the INTO clause,
''' we will interpret Aggregate operator as follows:
'''
''' FROM a in AA FROM a in AA
''' AGGREGATE b in a.BB => LET count = (FROM b IN a.BB).Count()
''' INTO Count()
'''
''' FROM a in AA FROM a in AA
''' AGGREGATE b in a.BB => LET Group = (FROM b IN a.BB)
''' INTO Count(), Select a, Count=Group.Count(), Sum=Group.Sum(b=>b)
''' Sum(b)
'''
''' </summary>
Private Function BindAggregateClause(
source As BoundQueryClauseBase,
aggregate As AggregateClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundAggregateClause
Debug.Assert(operatorsEnumerator.Current Is aggregate)
' Let's interpret our group.
' Create LambdaSymbol for the shape of the Let-selector lambda.
Dim letSelectorParam As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(source.RangeVariables), 0,
source.CompoundVariableType,
aggregate, source.RangeVariables)
' The lambda that will contain the nested query.
Dim letSelectorLambdaSymbol = Me.CreateQueryLambdaSymbol(LambdaUtilities.GetAggregateLambdaBody(aggregate),
SynthesizedLambdaKind.AggregateQueryLambda,
ImmutableArray.Create(letSelectorParam))
' Create binder for the [Let] selector.
Dim letSelectorBinder As New QueryLambdaBinder(letSelectorLambdaSymbol, source.RangeVariables)
Dim declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol) = Nothing
Dim group As BoundQueryClauseBase = Nothing
Dim intoBinder As IntoClauseDisallowGroupReferenceBinder = Nothing
Dim letSelector As BoundExpression = letSelectorBinder.BindAggregateClauseFirstSelector(aggregate, operatorsEnumerator,
source.RangeVariables,
ImmutableArray(Of RangeVariableSymbol).Empty,
declaredRangeVariables,
group,
intoBinder,
diagnostics)
Dim letSelectorLambda As BoundQueryLambda
letSelectorLambda = CreateBoundQueryLambda(letSelectorLambdaSymbol,
source.RangeVariables,
letSelector,
exprIsOperandOfConditionalBranch:=False)
letSelectorLambdaSymbol.SetQueryLambdaReturnType(letSelector.Type)
letSelectorLambda.SetWasCompilerGenerated()
' Now bind the [Let] operator call.
Dim suppressDiagnostics As DiagnosticBag = Nothing
Dim underlyingExpression As BoundExpression
If source.Type.IsErrorType() Then
underlyingExpression = BadExpression(aggregate, ImmutableArray.Create(Of BoundNode)(source, letSelectorLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Dim callDiagnostics As DiagnosticBag = diagnostics
If ShouldSuppressDiagnostics(letSelectorLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
Debug.Assert(suppressDiagnostics Is Nothing)
suppressDiagnostics = DiagnosticBag.GetInstance()
callDiagnostics = suppressDiagnostics
End If
underlyingExpression = BindQueryOperatorCall(aggregate, source,
StringConstants.SelectMethod,
ImmutableArray.Create(Of BoundExpression)(letSelectorLambda),
aggregate.AggregateKeyword.Span,
callDiagnostics)
End If
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
Return CompleteAggregateClauseBinding(aggregate,
operatorsEnumerator,
source.RangeVariables,
ImmutableArray(Of RangeVariableSymbol).Empty,
underlyingExpression,
letSelectorBinder,
declaredRangeVariables,
letSelectorLambda.Expression.Type,
group,
intoBinder,
diagnostics)
End Function
Private Function CompleteAggregateClauseBinding(
aggregate As AggregateClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
sourceRangeVariablesPart1 As ImmutableArray(Of RangeVariableSymbol),
sourceRangeVariablesPart2 As ImmutableArray(Of RangeVariableSymbol),
firstSelectExpression As BoundExpression,
firstSelectSelectorBinder As QueryLambdaBinder,
firstSelectDeclaredRangeVariables As ImmutableArray(Of RangeVariableSymbol),
firstSelectCompoundVariableType As TypeSymbol,
group As BoundQueryClauseBase,
intoBinder As IntoClauseDisallowGroupReferenceBinder,
diagnostics As DiagnosticBag
) As BoundAggregateClause
Debug.Assert((sourceRangeVariablesPart1.Length = 0) = (sourceRangeVariablesPart2 = firstSelectSelectorBinder.RangeVariables))
Debug.Assert((sourceRangeVariablesPart2.Length = 0) = (sourceRangeVariablesPart1 = firstSelectSelectorBinder.RangeVariables))
Debug.Assert(firstSelectSelectorBinder.RangeVariables.Length = sourceRangeVariablesPart1.Length + sourceRangeVariablesPart2.Length)
Dim result As BoundAggregateClause
Dim aggregationVariables As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = aggregate.AggregationVariables
If aggregationVariables.Count <= 1 Then
' Simple case
Debug.Assert(intoBinder IsNot Nothing)
Debug.Assert(firstSelectDeclaredRangeVariables.Length <= 1)
result = New BoundAggregateClause(aggregate, Nothing, Nothing,
firstSelectExpression,
firstSelectSelectorBinder.RangeVariables.Concat(firstSelectDeclaredRangeVariables),
firstSelectCompoundVariableType,
ImmutableArray.Create(Of Binder)(firstSelectSelectorBinder, intoBinder),
firstSelectExpression.Type)
Else
' Complex case, apply the [Select].
Debug.Assert(intoBinder Is Nothing)
Debug.Assert(firstSelectDeclaredRangeVariables.Length = 1)
Dim suppressCallDiagnostics As Boolean = (firstSelectExpression.Kind = BoundKind.BadExpression)
If Not suppressCallDiagnostics AndAlso firstSelectExpression.HasErrors AndAlso firstSelectExpression.Kind = BoundKind.QueryClause Then
Dim query = DirectCast(firstSelectExpression, BoundQueryClause)
suppressCallDiagnostics = query.UnderlyingExpression.Kind = BoundKind.BadExpression
End If
Dim letOperator = New BoundQueryClause(aggregate,
firstSelectExpression,
firstSelectSelectorBinder.RangeVariables.Concat(firstSelectDeclaredRangeVariables),
firstSelectCompoundVariableType,
ImmutableArray(Of Binder).Empty,
firstSelectExpression.Type).MakeCompilerGenerated()
Dim selectSelectorParam As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(letOperator.RangeVariables), 0,
letOperator.CompoundVariableType,
aggregate, letOperator.RangeVariables)
' This lambda only contains non-user code. We associate it with the aggregate clause itself.
Debug.Assert(LambdaUtilities.IsNonUserCodeQueryLambda(aggregate))
Dim selectSelectorLambdaSymbol = Me.CreateQueryLambdaSymbol(aggregate,
SynthesizedLambdaKind.AggregateNonUserCodeQueryLambda,
ImmutableArray.Create(selectSelectorParam))
' Create new binder for the [Select] selector.
Dim groupRangeVar As RangeVariableSymbol = firstSelectDeclaredRangeVariables(0)
Dim selectSelectorBinder As New QueryLambdaBinder(selectSelectorLambdaSymbol, ImmutableArray(Of RangeVariableSymbol).Empty)
Dim groupReference = New BoundRangeVariable(groupRangeVar.Syntax, groupRangeVar, groupRangeVar.Type).MakeCompilerGenerated()
intoBinder = New IntoClauseDisallowGroupReferenceBinder(selectSelectorBinder,
groupReference, group.RangeVariables, group.CompoundVariableType,
firstSelectSelectorBinder.RangeVariables.Concat(group.RangeVariables))
' Compound range variable after the first [Let] has shape { [<compound key part1>, ][<compound key part2>, ]<group> }.
Dim compoundKeyReferencePart1 As BoundExpression
Dim keysRangeVariablesPart1 As ImmutableArray(Of RangeVariableSymbol)
Dim compoundKeyReferencePart2 As BoundExpression
Dim keysRangeVariablesPart2 As ImmutableArray(Of RangeVariableSymbol)
If sourceRangeVariablesPart1.Length > 0 Then
' So we need to get a reference to the first property of selector's parameter.
Dim anonymousType = DirectCast(selectSelectorParam.Type, AnonymousTypeManager.AnonymousTypePublicSymbol)
Dim keyProperty = anonymousType.Properties(0)
Debug.Assert(keyProperty.Type Is firstSelectSelectorBinder.LambdaSymbol.Parameters(0).Type)
compoundKeyReferencePart1 = New BoundPropertyAccess(aggregate,
keyProperty,
Nothing,
PropertyAccessKind.Get,
False,
New BoundParameter(selectSelectorParam.Syntax,
selectSelectorParam, False,
selectSelectorParam.Type).MakeCompilerGenerated(),
ImmutableArray(Of BoundExpression).Empty).MakeCompilerGenerated()
keysRangeVariablesPart1 = sourceRangeVariablesPart1
If sourceRangeVariablesPart2.Length > 0 Then
keyProperty = anonymousType.Properties(1)
Debug.Assert(keyProperty.Type Is firstSelectSelectorBinder.LambdaSymbol.Parameters(1).Type)
' We need to get a reference to the second property of selector's parameter.
compoundKeyReferencePart2 = New BoundPropertyAccess(aggregate,
keyProperty,
Nothing,
PropertyAccessKind.Get,
False,
New BoundParameter(selectSelectorParam.Syntax,
selectSelectorParam, False,
selectSelectorParam.Type).MakeCompilerGenerated(),
ImmutableArray(Of BoundExpression).Empty).MakeCompilerGenerated()
keysRangeVariablesPart2 = sourceRangeVariablesPart2
Else
compoundKeyReferencePart2 = Nothing
keysRangeVariablesPart2 = ImmutableArray(Of RangeVariableSymbol).Empty
End If
ElseIf sourceRangeVariablesPart2.Length > 0 Then
' So we need to get a reference to the first property of selector's parameter.
Dim anonymousType = DirectCast(selectSelectorParam.Type, AnonymousTypeManager.AnonymousTypePublicSymbol)
Dim keyProperty = anonymousType.Properties(0)
Debug.Assert(keyProperty.Type Is firstSelectSelectorBinder.LambdaSymbol.Parameters(1).Type)
compoundKeyReferencePart1 = New BoundPropertyAccess(aggregate,
keyProperty,
Nothing,
PropertyAccessKind.Get,
False,
New BoundParameter(selectSelectorParam.Syntax,
selectSelectorParam, False,
selectSelectorParam.Type).MakeCompilerGenerated(),
ImmutableArray(Of BoundExpression).Empty).MakeCompilerGenerated()
keysRangeVariablesPart1 = sourceRangeVariablesPart2
compoundKeyReferencePart2 = Nothing
keysRangeVariablesPart2 = ImmutableArray(Of RangeVariableSymbol).Empty
Else
compoundKeyReferencePart1 = Nothing
keysRangeVariablesPart1 = ImmutableArray(Of RangeVariableSymbol).Empty
compoundKeyReferencePart2 = Nothing
keysRangeVariablesPart2 = ImmutableArray(Of RangeVariableSymbol).Empty
End If
Dim declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol) = Nothing
Dim selectSelector As BoundExpression = intoBinder.BindIntoSelector(aggregate,
firstSelectSelectorBinder.RangeVariables,
compoundKeyReferencePart1,
keysRangeVariablesPart1,
compoundKeyReferencePart2,
keysRangeVariablesPart2,
Nothing,
aggregationVariables,
MustProduceFlatCompoundVariable(operatorsEnumerator),
declaredRangeVariables,
diagnostics)
Dim selectSelectorLambda = CreateBoundQueryLambda(selectSelectorLambdaSymbol,
letOperator.RangeVariables,
selectSelector,
exprIsOperandOfConditionalBranch:=False)
selectSelectorLambdaSymbol.SetQueryLambdaReturnType(selectSelector.Type)
selectSelectorLambda.SetWasCompilerGenerated()
Dim underlyingExpression As BoundExpression
Dim suppressDiagnostics As DiagnosticBag = Nothing
If letOperator.Type.IsErrorType() Then
underlyingExpression = BadExpression(aggregate, ImmutableArray.Create(Of BoundNode)(letOperator, selectSelectorLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Dim callDiagnostics As DiagnosticBag = diagnostics
If suppressCallDiagnostics OrElse ShouldSuppressDiagnostics(selectSelectorLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
suppressDiagnostics = DiagnosticBag.GetInstance()
callDiagnostics = suppressDiagnostics
End If
underlyingExpression = BindQueryOperatorCall(aggregate, letOperator,
StringConstants.SelectMethod,
ImmutableArray.Create(Of BoundExpression)(selectSelectorLambda),
aggregate.AggregateKeyword.Span,
callDiagnostics)
End If
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
result = New BoundAggregateClause(aggregate, Nothing, Nothing,
underlyingExpression,
firstSelectSelectorBinder.RangeVariables.Concat(declaredRangeVariables),
selectSelectorLambda.Expression.Type,
ImmutableArray.Create(Of Binder)(firstSelectSelectorBinder, intoBinder),
underlyingExpression.Type)
End If
Debug.Assert(Not result.Binders.IsDefault AndAlso result.Binders.Length = 2 AndAlso
result.Binders(0) IsNot Nothing AndAlso result.Binders(1) IsNot Nothing)
Return result
End Function
''' <summary>
''' Apply implicit Select operator at the end of the query to
''' ensure that at least one query operator is called.
'''
''' Basically makes query like:
''' From a In AA
''' into:
''' From a In AA Select a
''' </summary>
Private Function BindFinalImplicitSelectClause(
source As BoundQueryClauseBase,
diagnostics As DiagnosticBag
) As BoundQueryClause
Debug.Assert(Not source.Type.IsErrorType())
Dim fromClauseSyntax = DirectCast(source.Syntax.Parent, FromClauseSyntax)
' Create LambdaSymbol for the shape of the selector.
Dim param As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(source.RangeVariables), 0,
source.CompoundVariableType,
fromClauseSyntax, source.RangeVariables)
' An implicit selector is an identity (x => x) function that doesn't contain any user code.
LambdaUtilities.IsNonUserCodeQueryLambda(fromClauseSyntax)
Dim lambdaSymbol = Me.CreateQueryLambdaSymbol(fromClauseSyntax,
SynthesizedLambdaKind.FromNonUserCodeQueryLambda,
ImmutableArray.Create(param))
lambdaSymbol.SetQueryLambdaReturnType(source.CompoundVariableType)
Dim selector As BoundExpression = New BoundParameter(param.Syntax,
param,
isLValue:=False,
type:=param.Type).MakeCompilerGenerated()
Debug.Assert(Not selector.HasErrors)
Dim selectorLambda = CreateBoundQueryLambda(lambdaSymbol,
ImmutableArray(Of RangeVariableSymbol).Empty,
selector,
exprIsOperandOfConditionalBranch:=False)
selectorLambda.SetWasCompilerGenerated()
Debug.Assert(Not selectorLambda.HasErrors)
Dim suppressDiagnostics As DiagnosticBag = Nothing
If param.Type.IsErrorType() Then
suppressDiagnostics = DiagnosticBag.GetInstance()
diagnostics = suppressDiagnostics
End If
Dim boundCallOrBadExpression As BoundExpression
boundCallOrBadExpression = BindQueryOperatorCall(source.Syntax.Parent, source,
StringConstants.SelectMethod,
ImmutableArray.Create(Of BoundExpression)(selectorLambda),
source.Syntax.Span,
diagnostics)
Debug.Assert(boundCallOrBadExpression.WasCompilerGenerated)
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
Return New BoundQueryClause(source.Syntax.Parent,
boundCallOrBadExpression,
ImmutableArray(Of RangeVariableSymbol).Empty,
source.CompoundVariableType,
ImmutableArray(Of Binder).Empty,
boundCallOrBadExpression.Type).MakeCompilerGenerated()
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Select operator.
'''
''' {Preceding query operators} Select {expression range variables}
'''
''' From a In AA Select b ==> AA.Select(Function(a) b)
'''
''' From a In AA Select b, c ==> AA.Select(Function(a) New With {b, c})
''' </summary>
Private Function BindSelectClause(
source As BoundQueryClauseBase,
clauseSyntax As SelectClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundQueryClause
Debug.Assert(clauseSyntax Is operatorsEnumerator.Current)
' Create LambdaSymbol for the shape of the selector.
Dim param As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(source.RangeVariables), 0,
source.CompoundVariableType,
clauseSyntax, source.RangeVariables)
Dim lambdaSymbol = Me.CreateQueryLambdaSymbol(LambdaUtilities.GetSelectLambdaBody(clauseSyntax),
SynthesizedLambdaKind.SelectQueryLambda,
ImmutableArray.Create(param))
' Create binder for the selector.
Dim selectorBinder As New QueryLambdaBinder(lambdaSymbol, source.RangeVariables)
Dim declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol) = Nothing
Dim selector As BoundExpression = selectorBinder.BindSelectClauseSelector(clauseSyntax,
operatorsEnumerator,
declaredRangeVariables,
diagnostics)
Dim selectorLambda = CreateBoundQueryLambda(lambdaSymbol,
source.RangeVariables,
selector,
exprIsOperandOfConditionalBranch:=False)
lambdaSymbol.SetQueryLambdaReturnType(selector.Type)
selectorLambda.SetWasCompilerGenerated()
' Now bind the call.
Dim boundCallOrBadExpression As BoundExpression
If source.Type.IsErrorType() Then
boundCallOrBadExpression = BadExpression(clauseSyntax, ImmutableArray.Create(Of BoundNode)(source, selectorLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Dim suppressDiagnostics As DiagnosticBag = Nothing
If ShouldSuppressDiagnostics(selectorLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
suppressDiagnostics = DiagnosticBag.GetInstance()
diagnostics = suppressDiagnostics
End If
boundCallOrBadExpression = BindQueryOperatorCall(clauseSyntax, source,
StringConstants.SelectMethod,
ImmutableArray.Create(Of BoundExpression)(selectorLambda),
clauseSyntax.SelectKeyword.Span,
diagnostics)
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
End If
Return New BoundQueryClause(clauseSyntax,
boundCallOrBadExpression,
declaredRangeVariables,
selectorLambda.Expression.Type,
ImmutableArray.Create(Of Binder)(selectorBinder),
boundCallOrBadExpression.Type)
End Function
Private Shared Function ShouldSuppressDiagnostics(lambda As BoundQueryLambda) As Boolean
If lambda.HasErrors Then
Return True
End If
For Each param As ParameterSymbol In lambda.LambdaSymbol.Parameters
If param.Type.IsErrorType() Then
Return True
End If
Next
Dim bodyType As TypeSymbol = lambda.Expression.Type
Return bodyType IsNot Nothing AndAlso bodyType.IsErrorType()
End Function
Private Shared Function ShadowsRangeVariableInTheChildScope(
childScopeBinder As Binder,
rangeVar As RangeVariableSymbol
) As Boolean
Dim lookup = LookupResult.GetInstance()
childScopeBinder.LookupInSingleBinder(lookup, rangeVar.Name, 0, Nothing, childScopeBinder, useSiteDiagnostics:=Nothing)
Dim result As Boolean = (lookup.IsGood AndAlso lookup.Symbols(0).Kind = SymbolKind.RangeVariable)
lookup.Free()
Return result
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Let operator.
'''
''' {Preceding query operators} Let {expression range variables}
'''
''' Ex: From a In AA Let b ==> AA.Select(Function(a) New With {a, b})
'''
''' Ex: From a In AA Let b, c ==> AA.Select(Function(a) New With {a, b}).Select(Function({a, b}) New With {a, b, c})
'''
''' Note, that preceding Select operator can introduce unnamed range variable, which is dropped by the Let
'''
''' Ex: From a In AA Select a + 1 Let b ==> AA.Select(Function(a) a + 1).Select(Function(unnamed) b)
'''
''' Also, depending on the amount of expression range variables declared by the Let, and the following query operators,
''' translation can produce a nested, as opposed to flat, compound variable.
'''
''' Ex: From a In AA Let b, c, d ==> AA.Select(Function(a) New With {a, b}).
''' Select(Function({a, b}) New With {{a, b}, c}).
''' Select(Function({{a, b}, c}) New With {a, b, c, d})
''' </summary>
Private Function BindLetClause(
source As BoundQueryClauseBase,
clauseSyntax As LetClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag,
Optional skipFirstVariable As Boolean = False
) As BoundQueryClause
Debug.Assert(clauseSyntax Is operatorsEnumerator.Current)
Dim suppressDiagnostics As DiagnosticBag = Nothing
Dim callDiagnostics As DiagnosticBag = diagnostics
Dim variables As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax) = clauseSyntax.Variables
Debug.Assert(variables.Count > 0, "Malformed syntax tree.")
If variables.Count = 0 Then
' Handle malformed tree gracefully.
Debug.Assert(Not skipFirstVariable)
Return New BoundQueryClause(clauseSyntax,
BadExpression(clauseSyntax, source, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated(),
source.RangeVariables.Add(RangeVariableSymbol.CreateForErrorRecovery(Me,
clauseSyntax,
ErrorTypeSymbol.UnknownResultType)),
ErrorTypeSymbol.UnknownResultType,
ImmutableArray.Create(Me),
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
Debug.Assert(Not skipFirstVariable OrElse source.Syntax Is variables.First)
For i = If(skipFirstVariable, 1, 0) To variables.Count - 1
Dim variable As ExpressionRangeVariableSyntax = variables(i)
' Create LambdaSymbol for the shape of the selector lambda.
Dim param As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(source.RangeVariables), 0,
source.CompoundVariableType,
variable, source.RangeVariables)
Dim lambdaSymbol = Me.CreateQueryLambdaSymbol(LambdaUtilities.GetLetVariableLambdaBody(variable),
SynthesizedLambdaKind.LetVariableQueryLambda,
ImmutableArray.Create(param))
' Create binder for a variable expression.
Dim selectorBinder As New QueryLambdaBinder(lambdaSymbol, source.RangeVariables)
Dim declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol) = Nothing
Dim selector As BoundExpression = selectorBinder.BindLetClauseVariableSelector(variable,
operatorsEnumerator,
declaredRangeVariables,
diagnostics)
Dim selectorLambda = CreateBoundQueryLambda(lambdaSymbol,
source.RangeVariables,
selector,
exprIsOperandOfConditionalBranch:=False)
lambdaSymbol.SetQueryLambdaReturnType(selector.Type)
selectorLambda.SetWasCompilerGenerated()
' Now bind the call.
Dim boundCallOrBadExpression As BoundExpression
If source.Type.IsErrorType() Then
boundCallOrBadExpression = BadExpression(variable, ImmutableArray.Create(Of BoundNode)(source, selectorLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
If suppressDiagnostics Is Nothing AndAlso ShouldSuppressDiagnostics(selectorLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
suppressDiagnostics = DiagnosticBag.GetInstance()
callDiagnostics = suppressDiagnostics
End If
Dim operatorNameLocation As TextSpan
If i = 0 Then
' This is the first variable.
operatorNameLocation = clauseSyntax.LetKeyword.Span
Else
operatorNameLocation = variables.GetSeparator(i - 1).Span
End If
boundCallOrBadExpression = BindQueryOperatorCall(variable, source,
StringConstants.SelectMethod,
ImmutableArray.Create(Of BoundExpression)(selectorLambda),
operatorNameLocation,
callDiagnostics)
End If
source = New BoundQueryClause(variable,
boundCallOrBadExpression,
source.RangeVariables.Concat(declaredRangeVariables),
selectorLambda.Expression.Type,
ImmutableArray.Create(Of Binder)(selectorBinder),
boundCallOrBadExpression.Type)
Next
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
Return DirectCast(source, BoundQueryClause)
End Function
''' <summary>
''' In some scenarios, it is safe to leave compound variable in nested form when there is an
''' operator down the road that does its own projection (Select, Group By, ...).
''' All following operators have to take an Anonymous Type in both cases and, since there is no way to
''' restrict the shape of the Anonymous Type in method's declaration, the operators should be
''' insensitive to the shape of the Anonymous Type.
''' </summary>
Private Shared Function MustProduceFlatCompoundVariable(
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator
) As Boolean
While operatorsEnumerator.MoveNext()
Select Case operatorsEnumerator.Current.Kind
Case SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause,
SyntaxKind.SelectClause,
SyntaxKind.LetClause,
SyntaxKind.FromClause,
SyntaxKind.AggregateClause
Return False
Case SyntaxKind.GroupByClause
' If [Group By] doesn't have selector for a group's element, we must produce flat result.
' Element of the group can be observed through result of the query.
Dim groupBy = DirectCast(operatorsEnumerator.Current, GroupByClauseSyntax)
Return groupBy.Items.Count = 0
End Select
End While
Return True
End Function
''' <summary>
''' In some scenarios, it is safe to leave compound variable in nested form when there is an
''' operator down the road that does its own projection (Select, Group By, ...).
''' All following operators have to take an Anonymous Type in both cases and, since there is no way to
''' restrict the shape of the Anonymous Type in method's declaration, the operators should be
''' insensitive to the shape of the Anonymous Type.
''' </summary>
Private Shared Function MustProduceFlatCompoundVariable(
groupOrInnerJoin As JoinClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator
) As Boolean
Select Case groupOrInnerJoin.Parent.Kind
Case SyntaxKind.SimpleJoinClause
' If we are nested into an Inner Join, it is safe to not flatten.
' Parent join will take care of flattening.
Return False
Case SyntaxKind.GroupJoinClause
Dim groupJoin = DirectCast(groupOrInnerJoin.Parent, GroupJoinClauseSyntax)
' If we are nested into a Group Join, we are building the group for it.
' It is safe to not flatten, if there is another nested join after this one,
' the last nested join will take care of flattening.
Return groupOrInnerJoin Is groupJoin.AdditionalJoins.LastOrDefault
Case Else
Return MustProduceFlatCompoundVariable(operatorsEnumerator)
End Select
End Function
''' <summary>
''' Given result of binding preceding query operators, if any, bind the following From operator.
'''
''' [{Preceding query operators}] From {collection range variables}
'''
''' Ex: From a In AA ==> AA
'''
''' Ex: From a In AA, b in BB ==> AA.SelectMany(Function(a) BB, Function(a, b) New With {a, b})
'''
''' Ex: {source with range variable 'd'} From a In AA, b in BB ==> source.SelectMany(Function(d) AA, Function(d, a) New With {d, a}).
''' SelectMany(Function({d, a}) BB,
''' Function({d, a}, b) New With {d, a, b})
'''
''' Note, that preceding Select operator can introduce unnamed range variable, which is dropped by the From
'''
''' Ex: From a In AA Select a + 1 From b in BB ==> AA.Select(Function(a) a + 1).
''' SelectMany(Function(unnamed) BB,
''' Function(unnamed, b) b)
'''
''' Also, depending on the amount of collection range variables declared by the From, and the following query operators,
''' translation can produce a nested, as opposed to flat, compound variable.
'''
''' Ex: From a In AA From b In BB, c In CC, d In DD ==> AA.SelectMany(Function(a) BB, Function(a, b) New With {a, b}).
''' SelectMany(Function({a, b}) CC, Function({a, b}, c) New With {{a, b}, c}).
''' SelectMany(Function({{a, b}, c}) DD,
''' Function({{a, b}, c}, d) New With {a, b, c, d})
'''
''' If From operator translation results in a SelectMany call and the From is immediately followed by a Select or a Let operator,
''' they are absorbed by the From translation. When this happens, operatorsEnumerator is advanced appropriately.
'''
''' Ex: From a In AA From b In BB Select a + b ==> AA.SelectMany(Function(a) BB, Function(a, b) a + b)
'''
''' Ex: From a In AA From b In BB Let c ==> AA.SelectMany(Function(a) BB, Function(a, b) new With {a, b, c})
'''
''' </summary>
Private Function BindFromClause(
sourceOpt As BoundQueryClauseBase,
from As FromClauseSyntax,
ByRef operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundQueryClauseBase
Debug.Assert(from Is operatorsEnumerator.Current)
Return BindCollectionRangeVariables(from, sourceOpt, from.Variables, operatorsEnumerator, diagnostics)
End Function
''' <summary>
''' See comments for BindFromClause method, this method actually does all the work.
''' </summary>
Private Function BindCollectionRangeVariables(
clauseSyntax As QueryClauseSyntax,
sourceOpt As BoundQueryClauseBase,
variables As SeparatedSyntaxList(Of CollectionRangeVariableSyntax),
ByRef operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundQueryClauseBase
Debug.Assert(clauseSyntax.IsKind(SyntaxKind.AggregateClause) OrElse clauseSyntax.IsKind(SyntaxKind.FromClause))
Debug.Assert(variables.Count > 0, "Malformed syntax tree.")
' Handle malformed tree gracefully.
If variables.Count = 0 Then
Dim rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, clauseSyntax, ErrorTypeSymbol.UnknownResultType)
If sourceOpt Is Nothing Then
Return New BoundQueryableSource(clauseSyntax,
New BoundQuerySource(BadExpression(clauseSyntax, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()).MakeCompilerGenerated(),
Nothing,
ImmutableArray.Create(rangeVar),
ErrorTypeSymbol.UnknownResultType,
ImmutableArray.Create(Me),
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
Else
Return New BoundQueryClause(clauseSyntax,
BadExpression(clauseSyntax, sourceOpt, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated(),
sourceOpt.RangeVariables.Add(rangeVar),
ErrorTypeSymbol.UnknownResultType,
ImmutableArray.Create(Me),
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
End If
Dim source As BoundQueryClauseBase = sourceOpt
If source Is Nothing Then
' We are at the beginning of the query.
' Let's go ahead and process the first collection range variable then.
source = BindCollectionRangeVariable(variables(0), True, Nothing, diagnostics)
Debug.Assert(source.RangeVariables.Length = 1)
End If
Dim suppressDiagnostics As DiagnosticBag = Nothing
Dim callDiagnostics As DiagnosticBag = diagnostics
For i = If(source Is sourceOpt, 0, 1) To variables.Count - 1
Dim variable As CollectionRangeVariableSyntax = variables(i)
' Create LambdaSymbol for the shape of the many-selector lambda.
Dim manySelectorParam As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(source.RangeVariables), 0,
source.CompoundVariableType,
variable, source.RangeVariables)
Dim manySelectorLambdaSymbol = Me.CreateQueryLambdaSymbol(LambdaUtilities.GetFromOrAggregateVariableLambdaBody(variable),
SynthesizedLambdaKind.FromOrAggregateVariableQueryLambda,
ImmutableArray.Create(manySelectorParam))
' Create binder for the many selector.
Dim manySelectorBinder As New QueryLambdaBinder(manySelectorLambdaSymbol, source.RangeVariables)
Dim manySelector As BoundQueryableSource = manySelectorBinder.BindCollectionRangeVariable(variable, False, Nothing, diagnostics)
Debug.Assert(manySelector.RangeVariables.Length = 1)
Dim manySelectorLambda = CreateBoundQueryLambda(manySelectorLambdaSymbol,
source.RangeVariables,
manySelector,
exprIsOperandOfConditionalBranch:=False)
' Note, we are not setting return type for the manySelectorLambdaSymbol because
' we want it to be taken from the target delegate type. We don't care what it is going to be
' because it doesn't affect types of range variables after this operator.
manySelectorLambda.SetWasCompilerGenerated()
' Create LambdaSymbol for the shape of the join-selector lambda.
Dim joinSelectorParamLeft As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterNameLeft(source.RangeVariables), 0,
source.CompoundVariableType,
variable, source.RangeVariables)
Dim joinSelectorParamRight As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterNameRight(manySelector.RangeVariables), 1,
manySelector.CompoundVariableType,
variable, manySelector.RangeVariables)
Dim lambdaBinders As ImmutableArray(Of Binder)
' If this is the last collection range variable, see if the next operator is
' a Select or a Let. If it is, we should absorb it by putting its selector
' in the join lambda.
Dim absorbNextOperator As QueryClauseSyntax = Nothing
If i = variables.Count - 1 Then
absorbNextOperator = JoinShouldAbsorbNextOperator(operatorsEnumerator)
End If
Dim sourceRangeVariables = source.RangeVariables
Dim joinSelectorRangeVariables As ImmutableArray(Of RangeVariableSymbol) = sourceRangeVariables.Concat(manySelector.RangeVariables)
Dim joinSelectorDeclaredRangeVariables As ImmutableArray(Of RangeVariableSymbol)
Dim joinSelector As BoundExpression
Dim group As BoundQueryClauseBase = Nothing
Dim intoBinder As IntoClauseDisallowGroupReferenceBinder = Nothing
Dim joinSelectorBinder As QueryLambdaBinder = Nothing
Dim joinSelectorLambdaKind As SynthesizedLambdaKind = Nothing
Dim joinSelectorSyntax As VisualBasicSyntaxNode = Nothing
GetAbsorbingJoinSelectorLambdaKindAndSyntax(clauseSyntax, absorbNextOperator, joinSelectorLambdaKind, joinSelectorSyntax)
Dim joinSelectorLambdaSymbol = Me.CreateQueryLambdaSymbol(joinSelectorSyntax,
joinSelectorLambdaKind,
ImmutableArray.Create(joinSelectorParamLeft, joinSelectorParamRight))
If absorbNextOperator IsNot Nothing Then
' Absorb selector of the next operator.
joinSelectorBinder = New QueryLambdaBinder(joinSelectorLambdaSymbol, joinSelectorRangeVariables)
joinSelectorDeclaredRangeVariables = Nothing
joinSelector = joinSelectorBinder.BindAbsorbingJoinSelector(absorbNextOperator,
operatorsEnumerator,
sourceRangeVariables,
manySelector.RangeVariables,
joinSelectorDeclaredRangeVariables,
group,
intoBinder,
diagnostics)
lambdaBinders = ImmutableArray.Create(Of Binder)(manySelectorBinder, joinSelectorBinder)
Else
joinSelectorDeclaredRangeVariables = ImmutableArray(Of RangeVariableSymbol).Empty
If sourceRangeVariables.Length > 0 Then
' Need to build an Anonymous Type.
joinSelectorBinder = New QueryLambdaBinder(joinSelectorLambdaSymbol, joinSelectorRangeVariables)
' If it is not the last variable in the list, we simply combine source's
' compound variable (an instance of its Anonymous Type) with our new variable,
' creating new compound variable of nested Anonymous Type.
' In some scenarios, it is safe to leave compound variable in nested form when there is an
' operator down the road that does its own projection (Select, Group By, ...).
' All following operators have to take an Anonymous Type in both cases and, since there is no way to
' restrict the shape of the Anonymous Type in method's declaration, the operators should be
' insensitive to the shape of the Anonymous Type.
joinSelector = joinSelectorBinder.BuildJoinSelector(variable,
(i = variables.Count - 1 AndAlso
MustProduceFlatCompoundVariable(operatorsEnumerator)),
diagnostics)
Else
' Easy case, no need to build an Anonymous Type.
Debug.Assert(sourceRangeVariables.Length = 0)
joinSelector = New BoundParameter(joinSelectorParamRight.Syntax, joinSelectorParamRight,
False, joinSelectorParamRight.Type).MakeCompilerGenerated()
End If
lambdaBinders = ImmutableArray.Create(Of Binder)(manySelectorBinder)
End If
' Join selector is either associated with absorbed select/let/aggregate clause
' or it doesn't contain user code (just pairs outer with inner into an anonymous type or is an identity).
Dim joinSelectorLambda = CreateBoundQueryLambda(joinSelectorLambdaSymbol,
joinSelectorRangeVariables,
joinSelector,
exprIsOperandOfConditionalBranch:=False)
joinSelectorLambdaSymbol.SetQueryLambdaReturnType(joinSelector.Type)
joinSelectorLambda.SetWasCompilerGenerated()
' Now bind the call.
Dim boundCallOrBadExpression As BoundExpression
If source.Type.IsErrorType() Then
boundCallOrBadExpression = BadExpression(variable, ImmutableArray.Create(Of BoundNode)(source, manySelectorLambda, joinSelectorLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
If suppressDiagnostics Is Nothing AndAlso
(ShouldSuppressDiagnostics(manySelectorLambda) OrElse ShouldSuppressDiagnostics(joinSelectorLambda)) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
suppressDiagnostics = DiagnosticBag.GetInstance()
callDiagnostics = suppressDiagnostics
End If
Dim operatorNameLocation As TextSpan
If i = 0 Then
' This is the first variable.
operatorNameLocation = clauseSyntax.GetFirstToken().Span
Else
operatorNameLocation = variables.GetSeparator(i - 1).Span
End If
boundCallOrBadExpression = BindQueryOperatorCall(variable, source,
StringConstants.SelectManyMethod,
ImmutableArray.Create(Of BoundExpression)(manySelectorLambda, joinSelectorLambda),
operatorNameLocation,
callDiagnostics)
End If
source = New BoundQueryClause(variable,
boundCallOrBadExpression,
joinSelectorRangeVariables,
joinSelectorLambda.Expression.Type,
lambdaBinders,
boundCallOrBadExpression.Type)
If absorbNextOperator IsNot Nothing Then
Debug.Assert(i = variables.Count - 1)
source = AbsorbOperatorFollowingJoin(DirectCast(source, BoundQueryClause),
absorbNextOperator, operatorsEnumerator,
joinSelectorDeclaredRangeVariables,
joinSelectorBinder,
sourceRangeVariables,
manySelector.RangeVariables,
group,
intoBinder,
diagnostics)
Exit For
End If
Next
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
Return source
End Function
Private Shared Sub GetAbsorbingJoinSelectorLambdaKindAndSyntax(
clauseSyntax As QueryClauseSyntax,
absorbNextOperator As QueryClauseSyntax,
<Out> ByRef lambdaKind As SynthesizedLambdaKind,
<Out> ByRef lambdaSyntax As VisualBasicSyntaxNode)
' Join selector is either associated with absorbed select/let/aggregate clause
' or it doesn't contain user code (just pairs outer with inner into an anonymous type or is an identity).
If absorbNextOperator Is Nothing Then
Select Case clauseSyntax.Kind
Case SyntaxKind.SimpleJoinClause
lambdaKind = SynthesizedLambdaKind.JoinNonUserCodeQueryLambda
Case SyntaxKind.FromClause
lambdaKind = SynthesizedLambdaKind.FromNonUserCodeQueryLambda
Case SyntaxKind.AggregateClause
lambdaKind = SynthesizedLambdaKind.FromNonUserCodeQueryLambda
Case Else
Throw ExceptionUtilities.UnexpectedValue(clauseSyntax.Kind)
End Select
lambdaSyntax = clauseSyntax
Debug.Assert(LambdaUtilities.IsNonUserCodeQueryLambda(lambdaSyntax))
Else
Select Case absorbNextOperator.Kind
Case SyntaxKind.AggregateClause
Dim firstVariable = DirectCast(absorbNextOperator, AggregateClauseSyntax).Variables.First
lambdaSyntax = LambdaUtilities.GetFromOrAggregateVariableLambdaBody(firstVariable)
lambdaKind = SynthesizedLambdaKind.AggregateQueryLambda
Case SyntaxKind.LetClause
Dim firstVariable = DirectCast(absorbNextOperator, LetClauseSyntax).Variables.First
lambdaSyntax = LambdaUtilities.GetLetVariableLambdaBody(firstVariable)
lambdaKind = SynthesizedLambdaKind.LetVariableQueryLambda
Case SyntaxKind.SelectClause
Dim selectClause = DirectCast(absorbNextOperator, SelectClauseSyntax)
lambdaSyntax = LambdaUtilities.GetSelectLambdaBody(selectClause)
lambdaKind = SynthesizedLambdaKind.SelectQueryLambda
Case Else
Throw ExceptionUtilities.UnexpectedValue(absorbNextOperator.Kind)
End Select
Debug.Assert(LambdaUtilities.IsLambdaBody(lambdaSyntax))
End If
End Sub
Private Shared Function JoinShouldAbsorbNextOperator(
ByRef operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator
) As QueryClauseSyntax
Dim copyOfOperatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator = operatorsEnumerator
If copyOfOperatorsEnumerator.MoveNext() Then
Dim nextOperator As QueryClauseSyntax = copyOfOperatorsEnumerator.Current
Select Case nextOperator.Kind
Case SyntaxKind.LetClause
If DirectCast(nextOperator, LetClauseSyntax).Variables.Count > 0 Then
' Absorb Let
operatorsEnumerator = copyOfOperatorsEnumerator
Return nextOperator
Else
' Malformed tree.
Debug.Assert(DirectCast(nextOperator, LetClauseSyntax).Variables.Count > 0, "Malformed syntax tree.")
End If
Case SyntaxKind.SelectClause
' Absorb Select
operatorsEnumerator = copyOfOperatorsEnumerator
Return nextOperator
Case SyntaxKind.AggregateClause
' Absorb Aggregate
operatorsEnumerator = copyOfOperatorsEnumerator
Return nextOperator
End Select
End If
Return Nothing
End Function
Private Function AbsorbOperatorFollowingJoin(
absorbingJoin As BoundQueryClause,
absorbNextOperator As QueryClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
joinSelectorDeclaredRangeVariables As ImmutableArray(Of RangeVariableSymbol),
joinSelectorBinder As QueryLambdaBinder,
leftRangeVariables As ImmutableArray(Of RangeVariableSymbol),
rightRangeVariables As ImmutableArray(Of RangeVariableSymbol),
group As BoundQueryClauseBase,
intoBinder As IntoClauseDisallowGroupReferenceBinder,
diagnostics As DiagnosticBag
) As BoundQueryClauseBase
Debug.Assert(absorbNextOperator Is operatorsEnumerator.Current)
Debug.Assert(absorbingJoin.Binders.Length > 1)
Select Case absorbNextOperator.Kind
Case SyntaxKind.SelectClause
' Absorb Select.
Return New BoundQueryClause(absorbNextOperator,
absorbingJoin, joinSelectorDeclaredRangeVariables,
absorbingJoin.CompoundVariableType,
ImmutableArray.Create(absorbingJoin.Binders.Last),
absorbingJoin.Type)
Case SyntaxKind.LetClause
' Absorb Let.
' First expression range variable was handled by the join selector,
' create node for it.
Dim [let] = DirectCast(absorbNextOperator, LetClauseSyntax)
Debug.Assert([let].Variables.Count > 0)
Dim firstVariable As ExpressionRangeVariableSyntax = [let].Variables.First
Dim absorbedLet As New BoundQueryClause(firstVariable,
absorbingJoin,
absorbingJoin.RangeVariables.Concat(joinSelectorDeclaredRangeVariables),
absorbingJoin.CompoundVariableType,
ImmutableArray.Create(absorbingJoin.Binders.Last),
absorbingJoin.Type)
' Handle the rest of the variables.
Return BindLetClause(absorbedLet, [let], operatorsEnumerator, diagnostics, skipFirstVariable:=True)
Case SyntaxKind.AggregateClause
' Absorb Aggregate.
Return CompleteAggregateClauseBinding(DirectCast(absorbNextOperator, AggregateClauseSyntax),
operatorsEnumerator,
leftRangeVariables,
rightRangeVariables,
absorbingJoin,
joinSelectorBinder,
joinSelectorDeclaredRangeVariables,
absorbingJoin.CompoundVariableType,
group,
intoBinder,
diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(absorbNextOperator.Kind)
End Select
End Function
''' <summary>
''' Given result of binding preceding query operators, the outer, bind the following Join operator.
'''
''' [{Preceding query operators}] Join {collection range variable}
''' [{additional joins}]
''' On {condition}
'''
''' Ex: From a In AA Join b in BB On Key(a) Equals Key(b) ==> AA.Join(BB, Function(a) Key(a), Function(b) Key(b),
''' Function(a, b) New With {a, b})
'''
''' Ex: From a In AA AA.Join(
''' Join b in BB BB.Join(CC, Function(b) Key(b), Function(c) Key(c),
''' Join c in CC ==> Function(b, c) New With {b, c}),
''' On Key(c) Equals Key(b) Function(a) Key(a), Function({b, c}) Key(b),
''' On Key(a) Equals Key(b) Function(a, {b, c}) New With {a, b, c})
'''
'''
''' Also, depending on the amount of collection range variables in scope, and the following query operators,
''' translation can produce a nested, as opposed to flat, compound variable.
'''
''' Ex: From a In AA AA.Join(BB, Function(a) Key(a), Function(b) Key(b),
''' Join b in BB Function(a, b) New With {a, b}).
''' On Key(a) Equals Key(b) Join(CC, Function({a, b}) Key(a, b), Function(c) Key(c),
''' Join c in CC ==> Function({a, b}, c) New With {{a, b}, c}).
''' On Key(c) Equals Key(a, b) Join(DD, Function({{a, b}, c}) Key(a, b, c), Function(d) Key(d),
''' Join d in DD Function({{a, b}, c}, d) New With {a, b, c, d})
''' On Key(a, b, c) Equals Key(d)
'''
''' If Join is immediately followed by a Select or a Let operator, they are absorbed by the translation.
''' When this happens, operatorsEnumerator is advanced appropriately.
'''
''' Ex: From a In AA Join b in BB On Key(a) Equals Key(b) ==> AA.Join(BB, Function(a) Key(a), Function(b) Key(b),
''' Select a + b Function(a, b) a + b)
'''
''' Ex: From a In AA Join b in BB On Key(a) Equals Key(b) ==> AA.Join(BB, Function(a) Key(a), Function(b) Key(b),
''' Let c Function(a, b) New With {a, b, c})
'''
''' </summary>
Private Function BindInnerJoinClause(
outer As BoundQueryClauseBase,
join As SimpleJoinClauseSyntax,
declaredNames As HashSet(Of String),
ByRef operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundQueryClauseBase
Debug.Assert(join.Kind = SyntaxKind.SimpleJoinClause)
Debug.Assert((declaredNames IsNot Nothing) = (join.Parent.Kind = SyntaxKind.SimpleJoinClause OrElse join.Parent.Kind = SyntaxKind.GroupJoinClause))
Dim isNested As Boolean
If declaredNames Is Nothing Then
Debug.Assert(join Is operatorsEnumerator.Current)
isNested = False
declaredNames = CreateSetOfDeclaredNames(outer.RangeVariables)
Else
isNested = True
AssertDeclaredNames(declaredNames, outer.RangeVariables)
End If
Debug.Assert(join.JoinedVariables.Count = 1, "Malformed syntax tree.")
Dim inner As BoundQueryClauseBase
If join.JoinedVariables.Count = 0 Then
' Malformed tree.
Dim rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, join, ErrorTypeSymbol.UnknownResultType)
inner = New BoundQueryableSource(join,
New BoundQuerySource(BadExpression(join, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()).MakeCompilerGenerated(),
Nothing,
ImmutableArray.Create(rangeVar),
ErrorTypeSymbol.UnknownResultType,
ImmutableArray(Of Binder).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True).MakeCompilerGenerated()
Else
inner = BindCollectionRangeVariable(join.JoinedVariables(0), False, declaredNames, diagnostics)
End If
For Each additionalJoin As JoinClauseSyntax In join.AdditionalJoins
Select Case additionalJoin.Kind
Case SyntaxKind.SimpleJoinClause
inner = BindInnerJoinClause(inner, DirectCast(additionalJoin, SimpleJoinClauseSyntax), declaredNames, Nothing, diagnostics)
Case SyntaxKind.GroupJoinClause
inner = BindGroupJoinClause(inner, DirectCast(additionalJoin, GroupJoinClauseSyntax), declaredNames, Nothing, diagnostics)
End Select
Next
AssertDeclaredNames(declaredNames, inner.RangeVariables)
' Bind keys.
Dim outerKeyLambda As BoundQueryLambda = Nothing
Dim innerKeyLambda As BoundQueryLambda = Nothing
Dim outerKeyBinder As QueryLambdaBinder = Nothing
Dim innerKeyBinder As QueryLambdaBinder = Nothing
Dim joinSelectorRangeVariables As ImmutableArray(Of RangeVariableSymbol) = outer.RangeVariables.Concat(inner.RangeVariables)
QueryLambdaBinder.BindJoinKeys(Me, join, outer, inner,
joinSelectorRangeVariables,
outerKeyLambda, outerKeyBinder,
innerKeyLambda, innerKeyBinder,
diagnostics)
' Create LambdaSymbol for the shape of the join-selector lambda.
Dim joinSelectorParamLeft As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterNameLeft(outer.RangeVariables), 0,
outer.CompoundVariableType,
join, outer.RangeVariables)
Dim joinSelectorParamRight As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterNameRight(inner.RangeVariables), 1,
inner.CompoundVariableType,
join, inner.RangeVariables)
Dim lambdaBinders As ImmutableArray(Of Binder)
' If the next operator is a Select or a Let, we should absorb it by putting its selector
' in the join lambda.
Dim absorbNextOperator As QueryClauseSyntax = Nothing
If Not isNested Then
absorbNextOperator = JoinShouldAbsorbNextOperator(operatorsEnumerator)
End If
Dim joinSelectorDeclaredRangeVariables As ImmutableArray(Of RangeVariableSymbol)
Dim joinSelector As BoundExpression
Dim group As BoundQueryClauseBase = Nothing
Dim intoBinder As IntoClauseDisallowGroupReferenceBinder = Nothing
Dim joinSelectorLambdaKind As SynthesizedLambdaKind = Nothing
Dim joinSelectorSyntax As VisualBasicSyntaxNode = Nothing
GetAbsorbingJoinSelectorLambdaKindAndSyntax(join, absorbNextOperator, joinSelectorLambdaKind, joinSelectorSyntax)
Dim joinSelectorLambdaSymbol = Me.CreateQueryLambdaSymbol(joinSelectorSyntax,
joinSelectorLambdaKind,
ImmutableArray.Create(joinSelectorParamLeft, joinSelectorParamRight))
Dim joinSelectorBinder As New QueryLambdaBinder(joinSelectorLambdaSymbol, joinSelectorRangeVariables)
If absorbNextOperator IsNot Nothing Then
' Absorb selector of the next operator.
joinSelectorDeclaredRangeVariables = Nothing
joinSelectorSyntax = Nothing
joinSelector = joinSelectorBinder.BindAbsorbingJoinSelector(absorbNextOperator,
operatorsEnumerator,
outer.RangeVariables,
inner.RangeVariables,
joinSelectorDeclaredRangeVariables,
group,
intoBinder,
diagnostics)
lambdaBinders = ImmutableArray.Create(Of Binder)(outerKeyBinder, innerKeyBinder, joinSelectorBinder)
Else
Debug.Assert(outer.RangeVariables.Length > 0 AndAlso inner.RangeVariables.Length > 0)
joinSelectorDeclaredRangeVariables = ImmutableArray(Of RangeVariableSymbol).Empty
' Need to build an Anonymous Type.
' In some scenarios, it is safe to leave compound variable in nested form when there is an
' operator down the road that does its own projection (Select, Group By, ...).
' All following operators have to take an Anonymous Type in both cases and, since there is no way to
' restrict the shape of the Anonymous Type in method's declaration, the operators should be
' insensitive to the shape of the Anonymous Type.
joinSelector = joinSelectorBinder.BuildJoinSelector(join,
MustProduceFlatCompoundVariable(join, operatorsEnumerator),
diagnostics)
' Not including joinSelectorBinder because there is no syntax behind this joinSelector,
' it is purely synthetic.
lambdaBinders = ImmutableArray.Create(Of Binder)(outerKeyBinder, innerKeyBinder)
End If
Dim joinSelectorLambda = CreateBoundQueryLambda(joinSelectorLambdaSymbol,
joinSelectorRangeVariables,
joinSelector,
exprIsOperandOfConditionalBranch:=False)
joinSelectorLambdaSymbol.SetQueryLambdaReturnType(joinSelector.Type)
joinSelectorLambda.SetWasCompilerGenerated()
' Now bind the call.
Dim boundCallOrBadExpression As BoundExpression
If outer.Type.IsErrorType() Then
boundCallOrBadExpression = BadExpression(join, ImmutableArray.Create(Of BoundNode)(outer, inner, outerKeyLambda, innerKeyLambda, joinSelectorLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Dim callDiagnostics As DiagnosticBag = diagnostics
Dim suppressDiagnostics As DiagnosticBag = Nothing
If inner.HasErrors OrElse inner.Type.IsErrorType() OrElse
ShouldSuppressDiagnostics(outerKeyLambda) OrElse
ShouldSuppressDiagnostics(innerKeyLambda) OrElse
ShouldSuppressDiagnostics(joinSelectorLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
suppressDiagnostics = DiagnosticBag.GetInstance()
callDiagnostics = suppressDiagnostics
End If
boundCallOrBadExpression = BindQueryOperatorCall(join, outer,
StringConstants.JoinMethod,
ImmutableArray.Create(Of BoundExpression)(inner, outerKeyLambda, innerKeyLambda, joinSelectorLambda),
join.JoinKeyword.Span,
callDiagnostics)
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
End If
Dim result As BoundQueryClauseBase = New BoundQueryClause(join,
boundCallOrBadExpression,
joinSelectorRangeVariables,
joinSelectorLambda.Expression.Type,
lambdaBinders,
boundCallOrBadExpression.Type)
If absorbNextOperator IsNot Nothing Then
Debug.Assert(Not isNested)
result = AbsorbOperatorFollowingJoin(DirectCast(result, BoundQueryClause),
absorbNextOperator, operatorsEnumerator,
joinSelectorDeclaredRangeVariables,
joinSelectorBinder,
outer.RangeVariables,
inner.RangeVariables,
group,
intoBinder,
diagnostics)
End If
Return result
End Function
Private Shared Function CreateSetOfDeclaredNames() As HashSet(Of String)
Return New HashSet(Of String)(CaseInsensitiveComparison.Comparer)
End Function
Private Shared Function CreateSetOfDeclaredNames(rangeVariables As ImmutableArray(Of RangeVariableSymbol)) As HashSet(Of String)
Dim declaredNames As New HashSet(Of String)(CaseInsensitiveComparison.Comparer)
For Each rangeVar As RangeVariableSymbol In rangeVariables
declaredNames.Add(rangeVar.Name)
Next
Return declaredNames
End Function
<Conditional("DEBUG")>
Private Shared Sub AssertDeclaredNames(declaredNames As HashSet(Of String), rangeVariables As ImmutableArray(Of RangeVariableSymbol))
#If DEBUG Then
For Each rangeVar As RangeVariableSymbol In rangeVariables
If Not rangeVar.Name.StartsWith("$"c, StringComparison.Ordinal) Then
Debug.Assert(declaredNames.Contains(rangeVar.Name))
End If
Next
#End If
End Sub
''' <summary>
''' Given result of binding preceding query operators, the outer, bind the following Group Join operator.
'''
''' [{Preceding query operators}] Group Join {collection range variable}
''' [{additional joins}]
''' On {condition}
''' Into {aggregation range variables}
'''
''' Ex: From a In AA Group Join b in BB AA.GroupJoin(BB, Function(a) Key(a), Function(b) Key(b),
''' On Key(a) Equals Key(b) ==> Function(a, group_b) New With {a, group_b.Count()})
''' Into Count()
'''
''' Also, depending on the amount of collection range variables in scope, and the following query operators,
''' translation can produce a nested, as opposed to flat, compound variable (see BindInnerJoinClause for an example).
'''
''' Note, that type of the group must be inferred from the set of available GroupJoin operators in order to be able to
''' interpret the aggregation range variables.
''' </summary>
Private Function BindGroupJoinClause(
outer As BoundQueryClauseBase,
groupJoin As GroupJoinClauseSyntax,
declaredNames As HashSet(Of String),
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
diagnostics As DiagnosticBag
) As BoundQueryClause
Debug.Assert((declaredNames IsNot Nothing) = (groupJoin.Parent.Kind = SyntaxKind.SimpleJoinClause OrElse groupJoin.Parent.Kind = SyntaxKind.GroupJoinClause))
' Shadowing rules for range variables declared by [Group Join] are a little
' bit tricky:
' 1) Range variables declared within the inner source (JoinedVariables + AdditionalJoins)
' can survive only up until the [On] clause, after that, even those in scope, move out of scope
' into the Group. Other range variables in scope in the [On] are the outer's range variables.
' Range variables from outer's outer are not in scope and, therefore, are never shadowed by the
' same-named inner source range variables. Range variables declared within the inner source that
' go out of scope before interpretation reaches the [On] clause do not shadow even same-named
' outer's range variables.
'
' 2) Range variables declared in the [Into] clause must not shadow outer's range variables simply
' because they are merged into the same Anonymous Type by the [Into] selector. They also must
' not shadow outer's outer range variables (possibly throughout the whole hierarchy),
' with which they will later get into the same scope within an [On] clause. Note, that declaredNames
' parameter, when passed, includes the names of all such range variables and this function will add
' to this set.
Dim namesInScopeInOnClause As HashSet(Of String) = CreateSetOfDeclaredNames(outer.RangeVariables)
If declaredNames Is Nothing Then
Debug.Assert(groupJoin Is operatorsEnumerator.Current)
declaredNames = CreateSetOfDeclaredNames(outer.RangeVariables)
Else
AssertDeclaredNames(declaredNames, outer.RangeVariables)
End If
Debug.Assert(groupJoin.JoinedVariables.Count = 1, "Malformed syntax tree.")
Dim inner As BoundQueryClauseBase
If groupJoin.JoinedVariables.Count = 0 Then
' Malformed tree.
Dim rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, groupJoin, ErrorTypeSymbol.UnknownResultType)
inner = New BoundQueryableSource(groupJoin,
New BoundQuerySource(BadExpression(groupJoin, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()).MakeCompilerGenerated(),
Nothing,
ImmutableArray.Create(rangeVar),
ErrorTypeSymbol.UnknownResultType,
ImmutableArray(Of Binder).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True).MakeCompilerGenerated()
Else
inner = BindCollectionRangeVariable(groupJoin.JoinedVariables(0), False, namesInScopeInOnClause, diagnostics)
End If
For Each additionalJoin As JoinClauseSyntax In groupJoin.AdditionalJoins
Select Case additionalJoin.Kind
Case SyntaxKind.SimpleJoinClause
inner = BindInnerJoinClause(inner, DirectCast(additionalJoin, SimpleJoinClauseSyntax), namesInScopeInOnClause, Nothing, diagnostics)
Case SyntaxKind.GroupJoinClause
inner = BindGroupJoinClause(inner, DirectCast(additionalJoin, GroupJoinClauseSyntax), namesInScopeInOnClause, Nothing, diagnostics)
End Select
Next
Debug.Assert(outer.RangeVariables.Length > 0 AndAlso inner.RangeVariables.Length > 0)
AssertDeclaredNames(namesInScopeInOnClause, inner.RangeVariables)
' Bind keys.
Dim outerKeyLambda As BoundQueryLambda = Nothing
Dim innerKeyLambda As BoundQueryLambda = Nothing
Dim outerKeyBinder As QueryLambdaBinder = Nothing
Dim innerKeyBinder As QueryLambdaBinder = Nothing
QueryLambdaBinder.BindJoinKeys(Me, groupJoin, outer, inner,
outer.RangeVariables.Concat(inner.RangeVariables),
outerKeyLambda, outerKeyBinder,
innerKeyLambda, innerKeyBinder,
diagnostics)
' Infer type of the resulting group.
Dim methodGroup As BoundMethodGroup = Nothing
Dim groupType As TypeSymbol = InferGroupType(outer, inner, groupJoin, outerKeyLambda, innerKeyLambda, methodGroup, diagnostics)
' Bind the INTO selector.
Dim intoBinder As IntoClauseBinder = Nothing
Dim intoRangeVariables As ImmutableArray(Of RangeVariableSymbol) = Nothing
Dim intoLambda As BoundQueryLambda = BindIntoSelectorLambda(groupJoin, outer.RangeVariables, outer.CompoundVariableType,
True, declaredNames,
groupType, inner.RangeVariables, inner.CompoundVariableType,
groupJoin.AggregationVariables,
MustProduceFlatCompoundVariable(groupJoin, operatorsEnumerator),
diagnostics, intoBinder, intoRangeVariables)
' Now bind the call.
Dim boundCallOrBadExpression As BoundExpression
If outer.Type.IsErrorType() OrElse methodGroup Is Nothing Then
boundCallOrBadExpression = BadExpression(groupJoin, ImmutableArray.Create(Of BoundNode)(outer, inner, outerKeyLambda, innerKeyLambda, intoLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Dim callDiagnostics As DiagnosticBag = diagnostics
If inner.HasErrors OrElse inner.Type.IsErrorType() OrElse
ShouldSuppressDiagnostics(outerKeyLambda) OrElse
ShouldSuppressDiagnostics(innerKeyLambda) OrElse
ShouldSuppressDiagnostics(intoLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
callDiagnostics = DiagnosticBag.GetInstance()
End If
' Reusing method group that we got while inferring group type, this way we can avoid doing name lookup again.
boundCallOrBadExpression = BindQueryOperatorCall(groupJoin, outer,
StringConstants.GroupJoinMethod,
methodGroup,
ImmutableArray.Create(Of BoundExpression)(inner, outerKeyLambda, innerKeyLambda, intoLambda),
groupJoin.JoinKeyword.Span,
callDiagnostics)
If callDiagnostics IsNot diagnostics Then
callDiagnostics.Free()
End If
End If
Return New BoundQueryClause(groupJoin,
boundCallOrBadExpression,
outer.RangeVariables.Concat(intoRangeVariables),
intoLambda.Expression.Type,
ImmutableArray.Create(Of Binder)(outerKeyBinder, innerKeyBinder, intoBinder),
boundCallOrBadExpression.Type)
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Group By operator.
'''
''' [{Preceding query operators}] Group [{items expression range variables}]
''' By {keys expression range variables}
''' Into {aggregation range variables}
'''
''' Ex: From a In AA Group By Key(a) AA.GroupBy(Function(a) Key(a),
''' Into Count() ==> Function(key, group_a) New With {key, group_a.Count()})
'''
''' Ex: From a In AA Group Item(a) AA.GroupBy(Function(a) Key(a),
''' By Key(a) ==> Function(a) Item(a),
''' Into Count() Function(key, group_a) New With {key, group_a.Count()})
'''
''' Note, that type of the group must be inferred from the set of available GroupBy operators in order to be able to
''' interpret the aggregation range variables.
''' </summary>
Private Function BindGroupByClause(
source As BoundQueryClauseBase,
groupBy As GroupByClauseSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
' Handle group items.
Dim itemsLambdaBinder As QueryLambdaBinder = Nothing
Dim itemsRangeVariables As ImmutableArray(Of RangeVariableSymbol) = Nothing
Dim itemsLambda As BoundQueryLambda = BindGroupByItems(source, groupBy, itemsLambdaBinder, itemsRangeVariables, diagnostics)
' Handle grouping keys.
Dim keysLambdaBinder As QueryLambdaBinder = Nothing
Dim keysRangeVariables As ImmutableArray(Of RangeVariableSymbol) = Nothing
Dim keysLambda As BoundQueryLambda = BindGroupByKeys(source, groupBy, keysLambdaBinder, keysRangeVariables, diagnostics)
Debug.Assert(keysLambda IsNot Nothing)
' Infer type of the resulting group.
Dim methodGroup As BoundMethodGroup = Nothing
Dim groupType As TypeSymbol = InferGroupType(source, groupBy, itemsLambda, keysLambda, keysRangeVariables, methodGroup, diagnostics)
' Bind the INTO selector.
Dim groupRangeVariables As ImmutableArray(Of RangeVariableSymbol)
Dim groupCompoundVariableType As TypeSymbol
If itemsLambda Is Nothing Then
groupRangeVariables = source.RangeVariables
groupCompoundVariableType = source.CompoundVariableType
Else
groupRangeVariables = itemsRangeVariables
groupCompoundVariableType = itemsLambda.Expression.Type
End If
Dim intoBinder As IntoClauseBinder = Nothing
Dim intoRangeVariables As ImmutableArray(Of RangeVariableSymbol) = Nothing
Dim intoLambda As BoundQueryLambda = BindIntoSelectorLambda(groupBy, keysRangeVariables, keysLambda.Expression.Type, False, Nothing,
groupType, groupRangeVariables, groupCompoundVariableType,
groupBy.AggregationVariables, True,
diagnostics, intoBinder, intoRangeVariables)
' Now bind the call.
Dim groupByArguments() As BoundExpression
Dim lambdaBinders As ImmutableArray(Of Binder)
Debug.Assert((itemsLambda Is Nothing) = (itemsLambdaBinder Is Nothing))
If itemsLambda Is Nothing Then
groupByArguments = {keysLambda, intoLambda}
lambdaBinders = ImmutableArray.Create(Of Binder)(keysLambdaBinder, intoBinder)
Else
groupByArguments = {keysLambda, itemsLambda, intoLambda}
lambdaBinders = ImmutableArray.Create(Of Binder)(keysLambdaBinder, itemsLambdaBinder, intoBinder)
End If
Dim boundCallOrBadExpression As BoundExpression
If source.Type.IsErrorType() OrElse methodGroup Is Nothing Then
boundCallOrBadExpression = BadExpression(groupBy,
ImmutableArray.Create(Of BoundNode)(source).AddRange(groupByArguments),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Dim callDiagnostics As DiagnosticBag = diagnostics
If ShouldSuppressDiagnostics(keysLambda) OrElse ShouldSuppressDiagnostics(intoLambda) OrElse
(itemsLambda IsNot Nothing AndAlso ShouldSuppressDiagnostics(itemsLambda)) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
callDiagnostics = DiagnosticBag.GetInstance()
End If
' Reusing method group that we got while inferring group type, this way we can avoid doing name lookup again.
boundCallOrBadExpression = BindQueryOperatorCall(groupBy, source,
StringConstants.GroupByMethod,
methodGroup,
groupByArguments.AsImmutableOrNull(),
GetGroupByOperatorNameSpan(groupBy),
callDiagnostics)
If callDiagnostics IsNot diagnostics Then
callDiagnostics.Free()
End If
End If
Return New BoundQueryClause(groupBy,
boundCallOrBadExpression,
keysRangeVariables.Concat(intoRangeVariables),
intoLambda.Expression.Type,
lambdaBinders,
boundCallOrBadExpression.Type)
End Function
Private Shared Function GetGroupByOperatorNameSpan(groupBy As GroupByClauseSyntax) As TextSpan
If groupBy.Items.Count = 0 Then
Return GetQueryOperatorNameSpan(groupBy.GroupKeyword, groupBy.ByKeyword)
Else
Return groupBy.GroupKeyword.Span
End If
End Function
''' <summary>
''' Returns Nothing if items were omitted.
''' </summary>
Private Function BindGroupByItems(
source As BoundQueryClauseBase,
groupBy As GroupByClauseSyntax,
<Out()> ByRef itemsLambdaBinder As QueryLambdaBinder,
<Out()> ByRef itemsRangeVariables As ImmutableArray(Of RangeVariableSymbol),
diagnostics As DiagnosticBag
) As BoundQueryLambda
Debug.Assert(itemsLambdaBinder Is Nothing)
Debug.Assert(itemsRangeVariables.IsDefault)
' Handle group items.
Dim itemsLambda As BoundQueryLambda = Nothing
Dim items As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax) = groupBy.Items
If items.Count > 0 Then
Dim itemsParam As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(source.RangeVariables), 0,
source.CompoundVariableType,
groupBy, source.RangeVariables)
Dim itemsLambdaSymbol = Me.CreateQueryLambdaSymbol(LambdaUtilities.GetGroupByItemsLambdaBody(groupBy),
SynthesizedLambdaKind.GroupByItemsQueryLambda,
ImmutableArray.Create(itemsParam))
' Create binder for the selector.
itemsLambdaBinder = New QueryLambdaBinder(itemsLambdaSymbol, source.RangeVariables)
Dim itemsSelector = itemsLambdaBinder.BindExpressionRangeVariables(items, False, groupBy,
itemsRangeVariables, diagnostics)
itemsLambda = CreateBoundQueryLambda(itemsLambdaSymbol,
source.RangeVariables,
itemsSelector,
exprIsOperandOfConditionalBranch:=False)
itemsLambdaSymbol.SetQueryLambdaReturnType(itemsSelector.Type)
itemsLambda.SetWasCompilerGenerated()
Else
itemsLambdaBinder = Nothing
itemsRangeVariables = ImmutableArray(Of RangeVariableSymbol).Empty
End If
Debug.Assert((itemsLambda Is Nothing) = (itemsLambdaBinder Is Nothing))
Debug.Assert(Not itemsRangeVariables.IsDefault)
Debug.Assert(itemsLambda IsNot Nothing OrElse itemsRangeVariables.Length = 0)
Return itemsLambda
End Function
Private Function BindGroupByKeys(
source As BoundQueryClauseBase,
groupBy As GroupByClauseSyntax,
<Out()> ByRef keysLambdaBinder As QueryLambdaBinder,
<Out()> ByRef keysRangeVariables As ImmutableArray(Of RangeVariableSymbol),
diagnostics As DiagnosticBag
) As BoundQueryLambda
Debug.Assert(keysLambdaBinder Is Nothing)
Debug.Assert(keysRangeVariables.IsDefault)
Dim keys As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax) = groupBy.Keys
Dim keysParam As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(source.RangeVariables), 0,
source.CompoundVariableType,
groupBy, source.RangeVariables)
Dim keysLambdaSymbol = Me.CreateQueryLambdaSymbol(LambdaUtilities.GetGroupByKeysLambdaBody(groupBy),
SynthesizedLambdaKind.GroupByKeysQueryLambda,
ImmutableArray.Create(keysParam))
' Create binder for the selector.
keysLambdaBinder = New QueryLambdaBinder(keysLambdaSymbol, source.RangeVariables)
Dim keysSelector = keysLambdaBinder.BindExpressionRangeVariables(keys, True, groupBy,
keysRangeVariables, diagnostics)
Dim keysLambda = CreateBoundQueryLambda(keysLambdaSymbol,
source.RangeVariables,
keysSelector,
exprIsOperandOfConditionalBranch:=False)
keysLambdaSymbol.SetQueryLambdaReturnType(keysSelector.Type)
keysLambda.SetWasCompilerGenerated()
Return keysLambda
End Function
''' <summary>
''' Infer type of the group for a Group By operator from the set of available GroupBy methods.
'''
''' In short, given already bound itemsLambda and keysLambda, this method performs overload
''' resolution over the set of available GroupBy operator methods using fake Into lambda:
''' Function(key, group As typeToBeInferred) New With {group}
'''
''' If resolution succeeds, the type inferred for the best candidate is our result.
''' </summary>
Private Function InferGroupType(
source As BoundQueryClauseBase,
groupBy As GroupByClauseSyntax,
itemsLambda As BoundQueryLambda,
keysLambda As BoundQueryLambda,
keysRangeVariables As ImmutableArray(Of RangeVariableSymbol),
<Out()> ByRef methodGroup As BoundMethodGroup,
diagnostics As DiagnosticBag
) As TypeSymbol
Debug.Assert(methodGroup Is Nothing)
Dim groupType As TypeSymbol = ErrorTypeSymbol.UnknownResultType
If Not source.Type.IsErrorType() Then
methodGroup = LookupQueryOperator(groupBy, source, StringConstants.GroupByMethod, Nothing, diagnostics)
Debug.Assert(methodGroup Is Nothing OrElse methodGroup.ResultKind = LookupResultKind.Good OrElse methodGroup.ResultKind = LookupResultKind.Inaccessible)
If methodGroup Is Nothing Then
ReportDiagnostic(diagnostics, Location.Create(groupBy.SyntaxTree, GetGroupByOperatorNameSpan(groupBy)), ERRID.ERR_QueryOperatorNotFound, StringConstants.GroupByMethod)
ElseIf Not (ShouldSuppressDiagnostics(keysLambda) OrElse
(itemsLambda IsNot Nothing AndAlso ShouldSuppressDiagnostics(itemsLambda))) Then
Dim inferenceLambda As New GroupTypeInferenceLambda(groupBy, Me,
(New ParameterSymbol() {
CreateQueryLambdaParameterSymbol(StringConstants.It1,
0,
keysLambda.Expression.Type,
groupBy, keysRangeVariables),
CreateQueryLambdaParameterSymbol(StringConstants.It2,
1,
Nothing,
groupBy)}).AsImmutableOrNull(),
Compilation)
Dim groupByArguments() As BoundExpression
If itemsLambda Is Nothing Then
groupByArguments = {keysLambda, inferenceLambda}
Else
groupByArguments = {keysLambda, itemsLambda, inferenceLambda}
End If
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim results As OverloadResolution.OverloadResolutionResult = OverloadResolution.QueryOperatorInvocationOverloadResolution(methodGroup,
groupByArguments.AsImmutableOrNull(), Me,
useSiteDiagnostics)
diagnostics.Add(groupBy, useSiteDiagnostics)
If results.BestResult.HasValue Then
Dim method = DirectCast(results.BestResult.Value.Candidate.UnderlyingSymbol, MethodSymbol)
Dim resultSelector As TypeSymbol = method.Parameters(groupByArguments.Length - 1).Type
groupType = resultSelector.DelegateOrExpressionDelegate(Me).DelegateInvokeMethod.Parameters(1).Type
ElseIf Not source.HasErrors Then
ReportDiagnostic(diagnostics, Location.Create(groupBy.SyntaxTree, GetGroupByOperatorNameSpan(groupBy)), ERRID.ERR_QueryOperatorNotFound, StringConstants.GroupByMethod)
End If
End If
End If
Debug.Assert(groupType IsNot Nothing)
Return groupType
End Function
''' <summary>
''' Infer type of the group for a Group Join operator from the set of available GroupJoin methods.
'''
''' In short, given already bound inner source and the join key lambdas, this method performs overload
''' resolution over the set of available GroupJoin operator methods using fake Into lambda:
''' Function(outerVar, group As typeToBeInferred) New With {group}
'''
''' If resolution succeeds, the type inferred for the best candidate is our result.
''' </summary>
Private Function InferGroupType(
outer As BoundQueryClauseBase,
inner As BoundQueryClauseBase,
groupJoin As GroupJoinClauseSyntax,
outerKeyLambda As BoundQueryLambda,
innerKeyLambda As BoundQueryLambda,
<Out()> ByRef methodGroup As BoundMethodGroup,
diagnostics As DiagnosticBag
) As TypeSymbol
Debug.Assert(methodGroup Is Nothing)
Dim groupType As TypeSymbol = ErrorTypeSymbol.UnknownResultType
If Not outer.Type.IsErrorType() Then
' If outer's type is "good", we should always do a lookup, even if we won't attempt the inference
' because BindGroupJoinClause still expects to have a group, unless the lookup fails.
methodGroup = LookupQueryOperator(groupJoin, outer, StringConstants.GroupJoinMethod, Nothing, diagnostics)
Debug.Assert(methodGroup Is Nothing OrElse methodGroup.ResultKind = LookupResultKind.Good OrElse methodGroup.ResultKind = LookupResultKind.Inaccessible)
If methodGroup Is Nothing Then
ReportDiagnostic(diagnostics,
Location.Create(groupJoin.SyntaxTree, GetQueryOperatorNameSpan(groupJoin.GroupKeyword, groupJoin.JoinKeyword)),
ERRID.ERR_QueryOperatorNotFound, StringConstants.GroupJoinMethod)
ElseIf Not ShouldSuppressDiagnostics(innerKeyLambda) AndAlso Not ShouldSuppressDiagnostics(outerKeyLambda) AndAlso
Not inner.HasErrors AndAlso Not inner.Type.IsErrorType() Then
Dim inferenceLambda As New GroupTypeInferenceLambda(groupJoin, Me,
(New ParameterSymbol() {
CreateQueryLambdaParameterSymbol(StringConstants.It1,
0,
outer.CompoundVariableType,
groupJoin, outer.RangeVariables),
CreateQueryLambdaParameterSymbol(StringConstants.It2,
1,
Nothing,
groupJoin)}).AsImmutableOrNull(),
Compilation)
Dim groupJoinArguments() As BoundExpression = {inner, outerKeyLambda, innerKeyLambda, inferenceLambda}
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim results As OverloadResolution.OverloadResolutionResult = OverloadResolution.QueryOperatorInvocationOverloadResolution(methodGroup,
groupJoinArguments.AsImmutableOrNull(), Me,
useSiteDiagnostics)
diagnostics.Add(groupJoin, useSiteDiagnostics)
If results.BestResult.HasValue Then
Dim method = DirectCast(results.BestResult.Value.Candidate.UnderlyingSymbol, MethodSymbol)
Dim resultSelector As TypeSymbol = method.Parameters(groupJoinArguments.Length - 1).Type
Dim resultSelectorDelegate = resultSelector.DelegateOrExpressionDelegate(Me)
groupType = resultSelectorDelegate.DelegateInvokeMethod.Parameters(1).Type
ElseIf Not outer.HasErrors Then
ReportDiagnostic(diagnostics,
Location.Create(groupJoin.SyntaxTree, GetQueryOperatorNameSpan(groupJoin.GroupKeyword, groupJoin.JoinKeyword)),
ERRID.ERR_QueryOperatorNotFound, StringConstants.GroupJoinMethod)
End If
End If
End If
Debug.Assert(groupType IsNot Nothing)
Return groupType
End Function
''' <summary>
''' This is a helper method to create a BoundQueryLambda for an Into clause
''' of a Group By or a Group Join operator.
''' </summary>
Private Function BindIntoSelectorLambda(
clauseSyntax As QueryClauseSyntax,
keysRangeVariables As ImmutableArray(Of RangeVariableSymbol),
keysCompoundVariableType As TypeSymbol,
addKeysInScope As Boolean,
declaredNames As HashSet(Of String),
groupType As TypeSymbol,
groupRangeVariables As ImmutableArray(Of RangeVariableSymbol),
groupCompoundVariableType As TypeSymbol,
aggregationVariables As SeparatedSyntaxList(Of AggregationRangeVariableSyntax),
mustProduceFlatCompoundVariable As Boolean,
diagnostics As DiagnosticBag,
<Out()> ByRef intoBinder As IntoClauseBinder,
<Out()> ByRef intoRangeVariables As ImmutableArray(Of RangeVariableSymbol)
) As BoundQueryLambda
Debug.Assert(clauseSyntax.Kind = SyntaxKind.GroupByClause OrElse clauseSyntax.Kind = SyntaxKind.GroupJoinClause)
Debug.Assert(mustProduceFlatCompoundVariable OrElse clauseSyntax.Kind = SyntaxKind.GroupJoinClause)
Debug.Assert((declaredNames IsNot Nothing) = (clauseSyntax.Kind = SyntaxKind.GroupJoinClause))
Debug.Assert(keysRangeVariables.Length > 0)
Debug.Assert(intoBinder Is Nothing)
Debug.Assert(intoRangeVariables.IsDefault)
Dim keyParam As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(keysRangeVariables), 0,
keysCompoundVariableType,
clauseSyntax, keysRangeVariables)
Dim groupParam As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(StringConstants.ItAnonymous, 1,
groupType, clauseSyntax)
Debug.Assert(LambdaUtilities.IsNonUserCodeQueryLambda(clauseSyntax))
Dim intoLambdaSymbol = Me.CreateQueryLambdaSymbol(clauseSyntax,
SynthesizedLambdaKind.GroupNonUserCodeQueryLambda,
ImmutableArray.Create(keyParam, groupParam))
' Create binder for the INTO lambda.
Dim intoLambdaBinder As New QueryLambdaBinder(intoLambdaSymbol, ImmutableArray(Of RangeVariableSymbol).Empty)
Dim groupReference = New BoundParameter(groupParam.Syntax, groupParam, False, groupParam.Type).MakeCompilerGenerated()
intoBinder = New IntoClauseBinder(intoLambdaBinder,
groupReference, groupRangeVariables, groupCompoundVariableType,
If(addKeysInScope, keysRangeVariables.Concat(groupRangeVariables), groupRangeVariables))
Dim intoSelector As BoundExpression = intoBinder.BindIntoSelector(clauseSyntax,
keysRangeVariables,
New BoundParameter(keyParam.Syntax, keyParam, False, keyParam.Type).MakeCompilerGenerated(),
keysRangeVariables,
Nothing,
ImmutableArray(Of RangeVariableSymbol).Empty,
declaredNames,
aggregationVariables,
mustProduceFlatCompoundVariable,
intoRangeVariables,
diagnostics)
Dim intoLambda = CreateBoundQueryLambda(intoLambdaSymbol,
keysRangeVariables,
intoSelector,
exprIsOperandOfConditionalBranch:=False)
intoLambdaSymbol.SetQueryLambdaReturnType(intoSelector.Type)
intoLambda.SetWasCompilerGenerated()
Return intoLambda
End Function
Private Sub VerifyRangeVariableName(rangeVar As RangeVariableSymbol, identifier As SyntaxToken, diagnostics As DiagnosticBag)
Debug.Assert(identifier.Parent Is rangeVar.Syntax)
If identifier.GetTypeCharacter() <> TypeCharacter.None Then
ReportDiagnostic(diagnostics, identifier, ERRID.ERR_QueryAnonymousTypeDisallowsTypeChar)
End If
If Compilation.ObjectType.GetMembers(rangeVar.Name).Length > 0 Then
ReportDiagnostic(diagnostics, identifier, ERRID.ERR_QueryInvalidControlVariableName1)
Else
VerifyNameShadowingInMethodBody(rangeVar, identifier, identifier, diagnostics)
End If
End Sub
Private Function GetQueryLambdaParameterSyntax(syntaxNode As VisualBasicSyntaxNode, rangeVariables As ImmutableArray(Of RangeVariableSymbol)) As VisualBasicSyntaxNode
If rangeVariables.Length = 1 Then
Return rangeVariables(0).Syntax
End If
Return syntaxNode
End Function
Private Function CreateQueryLambdaParameterSymbol(
name As String,
ordinal As Integer,
type As TypeSymbol,
syntaxNode As VisualBasicSyntaxNode,
rangeVariables As ImmutableArray(Of RangeVariableSymbol)
) As BoundLambdaParameterSymbol
syntaxNode = Me.GetQueryLambdaParameterSyntax(syntaxNode, rangeVariables)
Dim param = New BoundLambdaParameterSymbol(name, ordinal, type, isByRef:=False, syntaxNode:=syntaxNode, location:=syntaxNode.GetLocation())
Return param
End Function
Private Function CreateQueryLambdaParameterSymbol(
name As String,
ordinal As Integer,
type As TypeSymbol,
syntaxNode As VisualBasicSyntaxNode
) As BoundLambdaParameterSymbol
Dim param = New BoundLambdaParameterSymbol(name, ordinal, type, isByRef:=False, syntaxNode:=syntaxNode, location:=syntaxNode.GetLocation())
Return param
End Function
Private Shared Function GetQueryLambdaParameterName(rangeVariables As ImmutableArray(Of RangeVariableSymbol)) As String
Select Case rangeVariables.Length
Case 0
Return StringConstants.ItAnonymous
Case 1
Return rangeVariables(0).Name
Case Else
Return StringConstants.It
End Select
End Function
Private Shared Function GetQueryLambdaParameterNameLeft(rangeVariables As ImmutableArray(Of RangeVariableSymbol)) As String
Select Case rangeVariables.Length
Case 0
Return StringConstants.ItAnonymous
Case 1
Return rangeVariables(0).Name
Case Else
Return StringConstants.It1
End Select
End Function
Private Shared Function GetQueryLambdaParameterNameRight(rangeVariables As ImmutableArray(Of RangeVariableSymbol)) As String
Select Case rangeVariables.Length
Case 0
Throw ExceptionUtilities.UnexpectedValue(rangeVariables.Length)
Case 1
Return rangeVariables(0).Name
Case Else
Return StringConstants.It2
End Select
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Where operator.
'''
''' {Preceding query operators} Where {expression}
'''
''' Ex: From a In AA Where a > 0 ==> AA.Where(Function(a) a > b)
'''
''' </summary>
Private Function BindWhereClause(
source As BoundQueryClauseBase,
where As WhereClauseSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
Return BindFilterQueryOperator(source, where,
StringConstants.WhereMethod, where.WhereKeyword.Span,
where.Condition, diagnostics)
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Skip While operator.
'''
''' {Preceding query operators} Skip While {expression}
'''
''' Ex: From a In AA Skip While a > 0 ==> AA.SkipWhile(Function(a) a > b)
'''
''' </summary>
Private Function BindSkipWhileClause(
source As BoundQueryClauseBase,
skipWhile As PartitionWhileClauseSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
Return BindFilterQueryOperator(source, skipWhile,
StringConstants.SkipWhileMethod,
GetQueryOperatorNameSpan(skipWhile.SkipOrTakeKeyword, skipWhile.WhileKeyword),
skipWhile.Condition, diagnostics)
End Function
Private Shared Function GetQueryOperatorNameSpan(ByRef left As SyntaxToken, ByRef right As SyntaxToken) As TextSpan
Dim operatorNameSpan As TextSpan = left.Span
If right.ValueText.Length > 0 Then
operatorNameSpan = TextSpan.FromBounds(operatorNameSpan.Start, right.Span.End)
End If
Return operatorNameSpan
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Take While operator.
'''
''' {Preceding query operators} Take While {expression}
'''
''' Ex: From a In AA Skip While a > 0 ==> AA.TakeWhile(Function(a) a > b)
'''
''' </summary>
Private Function BindTakeWhileClause(
source As BoundQueryClauseBase,
takeWhile As PartitionWhileClauseSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
Return BindFilterQueryOperator(source, takeWhile,
StringConstants.TakeWhileMethod,
GetQueryOperatorNameSpan(takeWhile.SkipOrTakeKeyword, takeWhile.WhileKeyword),
takeWhile.Condition, diagnostics)
End Function
''' <summary>
''' This helper method does all the work to bind Where, Take While and Skip While query operators.
''' </summary>
Private Function BindFilterQueryOperator(
source As BoundQueryClauseBase,
operatorSyntax As QueryClauseSyntax,
operatorName As String,
operatorNameLocation As TextSpan,
condition As ExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
Dim suppressDiagnostics As DiagnosticBag = Nothing
' Create LambdaSymbol for the shape of the filter lambda.
Dim param As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(source.RangeVariables), 0,
source.CompoundVariableType,
condition, source.RangeVariables)
Debug.Assert(LambdaUtilities.IsLambdaBody(condition))
Dim lambdaSymbol = Me.CreateQueryLambdaSymbol(condition,
SynthesizedLambdaKind.FilterConditionQueryLambda,
ImmutableArray.Create(param))
' Create binder for a filter condition.
Dim filterBinder As New QueryLambdaBinder(lambdaSymbol, source.RangeVariables)
' Bind condition as a value, conversion should take care of the rest (making it an RValue, etc.).
Dim predicate As BoundExpression = filterBinder.BindValue(condition, diagnostics)
' Need to verify result type of the condition and enforce ExprIsOperandOfConditionalBranch for possible future conversions.
' In order to do verification, we simply attempt conversion to boolean in the same manner as BindBooleanExpression.
Dim conversionDiagnostic = DiagnosticBag.GetInstance()
Dim boolSymbol As NamedTypeSymbol = GetSpecialType(SpecialType.System_Boolean, condition, diagnostics)
' If predicate has type Object we will keep result of conversion, otherwise we drop it.
Dim predicateType As TypeSymbol = predicate.Type
Dim keepConvertedPredicate As Boolean = False
If predicateType Is Nothing Then
If predicate.IsNothingLiteral() Then
keepConvertedPredicate = True
End If
ElseIf predicateType.IsObjectType() Then
keepConvertedPredicate = True
End If
Dim convertedToBoolean As BoundExpression = filterBinder.ApplyImplicitConversion(condition,
boolSymbol, predicate,
conversionDiagnostic, isOperandOfConditionalBranch:=True)
' If we don't keep result of the conversion, keep diagnostic if conversion failed.
If keepConvertedPredicate Then
predicate = convertedToBoolean
diagnostics.AddRange(conversionDiagnostic)
ElseIf convertedToBoolean.HasErrors AndAlso conversionDiagnostic.HasAnyErrors() Then
diagnostics.AddRange(conversionDiagnostic)
' Suppress any additional diagnostic, otherwise we might end up with duplicate errors.
If suppressDiagnostics Is Nothing Then
suppressDiagnostics = DiagnosticBag.GetInstance()
diagnostics = suppressDiagnostics
End If
End If
conversionDiagnostic.Free()
' Bind the Filter
Dim filterLambda = CreateBoundQueryLambda(lambdaSymbol,
source.RangeVariables,
predicate,
exprIsOperandOfConditionalBranch:=True)
filterLambda.SetWasCompilerGenerated()
' Now bind the call.
Dim boundCallOrBadExpression As BoundExpression
If source.Type.IsErrorType() Then
boundCallOrBadExpression = BadExpression(operatorSyntax, ImmutableArray.Create(Of BoundNode)(source, filterLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
If suppressDiagnostics Is Nothing AndAlso ShouldSuppressDiagnostics(filterLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
suppressDiagnostics = DiagnosticBag.GetInstance()
diagnostics = suppressDiagnostics
End If
boundCallOrBadExpression = BindQueryOperatorCall(operatorSyntax, source,
operatorName,
ImmutableArray.Create(Of BoundExpression)(filterLambda),
operatorNameLocation,
diagnostics)
End If
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
Return New BoundQueryClause(operatorSyntax,
boundCallOrBadExpression,
source.RangeVariables,
source.CompoundVariableType,
ImmutableArray.Create(Of Binder)(filterBinder),
boundCallOrBadExpression.Type)
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Distinct operator.
'''
''' {Preceding query operators} Distinct
'''
''' Ex: From a In AA Distinct ==> AA.Distinct()
'''
''' </summary>
Private Function BindDistinctClause(
source As BoundQueryClauseBase,
distinct As DistinctClauseSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
Dim boundCallOrBadExpression As BoundExpression
If source.Type.IsErrorType() Then
' Operator BindQueryClauseCall will fail, let's not bother.
boundCallOrBadExpression = BadExpression(distinct, ImmutableArray.Create(Of BoundNode)(source),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
boundCallOrBadExpression = BindQueryOperatorCall(distinct, source,
StringConstants.DistinctMethod,
ImmutableArray(Of BoundExpression).Empty,
distinct.DistinctKeyword.Span,
diagnostics)
End If
Return New BoundQueryClause(distinct,
boundCallOrBadExpression,
source.RangeVariables,
source.CompoundVariableType,
ImmutableArray(Of Binder).Empty,
boundCallOrBadExpression.Type)
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Skip operator.
'''
''' {Preceding query operators} Skip {expression}
'''
''' Ex: From a In AA Skip 10 ==> AA.Skip(10)
'''
''' </summary>
Private Function BindSkipClause(
source As BoundQueryClauseBase,
skip As PartitionClauseSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
Return BindPartitionClause(source, skip, StringConstants.SkipMethod, diagnostics)
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Take operator.
'''
''' {Preceding query operators} Take {expression}
'''
''' Ex: From a In AA Take 10 ==> AA.Take(10)
'''
''' </summary>
Private Function BindTakeClause(
source As BoundQueryClauseBase,
take As PartitionClauseSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
Return BindPartitionClause(source, take, StringConstants.TakeMethod, diagnostics)
End Function
''' <summary>
''' This helper method does all the work to bind Take and Skip query operators.
''' </summary>
Private Function BindPartitionClause(
source As BoundQueryClauseBase,
partition As PartitionClauseSyntax,
operatorName As String,
diagnostics As DiagnosticBag
) As BoundQueryClause
' Bind the Count expression as a value, conversion should take care of the rest (making it an RValue, etc.).
Dim boundCount As BoundExpression = Me.BindValue(partition.Count, diagnostics)
' Now bind the call.
Dim boundCallOrBadExpression As BoundExpression
If source.Type.IsErrorType() Then
boundCallOrBadExpression = BadExpression(partition, ImmutableArray.Create(Of BoundNode)(source, boundCount),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Dim suppressDiagnostics As DiagnosticBag = Nothing
If boundCount.HasErrors OrElse (boundCount.Type IsNot Nothing AndAlso boundCount.Type.IsErrorType()) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
suppressDiagnostics = DiagnosticBag.GetInstance()
diagnostics = suppressDiagnostics
End If
boundCallOrBadExpression = BindQueryOperatorCall(partition, source,
operatorName,
ImmutableArray.Create(Of BoundExpression)(boundCount),
partition.SkipOrTakeKeyword.Span,
diagnostics)
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
End If
Return New BoundQueryClause(partition,
boundCallOrBadExpression,
source.RangeVariables,
source.CompoundVariableType,
ImmutableArray(Of Binder).Empty,
boundCallOrBadExpression.Type)
End Function
''' <summary>
''' Given result of binding preceding query operators, the source, bind the following Order By operator.
'''
''' {Preceding query operators} Order By {orderings}
'''
''' Ex: From a In AA Order By a ==> AA.OrderBy(Function(a) a)
'''
''' Ex: From a In AA Order By a.Key1, a.Key2 Descending ==> AA.OrderBy(Function(a) a.Key1).ThenByDescending(Function(a) a.Key2)
'''
''' </summary>
Private Function BindOrderByClause(
source As BoundQueryClauseBase,
orderBy As OrderByClauseSyntax,
diagnostics As DiagnosticBag
) As BoundQueryClause
Dim suppressDiagnostics As DiagnosticBag = Nothing
Dim callDiagnostics As DiagnosticBag = diagnostics
Dim lambdaParameterName As String = GetQueryLambdaParameterName(source.RangeVariables)
Dim sourceOrPreviousOrdering As BoundQueryPart = source
Dim orderByOrderings As SeparatedSyntaxList(Of OrderingSyntax) = orderBy.Orderings
If orderByOrderings.Count = 0 Then
' Malformed tree.
Debug.Assert(orderByOrderings.Count > 0, "Malformed syntax tree.")
Return New BoundQueryClause(orderBy,
BadExpression(orderBy, source, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated(),
source.RangeVariables,
source.CompoundVariableType,
ImmutableArray.Create(Me),
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
Dim keyBinder As QueryLambdaBinder = Nothing
For i = 0 To orderByOrderings.Count - 1
Dim ordering As OrderingSyntax = orderByOrderings(i)
' Create LambdaSymbol for the shape of the key lambda.
Dim param As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(lambdaParameterName, 0,
source.CompoundVariableType,
ordering.Expression, source.RangeVariables)
Dim lambdaSymbol = Me.CreateQueryLambdaSymbol(LambdaUtilities.GetOrderingLambdaBody(ordering),
SynthesizedLambdaKind.OrderingQueryLambda,
ImmutableArray.Create(param))
' Create binder for a key expression.
keyBinder = New QueryLambdaBinder(lambdaSymbol, source.RangeVariables)
' Bind expression as a value, conversion during overload resolution should take care of the rest (making it an RValue, etc.).
Dim key As BoundExpression = keyBinder.BindValue(ordering.Expression, diagnostics)
Dim keyLambda = CreateBoundQueryLambda(lambdaSymbol,
source.RangeVariables,
key,
exprIsOperandOfConditionalBranch:=False)
keyLambda.SetWasCompilerGenerated()
' Now bind the call.
Dim boundCallOrBadExpression As BoundExpression
If sourceOrPreviousOrdering.Type.IsErrorType() Then
boundCallOrBadExpression = BadExpression(ordering, ImmutableArray.Create(Of BoundNode)(sourceOrPreviousOrdering, keyLambda),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
If suppressDiagnostics Is Nothing AndAlso ShouldSuppressDiagnostics(keyLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
suppressDiagnostics = DiagnosticBag.GetInstance()
callDiagnostics = suppressDiagnostics
End If
Dim operatorName As String
Dim operatorNameLocation As TextSpan
If i = 0 Then
' This is the first ordering.
If ordering.Kind = SyntaxKind.AscendingOrdering Then
operatorName = StringConstants.OrderByMethod
Else
Debug.Assert(ordering.Kind = SyntaxKind.DescendingOrdering)
operatorName = StringConstants.OrderByDescendingMethod
End If
operatorNameLocation = GetQueryOperatorNameSpan(orderBy.OrderKeyword, orderBy.ByKeyword)
Else
If ordering.Kind = SyntaxKind.AscendingOrdering Then
operatorName = StringConstants.ThenByMethod
Else
Debug.Assert(ordering.Kind = SyntaxKind.DescendingOrdering)
operatorName = StringConstants.ThenByDescendingMethod
End If
operatorNameLocation = orderByOrderings.GetSeparator(i - 1).Span
End If
boundCallOrBadExpression = BindQueryOperatorCall(ordering, sourceOrPreviousOrdering,
operatorName,
ImmutableArray.Create(Of BoundExpression)(keyLambda),
operatorNameLocation,
callDiagnostics)
End If
sourceOrPreviousOrdering = New BoundOrdering(ordering, boundCallOrBadExpression, boundCallOrBadExpression.Type)
Next
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
Debug.Assert(sourceOrPreviousOrdering IsNot source)
Debug.Assert(keyBinder IsNot Nothing)
Return New BoundQueryClause(orderBy,
sourceOrPreviousOrdering,
source.RangeVariables,
source.CompoundVariableType,
ImmutableArray.Create(Of Binder)(keyBinder),
sourceOrPreviousOrdering.Type)
End Function
''' <summary>
''' This is a top level binder used to bind bodies of query lambdas.
''' It also contains a bunch of helper methods to bind bodies of a particular kind.
''' </summary>
Private NotInheritable Class QueryLambdaBinder
Inherits BlockBaseBinder(Of RangeVariableSymbol) ' BlockBaseBinder implements various lookup methods as we need.
Private ReadOnly _lambdaSymbol As LambdaSymbol
Private ReadOnly _rangeVariables As ImmutableArray(Of RangeVariableSymbol)
Public Sub New(lambdaSymbol As LambdaSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol))
MyBase.New(lambdaSymbol.ContainingBinder)
_lambdaSymbol = lambdaSymbol
_rangeVariables = rangeVariables
End Sub
Friend Overrides ReadOnly Property Locals As ImmutableArray(Of RangeVariableSymbol)
Get
Return _rangeVariables
End Get
End Property
Public ReadOnly Property RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Get
Return _rangeVariables
End Get
End Property
Public Overrides ReadOnly Property ContainingMember As Symbol
Get
Return _lambdaSymbol
End Get
End Property
Public ReadOnly Property LambdaSymbol As LambdaSymbol
Get
Return _lambdaSymbol
End Get
End Property
Public Overrides ReadOnly Property IsInQuery As Boolean
Get
Return True
End Get
End Property
''' <summary>
''' Bind body of a lambda representing Select operator selector in context of this binder.
''' </summary>
Public Function BindSelectClauseSelector(
[select] As SelectClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
<Out()> ByRef declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol),
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(declaredRangeVariables.IsDefault)
Dim selectVariables As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax) = [select].Variables
Dim requireRangeVariable As Boolean
If selectVariables.Count = 1 Then
requireRangeVariable = False
' If there is a Join or a GroupJoin ahead, this operator must
' add a range variable into the scope.
While operatorsEnumerator.MoveNext()
Select Case operatorsEnumerator.Current.Kind
Case SyntaxKind.SimpleJoinClause, SyntaxKind.GroupJoinClause
requireRangeVariable = True
Exit While
Case SyntaxKind.SelectClause, SyntaxKind.LetClause, SyntaxKind.FromClause
Exit While
Case SyntaxKind.AggregateClause
Exit While
Case SyntaxKind.GroupByClause
Exit While
End Select
End While
Else
requireRangeVariable = True
End If
Return BindExpressionRangeVariables(selectVariables,
requireRangeVariable,
[select],
declaredRangeVariables,
diagnostics)
End Function
''' <summary>
''' Bind Select like selector based on the set of expression range variables in context of this binder.
''' </summary>
Public Function BindExpressionRangeVariables(
selectVariables As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax),
requireRangeVariable As Boolean,
selectorSyntax As QueryClauseSyntax,
<Out()> ByRef declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol),
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(selectorSyntax IsNot Nothing AndAlso declaredRangeVariables.IsDefault)
Dim selector As BoundExpression
If selectVariables.Count = 1 Then
' Simple case, one item in the projection.
Dim item As ExpressionRangeVariableSyntax = selectVariables(0)
selector = Nothing ' Suppress definite assignment error.
Debug.Assert(item.NameEquals Is Nothing OrElse item.NameEquals.AsClause Is Nothing)
' Using enclosing binder for shadowing check, because range variables brought in scope by the current binder
' are no longer in scope after the Select. So, it is fine to shadow them.
Dim rangeVar As RangeVariableSymbol = Me.BindExpressionRangeVariable(item, requireRangeVariable, Me.ContainingBinder, Nothing, selector, diagnostics)
If rangeVar IsNot Nothing Then
declaredRangeVariables = ImmutableArray.Create(Of RangeVariableSymbol)(rangeVar)
Else
Debug.Assert(Not requireRangeVariable)
declaredRangeVariables = ImmutableArray(Of RangeVariableSymbol).Empty
End If
ElseIf selectVariables.Count = 0 Then
' Malformed tree
Debug.Assert(selectVariables.Count > 0, "Malformed syntax tree.")
selector = BadExpression(selectorSyntax, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
declaredRangeVariables = ImmutableArray.Create(RangeVariableSymbol.CreateForErrorRecovery(Me, selectorSyntax, selector.Type))
Else
' Need to build an Anonymous Type
Dim selectors = New BoundExpression(selectVariables.Count - 1) {}
Dim declaredNames As HashSet(Of String) = CreateSetOfDeclaredNames()
Dim rangeVariables(selectVariables.Count - 1) As RangeVariableSymbol
For i As Integer = 0 To selectVariables.Count - 1
Debug.Assert(selectVariables(i).NameEquals Is Nothing OrElse selectVariables(i).NameEquals.AsClause Is Nothing)
' Using enclosing binder for shadowing check, because range variables brought in scope by the current binder
' are no longer in scope after the Select. So, it is fine to shadow them.
Dim rangeVar As RangeVariableSymbol = Me.BindExpressionRangeVariable(selectVariables(i), True, Me.ContainingBinder, declaredNames, selectors(i), diagnostics)
Debug.Assert(rangeVar IsNot Nothing)
rangeVariables(i) = rangeVar
Next
AssertDeclaredNames(declaredNames, rangeVariables.AsImmutableOrNull())
Dim fields = New AnonymousTypeField(selectVariables.Count - 1) {}
For i As Integer = 0 To rangeVariables.Length - 1
Dim rangeVar As RangeVariableSymbol = rangeVariables(i)
fields(i) = New AnonymousTypeField(
rangeVar.Name, rangeVar.Type, rangeVar.Syntax.GetLocation(), isKeyOrByRef:=True)
Next
selector = BindAnonymousObjectCreationExpression(selectorSyntax,
New AnonymousTypeDescriptor(fields.AsImmutableOrNull(),
selectorSyntax.QueryClauseKeywordOrRangeVariableIdentifier.GetLocation(),
True),
selectors.AsImmutableOrNull(),
diagnostics).MakeCompilerGenerated()
declaredRangeVariables = rangeVariables.AsImmutableOrNull()
End If
Debug.Assert(Not declaredRangeVariables.IsDefault AndAlso selectorSyntax IsNot Nothing)
Return selector
End Function
''' <summary>
''' Bind ExpressionRangeVariableSyntax in context of this binder.
''' </summary>
Private Function BindExpressionRangeVariable(
item As ExpressionRangeVariableSyntax,
requireRangeVariable As Boolean,
shadowingCheckBinder As Binder,
declaredNames As HashSet(Of String),
<Out()> ByRef selector As BoundExpression,
diagnostics As DiagnosticBag
) As RangeVariableSymbol
Debug.Assert(selector Is Nothing)
Dim variableName As VariableNameEqualsSyntax = item.NameEquals
' Figure out the name of the new range variable
Dim rangeVarName As String = Nothing
Dim rangeVarNameSyntax As SyntaxToken = Nothing
Dim targetVariableType As TypeSymbol = Nothing
If variableName IsNot Nothing Then
rangeVarNameSyntax = variableName.Identifier.Identifier
rangeVarName = rangeVarNameSyntax.ValueText
' Deal with AsClauseOpt and various modifiers.
If variableName.AsClause IsNot Nothing Then
targetVariableType = DecodeModifiedIdentifierType(variableName.Identifier,
variableName.AsClause,
Nothing,
Nothing,
diagnostics,
ModifiedIdentifierTypeDecoderContext.LocalType Or
ModifiedIdentifierTypeDecoderContext.QueryRangeVariableType)
ElseIf variableName.Identifier.Nullable.Node IsNot Nothing Then
ReportDiagnostic(diagnostics, variableName.Identifier.Nullable, ERRID.ERR_NullableTypeInferenceNotSupported)
End If
Else
' Infer the name from expression
Dim failedToInferFromXmlName As XmlNameSyntax = Nothing
Dim nameToken As SyntaxToken = item.Expression.ExtractAnonymousTypeMemberName(failedToInferFromXmlName)
If nameToken.Kind <> SyntaxKind.None Then
rangeVarNameSyntax = nameToken
rangeVarName = rangeVarNameSyntax.ValueText
ElseIf requireRangeVariable Then
If failedToInferFromXmlName IsNot Nothing Then
ReportDiagnostic(diagnostics, failedToInferFromXmlName.LocalName, ERRID.ERR_QueryAnonTypeFieldXMLNameInference)
Else
ReportDiagnostic(diagnostics, item.Expression, ERRID.ERR_QueryAnonymousTypeFieldNameInference)
End If
End If
End If
If rangeVarName IsNot Nothing AndAlso rangeVarName.Length = 0 Then
' Empty string must have been a syntax error.
rangeVarName = Nothing
End If
selector = BindValue(item.Expression, diagnostics)
If targetVariableType Is Nothing Then
selector = MakeRValue(selector, diagnostics)
Else
selector = ApplyImplicitConversion(item.Expression, targetVariableType, selector, diagnostics)
End If
Dim rangeVar As RangeVariableSymbol = Nothing
If rangeVarName IsNot Nothing Then
rangeVar = RangeVariableSymbol.Create(Me, rangeVarNameSyntax, selector.Type)
' Note what we are doing here:
' We are creating BoundRangeVariableAssignment before doing any shadowing checks
' so that SemanticModel can find the declared symbol, but, if the variable will conflict with another
' variable in the same child scope, we will not add it to the scope. Instead, we create special
' error recovery range variable symbol and add it to the scope at the same place, making sure
' that the earlier declared range variable wins during name lookup.
' As an alternative, we could still add the original range variable symbol to the scope and then,
' while we are binding the rest of the query in error recovery mode, references to the name would
' cause ambiguity. However, this could negatively affect IDE experience. Also, as we build an
' Anonymous Type for the compound range variables, we would end up with a type with duplicate members,
' which could cause problems elsewhere.
selector = New BoundRangeVariableAssignment(item, rangeVar, selector, selector.Type)
Dim doErrorRecovery As Boolean = False
If declaredNames IsNot Nothing AndAlso Not declaredNames.Add(rangeVarName) Then
Debug.Assert(item.Parent.Kind = SyntaxKind.SelectClause OrElse item.Parent.Kind = SyntaxKind.GroupByClause)
ReportDiagnostic(diagnostics, rangeVarNameSyntax, ERRID.ERR_QueryDuplicateAnonTypeMemberName1, rangeVarName)
doErrorRecovery = True ' Shouldn't add to the scope.
Else
shadowingCheckBinder.VerifyRangeVariableName(rangeVar, rangeVarNameSyntax, diagnostics)
If item.Parent.Kind = SyntaxKind.LetClause AndAlso ShadowsRangeVariableInTheChildScope(shadowingCheckBinder, rangeVar) Then
' We are about to add this range variable to the current child scope.
' Shadowing error was reported earlier.
doErrorRecovery = True ' Shouldn't add to the scope.
End If
End If
If doErrorRecovery Then
If requireRangeVariable Then
rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, rangeVar.Syntax, selector.Type)
Else
rangeVar = Nothing
End If
End If
ElseIf requireRangeVariable Then
Debug.Assert(rangeVar Is Nothing)
rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, item, selector.Type)
End If
Debug.Assert(selector IsNot Nothing)
Debug.Assert(Not requireRangeVariable OrElse rangeVar IsNot Nothing)
Return rangeVar
End Function
''' <summary>
''' Bind Let operator selector for a particular ExpressionRangeVariableSyntax.
''' Takes care of "carrying over" of previously declared range variables as well as introduction of the new one.
''' </summary>
Public Function BindLetClauseVariableSelector(
variable As ExpressionRangeVariableSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
<Out()> ByRef declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol),
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(declaredRangeVariables.IsDefault)
Dim selector As BoundExpression = Nothing
' Using selector binder for shadowing checks because all its range variables stay in scope
' after the operator.
Dim rangeVar As RangeVariableSymbol = Me.BindExpressionRangeVariable(variable, True, Me, Nothing, selector, diagnostics)
Debug.Assert(rangeVar IsNot Nothing)
declaredRangeVariables = ImmutableArray.Create(rangeVar)
If _rangeVariables.Length > 0 Then
' Need to build an Anonymous Type.
' If it is not the last variable in the list, we simply combine source's
' compound variable (an instance of its Anonymous Type) with our new variable,
' creating new compound variable of nested Anonymous Type.
' In some scenarios, it is safe to leave compound variable in nested form when there is an
' operator down the road that does its own projection (Select, Group By, ...).
' All following operators have to take an Anonymous Type in both cases and, since there is no way to
' restrict the shape of the Anonymous Type in method's declaration, the operators should be
' insensitive to the shape of the Anonymous Type.
selector = BuildJoinSelector(variable,
(variable Is DirectCast(operatorsEnumerator.Current, LetClauseSyntax).Variables.Last() AndAlso
MustProduceFlatCompoundVariable(operatorsEnumerator)),
diagnostics,
rangeVar, selector)
Else
' Easy case, no need to build an Anonymous Type.
Debug.Assert(_rangeVariables.Length = 0)
End If
Debug.Assert(Not declaredRangeVariables.IsDefault)
Return selector
End Function
''' <summary>
''' Bind body of a lambda representing first Select operator selector for an aggregate clause in context of this binder.
''' </summary>
Public Function BindAggregateClauseFirstSelector(
aggregate As AggregateClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
rangeVariablesPart1 As ImmutableArray(Of RangeVariableSymbol),
rangeVariablesPart2 As ImmutableArray(Of RangeVariableSymbol),
<Out()> ByRef declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol),
<Out()> ByRef group As BoundQueryClauseBase,
<Out()> ByRef intoBinder As IntoClauseDisallowGroupReferenceBinder,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(operatorsEnumerator.Current Is aggregate)
Debug.Assert(declaredRangeVariables.IsDefault)
Debug.Assert((rangeVariablesPart1.Length = 0) = (rangeVariablesPart2 = _rangeVariables))
Debug.Assert((rangeVariablesPart2.Length = 0) = (rangeVariablesPart1 = _rangeVariables))
Debug.Assert(_lambdaSymbol.ParameterCount = If(rangeVariablesPart2.Length = 0, 1, 2))
Debug.Assert(_rangeVariables.Length = rangeVariablesPart1.Length + rangeVariablesPart2.Length)
' Let's interpret our group.
Dim groupAdditionalOperators As SyntaxList(Of QueryClauseSyntax).Enumerator = aggregate.AdditionalQueryOperators.GetEnumerator()
' Note, this call can advance [groupAdditionalOperators] enumerator if it absorbs the following Let or Select.
group = BindCollectionRangeVariables(aggregate, Nothing, aggregate.Variables, groupAdditionalOperators, diagnostics)
group = BindSubsequentQueryOperators(group, groupAdditionalOperators, diagnostics)
' Now, deal with aggregate functions.
Dim aggregationVariables As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = aggregate.AggregationVariables
Dim letSelector As BoundExpression
Dim groupRangeVar As RangeVariableSymbol = Nothing
Select Case aggregationVariables.Count
Case 0
' Malformed syntax tree.
Debug.Assert(aggregationVariables.Count > 0, "Malformed syntax tree.")
declaredRangeVariables = ImmutableArray.Create(Of RangeVariableSymbol)(
RangeVariableSymbol.CreateForErrorRecovery(Me,
aggregate,
ErrorTypeSymbol.UnknownResultType))
letSelector = BadExpression(aggregate, group, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
intoBinder = New IntoClauseDisallowGroupReferenceBinder(New QueryLambdaBinder(_lambdaSymbol,
ImmutableArray(Of RangeVariableSymbol).Empty),
group, group.RangeVariables, group.CompoundVariableType,
_rangeVariables.Concat(group.RangeVariables))
Case 1
' Simple case - one aggregate function.
'
' FROM a in AA FROM a in AA
' AGGREGATE b in a.BB => LET count = (FROM b IN a.BB).Count()
' INTO Count()
'
intoBinder = New IntoClauseDisallowGroupReferenceBinder(New QueryLambdaBinder(_lambdaSymbol,
ImmutableArray(Of RangeVariableSymbol).Empty),
group, group.RangeVariables, group.CompoundVariableType,
_rangeVariables.Concat(group.RangeVariables))
Dim compoundKeyReferencePart1 As BoundExpression
Dim keysRangeVariablesPart1 As ImmutableArray(Of RangeVariableSymbol)
Dim compoundKeyReferencePart2 As BoundExpression
Dim keysRangeVariablesPart2 As ImmutableArray(Of RangeVariableSymbol)
Dim letSelectorParam As BoundLambdaParameterSymbol
If rangeVariablesPart1.Length > 0 Then
letSelectorParam = DirectCast(_lambdaSymbol.Parameters(0), BoundLambdaParameterSymbol)
compoundKeyReferencePart1 = New BoundParameter(letSelectorParam.Syntax, letSelectorParam, False, letSelectorParam.Type).MakeCompilerGenerated()
keysRangeVariablesPart1 = rangeVariablesPart1
If rangeVariablesPart2.Length > 0 Then
letSelectorParam = DirectCast(_lambdaSymbol.Parameters(1), BoundLambdaParameterSymbol)
compoundKeyReferencePart2 = New BoundParameter(letSelectorParam.Syntax, letSelectorParam, False, letSelectorParam.Type).MakeCompilerGenerated()
keysRangeVariablesPart2 = rangeVariablesPart2
Else
compoundKeyReferencePart2 = Nothing
keysRangeVariablesPart2 = ImmutableArray(Of RangeVariableSymbol).Empty
End If
ElseIf rangeVariablesPart2.Length > 0 Then
letSelectorParam = DirectCast(_lambdaSymbol.Parameters(1), BoundLambdaParameterSymbol)
compoundKeyReferencePart1 = New BoundParameter(letSelectorParam.Syntax, letSelectorParam, False, letSelectorParam.Type).MakeCompilerGenerated()
keysRangeVariablesPart1 = rangeVariablesPart2
compoundKeyReferencePart2 = Nothing
keysRangeVariablesPart2 = ImmutableArray(Of RangeVariableSymbol).Empty
Else
compoundKeyReferencePart1 = Nothing
keysRangeVariablesPart1 = ImmutableArray(Of RangeVariableSymbol).Empty
compoundKeyReferencePart2 = Nothing
keysRangeVariablesPart2 = ImmutableArray(Of RangeVariableSymbol).Empty
End If
letSelector = intoBinder.BindIntoSelector(aggregate,
_rangeVariables,
compoundKeyReferencePart1,
keysRangeVariablesPart1,
compoundKeyReferencePart2,
keysRangeVariablesPart2,
Nothing,
aggregationVariables,
MustProduceFlatCompoundVariable(operatorsEnumerator),
declaredRangeVariables,
diagnostics)
Case Else
' Complex case:
'
' FROM a in AA FROM a in AA
' AGGREGATE b in a.BB => LET Group = (FROM b IN a.BB)
' INTO Count(), Select a, Count=Group.Count(), Sum=Group.Sum(b=>b)
' Sum(b)
'
' Handle selector for the Let.
groupRangeVar = RangeVariableSymbol.CreateCompilerGenerated(Me, aggregate, StringConstants.Group, group.Type)
If _rangeVariables.Length = 0 Then
letSelector = group
Else
letSelector = BuildJoinSelector(aggregate,
mustProduceFlatCompoundVariable:=False, diagnostics:=diagnostics,
rangeVarOpt:=groupRangeVar, rangeVarValueOpt:=group)
End If
declaredRangeVariables = ImmutableArray.Create(Of RangeVariableSymbol)(groupRangeVar)
intoBinder = Nothing
End Select
Return letSelector
End Function
''' <summary>
''' Bind Join/From selector that absorbs following Select/Let in context of this binder.
''' </summary>
Public Function BindAbsorbingJoinSelector(
absorbNextOperator As QueryClauseSyntax,
operatorsEnumerator As SyntaxList(Of QueryClauseSyntax).Enumerator,
leftRangeVariables As ImmutableArray(Of RangeVariableSymbol),
rightRangeVariables As ImmutableArray(Of RangeVariableSymbol),
<Out> ByRef joinSelectorDeclaredRangeVariables As ImmutableArray(Of RangeVariableSymbol),
<Out> ByRef group As BoundQueryClauseBase,
<Out> ByRef intoBinder As IntoClauseDisallowGroupReferenceBinder,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(joinSelectorDeclaredRangeVariables.IsDefault)
Debug.Assert(absorbNextOperator Is operatorsEnumerator.Current)
group = Nothing
intoBinder = Nothing
Dim joinSelector As BoundExpression
Select Case absorbNextOperator.Kind
Case SyntaxKind.SelectClause
' Absorb Select
Dim [select] = DirectCast(absorbNextOperator, SelectClauseSyntax)
joinSelector = BindSelectClauseSelector([select],
operatorsEnumerator,
joinSelectorDeclaredRangeVariables,
diagnostics)
Case SyntaxKind.LetClause
' Absorb Let
Dim [let] = DirectCast(absorbNextOperator, LetClauseSyntax)
Debug.Assert([let].Variables.Count > 0)
joinSelector = BindLetClauseVariableSelector([let].Variables.First,
operatorsEnumerator,
joinSelectorDeclaredRangeVariables,
diagnostics)
Case SyntaxKind.AggregateClause
' Absorb Aggregate
Dim aggregate = DirectCast(absorbNextOperator, AggregateClauseSyntax)
joinSelector = BindAggregateClauseFirstSelector(aggregate,
operatorsEnumerator,
leftRangeVariables,
rightRangeVariables,
joinSelectorDeclaredRangeVariables,
group,
intoBinder,
diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(absorbNextOperator.Kind)
End Select
Return joinSelector
End Function
''' <summary>
''' Bind Join/Let like and mixed selector in context of this binder.
'''
''' Join like selector: Function(a, b) New With {a, b}
'''
''' Let like selector: Function(a) New With {a, letExpressionRangeVariable}
'''
''' Mixed selector: Function(a, b) New With {a, b, letExpressionRangeVariable}
''' </summary>
Public Function BuildJoinSelector(
syntax As VisualBasicSyntaxNode,
mustProduceFlatCompoundVariable As Boolean,
diagnostics As DiagnosticBag,
Optional rangeVarOpt As RangeVariableSymbol = Nothing,
Optional rangeVarValueOpt As BoundExpression = Nothing
) As BoundExpression
Debug.Assert(_rangeVariables.Length > 0)
Debug.Assert((rangeVarOpt Is Nothing) = (rangeVarValueOpt Is Nothing))
Debug.Assert(rangeVarOpt IsNot Nothing OrElse _lambdaSymbol.ParameterCount > 1)
Dim selectors As BoundExpression()
Dim fields As AnonymousTypeField()
' In some scenarios, it is safe to leave compound variable in nested form when there is an
' operator down the road that does its own projection (Select, Group By, ...).
' All following operators have to take an Anonymous Type in both cases and, since there is no way to
' restrict the shape of the Anonymous Type in method's declaration, the operators should be
' insensitive to the shape of the Anonymous Type.
Dim lastIndex As Integer
Dim sizeIncrease As Integer = If(rangeVarOpt Is Nothing, 0, 1)
Debug.Assert(sizeIncrease + _rangeVariables.Length > 1)
' Note, the special case for [sourceRangeVariables.Count = 1] helps in the
' following scenario:
' From x In Xs Select x+1 From y In Ys Let z= Zz, ...
' Selector lambda should be:
' Function(unnamed, y) New With {y, .z=Zz}
' The lambda has two parameters, but we have only one range variable that should be carried over.
' If we were simply copying lambda's parameters to the Anonymous Type instance, we would
' copy data that aren't needed (value of the first parameter should be dropped).
If _rangeVariables.Length = 1 OrElse mustProduceFlatCompoundVariable Then
' Need to flatten
lastIndex = _rangeVariables.Length + sizeIncrease - 1
selectors = New BoundExpression(lastIndex) {}
fields = New AnonymousTypeField(lastIndex) {}
For j As Integer = 0 To _rangeVariables.Length - 1
Dim leftVar As RangeVariableSymbol = _rangeVariables(j)
selectors(j) = New BoundRangeVariable(leftVar.Syntax, leftVar, leftVar.Type).MakeCompilerGenerated()
fields(j) = New AnonymousTypeField(leftVar.Name, leftVar.Type, leftVar.Syntax.GetLocation(), isKeyOrByRef:=True)
Next
Else
' Nesting ...
Debug.Assert(_rangeVariables.Length > 1)
Dim parameters As ImmutableArray(Of BoundLambdaParameterSymbol) = _lambdaSymbol.Parameters.As(Of BoundLambdaParameterSymbol)
lastIndex = parameters.Length + sizeIncrease - 1
selectors = New BoundExpression(lastIndex) {}
fields = New AnonymousTypeField(lastIndex) {}
For j As Integer = 0 To parameters.Length - 1
Dim param As BoundLambdaParameterSymbol = parameters(j)
selectors(j) = New BoundParameter(param.Syntax, param, False, param.Type).MakeCompilerGenerated()
fields(j) = New AnonymousTypeField(param.Name, param.Type, param.Syntax.GetLocation(), isKeyOrByRef:=True)
Next
End If
If rangeVarOpt IsNot Nothing Then
selectors(lastIndex) = rangeVarValueOpt
fields(lastIndex) = New AnonymousTypeField(
rangeVarOpt.Name, rangeVarOpt.Type, rangeVarOpt.Syntax.GetLocation(), isKeyOrByRef:=True)
End If
Return BindAnonymousObjectCreationExpression(syntax,
New AnonymousTypeDescriptor(fields.AsImmutableOrNull(),
syntax.QueryClauseKeywordOrRangeVariableIdentifier.GetLocation(),
True),
selectors.AsImmutableOrNull(),
diagnostics).MakeCompilerGenerated()
End Function
''' <summary>
''' Bind key selectors for a Join/Group Join operator.
''' </summary>
Public Shared Sub BindJoinKeys(
parentBinder As Binder,
join As JoinClauseSyntax,
outer As BoundQueryClauseBase,
inner As BoundQueryClauseBase,
joinSelectorRangeVariables As ImmutableArray(Of RangeVariableSymbol),
<Out()> ByRef outerKeyLambda As BoundQueryLambda,
<Out()> ByRef outerKeyBinder As QueryLambdaBinder,
<Out()> ByRef innerKeyLambda As BoundQueryLambda,
<Out()> ByRef innerKeyBinder As QueryLambdaBinder,
diagnostics As DiagnosticBag
)
Debug.Assert(outerKeyLambda Is Nothing)
Debug.Assert(outerKeyBinder Is Nothing)
Debug.Assert(innerKeyLambda Is Nothing)
Debug.Assert(innerKeyBinder Is Nothing)
Debug.Assert(joinSelectorRangeVariables.SequenceEqual(outer.RangeVariables.Concat(inner.RangeVariables)))
Dim outerKeyParam As BoundLambdaParameterSymbol = parentBinder.CreateQueryLambdaParameterSymbol(
GetQueryLambdaParameterName(outer.RangeVariables), 0,
outer.CompoundVariableType,
join, outer.RangeVariables)
Dim outerKeyLambdaSymbol = parentBinder.CreateQueryLambdaSymbol(LambdaUtilities.GetJoinLeftLambdaBody(join),
SynthesizedLambdaKind.JoinLeftQueryLambda,
ImmutableArray.Create(outerKeyParam))
outerKeyBinder = New QueryLambdaBinder(outerKeyLambdaSymbol, joinSelectorRangeVariables)
Dim innerKeyParam As BoundLambdaParameterSymbol = parentBinder.CreateQueryLambdaParameterSymbol(
GetQueryLambdaParameterName(inner.RangeVariables), 0,
inner.CompoundVariableType,
join, inner.RangeVariables)
Dim innerKeyLambdaSymbol = parentBinder.CreateQueryLambdaSymbol(LambdaUtilities.GetJoinRightLambdaBody(join),
SynthesizedLambdaKind.JoinRightQueryLambda,
ImmutableArray.Create(innerKeyParam))
innerKeyBinder = New QueryLambdaBinder(innerKeyLambdaSymbol, joinSelectorRangeVariables)
Dim suppressDiagnostics As DiagnosticBag = Nothing
Dim sideDeterminator As New JoinConditionSideDeterminationVisitor(outer.RangeVariables, inner.RangeVariables)
Dim joinConditions As SeparatedSyntaxList(Of JoinConditionSyntax) = join.JoinConditions
Dim outerKey As BoundExpression
Dim innerKey As BoundExpression
Dim keysAreGood As Boolean
If joinConditions.Count = 0 Then
' Malformed tree.
Debug.Assert(joinConditions.Count > 0, "Malformed syntax tree.")
outerKey = BadExpression(join, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
innerKey = BadExpression(join, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
keysAreGood = False
ElseIf joinConditions.Count = 1 Then
' Simple case, no need to build an Anonymous Type.
outerKey = Nothing
innerKey = Nothing
keysAreGood = BindJoinCondition(joinConditions(0),
outerKeyBinder,
outer.RangeVariables,
outerKey,
innerKeyBinder,
inner.RangeVariables,
innerKey,
sideDeterminator,
diagnostics,
suppressDiagnostics)
If Not keysAreGood Then
If outerKey.Type IsNot ErrorTypeSymbol.UnknownResultType Then
outerKey = BadExpression(outerKey.Syntax, outerKey, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
End If
If innerKey.Type IsNot ErrorTypeSymbol.UnknownResultType Then
innerKey = BadExpression(innerKey.Syntax, innerKey, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
End If
End If
Else
' Need to build a compound key as an instance of an Anonymous Type.
Dim outerKeys(joinConditions.Count - 1) As BoundExpression
Dim innerKeys(joinConditions.Count - 1) As BoundExpression
keysAreGood = True
For i As Integer = 0 To joinConditions.Count - 1
If Not BindJoinCondition(joinConditions(i),
outerKeyBinder,
outer.RangeVariables,
outerKeys(i),
innerKeyBinder,
inner.RangeVariables,
innerKeys(i),
sideDeterminator,
diagnostics,
suppressDiagnostics) Then
keysAreGood = False
End If
Next
If keysAreGood Then
Dim fields(joinConditions.Count - 1) As AnonymousTypeField
For i As Integer = 0 To joinConditions.Count - 1
fields(i) = New AnonymousTypeField(
"Key" & i.ToString(), outerKeys(i).Type, joinConditions(i).GetLocation(), isKeyOrByRef:=True)
Next
Dim descriptor As New AnonymousTypeDescriptor(fields.AsImmutableOrNull(),
join.OnKeyword.GetLocation(),
True)
outerKey = outerKeyBinder.BindAnonymousObjectCreationExpression(join, descriptor, outerKeys.AsImmutableOrNull(),
diagnostics).MakeCompilerGenerated()
innerKey = innerKeyBinder.BindAnonymousObjectCreationExpression(join, descriptor, innerKeys.AsImmutableOrNull(),
diagnostics).MakeCompilerGenerated()
Else
outerKey = BadExpression(join, DirectCast(outerKeys, BoundNode()).AsImmutableOrNull(), ErrorTypeSymbol.UnknownResultType)
innerKey = BadExpression(join, DirectCast(innerKeys, BoundNode()).AsImmutableOrNull(), ErrorTypeSymbol.UnknownResultType)
End If
End If
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
outerKeyLambda = CreateBoundQueryLambda(outerKeyLambdaSymbol,
outer.RangeVariables,
outerKey,
exprIsOperandOfConditionalBranch:=False)
outerKeyLambda.SetWasCompilerGenerated()
innerKeyLambda = CreateBoundQueryLambda(innerKeyLambdaSymbol,
inner.RangeVariables,
innerKey,
exprIsOperandOfConditionalBranch:=False)
innerKeyLambda.SetWasCompilerGenerated()
Debug.Assert(outerKeyLambda IsNot Nothing)
Debug.Assert(innerKeyLambda IsNot Nothing)
End Sub
Private Shared Function BindJoinCondition(
joinCondition As JoinConditionSyntax,
outerKeyBinder As QueryLambdaBinder,
outerRangeVariables As ImmutableArray(Of RangeVariableSymbol),
<Out()> ByRef outerKey As BoundExpression,
innerKeyBinder As QueryLambdaBinder,
innerRangeVariables As ImmutableArray(Of RangeVariableSymbol),
<Out()> ByRef innerKey As BoundExpression,
sideDeterminator As JoinConditionSideDeterminationVisitor,
diagnostics As DiagnosticBag,
ByRef suppressDiagnostics As DiagnosticBag
) As Boolean
Debug.Assert(outerKey Is Nothing AndAlso innerKey Is Nothing)
' For a JoinConditionSyntax (<left expr> Equals <right expr>), we are going to bind
' left side with outerKeyBinder, which has all range variables from outer and from inner
' in scope. Then, we try to figure out to which join side the left key actually belongs.
' If it turns out that it belongs to the inner side, we will bind the left again,
' but now using the innerKeyBinder. The reason why we need to rebind expressions is that
' innerKeyBinder, outerKeyBinder are each associated with different lambda symbols and
' the binding process might capture the lambda in the tree or in symbols referenced by
' the tree, so we can't safely move bound nodes between lambdas. Usually expressions are
' small and very simple, so rebinding them shouldn't create a noticeable performance impact.
' If that will not turn out to be the case, we might try to optimize by tracking if someone
' requested ContainingMember from outerKeyBinder while an expression is being bound and
' rebind only in that case.
' Similarly, in some scenarios we bind right key with innerKeyBinder first and then rebind
' it with outerKeyBinder.
Dim keysAreGood As Boolean
Dim left As BoundExpression = outerKeyBinder.BindRValue(joinCondition.Left, diagnostics)
Dim leftSide As JoinConditionSideDeterminationVisitor.Result
leftSide = sideDeterminator.DetermineTheSide(left, diagnostics)
If leftSide = JoinConditionSideDeterminationVisitor.Result.Outer Then
outerKey = left
innerKey = innerKeyBinder.BindRValue(joinCondition.Right, diagnostics)
keysAreGood = innerKeyBinder.VerifyJoinKeys(outerKey, outerRangeVariables, leftSide,
innerKey, innerRangeVariables, sideDeterminator.DetermineTheSide(innerKey, diagnostics),
diagnostics)
ElseIf leftSide = JoinConditionSideDeterminationVisitor.Result.Inner Then
' Rebind with the inner binder.
If suppressDiagnostics Is Nothing Then
suppressDiagnostics = DiagnosticBag.GetInstance()
End If
innerKey = innerKeyBinder.BindRValue(joinCondition.Left, suppressDiagnostics)
Debug.Assert(leftSide = sideDeterminator.DetermineTheSide(innerKey, diagnostics))
outerKey = outerKeyBinder.BindRValue(joinCondition.Right, diagnostics)
keysAreGood = innerKeyBinder.VerifyJoinKeys(outerKey, outerRangeVariables, sideDeterminator.DetermineTheSide(outerKey, diagnostics),
innerKey, innerRangeVariables, leftSide,
diagnostics)
Else
Dim right As BoundExpression = innerKeyBinder.BindRValue(joinCondition.Right, diagnostics)
Dim rightSide As JoinConditionSideDeterminationVisitor.Result
rightSide = sideDeterminator.DetermineTheSide(right, diagnostics)
If rightSide = JoinConditionSideDeterminationVisitor.Result.Outer Then
' Rebind with the outer binder.
If suppressDiagnostics Is Nothing Then
suppressDiagnostics = DiagnosticBag.GetInstance()
End If
outerKey = outerKeyBinder.BindRValue(joinCondition.Right, suppressDiagnostics)
innerKey = innerKeyBinder.BindRValue(joinCondition.Left, suppressDiagnostics)
keysAreGood = innerKeyBinder.VerifyJoinKeys(outerKey, outerRangeVariables, rightSide,
innerKey, innerRangeVariables, leftSide,
diagnostics)
Else
outerKey = left
innerKey = right
keysAreGood = innerKeyBinder.VerifyJoinKeys(outerKey, outerRangeVariables, leftSide,
innerKey, innerRangeVariables, rightSide,
diagnostics)
End If
Debug.Assert(Not keysAreGood)
End If
If keysAreGood Then
keysAreGood = Not (outerKey.Type.IsErrorType() OrElse innerKey.Type.IsErrorType())
End If
If keysAreGood AndAlso Not outerKey.Type.IsSameTypeIgnoringCustomModifiers(innerKey.Type) Then
' Apply conversion if available.
Dim targetType As TypeSymbol = Nothing
Dim intrinsicOperatorType As SpecialType = SpecialType.None
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim operatorKind As BinaryOperatorKind = OverloadResolution.ResolveBinaryOperator(BinaryOperatorKind.Equals,
outerKey, innerKey,
innerKeyBinder,
considerUserDefinedOrLateBound:=False,
intrinsicOperatorType:=intrinsicOperatorType,
userDefinedOperator:=Nothing,
useSiteDiagnostics:=useSiteDiagnostics)
If (operatorKind And BinaryOperatorKind.Equals) <> 0 AndAlso
(operatorKind And Not (BinaryOperatorKind.Equals Or BinaryOperatorKind.Lifted)) = 0 AndAlso
intrinsicOperatorType <> SpecialType.None Then
' There is an intrinsic (=) operator, use its argument type.
Debug.Assert(useSiteDiagnostics.IsNullOrEmpty)
targetType = innerKeyBinder.GetSpecialTypeForBinaryOperator(joinCondition, outerKey.Type, innerKey.Type, intrinsicOperatorType,
(operatorKind And BinaryOperatorKind.Lifted) <> 0, diagnostics)
Else
' Use dominant type.
Dim inferenceCollection = New TypeInferenceCollection()
inferenceCollection.AddType(outerKey.Type, RequiredConversion.Any, outerKey)
inferenceCollection.AddType(innerKey.Type, RequiredConversion.Any, innerKey)
Dim resultList = ArrayBuilder(Of DominantTypeData).GetInstance()
inferenceCollection.FindDominantType(resultList, Nothing, useSiteDiagnostics)
If diagnostics.Add(joinCondition, useSiteDiagnostics) Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
If resultList.Count = 1 Then
targetType = resultList(0).ResultType
End If
resultList.Free()
End If
If targetType Is Nothing Then
ReportDiagnostic(diagnostics, joinCondition, ERRID.ERR_EqualsTypeMismatch, outerKey.Type, innerKey.Type)
keysAreGood = False
Else
outerKey = outerKeyBinder.ApplyImplicitConversion(outerKey.Syntax, targetType, outerKey, diagnostics, False)
innerKey = innerKeyBinder.ApplyImplicitConversion(innerKey.Syntax, targetType, innerKey, diagnostics, False)
End If
End If
Debug.Assert(outerKey IsNot Nothing AndAlso innerKey IsNot Nothing)
Return keysAreGood
End Function
Private Function VerifyJoinKeys(
outerKey As BoundExpression,
outerRangeVariables As ImmutableArray(Of RangeVariableSymbol),
outerSide As JoinConditionSideDeterminationVisitor.Result,
innerKey As BoundExpression,
innerRangeVariables As ImmutableArray(Of RangeVariableSymbol),
innerSide As JoinConditionSideDeterminationVisitor.Result,
diagnostics As DiagnosticBag
) As Boolean
If outerSide = JoinConditionSideDeterminationVisitor.Result.Outer AndAlso
innerSide = JoinConditionSideDeterminationVisitor.Result.Inner Then
Return True
End If
If outerKey.HasErrors OrElse innerKey.HasErrors Then
Return False
End If
Dim builder = PooledStringBuilder.GetInstance()
Dim outerNames As String = BuildEqualsOperandIsBadErrorArgument(builder.Builder, outerRangeVariables)
Dim innerNames As String = BuildEqualsOperandIsBadErrorArgument(builder.Builder, innerRangeVariables)
builder.Free()
If outerNames Is Nothing OrElse innerNames Is Nothing Then
' Syntax errors were earlier reported.
Return False
End If
Dim errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_EqualsOperandIsBad, outerNames, innerNames)
Select Case outerSide
Case JoinConditionSideDeterminationVisitor.Result.Both,
JoinConditionSideDeterminationVisitor.Result.Inner
' Report errors on references to inner.
EqualsOperandIsBadErrorVisitor.Report(Me, errorInfo, innerRangeVariables, outerKey, diagnostics)
Case JoinConditionSideDeterminationVisitor.Result.None
ReportDiagnostic(diagnostics, outerKey.Syntax, errorInfo)
Case JoinConditionSideDeterminationVisitor.Result.Outer
' This side is good.
Case Else
Throw ExceptionUtilities.UnexpectedValue(outerSide)
End Select
Select Case innerSide
Case JoinConditionSideDeterminationVisitor.Result.Both,
JoinConditionSideDeterminationVisitor.Result.Outer
' Report errors on references to outer.
EqualsOperandIsBadErrorVisitor.Report(Me, errorInfo, outerRangeVariables, innerKey, diagnostics)
Case JoinConditionSideDeterminationVisitor.Result.None
ReportDiagnostic(diagnostics, innerKey.Syntax, errorInfo)
Case JoinConditionSideDeterminationVisitor.Result.Inner
' This side is good.
Case Else
Throw ExceptionUtilities.UnexpectedValue(innerSide)
End Select
Return False
End Function
Private Shared Function BuildEqualsOperandIsBadErrorArgument(
builder As System.Text.StringBuilder,
rangeVariables As ImmutableArray(Of RangeVariableSymbol)
) As String
builder.Clear()
Dim i As Integer
For i = 0 To rangeVariables.Length - 1
If Not rangeVariables(i).Name.StartsWith("$"c, StringComparison.Ordinal) Then
builder.Append("'"c)
builder.Append(rangeVariables(i).Name)
builder.Append("'"c)
i += 1
Exit For
End If
Next
For i = i To rangeVariables.Length - 1
If Not rangeVariables(i).Name.StartsWith("$"c, StringComparison.Ordinal) Then
builder.Append(","c)
builder.Append(" "c)
builder.Append("'"c)
builder.Append(rangeVariables(i).Name)
builder.Append("'"c)
End If
Next
If builder.Length = 0 Then
Return Nothing
End If
Return builder.ToString()
End Function
''' <summary>
''' Helper visitor to determine what join sides are referenced by an expression.
''' </summary>
Private Class JoinConditionSideDeterminationVisitor
Inherits BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
<Flags()>
Public Enum Result
None = 0
Outer = 1
Inner = 2
Both = Outer Or Inner
End Enum
Private ReadOnly _outerRangeVariables As ImmutableArray(Of Object) 'ImmutableArray(Of RangeVariableSymbol)
Private ReadOnly _innerRangeVariables As ImmutableArray(Of Object) 'ImmutableArray(Of RangeVariableSymbol)
Private _side As Result
Public Sub New(
outerRangeVariables As ImmutableArray(Of RangeVariableSymbol),
innerRangeVariables As ImmutableArray(Of RangeVariableSymbol)
)
_outerRangeVariables = StaticCast(Of Object).From(outerRangeVariables)
_innerRangeVariables = StaticCast(Of Object).From(innerRangeVariables)
End Sub
Public Function DetermineTheSide(node As BoundExpression, diagnostics As DiagnosticBag) As Result
_side = Result.None
Try
Visit(node)
Catch ex As CancelledByStackGuardException
ex.AddAnError(diagnostics)
End Try
Return _side
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Dim rangeVariable As RangeVariableSymbol = node.RangeVariable
If _outerRangeVariables.IndexOf(rangeVariable, ReferenceEqualityComparer.Instance) >= 0 Then
_side = _side Or Result.Outer
ElseIf _innerRangeVariables.IndexOf(rangeVariable, ReferenceEqualityComparer.Instance) >= 0 Then
_side = _side Or Result.Inner
End If
Return node
End Function
End Class
''' <summary>
''' Helper visitor to report query specific errors for an operand of an Equals expression.
''' </summary>
Private Class EqualsOperandIsBadErrorVisitor
Inherits BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
Private ReadOnly _binder As Binder
Private ReadOnly _errorInfo As DiagnosticInfo
Private ReadOnly _diagnostics As DiagnosticBag
Private ReadOnly _badRangeVariables As ImmutableArray(Of Object) 'ImmutableArray(Of RangeVariableSymbol)
Private Sub New(
binder As Binder,
errorInfo As DiagnosticInfo,
badRangeVariables As ImmutableArray(Of RangeVariableSymbol),
diagnostics As DiagnosticBag
)
_badRangeVariables = StaticCast(Of Object).From(badRangeVariables)
_binder = binder
_diagnostics = diagnostics
_errorInfo = errorInfo
End Sub
Public Shared Sub Report(
binder As Binder,
errorInfo As DiagnosticInfo,
badRangeVariables As ImmutableArray(Of RangeVariableSymbol),
node As BoundExpression,
diagnostics As DiagnosticBag
)
Dim v As New EqualsOperandIsBadErrorVisitor(binder, errorInfo, badRangeVariables, diagnostics)
Try
v.Visit(node)
Catch ex As CancelledByStackGuardException
ex.AddAnError(diagnostics)
End Try
End Sub
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Dim rangeVariable As RangeVariableSymbol = node.RangeVariable
If _badRangeVariables.IndexOf(rangeVariable, ReferenceEqualityComparer.Instance) >= 0 Then
ReportDiagnostic(_diagnostics, node.Syntax, _errorInfo)
End If
Return node
End Function
End Class
End Class
''' <summary>
''' Knows how to bind FunctionAggregationSyntax and GroupAggregationSyntax
''' within particular [Into] clause.
'''
''' Also implements Lookup/LookupNames methods to make sure that lookup without
''' container type, uses type of the group as the container type.
''' </summary>
Private Class IntoClauseBinder
Inherits Binder
Protected ReadOnly m_GroupReference As BoundExpression
Private ReadOnly _groupRangeVariables As ImmutableArray(Of RangeVariableSymbol)
Private ReadOnly _groupCompoundVariableType As TypeSymbol
Private ReadOnly _aggregationArgumentRangeVariables As ImmutableArray(Of RangeVariableSymbol)
Public Sub New(
parent As Binder,
groupReference As BoundExpression,
groupRangeVariables As ImmutableArray(Of RangeVariableSymbol),
groupCompoundVariableType As TypeSymbol,
aggregationArgumentRangeVariables As ImmutableArray(Of RangeVariableSymbol)
)
MyBase.New(parent)
m_GroupReference = groupReference
_groupRangeVariables = groupRangeVariables
_groupCompoundVariableType = groupCompoundVariableType
_aggregationArgumentRangeVariables = aggregationArgumentRangeVariables
End Sub
Friend Overrides Function BindGroupAggregationExpression(
group As GroupAggregationSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
Return New BoundGroupAggregation(group, m_GroupReference, m_GroupReference.Type)
End Function
''' <summary>
''' Given aggregationVariables, bind Into selector in context of this binder.
''' </summary>
Public Function BindIntoSelector(
syntaxNode As QueryClauseSyntax,
keysRangeVariables As ImmutableArray(Of RangeVariableSymbol),
compoundKeyReferencePart1 As BoundExpression,
keysRangeVariablesPart1 As ImmutableArray(Of RangeVariableSymbol),
compoundKeyReferencePart2 As BoundExpression,
keysRangeVariablesPart2 As ImmutableArray(Of RangeVariableSymbol),
declaredNames As HashSet(Of String),
aggregationVariables As SeparatedSyntaxList(Of AggregationRangeVariableSyntax),
mustProduceFlatCompoundVariable As Boolean,
<Out()> ByRef declaredRangeVariables As ImmutableArray(Of RangeVariableSymbol),
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(declaredRangeVariables.IsDefault)
Debug.Assert(compoundKeyReferencePart2 Is Nothing OrElse compoundKeyReferencePart1 IsNot Nothing)
Debug.Assert((compoundKeyReferencePart1 Is Nothing) = (keysRangeVariablesPart1.Length = 0))
Debug.Assert((compoundKeyReferencePart2 Is Nothing) = (keysRangeVariablesPart2.Length = 0))
Debug.Assert((compoundKeyReferencePart2 Is Nothing) = (keysRangeVariables = keysRangeVariablesPart1))
Debug.Assert(compoundKeyReferencePart1 Is Nothing OrElse keysRangeVariables.Length = keysRangeVariablesPart1.Length + keysRangeVariablesPart2.Length)
Dim keys As Integer = keysRangeVariables.Length
Dim selectors As BoundExpression()
Dim fields As AnonymousTypeField()
If declaredNames Is Nothing Then
declaredNames = CreateSetOfDeclaredNames(keysRangeVariables)
Else
AssertDeclaredNames(declaredNames, keysRangeVariables)
End If
Dim intoSelector As BoundExpression
Dim rangeVariables() As RangeVariableSymbol
Dim fieldsToReserveForAggregationVariables As Integer = Math.Max(aggregationVariables.Count, 1)
If keys + fieldsToReserveForAggregationVariables > 1 Then
' Need to build an Anonymous Type
' Add keys first.
If keys > 1 AndAlso Not mustProduceFlatCompoundVariable Then
If compoundKeyReferencePart2 Is Nothing Then
selectors = New BoundExpression(fieldsToReserveForAggregationVariables + 1 - 1) {}
fields = New AnonymousTypeField(selectors.Length - 1) {}
' Using syntax of the first range variable in the source, this shouldn't create any problems.
fields(0) = New AnonymousTypeField(GetQueryLambdaParameterName(keysRangeVariablesPart1),
compoundKeyReferencePart1.Type,
keysRangeVariables(0).Syntax.GetLocation(), isKeyOrByRef:=True)
selectors(0) = compoundKeyReferencePart1
keys = 1
Else
selectors = New BoundExpression(fieldsToReserveForAggregationVariables + 2 - 1) {}
fields = New AnonymousTypeField(selectors.Length - 1) {}
' Using syntax of the first range variable in the source, this shouldn't create any problems.
fields(0) = New AnonymousTypeField(GetQueryLambdaParameterNameLeft(keysRangeVariablesPart1),
compoundKeyReferencePart1.Type,
keysRangeVariablesPart1(0).Syntax.GetLocation(),
isKeyOrByRef:=True)
selectors(0) = compoundKeyReferencePart1
fields(1) = New AnonymousTypeField(GetQueryLambdaParameterNameRight(keysRangeVariablesPart2),
compoundKeyReferencePart2.Type,
keysRangeVariablesPart2(0).Syntax.GetLocation(),
isKeyOrByRef:=True)
selectors(1) = compoundKeyReferencePart2
keys = 2
End If
Else
selectors = New BoundExpression(keys + fieldsToReserveForAggregationVariables - 1) {}
fields = New AnonymousTypeField(selectors.Length - 1) {}
For i As Integer = 0 To keys - 1
Dim rangeVar As RangeVariableSymbol = keysRangeVariables(i)
fields(i) = New AnonymousTypeField(rangeVar.Name, rangeVar.Type, rangeVar.Syntax.GetLocation(), isKeyOrByRef:=True)
selectors(i) = New BoundRangeVariable(rangeVar.Syntax, rangeVar, rangeVar.Type).MakeCompilerGenerated()
Next
End If
' Now add aggregation variables.
rangeVariables = New RangeVariableSymbol(fieldsToReserveForAggregationVariables - 1) {}
If aggregationVariables.Count = 0 Then
' Malformed syntax tree.
Debug.Assert(aggregationVariables.Count > 0, "Malformed syntax tree.")
Dim rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, syntaxNode, ErrorTypeSymbol.UnknownResultType)
rangeVariables(0) = rangeVar
selectors(keys) = BadExpression(syntaxNode, m_GroupReference, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
fields(keys) = New AnonymousTypeField(rangeVar.Name, rangeVar.Type, rangeVar.Syntax.GetLocation(), isKeyOrByRef:=True)
Else
For i As Integer = 0 To aggregationVariables.Count - 1
Dim selector As BoundExpression = Nothing
Dim rangeVar As RangeVariableSymbol = BindAggregationRangeVariable(aggregationVariables(i),
declaredNames, selector,
diagnostics)
Debug.Assert(rangeVar IsNot Nothing)
rangeVariables(i) = rangeVar
selectors(keys + i) = selector
fields(keys + i) = New AnonymousTypeField(
rangeVar.Name, rangeVar.Type, rangeVar.Syntax.GetLocation(), isKeyOrByRef:=True)
Next
End If
Debug.Assert(selectors.Length > 1)
intoSelector = BindAnonymousObjectCreationExpression(syntaxNode,
New AnonymousTypeDescriptor(fields.AsImmutableOrNull(),
syntaxNode.QueryClauseKeywordOrRangeVariableIdentifier.GetLocation(),
True),
selectors.AsImmutableOrNull(),
diagnostics).MakeCompilerGenerated()
Else
Debug.Assert(keys = 0)
Dim rangeVar As RangeVariableSymbol
If aggregationVariables.Count = 0 Then
' Malformed syntax tree.
Debug.Assert(aggregationVariables.Count > 0, "Malformed syntax tree.")
rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, syntaxNode, ErrorTypeSymbol.UnknownResultType)
intoSelector = BadExpression(syntaxNode, m_GroupReference, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Debug.Assert(aggregationVariables.Count = 1)
intoSelector = Nothing
rangeVar = BindAggregationRangeVariable(aggregationVariables(0),
declaredNames, intoSelector,
diagnostics)
Debug.Assert(rangeVar IsNot Nothing)
End If
rangeVariables = {rangeVar}
End If
AssertDeclaredNames(declaredNames, rangeVariables.AsImmutableOrNull())
declaredRangeVariables = rangeVariables.AsImmutableOrNull()
Return intoSelector
End Function
Friend Overrides Function BindFunctionAggregationExpression(
functionAggregationSyntax As FunctionAggregationSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
If functionAggregationSyntax.FunctionName.GetTypeCharacter() <> TypeCharacter.None Then
ReportDiagnostic(diagnostics, functionAggregationSyntax.FunctionName, ERRID.ERR_TypeCharOnAggregation)
End If
Dim aggregationParam As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(GetQueryLambdaParameterName(_groupRangeVariables), 0,
_groupCompoundVariableType,
If(functionAggregationSyntax.Argument, functionAggregationSyntax),
_groupRangeVariables)
' Note [Binder:=Me.ContainingBinder] below. We are excluding this binder from the chain of
' binders for an argument of the function. Do not want it to interfere in any way given
' its special binding and Lookup/LookupNames behavior.
Dim aggregationLambdaSymbol = Me.ContainingBinder.CreateQueryLambdaSymbol(
If(LambdaUtilities.GetAggregationLambdaBody(functionAggregationSyntax), functionAggregationSyntax),
SynthesizedLambdaKind.AggregationQueryLambda,
ImmutableArray.Create(aggregationParam))
' Create binder for the aggregation.
Dim aggregationBinder As New QueryLambdaBinder(aggregationLambdaSymbol, _aggregationArgumentRangeVariables)
Dim arguments As ImmutableArray(Of BoundExpression)
Dim aggregationLambda As BoundQueryLambda = Nothing
If functionAggregationSyntax.Argument Is Nothing Then
arguments = ImmutableArray(Of BoundExpression).Empty
Else
' Bind argument as a value, conversion during overload resolution should take care of the rest (making it an RValue, etc.).
Dim aggregationSelector = aggregationBinder.BindValue(functionAggregationSyntax.Argument, diagnostics)
aggregationLambda = CreateBoundQueryLambda(aggregationLambdaSymbol,
_groupRangeVariables,
aggregationSelector,
exprIsOperandOfConditionalBranch:=False)
' Note, we are not setting ReturnType for aggregationLambdaSymbol to allow
' additional conversions. This type doesn't affect type of any range variable
' in the query.
aggregationLambda.SetWasCompilerGenerated()
arguments = ImmutableArray.Create(Of BoundExpression)(aggregationLambda)
End If
' Now bind the aggregation call.
Dim boundCallOrBadExpression As BoundExpression
If m_GroupReference.Type.IsErrorType() OrElse String.IsNullOrEmpty(functionAggregationSyntax.FunctionName.ValueText) Then
boundCallOrBadExpression = BadExpression(functionAggregationSyntax,
ImmutableArray.Create(Of BoundNode)(m_GroupReference).AddRange(arguments),
ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Dim callDiagnostics As DiagnosticBag = diagnostics
If aggregationLambda IsNot Nothing AndAlso ShouldSuppressDiagnostics(aggregationLambda) Then
' Operator BindQueryClauseCall will fail, let's suppress any additional errors it will report.
callDiagnostics = DiagnosticBag.GetInstance()
End If
boundCallOrBadExpression = BindQueryOperatorCall(functionAggregationSyntax, m_GroupReference,
functionAggregationSyntax.FunctionName.ValueText,
arguments,
functionAggregationSyntax.FunctionName.Span,
callDiagnostics)
If callDiagnostics IsNot diagnostics Then
callDiagnostics.Free()
End If
End If
Return New BoundQueryClause(functionAggregationSyntax, boundCallOrBadExpression,
ImmutableArray(Of RangeVariableSymbol).Empty,
boundCallOrBadExpression.Type,
ImmutableArray.Create(Of Binder)(aggregationBinder),
boundCallOrBadExpression.Type)
End Function
Public Overrides Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions)
If (options And (LookupOptionExtensions.ConsiderationMask Or LookupOptions.MustNotBeInstance)) <> 0 Then
Return
End If
' Should look for group's methods only.
AddMemberLookupSymbolsInfo(nameSet,
m_GroupReference.Type,
options Or CType(LookupOptions.MethodsOnly Or LookupOptions.MustBeInstance, LookupOptions))
End Sub
Public Overrides Sub Lookup(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
If (options And (LookupOptionExtensions.ConsiderationMask Or LookupOptions.MustNotBeInstance)) <> 0 Then
Return
End If
' Should look for group's methods only.
LookupMember(lookupResult,
m_GroupReference.Type,
name,
arity,
options Or CType(LookupOptions.MethodsOnly Or LookupOptions.MustBeInstance, LookupOptions),
useSiteDiagnostics)
End Sub
''' <summary>
''' Bind AggregationRangeVariableSyntax in context of this binder.
''' </summary>
Public Function BindAggregationRangeVariable(
item As AggregationRangeVariableSyntax,
declaredNames As HashSet(Of String),
<Out()> ByRef selector As BoundExpression,
diagnostics As DiagnosticBag
) As RangeVariableSymbol
Debug.Assert(selector Is Nothing)
Dim variableName As VariableNameEqualsSyntax = item.NameEquals
' Figure out the name of the new range variable
Dim rangeVarName As String = Nothing
Dim rangeVarNameSyntax As SyntaxToken = Nothing
If variableName IsNot Nothing Then
rangeVarNameSyntax = variableName.Identifier.Identifier
rangeVarName = rangeVarNameSyntax.ValueText
Debug.Assert(variableName.AsClause Is Nothing)
Else
' Infer the name from expression
Select Case item.Aggregation.Kind
Case SyntaxKind.GroupAggregation
' AggregateClause doesn't support GroupAggregation.
If item.Parent.Kind <> SyntaxKind.AggregateClause Then
rangeVarNameSyntax = DirectCast(item.Aggregation, GroupAggregationSyntax).GroupKeyword
rangeVarName = rangeVarNameSyntax.ValueText
End If
Case SyntaxKind.FunctionAggregation
rangeVarNameSyntax = DirectCast(item.Aggregation, FunctionAggregationSyntax).FunctionName
rangeVarName = rangeVarNameSyntax.ValueText
Case Else
Throw ExceptionUtilities.UnexpectedValue(item.Aggregation.Kind)
End Select
End If
' Bind the value.
selector = BindRValue(item.Aggregation, diagnostics)
If rangeVarName IsNot Nothing AndAlso rangeVarName.Length = 0 Then
' Empty string must have been a syntax error.
rangeVarName = Nothing
End If
Dim rangeVar As RangeVariableSymbol = Nothing
If rangeVarName IsNot Nothing Then
rangeVar = RangeVariableSymbol.Create(Me, rangeVarNameSyntax, selector.Type)
' Note what we are doing here:
' We are creating BoundRangeVariableAssignment before doing any shadowing checks
' so that SemanticModel can find the declared symbol, but, if the variable will conflict with another
' variable in the same child scope, we will not add it to the scope. Instead, we create special
' error recovery range variable symbol and add it to the scope at the same place, making sure
' that the earlier declared range variable wins during name lookup.
' As an alternative, we could still add the original range variable symbol to the scope and then,
' while we are binding the rest of the query in error recovery mode, references to the name would
' cause ambiguity. However, this could negatively affect IDE experience. Also, as we build an
' Anonymous Type for the compound range variables, we would end up with a type with duplicate members,
' which could cause problems elsewhere.
selector = New BoundRangeVariableAssignment(item, rangeVar, selector, selector.Type)
Dim doErrorRecovery As Boolean = False
If declaredNames IsNot Nothing AndAlso Not declaredNames.Add(rangeVarName) Then
ReportDiagnostic(diagnostics, rangeVarNameSyntax, ERRID.ERR_QueryDuplicateAnonTypeMemberName1, rangeVarName)
doErrorRecovery = True ' Shouldn't add to the scope.
Else
Me.VerifyRangeVariableName(rangeVar, rangeVarNameSyntax, diagnostics)
End If
If doErrorRecovery Then
rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, rangeVar.Syntax, selector.Type)
End If
Else
Debug.Assert(rangeVar Is Nothing)
rangeVar = RangeVariableSymbol.CreateForErrorRecovery(Me, item, selector.Type)
End If
Debug.Assert(selector IsNot Nothing)
Return rangeVar
End Function
End Class
''' <summary>
''' Same as IntoClauseBinder, but disallows references to GroupAggregationSyntax.
''' </summary>
Private Class IntoClauseDisallowGroupReferenceBinder
Inherits IntoClauseBinder
Public Sub New(
parent As Binder,
groupReference As BoundExpression,
groupRangeVariables As ImmutableArray(Of RangeVariableSymbol),
groupCompoundVariableType As TypeSymbol,
aggregationArgumentRangeVariables As ImmutableArray(Of RangeVariableSymbol)
)
MyBase.New(parent, groupReference, groupRangeVariables, groupCompoundVariableType, aggregationArgumentRangeVariables)
End Sub
Friend Overrides Function BindGroupAggregationExpression(group As GroupAggregationSyntax, diagnostics As DiagnosticBag) As BoundExpression
' Parser should have reported an error.
Return BadExpression(group, m_GroupReference, ErrorTypeSymbol.UnknownResultType)
End Function
End Class
''' <summary>
''' Bind CollectionRangeVariableSyntax, applying AsQueryable/AsEnumerable/Cast(Of Object) calls and
''' Select with implicit type conversion as appropriate.
''' </summary>
Private Function BindCollectionRangeVariable(
syntax As CollectionRangeVariableSyntax,
beginsTheQuery As Boolean,
declaredNames As HashSet(Of String),
diagnostics As DiagnosticBag
) As BoundQueryableSource
Debug.Assert(declaredNames Is Nothing OrElse syntax.Parent.Kind = SyntaxKind.SimpleJoinClause OrElse syntax.Parent.Kind = SyntaxKind.GroupJoinClause)
Dim source As BoundQueryPart = New BoundQuerySource(BindRValue(syntax.Expression, diagnostics))
Dim variableType As TypeSymbol = Nothing
Dim queryable As BoundExpression = ConvertToQueryableType(source, diagnostics, variableType)
Dim sourceIsNotQueryable As Boolean = False
If variableType Is Nothing Then
If Not source.HasErrors Then
ReportDiagnostic(diagnostics, syntax.Expression, ERRID.ERR_ExpectedQueryableSource, source.Type)
End If
sourceIsNotQueryable = True
ElseIf source IsNot queryable Then
source = New BoundToQueryableCollectionConversion(DirectCast(queryable, BoundCall)).MakeCompilerGenerated()
End If
' Deal with AsClauseOpt and various modifiers.
Dim targetVariableType As TypeSymbol = Nothing
If syntax.AsClause IsNot Nothing Then
targetVariableType = DecodeModifiedIdentifierType(syntax.Identifier,
syntax.AsClause,
Nothing,
Nothing,
diagnostics,
ModifiedIdentifierTypeDecoderContext.LocalType Or
ModifiedIdentifierTypeDecoderContext.QueryRangeVariableType)
ElseIf syntax.Identifier.Nullable.Node IsNot Nothing Then
ReportDiagnostic(diagnostics, syntax.Identifier.Nullable, ERRID.ERR_NullableTypeInferenceNotSupported)
End If
If variableType Is Nothing Then
Debug.Assert(sourceIsNotQueryable)
If targetVariableType Is Nothing Then
variableType = ErrorTypeSymbol.UnknownResultType
Else
variableType = targetVariableType
End If
ElseIf targetVariableType IsNot Nothing AndAlso
Not targetVariableType.IsSameTypeIgnoringCustomModifiers(variableType) Then
Debug.Assert(Not sourceIsNotQueryable AndAlso syntax.AsClause IsNot Nothing)
' Need to apply implicit Select that converts variableType to targetVariableType.
source = ApplyImplicitCollectionConversion(syntax, source, variableType, targetVariableType, diagnostics)
variableType = targetVariableType
End If
Dim variable As RangeVariableSymbol = Nothing
Dim rangeVarName As String = syntax.Identifier.Identifier.ValueText
Dim rangeVariableOpt As RangeVariableSymbol = Nothing
If rangeVarName IsNot Nothing AndAlso rangeVarName.Length = 0 Then
' Empty string must have been a syntax error.
rangeVarName = Nothing
End If
If rangeVarName IsNot Nothing Then
variable = RangeVariableSymbol.Create(Me, syntax.Identifier.Identifier, variableType)
' Note what we are doing here:
' We are capturing rangeVariableOpt before doing any shadowing checks
' so that SemanticModel can find the declared symbol, but, if the variable will conflict with another
' variable in the same child scope, we will not add it to the scope. Instead, we create special
' error recovery range variable symbol and add it to the scope at the same place, making sure
' that the earlier declared range variable wins during name lookup.
' As an alternative, we could still add the original range variable symbol to the scope and then,
' while we are binding the rest of the query in error recovery mode, references to the name would
' cause ambiguity. However, this could negatively affect IDE experience. Also, as we build an
' Anonymous Type for the compound range variables, we would end up with a type with duplicate members,
' which could cause problems elsewhere.
rangeVariableOpt = variable
Dim doErrorRecovery As Boolean = False
If declaredNames IsNot Nothing AndAlso Not declaredNames.Add(rangeVarName) Then
ReportDiagnostic(diagnostics, syntax.Identifier.Identifier, ERRID.ERR_QueryDuplicateAnonTypeMemberName1, rangeVarName)
doErrorRecovery = True ' Shouldn't add to the scope.
Else
' Check shadowing etc.
VerifyRangeVariableName(variable, syntax.Identifier.Identifier, diagnostics)
If Not beginsTheQuery AndAlso declaredNames Is Nothing Then
Debug.Assert(syntax.Parent.Kind = SyntaxKind.FromClause OrElse syntax.Parent.Kind = SyntaxKind.AggregateClause)
' We are about to add this range variable to the current child scope.
If ShadowsRangeVariableInTheChildScope(Me, variable) Then
' Shadowing error was reported earlier.
doErrorRecovery = True ' Shouldn't add to the scope.
End If
End If
End If
If doErrorRecovery Then
variable = RangeVariableSymbol.CreateForErrorRecovery(Me, variable.Syntax, variableType)
End If
Else
Debug.Assert(variable Is Nothing)
variable = RangeVariableSymbol.CreateForErrorRecovery(Me, syntax, variableType)
End If
Dim result As New BoundQueryableSource(syntax, source, rangeVariableOpt,
ImmutableArray.Create(variable), variableType,
ImmutableArray(Of Binder).Empty,
If(sourceIsNotQueryable, ErrorTypeSymbol.UnknownResultType, source.Type),
hasErrors:=sourceIsNotQueryable)
Return result
End Function
''' <summary>
''' Apply "conversion" to the source based on the target AsClause Type of the CollectionRangeVariableSyntax.
''' Returns implicit BoundQueryClause or the source, in case of an early failure.
''' </summary>
Private Function ApplyImplicitCollectionConversion(
syntax As CollectionRangeVariableSyntax,
source As BoundQueryPart,
variableType As TypeSymbol,
targetVariableType As TypeSymbol,
diagnostics As DiagnosticBag
) As BoundQueryPart
If source.Type.IsErrorType() Then
' If the source is already a "bad" type, we know that we will not be able to bind to the Select.
' Let's just report errors for the conversion between types, if any.
Dim sourceValue As New BoundRValuePlaceholder(syntax.AsClause, variableType)
ApplyImplicitConversion(syntax.AsClause, targetVariableType, sourceValue, diagnostics)
Else
' Create LambdaSymbol for the shape of the selector.
Dim param As BoundLambdaParameterSymbol = CreateQueryLambdaParameterSymbol(syntax.Identifier.Identifier.ValueText, 0,
variableType,
syntax.AsClause)
Debug.Assert(LambdaUtilities.IsNonUserCodeQueryLambda(syntax.AsClause))
Dim lambdaSymbol = Me.CreateQueryLambdaSymbol(syntax.AsClause,
SynthesizedLambdaKind.ConversionNonUserCodeQueryLambda,
ImmutableArray.Create(param))
lambdaSymbol.SetQueryLambdaReturnType(targetVariableType)
Dim selectorBinder As New QueryLambdaBinder(lambdaSymbol, ImmutableArray(Of RangeVariableSymbol).Empty)
Dim selector As BoundExpression = selectorBinder.ApplyImplicitConversion(syntax.AsClause, targetVariableType,
New BoundParameter(param.Syntax,
param,
isLValue:=False,
type:=variableType).MakeCompilerGenerated(),
diagnostics)
Dim selectorLambda = CreateBoundQueryLambda(lambdaSymbol,
ImmutableArray(Of RangeVariableSymbol).Empty,
selector,
exprIsOperandOfConditionalBranch:=False)
selectorLambda.SetWasCompilerGenerated()
Dim suppressDiagnostics As DiagnosticBag = Nothing
If ShouldSuppressDiagnostics(selectorLambda) Then
' If the selector is already "bad", we know that we will not be able to bind to the Select.
' Let's suppress additional errors.
suppressDiagnostics = DiagnosticBag.GetInstance()
diagnostics = suppressDiagnostics
End If
Dim boundCallOrBadExpression As BoundExpression
boundCallOrBadExpression = BindQueryOperatorCall(syntax.AsClause, source,
StringConstants.SelectMethod,
ImmutableArray.Create(Of BoundExpression)(selectorLambda),
syntax.AsClause.Span,
diagnostics)
Debug.Assert(boundCallOrBadExpression.WasCompilerGenerated)
If suppressDiagnostics IsNot Nothing Then
suppressDiagnostics.Free()
End If
Return New BoundQueryClause(source.Syntax,
boundCallOrBadExpression,
ImmutableArray(Of RangeVariableSymbol).Empty,
targetVariableType,
ImmutableArray.Create(Of Binder)(selectorBinder),
boundCallOrBadExpression.Type).MakeCompilerGenerated()
End If
Return source
End Function
''' <summary>
''' Convert source expression to queryable type by inferring control variable type
''' and applying AsQueryable/AsEnumerable or Cast(Of Object) calls.
'''
''' In case of success, returns possibly "converted" source and non-Nothing controlVariableType.
''' In case of failure, returns passed in source and Nothing as controlVariableType.
''' </summary>
Private Function ConvertToQueryableType(
source As BoundExpression,
diagnostics As DiagnosticBag,
<Out()> ByRef controlVariableType As TypeSymbol
) As BoundExpression
controlVariableType = Nothing
If Not source.IsValue OrElse source.Type.IsErrorType Then
Return source
End If
' 11.21.2 Queryable Types
' A queryable collection type must satisfy one of the following conditions, in order of preference:
' - It must define a conforming Select method.
' - It must have one of the following methods
' Function AsEnumerable() As CT
' Function AsQueryable() As CT
' which can be called to obtain a queryable collection. If both methods are provided, AsQueryable is preferred over AsEnumerable.
' - It must have a method
' Function Cast(Of T)() As CT
' which can be called with the type of the range variable to produce a queryable collection.
' Does it define a conforming Select method?
Dim inferredType As TypeSymbol = InferControlVariableType(source, diagnostics)
If inferredType IsNot Nothing Then
controlVariableType = inferredType
Return source
End If
Dim result As BoundExpression = Nothing
Dim additionalDiagnostics = DiagnosticBag.GetInstance()
' Does it have Function AsQueryable() As CT returning queryable collection?
Dim asQueryable As BoundExpression = BindQueryOperatorCall(source.Syntax, source, StringConstants.AsQueryableMethod,
ImmutableArray(Of BoundExpression).Empty,
source.Syntax.Span, additionalDiagnostics)
If Not asQueryable.HasErrors AndAlso asQueryable.Kind = BoundKind.Call Then
inferredType = InferControlVariableType(asQueryable, diagnostics)
If inferredType IsNot Nothing Then
controlVariableType = inferredType
result = asQueryable
diagnostics.AddRange(additionalDiagnostics)
End If
End If
If result Is Nothing Then
additionalDiagnostics.Clear()
' Does it have Function AsEnumerable() As CT returning queryable collection?
Dim asEnumerable As BoundExpression = BindQueryOperatorCall(source.Syntax, source, StringConstants.AsEnumerableMethod,
ImmutableArray(Of BoundExpression).Empty,
source.Syntax.Span, additionalDiagnostics)
If Not asEnumerable.HasErrors AndAlso asEnumerable.Kind = BoundKind.Call Then
inferredType = InferControlVariableType(asEnumerable, diagnostics)
If inferredType IsNot Nothing Then
controlVariableType = inferredType
result = asEnumerable
diagnostics.AddRange(additionalDiagnostics)
End If
End If
End If
If result Is Nothing Then
additionalDiagnostics.Clear()
' If it has Function Cast(Of T)() As CT, call it with T == Object and assume Object is control variable type.
inferredType = GetSpecialType(SpecialType.System_Object, source.Syntax, additionalDiagnostics)
Dim cast As BoundExpression = BindQueryOperatorCall(source.Syntax, source, StringConstants.CastMethod,
New BoundTypeArguments(source.Syntax,
ImmutableArray.Create(Of TypeSymbol)(inferredType)),
ImmutableArray(Of BoundExpression).Empty,
source.Syntax.Span, additionalDiagnostics)
If Not cast.HasErrors AndAlso cast.Kind = BoundKind.Call Then
controlVariableType = inferredType
result = cast
diagnostics.AddRange(additionalDiagnostics)
End If
End If
additionalDiagnostics.Free()
Debug.Assert((result Is Nothing) = (controlVariableType Is Nothing))
Return If(result Is Nothing, source, result)
End Function
''' <summary>
''' Given query operator source, infer control variable type from available
''' 'Select' methods.
'''
''' Returns inferred type or Nothing.
''' </summary>
Private Function InferControlVariableType(source As BoundExpression, diagnostics As DiagnosticBag) As TypeSymbol
Debug.Assert(source.IsValue)
Dim result As TypeSymbol = Nothing
' Look for Select methods available for the source.
Dim lookupResult As LookupResult = LookupResult.GetInstance()
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
LookupMember(lookupResult, source.Type, StringConstants.SelectMethod, 0, QueryOperatorLookupOptions, useSiteDiagnostics)
If lookupResult.IsGood Then
Dim failedDueToAnAmbiguity As Boolean = False
' Name lookup does not look for extension methods if it found a suitable
' instance method, which is a good thing because according to language spec:
'
' 11.21.2 Queryable Types
' ... , when determining the element type of a collection if there
' are instance methods that match well-known methods, then any extension methods
' that match well-known methods are ignored.
Debug.Assert((QueryOperatorLookupOptions And LookupOptions.EagerlyLookupExtensionMethods) = 0)
result = InferControlVariableType(lookupResult.Symbols, failedDueToAnAmbiguity)
If result Is Nothing AndAlso Not failedDueToAnAmbiguity AndAlso Not lookupResult.Symbols(0).IsReducedExtensionMethod() Then
' We tried to infer from instance methods and there were no suitable 'Select' method,
' let's try to infer from extension methods.
lookupResult.Clear()
Me.LookupExtensionMethods(lookupResult, source.Type, StringConstants.SelectMethod, 0, QueryOperatorLookupOptions, useSiteDiagnostics)
If lookupResult.IsGood Then
result = InferControlVariableType(lookupResult.Symbols, failedDueToAnAmbiguity)
End If
End If
End If
diagnostics.Add(source, useSiteDiagnostics)
lookupResult.Free()
Return result
End Function
''' <summary>
''' Given a set of 'Select' methods, infer control variable type.
'''
''' Returns inferred type or Nothing.
''' </summary>
Private Function InferControlVariableType(
methods As ArrayBuilder(Of Symbol),
<Out()> ByRef failedDueToAnAmbiguity As Boolean
) As TypeSymbol
Dim result As TypeSymbol = Nothing
failedDueToAnAmbiguity = False
For Each method As MethodSymbol In methods
Dim inferredType As TypeSymbol = InferControlVariableType(method)
If inferredType IsNot Nothing Then
If inferredType.ReferencesMethodsTypeParameter(method) Then
failedDueToAnAmbiguity = True
Return Nothing
End If
If result Is Nothing Then
result = inferredType
ElseIf Not result.IsSameTypeIgnoringCustomModifiers(inferredType) Then
failedDueToAnAmbiguity = True
Return Nothing
End If
End If
Next
Return result
End Function
''' <summary>
''' Given a method, infer control variable type.
'''
''' Returns inferred type or Nothing.
''' </summary>
Private Function InferControlVariableType(method As MethodSymbol) As TypeSymbol
' Ignore Subs
If method.IsSub Then
Return Nothing
End If
' Only methods taking exactly one parameter are acceptable.
If method.ParameterCount <> 1 Then
Return Nothing
End If
Dim selectParameter As ParameterSymbol = method.Parameters(0)
If selectParameter.IsByRef Then
Return Nothing
End If
Dim parameterType As TypeSymbol = selectParameter.Type
' We are expecting a delegate type with the following shape:
' Function Selector (element as ControlVariableType) As AType
' The delegate type, directly converted to or argument of Expression(Of T)
Dim delegateType As NamedTypeSymbol = parameterType.DelegateOrExpressionDelegate(Me)
If delegateType Is Nothing Then
Return Nothing
End If
Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod
If invoke Is Nothing OrElse invoke.IsSub OrElse invoke.ParameterCount <> 1 Then
Return Nothing
End If
Dim invokeParameter As ParameterSymbol = invoke.Parameters(0)
' Do not allow Optional, ParamArray and ByRef.
If invokeParameter.IsOptional OrElse invokeParameter.IsByRef OrElse invokeParameter.IsParamArray Then
Return Nothing
End If
Dim controlVariableType As TypeSymbol = invokeParameter.Type
Return If(controlVariableType.IsErrorType(), Nothing, controlVariableType)
End Function
''' <summary>
''' Return method group or Nothing in case nothing was found.
''' Note, returned group might have ResultKind = "Inaccessible".
''' </summary>
Private Function LookupQueryOperator(
node As VisualBasicSyntaxNode,
source As BoundExpression,
operatorName As String,
typeArgumentsOpt As BoundTypeArguments,
diagnostics As DiagnosticBag
) As BoundMethodGroup
Dim lookupResult As LookupResult = LookupResult.GetInstance()
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
LookupMember(lookupResult, source.Type, operatorName, 0, QueryOperatorLookupOptions, useSiteDiagnostics)
Dim methodGroup As BoundMethodGroup = Nothing
' NOTE: Lookup may return Kind = LookupResultKind.Inaccessible or LookupResultKind.MustBeInstance;
'
' It looks we intentionally pass LookupResultKind.Inaccessible to CreateBoundMethodGroup(...)
' causing BC30390 to be generated instead of BC36594 reported by Dev11 (more accurate message?)
'
' As CreateBoundMethodGroup(...) only expects Kind = LookupResultKind.Good or
' LookupResultKind.Inaccessible in all other cases we just skip calling this method
' so that BC36594 is generated which what seems to what Dev11 does.
If Not lookupResult.IsClear AndAlso (lookupResult.Kind = LookupResultKind.Good OrElse lookupResult.Kind = LookupResultKind.Inaccessible) Then
methodGroup = CreateBoundMethodGroup(
node,
lookupResult,
QueryOperatorLookupOptions,
source,
typeArgumentsOpt,
QualificationKind.QualifiedViaValue).MakeCompilerGenerated()
End If
diagnostics.Add(node, useSiteDiagnostics)
lookupResult.Free()
Return methodGroup
End Function
Private Function BindQueryOperatorCall(
node As VisualBasicSyntaxNode,
source As BoundExpression,
operatorName As String,
arguments As ImmutableArray(Of BoundExpression),
operatorNameLocation As TextSpan,
diagnostics As DiagnosticBag
) As BoundExpression
Return BindQueryOperatorCall(node,
source,
operatorName,
LookupQueryOperator(node, source, operatorName, Nothing, diagnostics),
arguments,
operatorNameLocation,
diagnostics)
End Function
Private Function BindQueryOperatorCall(
node As VisualBasicSyntaxNode,
source As BoundExpression,
operatorName As String,
typeArgumentsOpt As BoundTypeArguments,
arguments As ImmutableArray(Of BoundExpression),
operatorNameLocation As TextSpan,
diagnostics As DiagnosticBag
) As BoundExpression
Return BindQueryOperatorCall(node,
source,
operatorName,
LookupQueryOperator(node, source, operatorName, typeArgumentsOpt, diagnostics),
arguments,
operatorNameLocation,
diagnostics)
End Function
''' <summary>
''' [methodGroup] can be Nothing if lookup didn't find anything.
''' </summary>
Private Function BindQueryOperatorCall(
node As VisualBasicSyntaxNode,
source As BoundExpression,
operatorName As String,
methodGroup As BoundMethodGroup,
arguments As ImmutableArray(Of BoundExpression),
operatorNameLocation As TextSpan,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(source.IsValue)
Debug.Assert(methodGroup Is Nothing OrElse
(methodGroup.ReceiverOpt Is source AndAlso
(methodGroup.ResultKind = LookupResultKind.Good OrElse methodGroup.ResultKind = LookupResultKind.Inaccessible)))
Dim boundCall As BoundExpression = Nothing
If methodGroup IsNot Nothing Then
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim results As OverloadResolution.OverloadResolutionResult = OverloadResolution.QueryOperatorInvocationOverloadResolution(methodGroup,
arguments, Me,
useSiteDiagnostics)
If diagnostics.Add(node, useSiteDiagnostics) Then
If methodGroup.ResultKind <> LookupResultKind.Inaccessible Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
End If
If Not results.BestResult.HasValue Then
' Create and report the diagnostic.
If results.Candidates.Length = 0 Then
results = OverloadResolution.QueryOperatorInvocationOverloadResolution(methodGroup, arguments, Me, includeEliminatedCandidates:=True,
useSiteDiagnostics:=useSiteDiagnostics)
End If
If results.Candidates.Length > 0 Then
boundCall = ReportOverloadResolutionFailureAndProduceBoundNode(node, methodGroup, arguments, Nothing, results,
diagnostics, callerInfoOpt:=Nothing, queryMode:=True,
diagnosticLocationOpt:=Location.Create(node.SyntaxTree, operatorNameLocation))
End If
Else
boundCall = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None, methodGroup,
arguments, results.BestResult.Value,
results.AsyncLambdaSubToFunctionMismatch,
diagnostics)
' May need to update return type for LambdaSymbols associated with query lambdas.
For i As Integer = 0 To arguments.Length - 1
Dim arg As BoundExpression = arguments(i)
If arg.Kind = BoundKind.QueryLambda Then
Dim queryLambda = DirectCast(arg, BoundQueryLambda)
If queryLambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then
Dim delegateReturnType As TypeSymbol = DirectCast(boundCall, BoundCall).Method.Parameters(i).Type.DelegateOrExpressionDelegate(Me).DelegateInvokeMethod.ReturnType
queryLambda.LambdaSymbol.SetQueryLambdaReturnType(delegateReturnType)
End If
End If
Next
End If
End If
If boundCall Is Nothing Then
Dim childBoundNodes As ImmutableArray(Of BoundNode)
If arguments.IsEmpty Then
childBoundNodes = ImmutableArray.Create(Of BoundNode)(If(methodGroup, source))
Else
Dim builder = ArrayBuilder(Of BoundNode).GetInstance()
builder.Add(If(methodGroup, source))
builder.AddRange(arguments)
childBoundNodes = builder.ToImmutableAndFree()
End If
If methodGroup Is Nothing Then
boundCall = BadExpression(node, childBoundNodes, ErrorTypeSymbol.UnknownResultType)
Else
Dim symbols = ArrayBuilder(Of Symbol).GetInstance()
methodGroup.GetExpressionSymbols(symbols)
Dim resultKind = LookupResultKind.OverloadResolutionFailure
If methodGroup.ResultKind < resultKind Then
resultKind = methodGroup.ResultKind
End If
boundCall = New BoundBadExpression(node, resultKind, symbols.ToImmutableAndFree(), childBoundNodes, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
End If
If boundCall.HasErrors AndAlso Not source.HasErrors Then
ReportDiagnostic(diagnostics, Location.Create(node.SyntaxTree, operatorNameLocation), ERRID.ERR_QueryOperatorNotFound, operatorName)
End If
boundCall.SetWasCompilerGenerated()
Return boundCall
End Function
End Class
End Namespace
|
VPashkov/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_Query.vb
|
Visual Basic
|
apache-2.0
| 280,023
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
''' <summary>
''' Structure is used to store all information which is needed to construct and classify a Delegate creation
''' expression later on.
''' </summary>
Friend Structure DelegateResolutionResult
' we store the DelegateConversions although it could be derived from MethodConversions to improve performance
Public ReadOnly DelegateConversions As ConversionKind
Public ReadOnly Target As MethodSymbol
Public ReadOnly MethodConversions As MethodConversionKind
Public ReadOnly Diagnostics As ImmutableArray(Of Diagnostic)
Public Sub New(
DelegateConversions As ConversionKind,
Target As MethodSymbol,
MethodConversions As MethodConversionKind,
Diagnostics As ImmutableArray(Of Diagnostic)
)
Me.DelegateConversions = DelegateConversions
Me.Target = Target
Me.Diagnostics = Diagnostics
Me.MethodConversions = MethodConversions
End Sub
End Structure
''' <summary>
''' Binds the AddressOf expression.
''' </summary>
''' <param name="node">The AddressOf expression node.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindAddressOfExpression(node As VisualBasicSyntaxNode, diagnostics As DiagnosticBag) As BoundExpression
Dim addressOfSyntax = DirectCast(node, UnaryExpressionSyntax)
Dim boundOperand = BindExpression(addressOfSyntax.Operand, isInvocationOrAddressOf:=True, diagnostics:=diagnostics, isOperandOfConditionalBranch:=False, eventContext:=False)
If boundOperand.Kind = BoundKind.LateMemberAccess Then
Return New BoundLateAddressOfOperator(node, Me, DirectCast(boundOperand, BoundLateMemberAccess), boundOperand.Type)
End If
' only accept MethodGroups as operands. More detailed checks (e.g. for Constructors follow later)
If boundOperand.Kind <> BoundKind.MethodGroup Then
If Not boundOperand.HasErrors Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_AddressOfOperandNotMethod)
End If
Return BadExpression(addressOfSyntax, boundOperand, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
End If
Dim hasErrors As Boolean = False
Dim group = DirectCast(boundOperand, BoundMethodGroup)
If IsGroupOfConstructors(group) Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_InvalidConstructorCall)
hasErrors = True
End If
Return New BoundAddressOfOperator(node, Me, group, hasErrors)
End Function
''' <summary>
''' Binds the delegate creation expression.
''' This comes in form of e.g.
''' Dim del as new DelegateType(AddressOf methodName)
''' </summary>
''' <param name="delegateType">Type of the delegate.</param>
''' <param name="argumentListOpt">The argument list.</param>
''' <param name="node">Syntax node to attach diagnostics to in case the argument list is nothing.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindDelegateCreationExpression(
delegateType As TypeSymbol,
argumentListOpt As ArgumentListSyntax,
node As VisualBasicSyntaxNode,
diagnostics As DiagnosticBag
) As BoundExpression
Dim boundFirstArgument As BoundExpression = Nothing
Dim argumentCount = 0
If argumentListOpt IsNot Nothing Then
argumentCount = argumentListOpt.Arguments.Count
End If
Dim hadErrorsInFirstArgument = False
' a delegate creation expression should have exactly one argument.
If argumentCount > 0 Then
Dim argumentSyntax = argumentListOpt.Arguments(0)
Dim expressionSyntax As ExpressionSyntax = Nothing
' a delegate creation expression does not care if what the name of a named argument
' was. Just take whatever was passed.
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
' omitted argument will leave expressionSyntax as nothing which means no binding, which is fine.
If expressionSyntax IsNot Nothing Then
If expressionSyntax.Kind = SyntaxKind.AddressOfExpression Then
boundFirstArgument = BindAddressOfExpression(expressionSyntax, diagnostics)
ElseIf expressionSyntax.IsLambdaExpressionSyntax() Then
' this covers the legal cases for SyntaxKind.MultiLineFunctionLambdaExpression,
' SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression and
' SyntaxKind.SingleLineSubLambdaExpression, as well as all the other invalid ones.
boundFirstArgument = BindExpression(expressionSyntax, diagnostics)
End If
If boundFirstArgument IsNot Nothing Then
hadErrorsInFirstArgument = boundFirstArgument.HasErrors
Debug.Assert(boundFirstArgument.Kind = BoundKind.BadExpression OrElse
boundFirstArgument.Kind = BoundKind.LateAddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.AddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.UnboundLambda)
If argumentCount = 1 Then
boundFirstArgument = ApplyImplicitConversion(node,
delegateType,
boundFirstArgument,
diagnostics:=diagnostics)
If boundFirstArgument.Syntax IsNot node Then
' We must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(boundFirstArgument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?")
boundFirstArgument = New BoundConversion(node, boundFirstArgument, ConversionKind.Identity, CheckOverflow, True, delegateType)
End If
Return boundFirstArgument
End If
End If
Else
boundFirstArgument = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundNode).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
End If
Dim ignoredDiagnostics = DiagnosticBag.GetInstance
Dim boundArguments(argumentCount - 1) As BoundExpression
If boundFirstArgument IsNot Nothing Then
boundFirstArgument = MakeRValue(boundFirstArgument, ignoredDiagnostics)
boundArguments(0) = boundFirstArgument
End If
' bind all arguments and ignore all diagnostics. These bound nodes will be passed to
' a BoundBadNode
For argumentIndex = If(boundFirstArgument Is Nothing, 0, 1) To argumentCount - 1
Dim expressionSyntax As ExpressionSyntax = Nothing
Dim argumentSyntax = argumentListOpt.Arguments(argumentIndex)
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
If expressionSyntax IsNot Nothing Then
boundArguments(argumentIndex) = BindValue(expressionSyntax, ignoredDiagnostics)
Else
boundArguments(argumentIndex) = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundNode).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
Next
ignoredDiagnostics.Free()
' the default error message in delegate creations if the passed arguments are empty or not a addressOf
' should be ERRID.ERR_NoDirectDelegateConstruction1
' if binding an AddressOf expression caused diagnostics these should be shown instead
If Not hadErrorsInFirstArgument OrElse
argumentCount <> 1 Then
ReportDiagnostic(diagnostics,
If(argumentListOpt, node),
ERRID.ERR_NoDirectDelegateConstruction1,
delegateType)
End If
Return BadExpression(node,
ImmutableArray.Create(Of BoundNode)(DirectCast(boundArguments, BoundNode())),
delegateType)
End Function
''' <summary>
''' Resolves the target method for the delegate and classifies the conversion
''' </summary>
''' <param name="addressOfExpression">The bound AddressOf expression itself.</param>
''' <param name="targetType">The delegate type to assign the result of the AddressOf operator to.</param>
''' <returns></returns>
Friend Shared Function InterpretDelegateBinding(
addressOfExpression As BoundAddressOfOperator,
targetType As TypeSymbol,
isForHandles As Boolean
) As DelegateResolutionResult
Debug.Assert(targetType IsNot Nothing)
Dim diagnostics = DiagnosticBag.GetInstance()
Dim result As OverloadResolution.OverloadResolutionResult = Nothing
Dim fromMethod As MethodSymbol = Nothing
Dim syntaxTree = addressOfExpression.Syntax
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' must be a delegate, and also a concrete delegate
If targetType.SpecialType = SpecialType.System_Delegate OrElse
targetType.SpecialType = SpecialType.System_MulticastDelegate Then
' 'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotCreatableDelegate1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
ElseIf targetType.TypeKind <> TypeKind.Delegate Then
' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.
If targetType.TypeKind <> TypeKind.Error Then
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotDelegate1, targetType)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod
If delegateInvoke IsNot Nothing Then
If addressOfExpression.Binder.ReportDelegateInvokeUseSiteError(diagnostics, syntaxTree, targetType, delegateInvoke) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
' todo(rbeckers) if (IsLateReference(addressOfExpression))
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression,
delegateInvoke,
False,
diagnostics)
fromMethod = matchingMethod.Key
methodConversions = matchingMethod.Value
End If
Else
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_UnsupportedMethod1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' show diagnostics if the an instance method is used in a shared context.
If fromMethod IsNot Nothing Then
' Generate an error, but continue processing
If addressOfExpression.Binder.CheckSharedSymbolAccess(addressOfExpression.Syntax,
fromMethod.IsShared,
addressOfExpression.MethodGroup.ReceiverOpt,
addressOfExpression.MethodGroup.QualificationKind,
diagnostics) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' TODO: Check boxing of restricted types, report ERRID_RestrictedConversion1 and continue.
Dim receiver As BoundExpression = addressOfExpression.MethodGroup.ReceiverOpt
If fromMethod IsNot Nothing Then
If fromMethod.IsMustOverride AndAlso receiver IsNot Nothing AndAlso
(receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then
' Generate an error, but continue processing
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax,
If(receiver.IsMyBaseReference,
ERRID.ERR_MyBaseAbstractCall1,
ERRID.ERR_MyClassAbstractCall1),
fromMethod)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
If Not fromMethod.IsShared AndAlso
fromMethod.ContainingType.IsNullableType AndAlso
Not fromMethod.IsOverrides Then
Dim addressOfSyntax As VisualBasicSyntaxNode = addressOfExpression.Syntax
Dim addressOfExpressionSyntax = DirectCast(addressOfExpression.Syntax, UnaryExpressionSyntax)
If (addressOfExpressionSyntax IsNot Nothing) Then
addressOfSyntax = addressOfExpressionSyntax.Operand
End If
' Generate an error, but continue processing
ReportDiagnostic(diagnostics,
addressOfSyntax,
ERRID.ERR_AddressOfNullableMethod,
fromMethod.ContainingType,
SyntaxFacts.GetText(SyntaxKind.AddressOfKeyword))
' There's no real need to set MethodConversionKind.Error because there are no overloads of the same method where one
' may be legal to call because it's shared and the other's not.
' However to be future proof, we set it regardless.
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
addressOfExpression.Binder.ReportDiagnosticsIfObsolete(diagnostics, fromMethod, addressOfExpression.MethodGroup.Syntax)
End If
Dim delegateConversions As ConversionKind = Conversions.DetermineDelegateRelaxationLevel(methodConversions)
If (delegateConversions And ConversionKind.DelegateRelaxationLevelInvalid) <> ConversionKind.DelegateRelaxationLevelInvalid Then
If Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=Not isForHandles) Then
delegateConversions = delegateConversions Or ConversionKind.Narrowing
Else
delegateConversions = delegateConversions Or ConversionKind.Widening
End If
End If
Return New DelegateResolutionResult(delegateConversions, fromMethod, methodConversions, diagnostics.ToReadOnlyAndFree())
End Function
Friend Function ReportDelegateInvokeUseSiteError(
diagBag As DiagnosticBag,
syntax As VisualBasicSyntaxNode,
delegateType As TypeSymbol,
invoke As MethodSymbol
) As Boolean
Debug.Assert(delegateType IsNot Nothing)
Debug.Assert(invoke IsNot Nothing)
Dim useSiteErrorInfo As DiagnosticInfo = invoke.GetUseSiteErrorInfo()
If useSiteErrorInfo IsNot Nothing Then
If useSiteErrorInfo.Code = ERRID.ERR_UnsupportedMethod1 Then
ReportDiagnostic(diagBag, syntax, ERRID.ERR_UnsupportedMethod1, delegateType)
Else
ReportDiagnostic(diagBag, syntax, useSiteErrorInfo)
End If
Return True
End If
Return False
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <returns>The resolved method if any.</returns>
Friend Shared Function ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As DiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim argumentDiagnostics = DiagnosticBag.GetInstance
Dim couldTryZeroArgumentRelaxation As Boolean = True
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
argumentDiagnostics,
useZeroArgumentRelaxation:=False,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' If there have been parameters and if there was no ambiguous match before, try zero argument relaxation.
If matchingMethod.Key Is Nothing AndAlso couldTryZeroArgumentRelaxation Then
Dim zeroArgumentDiagnostics = DiagnosticBag.GetInstance
Dim argumentMatchingMethod = matchingMethod
matchingMethod = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
zeroArgumentDiagnostics,
useZeroArgumentRelaxation:=True,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' if zero relaxation did not find something, we'll report the diagnostics of the
' non zero relaxation try, else the diagnostics of the zero argument relaxation.
If matchingMethod.Key Is Nothing Then
diagnostics.AddRange(argumentDiagnostics)
matchingMethod = argumentMatchingMethod
Else
diagnostics.AddRange(zeroArgumentDiagnostics)
End If
zeroArgumentDiagnostics.Free()
Else
diagnostics.AddRange(argumentDiagnostics)
End If
argumentDiagnostics.Free()
' check that there's not method returned if there is no conversion.
Debug.Assert(matchingMethod.Key Is Nothing OrElse (matchingMethod.Value And MethodConversionKind.AllErrorReasons) = 0)
Return matchingMethod
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <param name="useZeroArgumentRelaxation">if set to <c>true</c> use zero argument relaxation.</param>
''' <returns>The resolved method if any.</returns>
Private Shared Function ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As DiagnosticBag,
useZeroArgumentRelaxation As Boolean,
ByRef couldTryZeroArgumentRelaxation As Boolean
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim boundArguments = ImmutableArray(Of BoundExpression).Empty
If Not useZeroArgumentRelaxation Then
' build array of bound expressions for overload resolution (BoundLocal is easy to create)
Dim toMethodParameters = toMethod.Parameters
Dim parameterCount = toMethodParameters.Length
If parameterCount > 0 Then
Dim boundParameterArguments(parameterCount - 1) As BoundExpression
Dim argumentIndex As Integer = 0
Dim syntaxTree As SyntaxTree
Dim addressOfSyntax = addressOfExpression.Syntax
syntaxTree = addressOfExpression.Binder.SyntaxTree
For Each parameter In toMethodParameters
Dim parameterType = parameter.Type
Dim tempParamSymbol = New SynthesizedLocal(toMethod, parameterType, SynthesizedLocalKind.LoweringTemp)
' TODO: Switch to using BoundValuePlaceholder, but we need it to be able to appear
' as an LValue in case of a ByRef parameter.
Dim tempBoundParameter As BoundExpression = New BoundLocal(addressOfSyntax,
tempParamSymbol,
parameterType)
' don't treat ByVal parameters as lvalues in the following OverloadResolution
If Not parameter.IsByRef Then
tempBoundParameter = tempBoundParameter.MakeRValue()
End If
boundParameterArguments(argumentIndex) = tempBoundParameter
argumentIndex += 1
Next
boundArguments = boundParameterArguments.AsImmutableOrNull()
Else
couldTryZeroArgumentRelaxation = False
End If
End If
Dim delegateReturnType As TypeSymbol
Dim delegateReturnTypeReferenceBoundNode As BoundNode
If ignoreMethodReturnType Then
' Keep them Nothing such that the delegate's return type won't be taken part of in overload resolution
' when we are inferring the return type.
delegateReturnType = Nothing
delegateReturnTypeReferenceBoundNode = Nothing
Else
delegateReturnType = toMethod.ReturnType
delegateReturnTypeReferenceBoundNode = addressOfExpression
End If
' Let's go through overload resolution, pretending that Option Strict is Off and see if it succeeds.
Dim resolutionBinder As Binder
If addressOfExpression.Binder.OptionStrict <> VisualBasic.OptionStrict.Off Then
resolutionBinder = New OptionStrictOffBinder(addressOfExpression.Binder)
Else
resolutionBinder = addressOfExpression.Binder
End If
Debug.Assert(resolutionBinder.OptionStrict = VisualBasic.OptionStrict.Off)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfExpression.MethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=False,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteDiagnostics:=useSiteDiagnostics)
If diagnostics.Add(addressOfExpression.MethodGroup, useSiteDiagnostics) Then
couldTryZeroArgumentRelaxation = False
If addressOfExpression.MethodGroup.ResultKind <> LookupResultKind.Inaccessible Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
End If
Dim addressOfMethodGroup = addressOfExpression.MethodGroup
If resolutionResult.BestResult.HasValue Then
Return ValidateMethodForDelegateInvoke(
addressOfExpression,
resolutionResult.BestResult.Value,
toMethod,
ignoreMethodReturnType,
useZeroArgumentRelaxation,
diagnostics)
End If
' Overload Resolution didn't find a match
If resolutionResult.Candidates.Length = 0 Then
resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfMethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=True,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteDiagnostics:=useSiteDiagnostics)
End If
Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance()
Dim bestSymbols = ImmutableArray(Of Symbol).Empty
Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(resolutionResult, bestCandidates, bestSymbols)
Debug.Assert(bestCandidates.Count > 0 AndAlso bestCandidates.Count > 0)
Dim bestCandidatesState As OverloadResolution.CandidateAnalysisResultState = bestCandidates(0).State
If bestCandidatesState = VisualBasic.OverloadResolution.CandidateAnalysisResultState.Applicable Then
' if there is an applicable candidate in the list, we know it must be an ambiguous match
' (or there are more applicable candidates in this list), otherwise this would have been
' the best match.
Debug.Assert(bestCandidates.Count > 1 AndAlso bestSymbols.Length > 1)
' there are multiple candidates, so it ambiguous and zero argument relaxation will not be tried,
' unless the candidates require narrowing.
If Not bestCandidates(0).RequiresNarrowingConversion Then
couldTryZeroArgumentRelaxation = False
End If
End If
If bestSymbols.Length = 1 AndAlso
(bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch) Then
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
bestSymbols(0), useSiteDiagnostics:=Nothing))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
resolutionBinder.ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
DirectCast(bestSymbols(0), MethodSymbol),
diagnostics)
Else
If bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.Ambiguous Then
couldTryZeroArgumentRelaxation = False
End If
Dim unused = resolutionBinder.ReportOverloadResolutionFailureAndProduceBoundNode(
addressOfExpression.MethodGroup.Syntax,
addressOfMethodGroup,
bestCandidates,
bestSymbols,
commonReturnType,
boundArguments,
Nothing,
diagnostics,
delegateSymbol:=toMethod.ContainingType,
callerInfoOpt:=Nothing)
End If
bestCandidates.Free()
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, MethodConversionKind.Error_OverloadResolution)
End Function
Private Shared Function ValidateMethodForDelegateInvoke(
addressOfExpression As BoundAddressOfOperator,
analysisResult As OverloadResolution.CandidateAnalysisResult,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
useZeroArgumentRelaxation As Boolean,
diagnostics As DiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' determine conversions based on return type
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If Not ignoreMethodReturnType Then
methodConversions = methodConversions Or Conversions.ClassifyMethodConversionBasedOnReturnType(analysisResult.Candidate.ReturnType, toMethod.ReturnType, useSiteDiagnostics)
If diagnostics.Add(addressOfOperandSyntax, useSiteDiagnostics) Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
End If
If useZeroArgumentRelaxation Then
Debug.Assert(toMethod.ParameterCount > 0)
' special flag for ignoring all arguments (zero argument relaxation)
If analysisResult.Candidate.ParameterCount = 0 Then
methodConversions = methodConversions Or MethodConversionKind.AllArgumentsIgnored
Else
' We can get here if all method's parameters are Optional/ParamArray, however,
' according to the language spec, zero arguments relaxation is allowed only
' if target method has no parameters. Here is the quote:
' "method referenced by the method pointer, but it is not applicable due to
' the fact that it has no parameters and the delegate type does, then the method
' is considered applicable and the parameters are simply ignored."
'
' There is a bug in Dev10, sometimes it erroneously allows zero-argument relaxation against
' a method with optional parameters, if parameters of the delegate invoke can be passed to
' the method (i.e. without dropping them). See unit-test Bug12211 for an example.
methodConversions = methodConversions Or MethodConversionKind.Error_IllegalToIgnoreAllArguments
End If
Else
' determine conversions based on arguments
methodConversions = methodConversions Or GetDelegateMethodConversionBasedOnArguments(analysisResult, toMethod, useSiteDiagnostics)
If diagnostics.Add(addressOfOperandSyntax, useSiteDiagnostics) Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
End If
Dim targetMethodSymbol = DirectCast(analysisResult.Candidate.UnderlyingSymbol, MethodSymbol)
If Conversions.IsDelegateRelaxationSupportedFor(methodConversions) Then
Dim typeArgumentInferenceDiagnosticsOpt = analysisResult.TypeArgumentInferenceDiagnosticsOpt
If typeArgumentInferenceDiagnosticsOpt IsNot Nothing Then
diagnostics.AddRange(typeArgumentInferenceDiagnosticsOpt)
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good Then
addressOfExpression.Binder.CheckMemberTypeAccessibility(diagnostics, addressOfOperandSyntax, targetMethodSymbol)
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(targetMethodSymbol, methodConversions)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
addressOfExpression.Binder.ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
targetMethodSymbol,
diagnostics)
End If
Debug.Assert((methodConversions And MethodConversionKind.AllErrorReasons) <> 0)
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
analysisResult.Candidate.UnderlyingSymbol, useSiteDiagnostics:=Nothing))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, methodConversions)
End Function
Private Sub ReportDelegateBindingMismatchStrictOff(
syntax As VisualBasicSyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As DiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
Private Sub ReportDelegateBindingIncompatible(
syntax As VisualBasicSyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As DiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
''' <summary>
''' Determines the method conversion for delegates based on the arguments.
''' </summary>
''' <param name="bestResult">The resolution result.</param>
''' <param name="delegateInvoke">The delegate invoke method.</param>
Private Shared Function GetDelegateMethodConversionBasedOnArguments(
bestResult As OverloadResolution.CandidateAnalysisResult,
delegateInvoke As MethodSymbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As MethodConversionKind
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' in contrast to the native compiler we know that there is a legal conversion and we do not
' need to classify invalid conversions.
' however there is still the ParamArray expansion that needs special treatment.
' if there is one conversion needed, the array ConversionsOpt contains all conversions for all used parameters
' (including e.g. identity conversion). If a ParamArray was expanded, there will be a conversion for each
' expanded parameter.
Dim bestCandidate As OverloadResolution.Candidate = bestResult.Candidate
Dim candidateParameterCount = bestCandidate.ParameterCount
Dim candidateLastParameterIndex = candidateParameterCount - 1
Dim delegateParameterCount = delegateInvoke.ParameterCount
Dim lastCommonIndex = Math.Min(candidateParameterCount, delegateParameterCount) - 1
' IsExpandedParamArrayForm is true if there was no, one or more parameters given for the ParamArray
' Note: if an array was passed, IsExpandedParamArrayForm is false.
If bestResult.IsExpandedParamArrayForm Then
' Dev10 always sets the ExcessOptionalArgumentsOnTarget whenever the last parameter of the target was a
' ParamArray. This forces a stub for the ParamArray conversion, that is needed for the ParamArray in any case.
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
ElseIf candidateParameterCount > delegateParameterCount Then
' An omission of optional parameters for expanded ParamArray form doesn't add anything new for
' the method conversion. Non-expanded ParamArray form, would be dismissed by overload resolution
' if there were omitted optional parameters because it is illegal to omit the ParamArray argument
' in non-expanded form.
' there are optional parameters that have not been exercised by the delegate.
' e.g. Delegate Sub(b As Byte) -> Sub Target(b As Byte, Optional c as Byte)
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
#If DEBUG Then
' check that all unused parameters on the target are optional
For parameterIndex = delegateParameterCount To candidateParameterCount - 1
Debug.Assert(bestCandidate.Parameters(parameterIndex).IsOptional)
Next
#End If
ElseIf lastCommonIndex >= 0 AndAlso
bestCandidate.Parameters(lastCommonIndex).IsParamArray AndAlso
delegateInvoke.Parameters(lastCommonIndex).IsByRef AndAlso
bestCandidate.Parameters(lastCommonIndex).IsByRef AndAlso
Not bestResult.ConversionsOpt.IsDefaultOrEmpty AndAlso
Not Conversions.IsIdentityConversion(bestResult.ConversionsOpt(lastCommonIndex).Key) Then
' Dev10 has the following behavior that needs to be re-implemented:
' Using
' Sub Target(ByRef Base())
' with a
' Delegate Sub Del(ByRef ParamArray Base())
' does not create a stub and the values are transported ByRef
' however using a
' Sub Target(ByRef ParamArray Base())
' with a
' Delegate Del(ByRef Derived()) (with or without ParamArray, works with Option Strict Off only)
' creates a stub and transports the values ByVal.
' Note: if the ParamArray is not expanded, the parameter count must match
Debug.Assert(candidateParameterCount = delegateParameterCount)
Debug.Assert(Conversions.IsWideningConversion(bestResult.ConversionsOpt(lastCommonIndex).Key))
Dim conv = Conversions.ClassifyConversion(bestCandidate.Parameters(lastCommonIndex).Type,
delegateInvoke.Parameters(lastCommonIndex).Type,
useSiteDiagnostics)
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conv.Key,
delegateInvoke.Parameters(lastCommonIndex).Type)
End If
' the overload resolution does not consider ByRef/ByVal mismatches, so we need to check the
' parameters here.
' first iterate over the common parameters
For parameterIndex = 0 To lastCommonIndex
If delegateInvoke.Parameters(parameterIndex).IsByRef <> bestCandidate.Parameters(parameterIndex).IsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
' after the loop above the remaining parameters on the target can only be optional and/or a ParamArray
If bestResult.IsExpandedParamArrayForm AndAlso
(methodConversions And MethodConversionKind.Error_ByRefByValMismatch) <> MethodConversionKind.Error_ByRefByValMismatch Then
' if delegateParameterCount is smaller than targetParameterCount the for loop does not
' execute
Dim lastTargetParameterIsByRef = bestCandidate.Parameters(candidateLastParameterIndex).IsByRef
Debug.Assert(bestCandidate.Parameters(candidateLastParameterIndex).IsParamArray)
For parameterIndex = lastCommonIndex + 1 To delegateParameterCount - 1
' test against the last parameter of the target method
If delegateInvoke.Parameters(parameterIndex).IsByRef <> lastTargetParameterIsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
End If
' there have been conversions, check them all
If Not bestResult.ConversionsOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsOpt.Length - 1
Dim conversion = bestResult.ConversionsOpt(conversionIndex)
Dim delegateParameterType = delegateInvoke.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
delegateParameterType)
Next
End If
' in case of ByRef, there might also be backward conversions
If Not bestResult.ConversionsBackOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsBackOpt.Length - 1
Dim conversion = bestResult.ConversionsBackOpt(conversionIndex)
If Not Conversions.IsIdentityConversion(conversion.Key) Then
Dim targetMethodParameterType = bestCandidate.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
targetMethodParameterType)
End If
Next
End If
Return methodConversions
End Function
''' <summary>
''' Classifies the address of conversion.
''' </summary>
''' <param name="source">The bound AddressOf expression.</param>
''' <param name="destination">The target type to convert this AddressOf expression to.</param><returns></returns>
Friend Shared Function ClassifyAddressOfConversion(
source As BoundAddressOfOperator,
destination As TypeSymbol
) As ConversionKind
Return source.GetConversionClassification(destination)
End Function
Private Shared ReadOnly s_checkDelegateParameterModifierCallback As CheckParameterModifierDelegate = AddressOf CheckDelegateParameterModifier
''' <summary>
''' Checks if a parameter is a ParamArray and reports this as an error.
''' </summary>
''' <param name="container">The containing type.</param>
''' <param name="token">The current parameter token.</param>
''' <param name="flag">The flags of this parameter.</param>
''' <param name="diagnostics">The diagnostics.</param>
Private Shared Function CheckDelegateParameterModifier(
container As Symbol,
token As SyntaxToken,
flag As SourceParameterFlags,
diagnostics As DiagnosticBag
) As SourceParameterFlags
' 9.2.5.4: ParamArray parameters may not be specified in delegate or event declarations.
If (flag And SourceParameterFlags.ParamArray) = SourceParameterFlags.ParamArray Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_ParamArrayIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.ParamArray)
End If
' 9.2.5.3 Optional parameters may not be specified on delegate or event declarations
If (flag And SourceParameterFlags.Optional) = SourceParameterFlags.Optional Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_OptionalIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.Optional)
End If
Return flag
End Function
Private Shared Function GetDelegateOrEventKeywordText(sym As Symbol) As String
Dim keyword As SyntaxKind
If sym.Kind = SymbolKind.Event Then
keyword = SyntaxKind.EventKeyword
ElseIf TypeOf sym.ContainingType Is SynthesizedEventDelegateSymbol Then
keyword = SyntaxKind.EventKeyword
Else
keyword = SyntaxKind.DelegateKeyword
End If
Return SyntaxFacts.GetText(keyword)
End Function
''' <summary>
''' Reclassifies the bound address of operator into a delegate creation expression (if there is no delegate
''' relaxation required) or into a bound lambda expression (which gets a delegate creation expression later on)
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="delegateResolutionResult">The delegate resolution result.</param>
''' <param name="targetType">Type of the target.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Friend Function ReclassifyAddressOf(
addressOfExpression As BoundAddressOfOperator,
ByRef delegateResolutionResult As DelegateResolutionResult,
targetType As TypeSymbol,
diagnostics As DiagnosticBag,
isForHandles As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean
) As BoundExpression
If addressOfExpression.HasErrors Then
Return addressOfExpression
End If
Dim boundLambda As BoundLambda = Nothing
Dim relaxationReceiverPlaceholder As BoundRValuePlaceholder = Nothing
Dim syntaxNode = addressOfExpression.Syntax
Dim targetMethod As MethodSymbol = delegateResolutionResult.Target
Dim reducedFromDefinition As MethodSymbol = targetMethod.ReducedFrom
Dim sourceMethodGroup = addressOfExpression.MethodGroup
Dim receiver As BoundExpression = sourceMethodGroup.ReceiverOpt
Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing
If receiver IsNot Nothing AndAlso
Not addressOfExpression.HasErrors AndAlso
Not delegateResolutionResult.Diagnostics.HasAnyErrors Then
receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, targetMethod.IsShared, diagnostics, resolvedTypeOrValueReceiver)
End If
If Me.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingConversion(delegateResolutionResult.DelegateConversions) Then
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
ReportDelegateBindingMismatchStrictOff(addressOfOperandSyntax, DirectCast(targetType, NamedTypeSymbol), targetMethod, diagnostics)
Else
' When the target method is an extension method, we are creating so called curried delegate.
' However, CLR doesn't support creating curried delegates that close over a ByRef 'this' argument.
' A similar problem exists when the 'this' argument is a value type. For these cases we need a stub too,
' but they are not covered by MethodConversionKind.
If Conversions.IsStubRequiredForMethodConversion(delegateResolutionResult.MethodConversions) OrElse
(reducedFromDefinition IsNot Nothing AndAlso
(reducedFromDefinition.Parameters(0).IsByRef OrElse
targetMethod.ReceiverType.IsTypeParameter() OrElse
targetMethod.ReceiverType.IsValueType)) Then
' because of a delegate relaxation there is a conversion needed to create a delegate instance.
' We will create a lambda with the exact signature of the delegate. This lambda itself will
' call the target method.
boundLambda = BuildDelegateRelaxationLambda(syntaxNode, sourceMethodGroup.Syntax, receiver, targetMethod,
sourceMethodGroup.TypeArgumentsOpt, sourceMethodGroup.QualificationKind,
DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod,
delegateResolutionResult.DelegateConversions And ConversionKind.DelegateRelaxationLevelMask,
isZeroArgumentKnownToBeUsed:=(delegateResolutionResult.MethodConversions And MethodConversionKind.AllArgumentsIgnored) <> 0,
diagnostics:=diagnostics,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
relaxationReceiverPlaceholder:=relaxationReceiverPlaceholder)
End If
End If
Dim target As MethodSymbol = delegateResolutionResult.Target
' Check if the target is a partial method without implementation provided
If Not isForHandles AndAlso target.IsPartialWithoutImplementation Then
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax, ERRID.ERR_NoPartialMethodInAddressOf1, target)
End If
Dim newReceiver As BoundExpression
If receiver IsNot Nothing Then
If receiver.IsPropertyOrXmlPropertyAccess() Then
receiver = MakeRValue(receiver, diagnostics)
End If
newReceiver = Nothing
Else
newReceiver = If(resolvedTypeOrValueReceiver, sourceMethodGroup.ReceiverOpt)
End If
sourceMethodGroup = sourceMethodGroup.Update(sourceMethodGroup.TypeArgumentsOpt,
sourceMethodGroup.Methods,
sourceMethodGroup.PendingExtensionMethodsOpt,
sourceMethodGroup.ResultKind,
newReceiver,
sourceMethodGroup.QualificationKind)
' the delegate creation has the lambda stored internally to not clutter the bound tree with synthesized nodes
' in the first pass. Later on in the DelegateRewriter the node get's rewritten with the lambda if needed.
Return New BoundDelegateCreationExpression(syntaxNode,
receiver,
target,
boundLambda,
relaxationReceiverPlaceholder,
sourceMethodGroup,
targetType,
hasErrors:=False)
End Function
Private Function BuildDelegateRelaxationLambda(
syntaxNode As VisualBasicSyntaxNode,
methodGroupSyntax As VisualBasicSyntaxNode,
receiver As BoundExpression,
targetMethod As MethodSymbol,
typeArgumentsOpt As BoundTypeArguments,
qualificationKind As QualificationKind,
delegateInvoke As MethodSymbol,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As DiagnosticBag,
<Out()> ByRef relaxationReceiverPlaceholder As BoundRValuePlaceholder
) As BoundLambda
relaxationReceiverPlaceholder = Nothing
Dim unconstructedTargetMethod As MethodSymbol = targetMethod.ConstructedFrom
If typeArgumentsOpt Is Nothing AndAlso unconstructedTargetMethod.IsGenericMethod Then
typeArgumentsOpt = New BoundTypeArguments(methodGroupSyntax,
targetMethod.TypeArguments)
typeArgumentsOpt.SetWasCompilerGenerated()
End If
Dim actualReceiver As BoundExpression = receiver
' Figure out if we need to capture the receiver in a temp before creating the lambda
' in order to enforce correct semantics.
If actualReceiver IsNot Nothing AndAlso actualReceiver.IsValue() AndAlso Not actualReceiver.HasErrors Then
If actualReceiver.IsInstanceReference() AndAlso targetMethod.ReceiverType.IsReferenceType Then
Debug.Assert(Not actualReceiver.Type.IsTypeParameter())
Debug.Assert(Not actualReceiver.IsLValue) ' See the comment below why this is important.
Else
' Will need to capture the receiver in a temp, rewriter do the job.
relaxationReceiverPlaceholder = New BoundRValuePlaceholder(actualReceiver.Syntax, actualReceiver.Type)
actualReceiver = relaxationReceiverPlaceholder
End If
End If
Dim methodGroup = New BoundMethodGroup(methodGroupSyntax,
typeArgumentsOpt,
ImmutableArray.Create(unconstructedTargetMethod),
LookupResultKind.Good,
actualReceiver,
qualificationKind)
methodGroup.SetWasCompilerGenerated()
Return BuildDelegateRelaxationLambda(syntaxNode,
delegateInvoke,
methodGroup,
delegateRelaxation,
isZeroArgumentKnownToBeUsed,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
diagnostics)
End Function
''' <summary>
''' Build a lambda that has a shape of the [delegateInvoke] and calls
''' the only method from the [methodGroup] passing all parameters of the lambda
''' as arguments for the call.
''' Note, that usually the receiver of the [methodGroup] should be captured before entering the
''' relaxation lambda in order to prevent its reevaluation every time the lambda is invoked and
''' prevent its mutation.
'''
''' !!! Therefore, it is not common to call this overload directly. !!!
'''
''' </summary>
''' <param name="syntaxNode">Location to use for various synthetic nodes and symbols.</param>
''' <param name="delegateInvoke">The Invoke method to "implement".</param>
''' <param name="methodGroup">The method group with the only method in it.</param>
''' <param name="delegateRelaxation">Delegate relaxation to store within the new BoundLambda node.</param>
''' <param name="diagnostics"></param>
Private Function BuildDelegateRelaxationLambda(
syntaxNode As VisualBasicSyntaxNode,
delegateInvoke As MethodSymbol,
methodGroup As BoundMethodGroup,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As DiagnosticBag
) As BoundLambda
Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke)
Debug.Assert(methodGroup.Methods.Length = 1)
Debug.Assert(methodGroup.PendingExtensionMethodsOpt Is Nothing)
Debug.Assert((delegateRelaxation And (Not ConversionKind.DelegateRelaxationLevelMask)) = 0)
' build lambda symbol parameters matching the invocation method exactly. To do this,
' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method.
Dim delegateInvokeReturnType = delegateInvoke.ReturnType
Dim invokeParameters = delegateInvoke.Parameters
Dim invokeParameterCount = invokeParameters.Length
Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol
Dim addressOfLocation As Location = syntaxNode.GetLocation()
For parameterIndex = 0 To invokeParameterCount - 1
Dim parameter = invokeParameters(parameterIndex)
lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex),
parameter.Ordinal,
parameter.Type,
parameter.IsByRef,
syntaxNode,
addressOfLocation)
Next
' even if the return value is dropped, we're using the delegate's return type for
' this lambda symbol.
Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.DelegateRelaxationStub,
syntaxNode,
lambdaSymbolParameters.AsImmutableOrNull,
delegateInvokeReturnType,
Me)
' the body of the lambda only contains a call to the target (or a return of the return value of
' the call in case of a function)
' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except
' we are implementing a zero argument relaxation.
' These parameters will be used in the method invocation as passed parameters.
Dim method As MethodSymbol = methodGroup.Methods(0)
Dim droppedArguments = isZeroArgumentKnownToBeUsed OrElse (invokeParameterCount > 0 AndAlso method.ParameterCount = 0)
Dim targetParameterCount = If(droppedArguments, 0, invokeParameterCount)
Dim lambdaBoundParameters(targetParameterCount - 1) As BoundExpression
If Not droppedArguments Then
For parameterIndex = 0 To lambdaSymbolParameters.Count - 1
Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex)
Dim boundParameter = New BoundParameter(syntaxNode,
lambdaSymbolParameter,
lambdaSymbolParameter.Type)
boundParameter.SetWasCompilerGenerated()
lambdaBoundParameters(parameterIndex) = boundParameter
Next
End If
'The invocation of the target method must be bound in the context of the lambda
'The reason is that binding the invoke may introduce local symbols and they need
'to be properly parented to the lambda and not to the outer method.
Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, Me)
' Dev10 ignores the type characters used in the operand of an AddressOf operator.
' NOTE: we suppress suppressAbstractCallDiagnostics because it
' should have been reported already
Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindInvocationExpression(syntaxNode,
syntaxNode,
TypeCharacter.None,
methodGroup,
lambdaBoundParameters.AsImmutableOrNull,
Nothing,
diagnostics,
suppressAbstractCallDiagnostics:=True,
callerInfoOpt:=Nothing)
boundInvocationExpression.SetWasCompilerGenerated()
' In case of a function target that got assigned to a sub delegate, the return value will be dropped
Dim statementList As ImmutableArray(Of BoundStatement) = Nothing
If lambdaSymbol.IsSub Then
Dim statements(1) As BoundStatement
Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression)
boundStatement.SetWasCompilerGenerated()
statements(0) = boundStatement
boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing)
boundStatement.SetWasCompilerGenerated()
statements(1) = boundStatement
statementList = statements.AsImmutableOrNull
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation AndAlso
Not method.IsSub Then
If Not method.IsAsync Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = False
If method.MethodKind = MethodKind.DelegateInvoke AndAlso
methodGroup.ReceiverOpt IsNot Nothing AndAlso
methodGroup.ReceiverOpt.Kind = BoundKind.Conversion Then
Dim receiver = DirectCast(methodGroup.ReceiverOpt, BoundConversion)
If Not receiver.ExplicitCastInCode AndAlso
receiver.Operand.Kind = BoundKind.Lambda AndAlso
DirectCast(receiver.Operand, BoundLambda).LambdaSymbol.IsAsync AndAlso
receiver.Type.IsDelegateType() AndAlso
receiver.Type.IsAnonymousType Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = True
End If
End If
Else
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = method.ContainingAssembly Is Compilation.Assembly
End If
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation Then
ReportDiagnostic(diagnostics, syntaxNode, ERRID.WRN_UnobservedAwaitableDelegate)
End If
End If
Else
' process conversions between the return types of the target and invoke function if needed.
boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode,
delegateInvokeReturnType,
boundInvocationExpression,
diagnostics)
Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode,
boundInvocationExpression,
Nothing,
Nothing)
returnstmt.SetWasCompilerGenerated()
statementList = ImmutableArray.Create(returnstmt)
End If
Dim lambdaBody = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
statementList)
lambdaBody.SetWasCompilerGenerated()
Dim boundLambda = New BoundLambda(syntaxNode,
lambdaSymbol,
lambdaBody,
ImmutableArray(Of Diagnostic).Empty,
Nothing,
delegateRelaxation,
MethodConversionKind.Identity)
boundLambda.SetWasCompilerGenerated()
Return boundLambda
End Function
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_Delegates.vb
|
Visual Basic
|
apache-2.0
| 73,390
|
' 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.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions
Friend Class NameOfKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
If context.IsAnyExpressionContext Then
Return {CreateRecommendedKeywordForIntrinsicOperator(
SyntaxKind.NameOfKeyword,
VBFeaturesResources.NameOfFunction,
Glyph.MethodPublic,
New NameOfExpressionDocumentation(),
context.SemanticModel,
context.Position)}
End If
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End Function
End Class
End Namespace
|
KevinRansom/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Expressions/NameOfKeywordRecommender.vb
|
Visual Basic
|
apache-2.0
| 1,277
|
NameSpace Models.DMSCON
Partial Public Class ApplicationDocumentCommand
Inherits DMS.Base.Models.GenericEntity
#Region " Properties "
Public Overrides Property ID As String
Get
Return "{0}".FormatWith(AppDocCmdID)
End Get
Set(value as String)
AppDocCmdID=ToIntegerDB(value)
End Set
End Property
Private _AppCommand As String = "" ' Column 4
Public Property AppCommand As String
Get
Return _AppCommand
End Get
Set(value as String)
SetProperty(_AppCommand,value,"AppCommand")
End Set
End Property
Private _AppDocCmdID As Integer = -1 ' Column 0
Public Property AppDocCmdID As Integer
Get
Return _AppDocCmdID
End Get
Set(value as Integer)
SetProperty(_AppDocCmdID,value,"AppDocCmdID",{"ID"})
End Set
End Property
Private _AppDocID As Integer = -1 ' Column 1
Public Property AppDocID As Integer
Get
Return _AppDocID
End Get
Set(value as Integer)
SetProperty(_AppDocID,value,"AppDocID")
End Set
End Property
Private _CommandType As String = "" ' Column 6
Public Property CommandType As String
Get
Return _CommandType
End Get
Set(value as String)
SetProperty(_CommandType,value,"CommandType")
End Set
End Property
Private _CreateENHFile As Boolean = False ' Column 7
Public Property CreateENHFile As Boolean
Get
Return _CreateENHFile
End Get
Set(value as Boolean)
SetProperty(_CreateENHFile,value,"CreateENHFile")
End Set
End Property
Private _En1Command As String = "" ' Column 2
Public Property En1Command As String
Get
Return _En1Command
End Get
Set(value as String)
SetProperty(_En1Command,value,"En1Command")
End Set
End Property
Private _Order As Integer = -1 ' Column 3
Public Property Order As Integer
Get
Return _Order
End Get
Set(value as Integer)
SetProperty(_Order,value,"Order")
End Set
End Property
Private _Parameters As String = "" ' Column 5
Public Property Parameters As String
Get
Return _Parameters
End Get
Set(value as String)
SetProperty(_Parameters,value,"Parameters")
End Set
End Property
Private _WaitForRunApp As Boolean = False ' Column 8
Public Property WaitForRunApp As Boolean
Get
Return _WaitForRunApp
End Get
Set(value as Boolean)
SetProperty(_WaitForRunApp,value,"WaitForRunApp")
End Set
End Property
#End Region
Public Async Function Delete(dbAccess as DMS.Base.Data.IDBAccess) As Task
Await Delete(dbAccess,Me)
End Function
Public Overrides Sub LoadFromEntity(genericEntity As DMS.Base.Models.GenericEntity)
If Me Is genericEntity Then
Return
End If
If Not (TypeOf (genericEntity) Is ApplicationDocumentCommand) Then
Return
End If
Dim Entity As ApplicationDocumentCommand = DirectCast(genericEntity, ApplicationDocumentCommand)
Me.AppDocCmdID = Entity.AppDocCmdID
Me.AppDocID = Entity.AppDocID
Me.En1Command = Entity.En1Command
Me.Order = Entity.Order
Me.AppCommand = Entity.AppCommand
Me.Parameters = Entity.Parameters
Me.CommandType = Entity.CommandType
Me.CreateENHFile = Entity.CreateENHFile
Me.WaitForRunApp = Entity.WaitForRunApp
End Sub
Public Overrides Sub LoadFromReader(reader As IDataReader)
Me.AppDocCmdID = ToIntegerDB(reader(0))
Me.AppDocID = ToIntegerDB(reader(1))
Me.En1Command = ToStringDB(reader(2))
Me.Order = ToIntegerDB(reader(3))
Me.AppCommand = ToStringDB(reader(4))
Me.Parameters = ToStringDB(reader(5))
Me.CommandType = ToStringDB(reader(6))
Me.CreateENHFile = ToBooleanDB(reader(7))
Me.WaitForRunApp = ToBooleanDB(reader(8))
End Sub
Public Overrides Sub PopulateDataRow(ByRef dataRow As System.Data.DataRow)
dataRow.Item(0) = Me.AppDocCmdID
dataRow.Item(1) = Me.AppDocID
dataRow.Item(2) = Me.En1Command
dataRow.Item(3) = Me.Order
dataRow.Item(4) = Me.AppCommand
dataRow.Item(5) = Me.Parameters
dataRow.Item(6) = Me.CommandType
dataRow.Item(7) = Me.CreateENHFile
dataRow.Item(8) = Me.WaitForRunApp
End Sub
Public Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess) As Task
Await Upsert(dbAccess, Me)
End Function
Public Overrides Function GetParameters() As IDictionary(Of String, Object)
Dim Results As New Dictionary(Of String, Object)
Results.Add("AppDocCmdID", Me.AppDocCmdID)
Results.Add("AppDocID", Me.AppDocID)
Results.Add("En1Command", Me.En1Command)
Results.Add("Order", Me.Order)
Results.Add("AppCommand", Me.AppCommand)
Results.Add("Parameters", Me.Parameters)
Results.Add("CommandType", Me.CommandType)
Results.Add("CreateENHFile", Me.CreateENHFile)
Results.Add("WaitForRunApp", Me.WaitForRunApp)
Return Results
End Function
#Region " Shared "
Private Shared _DBDetails As DMS.Base.Models.DBDetails = Nothing
Public Shared Async Function Delete(dbAccess As DMS.Base.Data.IDBAccess, entities As IEnumerable(Of ApplicationDocumentCommand)) As Task
Dim Tasks As New List(Of Task)
For Each Entity As ApplicationDocumentCommand In entities
Tasks.Add(Delete(dbAccess, Entity))
Next
Await Task.WhenAll(Tasks)
End Function
Public Shared Async Function Delete(dbAccess As DMS.Base.Data.IDBAccess, entity As ApplicationDocumentCommand) As Task
Await dbAccess.ExecuteNonQuery(GetDBDetails.Delete, entity.GetParameters())
End Function
Public Shared Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess, entities As IEnumerable(Of ApplicationDocumentCommand)) As Task
If entities.Count = 1 Then
Await Upsert(dbAccess, entities.FirstOrDefault())
Else
Dim DBDetails As DMS.Base.Models.DBDetails = GetDBDetails()
Using DataTable As DataTable = GetDataTable()
For Each Entity As ApplicationDocumentCommand In entities
Dim DataRow As DataRow = DataTable.NewRow
Entity.PopulateDataRow(DataRow)
DataTable.Rows.Add(DataRow)
Next
Await dbAccess.Merge(DBDetails.CreateTemp, DBDetails.DropTemp, DataTable, DBDetails.Merge, DBDetails.TableName)
End Using
End If
End Function
Public Shared Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess, entity As ApplicationDocumentCommand) As Task
Dim Parameters As IDictionary(Of String, Object) = entity.GetParameters()
If String.IsNullOrEmpty(entity.ID) OrElse entity.ID.Equals("-1") OrElse ToIntegerDB(Await dbAccess.ExecuteScalar(GetDBDetails.CountSingle, Parameters)) <= 0 Then
entity.AppDocCmdID = ToIntegerDB(Await dbAccess.ExecuteScalar(GetDBDetails.Insert, Parameters))
Else
Await dbAccess.ExecuteNonQuery(GetDBDetails.Update, Parameters)
End If
End Function
Public Shared Async Function GetAll(dbAccess As DMS.Base.Data.IDBAccess) As Threading.Tasks.Task(Of IEnumerable(Of ApplicationDocumentCommand))
Return Await dbAccess.ExecuteReader(Of ApplicationDocumentCommand)(GetDBDetails.SelectAll)
End Function
Public Shared Function GetDataTable() As DataTable
Dim DataTable As New DataTable
DataTable.Columns.Add("AppDocCmdID")
DataTable.Columns.Add("AppDocID")
DataTable.Columns.Add("En1Command")
DataTable.Columns.Add("Order")
DataTable.Columns.Add("AppCommand")
DataTable.Columns.Add("Parameters")
DataTable.Columns.Add("CommandType")
DataTable.Columns.Add("CreateENHFile")
DataTable.Columns.Add("WaitForRunApp")
Return DataTable
End Function
Public Shared Function GetDBDetails() As DMS.Base.Models.DBDetails
If _DBDetails Is Nothing Then
_DBDetails = New DMS.Base.Models.DBDetails
_DBDetails.CountAll = "SELECT COUNT(*) FROM [ApplicationDocumentCommands]"
_DBDetails.CountSingle = "SELECT COUNT(*) FROM [ApplicationDocumentCommands] WHERE (([AppDocCmdID]=@AppDocCmdID))"
_DBDetails.CreateTemp = "CREATE TABLE #ApplicationDocumentCommands ([AppDocCmdID] [int] NULL,[AppDocID] [int] NULL,[En1Command] [varchar](255) NULL,[Order] [int] NULL,[AppCommand] [varchar](255) NULL,[Parameters] [varchar](255) NULL,[CommandType] [varchar](255) NULL,[CreateENHFile] [bit] NULL,[WaitForRunApp] [bit] NULL)"
_DBDetails.Delete = "DELETE FROM [ApplicationDocumentCommands] WHERE (([AppDocCmdID]=@AppDocCmdID))"
_DBDetails.DropTemp = "DROP TABLE #ApplicationDocumentCommands"
_DBDetails.GetDataTable = New DMS.Base.Delegates.GetDataTable(AddressOf GetDataTable)
_DBDetails.Insert = "INSERT INTO [ApplicationDocumentCommands] ([AppDocID],[En1Command],[Order],[AppCommand],[Parameters],[CommandType],[CreateENHFile],[WaitForRunApp]) OUTPUT Inserted.[AppDocCmdID] VALUES (@AppDocID,@En1Command,@Order,@AppCommand,@Parameters,@CommandType,@CreateENHFile,@WaitForRunApp)"
_DBDetails.Merge = "MERGE INTO [ApplicationDocumentCommands] As [Target] USING #ApplicationDocumentCommands As [Source] ON [Target].[AppDocCmdID]=[Source].[AppDocCmdID] WHEN MATCHED THEN UPDATE SET [Target].[AppDocID]=[Source].[AppDocID],[Target].[En1Command]=[Source].[En1Command],[Target].[Order]=[Source].[Order],[Target].[AppCommand]=[Source].[AppCommand],[Target].[Parameters]=[Source].[Parameters],[Target].[CommandType]=[Source].[CommandType],[Target].[CreateENHFile]=[Source].[CreateENHFile],[Target].[WaitForRunApp]=[Source].[WaitForRunApp] WHEN NOT MATCHED THEN INSERT ([AppDocID],[En1Command],[Order],[AppCommand],[Parameters],[CommandType],[CreateENHFile],[WaitForRunApp]) VALUES ([Source].[AppDocID],[Source].[En1Command],[Source].[Order],[Source].[AppCommand],[Source].[Parameters],[Source].[CommandType],[Source].[CreateENHFile],[Source].[WaitForRunApp]);"
_DBDetails.ModelName = "ApplicationDocumentCommand"
_DBDetails.SelectAll = "SELECT [AppDocCmdID],[AppDocID],[En1Command],[Order],[AppCommand],[Parameters],[CommandType],[CreateENHFile],[WaitForRunApp] FROM [ApplicationDocumentCommands]"
_DBDetails.TableName = "ApplicationDocumentCommands"
_DBDetails.Update = "UPDATE [ApplicationDocumentCommands] SET [AppDocID]=@AppDocID,[En1Command]=@En1Command,[Order]=@Order,[AppCommand]=@AppCommand,[Parameters]=@Parameters,[CommandType]=@CommandType,[CreateENHFile]=@CreateENHFile,[WaitForRunApp]=@WaitForRunApp WHERE (([AppDocCmdID]=@AppDocCmdID))"
End If
Return _DBDetails
End Function
#End Region
End Class
End Namespace
|
nublet/DMS
|
DMS.Base/Models/DMSCON/Base/ApplicationDocumentCommand.vb
|
Visual Basic
|
mit
| 10,210
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class OLStylePickerDialogLineControl
Inherits System.Windows.Forms.UserControl
'UserControl overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.GroupBox2 = New System.Windows.Forms.GroupBox()
Me.NumericUpDown3 = New System.Windows.Forms.NumericUpDown()
Me.Label6 = New System.Windows.Forms.Label()
Me.ComboBox2 = New System.Windows.Forms.ComboBox()
Me.Label5 = New System.Windows.Forms.Label()
Me.NumericUpDown1 = New System.Windows.Forms.NumericUpDown()
Me.Label4 = New System.Windows.Forms.Label()
Me.ComboBox1 = New System.Windows.Forms.ComboBox()
Me.Label3 = New System.Windows.Forms.Label()
Me.Button1 = New System.Windows.Forms.Button()
Me.Label2 = New System.Windows.Forms.Label()
Me.NumericUpDown2 = New System.Windows.Forms.NumericUpDown()
Me.Label1 = New System.Windows.Forms.Label()
Me.GroupBox2.SuspendLayout()
CType(Me.NumericUpDown3, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.NumericUpDown2, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'GroupBox2
'
Me.GroupBox2.Controls.Add(Me.NumericUpDown3)
Me.GroupBox2.Controls.Add(Me.Label6)
Me.GroupBox2.Controls.Add(Me.ComboBox2)
Me.GroupBox2.Controls.Add(Me.Label5)
Me.GroupBox2.Controls.Add(Me.NumericUpDown1)
Me.GroupBox2.Controls.Add(Me.Label4)
Me.GroupBox2.Controls.Add(Me.ComboBox1)
Me.GroupBox2.Controls.Add(Me.Label3)
Me.GroupBox2.Controls.Add(Me.Button1)
Me.GroupBox2.Controls.Add(Me.Label2)
Me.GroupBox2.Controls.Add(Me.NumericUpDown2)
Me.GroupBox2.Controls.Add(Me.Label1)
Me.GroupBox2.Location = New System.Drawing.Point(3, 3)
Me.GroupBox2.Name = "GroupBox2"
Me.GroupBox2.Size = New System.Drawing.Size(157, 206)
Me.GroupBox2.TabIndex = 8
Me.GroupBox2.TabStop = False
Me.GroupBox2.Text = "Line Style"
'
'NumericUpDown3
'
Me.NumericUpDown3.Location = New System.Drawing.Point(76, 133)
Me.NumericUpDown3.Name = "NumericUpDown3"
Me.NumericUpDown3.Size = New System.Drawing.Size(39, 20)
Me.NumericUpDown3.TabIndex = 22
'
'Label6
'
Me.Label6.AutoSize = True
Me.Label6.Location = New System.Drawing.Point(14, 135)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(54, 13)
Me.Label6.TabIndex = 21
Me.Label6.Text = "Miter Limit"
'
'ComboBox2
'
Me.ComboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.ComboBox2.FormattingEnabled = True
Me.ComboBox2.Items.AddRange(New Object() {"round", "miter", "bevel,"})
Me.ComboBox2.Location = New System.Drawing.Point(76, 101)
Me.ComboBox2.Name = "ComboBox2"
Me.ComboBox2.Size = New System.Drawing.Size(75, 21)
Me.ComboBox2.TabIndex = 20
'
'Label5
'
Me.Label5.AutoSize = True
Me.Label5.Location = New System.Drawing.Point(20, 104)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(49, 13)
Me.Label5.TabIndex = 19
Me.Label5.Text = "Line Join"
'
'NumericUpDown1
'
Me.NumericUpDown1.Location = New System.Drawing.Point(76, 159)
Me.NumericUpDown1.Name = "NumericUpDown1"
Me.NumericUpDown1.Size = New System.Drawing.Size(39, 20)
Me.NumericUpDown1.TabIndex = 18
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Location = New System.Drawing.Point(14, 161)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(55, 13)
Me.Label4.TabIndex = 17
Me.Label4.Text = "Line Dash"
'
'ComboBox1
'
Me.ComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.ComboBox1.FormattingEnabled = True
Me.ComboBox1.Items.AddRange(New Object() {"round", "square", "butt"})
Me.ComboBox1.Location = New System.Drawing.Point(76, 74)
Me.ComboBox1.Name = "ComboBox1"
Me.ComboBox1.Size = New System.Drawing.Size(75, 21)
Me.ComboBox1.TabIndex = 16
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Location = New System.Drawing.Point(20, 77)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(49, 13)
Me.Label3.TabIndex = 15
Me.Label3.Text = "Line Cap"
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(76, 45)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(28, 23)
Me.Button1.TabIndex = 11
Me.Button1.UseVisualStyleBackColor = True
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(10, 50)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(60, 13)
Me.Label2.TabIndex = 12
Me.Label2.Text = "Line Colour"
'
'NumericUpDown2
'
Me.NumericUpDown2.Location = New System.Drawing.Point(76, 19)
Me.NumericUpDown2.Name = "NumericUpDown2"
Me.NumericUpDown2.Size = New System.Drawing.Size(39, 20)
Me.NumericUpDown2.TabIndex = 14
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(14, 21)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(58, 13)
Me.Label1.TabIndex = 10
Me.Label1.Text = "Line Width"
'
'OLStylePickerDialogLineControl
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.Controls.Add(Me.GroupBox2)
Me.Name = "OLStylePickerDialogLineControl"
Me.Size = New System.Drawing.Size(167, 271)
Me.GroupBox2.ResumeLayout(False)
Me.GroupBox2.PerformLayout()
CType(Me.NumericUpDown3, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.NumericUpDown2, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox
Friend WithEvents ComboBox1 As System.Windows.Forms.ComboBox
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents NumericUpDown2 As System.Windows.Forms.NumericUpDown
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents ComboBox2 As System.Windows.Forms.ComboBox
Friend WithEvents Label5 As System.Windows.Forms.Label
Friend WithEvents NumericUpDown1 As System.Windows.Forms.NumericUpDown
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents NumericUpDown3 As System.Windows.Forms.NumericUpDown
Friend WithEvents Label6 As System.Windows.Forms.Label
End Class
|
JohnWilcock/OL3Designer
|
OL3Designer/UserControls/OLStyles/OL3StylePicker/OLStylePickerDialogLineControl.Designer.vb
|
Visual Basic
|
mit
| 8,203
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2018 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Friend Class CancelPnLGenerator
Inherits GeneratorBase
Implements IGenerator
Private Delegate Sub ApiMethodDelegate(requestId As Integer)
Private Const ModuleName As String = NameOf(CancelPnLGenerator)
Friend Overrides ReadOnly Property GeneratorDelegate As [Delegate] Implements IGenerator.GeneratorDelegate
Get
Return New ApiMethodDelegate(AddressOf cancelPnL)
End Get
End Property
Friend Overrides ReadOnly Property MessageType As ApiSocketOutMsgType
Get
Return ApiSocketOutMsgType.CancelPnL
End Get
End Property
Private Sub cancelPnL(requestId As Integer)
If ConnectionState <> ApiConnectionState.Connected Then Throw New InvalidOperationException("Not connected")
If ServerVersion < ApiServerVersion.PNL Then Throw New InvalidOperationException("PnL requests not supported")
Dim lWriter = CreateOutputMessageGenerator()
StartMessage(lWriter, MessageType)
lWriter.AddInteger(requestId, "Request Id")
lWriter.SendMessage(_EventConsumers.SocketDataConsumer)
End Sub
End Class
|
tradewright/tradewright-twsapi
|
src/IBAPI/Generators/CancelPnLGenerator.vb
|
Visual Basic
|
mit
| 2,320
|
''' <summary>
''' Provides application-specific behavior to supplement the default Application class.
''' </summary>
NotInheritable Class App
Inherits Application
''' <summary>
''' Initializes a new instance of the App class.
''' </summary>
Public Sub New()
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata Or
Microsoft.ApplicationInsights.WindowsCollectors.Session)
InitializeComponent()
End Sub
''' <summary>
''' Invoked when the application is launched normally by the end user. Other entry points
''' will be used when the application is launched to open a specific file, to display
''' search results, and so forth.
''' </summary>
''' <param name="e">Details about the launch request and process.</param>
Protected Overrides Sub OnLaunched(e As Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
#If DEBUG Then
' Show graphics profiling information while debugging.
If System.Diagnostics.Debugger.IsAttached Then
' Display the current frame rate counters
Me.DebugSettings.EnableFrameRateCounter = True
End If
#End If
Dim rootFrame As Frame = TryCast(Window.Current.Content, Frame)
' Do not repeat app initialization when the Window already has content,
' just ensure that the window is active
If rootFrame Is Nothing Then
' Create a Frame to act as the navigation context and navigate to the first page
rootFrame = New Frame()
AddHandler rootFrame.NavigationFailed, AddressOf OnNavigationFailed
If e.PreviousExecutionState = ApplicationExecutionState.Terminated Then
' TODO: Load state from previously suspended application
End If
' Place the frame in the current Window
Window.Current.Content = rootFrame
End If
If rootFrame.Content Is Nothing Then
' When the navigation stack isn't restored navigate to the first page,
' configuring the new page by passing required information as a navigation
' parameter
rootFrame.Navigate(GetType(MainPage), e.Arguments)
End If
' Ensure the current window is active
Window.Current.Activate()
End Sub
''' <summary>
''' Invoked when Navigation to a certain page fails
''' </summary>
''' <param name="sender">The Frame which failed navigation</param>
''' <param name="e">Details about the navigation failure</param>
Private Sub OnNavigationFailed(sender As Object, e As NavigationFailedEventArgs)
Throw New Exception("Failed to load Page " + e.SourcePageType.FullName)
End Sub
''' <summary>
''' Invoked when application execution is being suspended. Application state is saved
''' without knowing whether the application will be terminated or resumed with the contents
''' of memory still intact.
''' </summary>
''' <param name="sender">The source of the suspend request.</param>
''' <param name="e">Details about the suspend request.</param>
Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs) Handles Me.Suspending
Dim deferral As SuspendingDeferral = e.SuspendingOperation.GetDeferral()
' TODO: Save application state and stop any background activity
Dim dxgiDeviceManager As Lumia.Imaging.Direct2D.DxgiDeviceManager = New Lumia.Imaging.Direct2D.DxgiDeviceManager()
dxgiDeviceManager.Trim()
deferral.Complete()
End Sub
End Class
|
Microsoft/Lumia-imaging-sdk
|
Samples/QuickStart/vb/App.xaml.vb
|
Visual Basic
|
mit
| 3,670
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18444
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.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("CMDLauncher.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
Walkman100/CMDLauncher
|
My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,717
|
' Developer - Silent
' Date Created - 02/24/2014
'
' General Description - Simple Config class used for Business Object examples
Public Class Config
#Region " Modular Variables "
Private _Account As String
Private _Pwd As String
Private _Remember As Boolean = True
Private _Manager As Guid
#End Region
#Region " Constructors "
Public Sub New()
End Sub
#End Region
#Region " Public Properties "
''' <summary>
''' Property to hold the Account of the config
''' </summary>
''' <value>String</value>
''' <returns>Config Account</returns>
Public Property Account() As String
Get
Return _Account
End Get
Set(ByVal value As String)
_Account = value
'Console.WriteLine("Property {0} has been changed.", "Account")
End Set
End Property
''' <summary>
''' Property to hold the Pwd of the config
''' </summary>
''' <value>String</value>
''' <returns>Config Pwd</returns>
Public Property Pwd() As String
Get
Return _Pwd
End Get
Set(ByVal value As String)
_Pwd = value
'Console.WriteLine("Property {0} has been changed.", "Pwd")
End Set
End Property
''' <summary>
''' Property to hold the Remember of the config
''' </summary>
''' <value>Boolean</value>
''' <returns>Config Remember</returns>
Public Property Remember() As Boolean
Get
Return _Remember
End Get
Set(ByVal value As Boolean)
_Remember = value
'Console.WriteLine("Property {0} has been changed.", "Remember")
End Set
End Property
''' <summary>
''' Holds config managers ID
''' </summary>
''' <value>Guid</value>
''' <returns>Config managers Guid</returns>
Public Property Manager() As Guid
Get
Return _Manager
End Get
Set(ByVal value As Guid)
_Manager = value
'Console.WriteLine("Property {0} has been changed.", "Manager")
End Set
End Property
#End Region
End Class
|
kuastw/KUAS-AP-Windows
|
KUAS AP/Config.vb
|
Visual Basic
|
mit
| 2,227
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2018 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Imports System.Threading
Imports System.Threading.Tasks
Imports TradeWright.IBAPI.ApiException
Friend Class SocketHandler
''
' Description here
'
'@/
'@================================================================================
' Interfaces
'@================================================================================
'@================================================================================
' Events
'@================================================================================
'@================================================================================
' Enums
'@================================================================================
'@================================================================================
' Types
'@================================================================================
'@================================================================================
' Constants
'@================================================================================
Private Const ModuleName As String = NameOf(SocketHandler)
'@================================================================================
' Member variables
'@================================================================================
Private Socket As SocketManager
Private ReadOnly mServer As String
Private ReadOnly mPort As Integer
Private mKeepAlive As Boolean
Private mRetryingConnection As Boolean
Private mConnectionTimer As Timer
Private mIsConnecting As Boolean
Private mIsConnected As Boolean
Private mConnectionRetryIntervalSecs As Integer
' Called when a successful connection to Tws has been achieved.
Private ReadOnly mConnectedAction As Action
' Called when connection to Tws has failed
Private ReadOnly mConnectFailedAction As Action(Of String)
' Called when an attempt to connect to Tws is initiated.
Private ReadOnly mConnectingAction As Action
' Called when the connection to Tws is disconnected.
Private ReadOnly mConnectionClosedAction As Action(Of String)
' Called when we Disconnect from Tws
Private ReadOnly mDisconnectedAction As Action(Of String)
'@================================================================================
' Class Event Handlers
'@================================================================================
Friend Sub New(socket As SocketManager,
connectingAction As Action,
connectedAction As Action,
connectFailedAction As Action(Of String),
disconnectedAction As Action(Of String),
connectionClosedAction As Action(Of String),
connectionRetryIntervalSecs As Integer)
Me.Socket = socket
mServer = Me.Socket.Host
mPort = Me.Socket.Port
mConnectingAction = connectingAction
mConnectedAction = connectedAction
mConnectFailedAction = connectFailedAction
mDisconnectedAction = disconnectedAction
mConnectionClosedAction = connectionClosedAction
mConnectionRetryIntervalSecs = connectionRetryIntervalSecs
End Sub
'@================================================================================
' XXXX Interface Members
'@================================================================================
'================================================================================
' mConnectionTimer Event Handlers
'================================================================================
Private Sub mConnectionTimer_TimerExpired(state As Object)
mConnectionTimer = Nothing
Connect(mKeepAlive)
End Sub
'@================================================================================
' Properties
'@================================================================================
Friend Property ConnectionRetryIntervalSecs() As Integer
Get
ConnectionRetryIntervalSecs = mConnectionRetryIntervalSecs
End Get
Set()
mConnectionRetryIntervalSecs = Value
If mConnectionRetryIntervalSecs = 0 And mRetryingConnection Then mConnectionTimer = Nothing
End Set
End Property
Friend ReadOnly Property SocketManager As SocketManager
Get
Return Socket
End Get
End Property
'@================================================================================
' Methods
'@================================================================================
Friend Sub Connect(keepAlive As Boolean)
If mIsConnected Then Throw New InvalidOperationException("Already connected")
mKeepAlive = keepAlive
Dim s As String
s = $"Connecting to Tws: {getConnectionString()}"
IBAPI.EventLogger.Log(s, ModuleName, "Connect")
mIsConnecting = True
' we don't Await the following call because we don't want this Connect method to have to be async
Dim t = Socket.ConnectAsync(Sub()
mIsConnecting = False
mIsConnected = True
mConnectedAction()
End Sub,
Sub() handleTwsDisconnection("closed by peer", False),
AddressOf handleSocketError,
keepAlive)
mConnectingAction()
End Sub
Friend Sub Disconnect(pReason As String)
If Not (mIsConnecting Or mIsConnected) Then Exit Sub
mIsConnecting = False
mIsConnected = False
If Not mConnectionTimer Is Nothing Then mConnectionTimer.Dispose()
releaseSocket()
IBAPI.EventLogger.Log($"Disconnected from: {getConnectionString()} : {pReason}", ModuleName, NameOf(Disconnect))
handleTwsDisconnection("closed by application", True)
mDisconnectedAction(pReason)
End Sub
'@================================================================================
' Helper Functions
'@================================================================================
Private Function getConnectionString() As String
Return $"server={mServer} port={mPort}"
End Function
Private Sub handleSocketError(e As SocketEventArgs)
Dim errorNum = CType(e.Exception.ErrorCode, SocketErrorCode)
Select Case errorNum
Case SocketErrorCode.WSAEADDRNOTAVAIL,
SocketErrorCode.WSAENETUNREACH,
SocketErrorCode.WSAENETRESET,
SocketErrorCode.WSAECONNABORTED,
SocketErrorCode.WSAECONNREFUSED,
SocketErrorCode.WSAHOST_NOT_FOUND,
SocketErrorCode.WSATRY_AGAIN,
SocketErrorCode.WSAETIMEDOUT,
SocketErrorCode.WSAECONNRESET
releaseSocket()
If Not mIsConnected Then
IBAPI.EventLogger.Log($"Failed to connect to Tws {CStr(If(mConnectionRetryIntervalSecs <> 0, $" - retrying In {mConnectionRetryIntervalSecs} seconds", ""))}: {e.Exception.Message} : {getConnectionString()}", ModuleName, NameOf(handleSocketError))
e.ConnectionRetryInterval = mConnectionRetryIntervalSecs
mConnectFailedAction(e.Exception.Message)
If mConnectionRetryIntervalSecs <> 0 Then retryConnection()
Else
IBAPI.EventLogger.Log($"Socket error {e.Exception.ErrorCode} : {e.Exception.Message} : {getConnectionString()}", ModuleName, NameOf(handleSocketError))
handleTwsDisconnection(e.Exception.Message, False)
End If
Case Else
Throw New InvalidOperationException($"Socket error {e.Exception.ErrorCode}: {e.Exception.Message} : {getConnectionString()}")
End Select
End Sub
Private Sub handleTwsDisconnection(pMessage As String, pClosedByApplication As Boolean)
IBAPI.EventLogger.Log($"Connection to Tws closed: {pMessage} : {getConnectionString()}", ModuleName, NameOf(handleTwsDisconnection))
Socket = Nothing
mIsConnected = False
mConnectionClosedAction(pMessage)
If Not pClosedByApplication Then retryConnection()
End Sub
Private Sub releaseSocket()
If Not Socket Is Nothing Then
IBAPI.EventLogger.Log($"Releasing socket: {getConnectionString()}", ModuleName, NameOf(releaseSocket))
Socket.Close()
Socket = Nothing
End If
mIsConnected = False
End Sub
Private Sub retryConnection()
If mConnectionRetryIntervalSecs <> 0 Then
IBAPI.EventLogger.Log($"Reconnecting in {mConnectionRetryIntervalSecs} seconds", ModuleName, NameOf(retryConnection))
mConnectionTimer = New Timer(AddressOf mConnectionTimer_TimerExpired, Nothing, 1000 * mConnectionRetryIntervalSecs, Timeout.Infinite)
mRetryingConnection = True
End If
End Sub
End Class
|
tradewright/tradewright-twsapi
|
src/IBApi/SocketHandler.vb
|
Visual Basic
|
mit
| 10,468
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fCClientes_ConCC"
'-------------------------------------------------------------------------------------------'
Partial Class fCClientes_ConCC
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 loConsulta As New StringBuilder()
loConsulta.AppendLine("")
loConsulta.AppendLine("--Tabla temporal con los registros a listar")
loConsulta.AppendLine("CREATE TABLE #tmpRegistros( Codigo VARCHAR(10) COLLATE DATABASE_DEFAULT, ")
loConsulta.AppendLine(" Nombre VARCHAR(100) COLLATE DATABASE_DEFAULT, ")
loConsulta.AppendLine(" Estatus VARCHAR(15) COLLATE DATABASE_DEFAULT, ")
loConsulta.AppendLine(" Contable XML")
loConsulta.AppendLine(" );")
loConsulta.AppendLine("")
loConsulta.AppendLine("INSERT INTO #tmpRegistros(Codigo, Nombre, Estatus, Contable)")
loConsulta.AppendLine("SELECT Cod_Cla, ")
loConsulta.AppendLine(" Nom_Cla,")
loConsulta.AppendLine(" (CASE Status ")
loConsulta.AppendLine(" WHEN 'A' THEN 'Activo' ")
loConsulta.AppendLine(" WHEN 'I' THEN 'Inactivo'")
loConsulta.AppendLine(" ELSE 'Suspendido' ")
loConsulta.AppendLine(" END) AS Status,")
loConsulta.AppendLine(" Contable")
loConsulta.AppendLine("FROM Clases_Clientes")
loConsulta.AppendLine("")
loConsulta.AppendLine("-- En el SELECT final se expande el XML Contable para obtener las ")
loConsulta.AppendLine("-- Cuentas Contables, de Gastos y Centros de Costos de cada página del registro ")
loConsulta.AppendLine("SELECT #tmpRegistros.Codigo AS Codigo,")
loConsulta.AppendLine(" #tmpRegistros.Nombre AS Nombre,")
loConsulta.AppendLine(" #tmpRegistros.Estatus AS Estatus,")
loConsulta.AppendLine(" COALESCE(Detalles.Numero, 1) AS Numero,")
loConsulta.AppendLine(" COALESCE(Detalles.Pagina, '') AS Pagina,")
loConsulta.AppendLine(" COALESCE(Detalles.Cue_Con_Codigo, '') AS Cue_Con_Codigo,")
loConsulta.AppendLine(" COALESCE(Cuentas_Contables.Nom_Cue, '') AS Cue_Con_Nombre,")
loConsulta.AppendLine(" COALESCE(Detalles.Cue_Gas_Codigo, '') AS Cue_Gas_Codigo,")
loConsulta.AppendLine(" COALESCE(Cuentas_Gastos.Nom_Gas, '') AS Cue_Gas_Nombre,")
loConsulta.AppendLine(" COALESCE(Detalles.Cen_Cos_Codigo, '') AS Cen_Cos_Codigo,")
loConsulta.AppendLine(" COALESCE(Centros_Costos.Nom_Cen, '') AS Cen_Cos_Nombre,")
loConsulta.AppendLine(" COALESCE(Detalles.Cen_Cos_Porcentaje, 0) AS Cen_Cos_Porcentaje ")
loConsulta.AppendLine("FROM #tmpRegistros")
loConsulta.AppendLine(" LEFT JOIN ( SELECT Codigo,")
loConsulta.AppendLine(" (Ficha.C.value('@n[1]', 'VARCHAR(MAX)')+1) AS Numero,")
loConsulta.AppendLine(" Ficha.C.value('@nombre[1]', 'VARCHAR(MAX)') AS Pagina,")
loConsulta.AppendLine(" Ficha.C.value('./cue_con[1]', 'VARCHAR(MAX)') AS Cue_Con_Codigo,")
loConsulta.AppendLine(" Ficha.C.value('./cue_gas[1]', 'VARCHAR(MAX)') AS Cue_Gas_Codigo,")
loConsulta.AppendLine(" Costos.C.value('@codigo[1]', 'VARCHAR(MAX)') AS Cen_Cos_Codigo,")
loConsulta.AppendLine(" CAST(Costos.C.value('@porcentaje[1]', 'VARCHAR(MAX)') AS DECIMAL(28,10)) AS Cen_Cos_Porcentaje")
loConsulta.AppendLine(" FROM #tmpRegistros")
loConsulta.AppendLine(" CROSS APPLY Contable.nodes('contable/ficha') AS Ficha(C)")
loConsulta.AppendLine(" OUTER APPLY Contable.nodes('contable/ficha/centro_costo') AS Costos(C)")
loConsulta.AppendLine(" ) Detalles")
loConsulta.AppendLine(" ON Detalles.Codigo = #tmpRegistros.Codigo")
loConsulta.AppendLine(" LEFT JOIN Cuentas_Contables")
loConsulta.AppendLine(" ON Cuentas_Contables.Cod_Cue = Detalles.Cue_Con_Codigo")
loConsulta.AppendLine(" LEFT JOIN Cuentas_Gastos")
loConsulta.AppendLine(" ON Cuentas_Gastos.Cod_Gas = Detalles.Cue_Gas_Codigo")
loConsulta.AppendLine(" LEFT JOIN Centros_Costos")
loConsulta.AppendLine(" ON Centros_Costos.Cod_Cen = Detalles.Cen_Cos_Codigo")
loConsulta.AppendLine("ORDER BY #tmpRegistros.Codigo, COALESCE(Detalles.Numero, 1)")
loConsulta.AppendLine("")
'loConsulta.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
'Me.mEscribirConsulta(loComandoSeleccionar.ToString)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString, "curReportes")
'--------------------------------------------------'
' Carga la imagen del logo en cusReportes '
'--------------------------------------------------'
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fCClientes_ConCC", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfCClientes_ConCC.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' RJG: 31/10/14: Codigo inicial '
'-------------------------------------------------------------------------------------------'
' JJD: 31/10/14: Adecuacion para Cajas '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
fCClientes_ConCC.aspx.vb
|
Visual Basic
|
mit
| 9,018
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rResumen_Conceptos_SID"
'-------------------------------------------------------------------------------------------'
Partial Class rResumen_Conceptos_SID
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro2Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
'Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcParametro7Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7))
Dim lcParametro7Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(7))
Dim lcParametro8Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("CREATE TABLE #tmpResumen( Cod_Con CHAR(10) COLLATE DATABASE_DEFAULT,")
loComandoSeleccionar.AppendLine(" Nom_Con CHAR(100) COLLATE DATABASE_DEFAULT,")
loComandoSeleccionar.AppendLine(" Tipo CHAR(30) COLLATE DATABASE_DEFAULT,")
loComandoSeleccionar.AppendLine(" Asignacion DECIMAL(28, 10),")
loComandoSeleccionar.AppendLine(" Deduccion DECIMAL(28, 10),")
loComandoSeleccionar.AppendLine(" Otro DECIMAL(28, 10),")
loComandoSeleccionar.AppendLine(" Saldo DECIMAL(28, 10),")
loComandoSeleccionar.AppendLine(" Cod_Tra CHAR(10) COLLATE DATABASE_DEFAULT);")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine("INSERT INTO #tmpResumen(Cod_Con, Nom_Con, Tipo, Asignacion, Deduccion, Otro, Saldo, Cod_Tra)")
loComandoSeleccionar.AppendLine("SELECT Conceptos_Nomina.Cod_Con AS Cod_Con,")
loComandoSeleccionar.AppendLine(" Conceptos_Nomina.Nom_Con AS Nom_Con,")
loComandoSeleccionar.AppendLine(" Conceptos_Nomina.tipo AS tipo,")
loComandoSeleccionar.AppendLine(" SUM(CASE Conceptos_Nomina.tipo")
loComandoSeleccionar.AppendLine(" WHEN 'Asignacion' THEN Renglones_Recibos.mon_net ")
loComandoSeleccionar.AppendLine(" ELSE 0 END) AS Asignacion,")
loComandoSeleccionar.AppendLine(" SUM(CASE Conceptos_Nomina.tipo")
loComandoSeleccionar.AppendLine(" WHEN 'Deduccion' THEN Renglones_Recibos.mon_net")
loComandoSeleccionar.AppendLine(" WHEN 'Retencion' THEN Renglones_Recibos.mon_net")
loComandoSeleccionar.AppendLine(" ELSE 0 END) AS Deduccion,")
loComandoSeleccionar.AppendLine(" SUM(CASE Conceptos_Nomina.tipo ")
loComandoSeleccionar.AppendLine(" WHEN 'Otro' THEN Renglones_Recibos.mon_net ")
loComandoSeleccionar.AppendLine(" ELSE 0 END) AS Otro,")
loComandoSeleccionar.AppendLine(" COALESCE(Prestamos.Mon_sal, 0) AS Saldo, ")
loComandoSeleccionar.AppendLine(" Recibos.cod_tra AS Cod_Tra")
loComandoSeleccionar.AppendLine("FROM Renglones_Recibos")
loComandoSeleccionar.AppendLine(" JOIN Recibos ")
loComandoSeleccionar.AppendLine(" ON Recibos.Documento = Renglones_Recibos.Documento")
loComandoSeleccionar.AppendLine(" JOIN Conceptos_Nomina ")
loComandoSeleccionar.AppendLine(" ON Conceptos_Nomina.cod_con = Renglones_Recibos.cod_con ")
loComandoSeleccionar.AppendLine(" JOIN Trabajadores ")
loComandoSeleccionar.AppendLine(" ON Trabajadores.cod_tra = Recibos.cod_tra ")
loComandoSeleccionar.AppendLine(" LEFT JOIN Detalles_Prestamos ")
loComandoSeleccionar.AppendLine(" ON Detalles_Prestamos.documento = Renglones_Recibos.doc_ori")
loComandoSeleccionar.AppendLine(" AND Detalles_Prestamos.renglon = Renglones_Recibos.ren_ori")
loComandoSeleccionar.AppendLine(" AND Renglones_Recibos.Tip_Ori = 'Prestamos'")
loComandoSeleccionar.AppendLine(" LEFT JOIN Prestamos ")
loComandoSeleccionar.AppendLine(" ON Detalles_Prestamos.documento = Prestamos.documento")
loComandoSeleccionar.AppendLine(" AND Prestamos.status = 'Confirmado'")
loComandoSeleccionar.AppendLine(" AND Prestamos.Mon_Sal > 0")
loComandoSeleccionar.AppendLine("WHERE Conceptos_Nomina.Cod_Con BETWEEN " & lcParametro0Desde & " AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Recibos.Fecha BETWEEN " & lcParametro1Desde & " AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Conceptos_Nomina.Tipo IN (" & lcParametro2Desde & ")")
loComandoSeleccionar.AppendLine(" AND Recibos.Cod_Con BETWEEN " & lcParametro3Desde & " AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Trabajadores.Cod_Dep BETWEEN " & lcParametro4Desde & " AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Trabajadores.Cod_Suc BETWEEN " & lcParametro5Desde & " AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Trabajadores.Cod_Tra BETWEEN " & lcParametro6Desde & " AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Conceptos_Nomina.Tipo BETWEEN " & lcParametro7Desde & " AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Recibos.Status IN (" & lcParametro8Desde & ")")
loComandoSeleccionar.AppendLine("GROUP BY conceptos_Nomina.Cod_Con,")
loComandoSeleccionar.AppendLine(" conceptos_Nomina.Nom_Con,")
loComandoSeleccionar.AppendLine(" conceptos_Nomina.Tipo, ")
loComandoSeleccionar.AppendLine(" COALESCE(Prestamos.Documento, ''),")
loComandoSeleccionar.AppendLine(" COALESCE(Prestamos.Mon_sal, 0),")
loComandoSeleccionar.AppendLine(" Recibos.cod_tra")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("SELECT Cod_Con, Nom_Con, Tipo, ")
loComandoSeleccionar.AppendLine(" SUM(Asignacion) AS Asignacion, ")
loComandoSeleccionar.AppendLine(" SUM(Deduccion) AS Deduccion, ")
loComandoSeleccionar.AppendLine(" SUM(Otro) AS Otro, ")
loComandoSeleccionar.AppendLine(" SUM(Saldo) AS Saldo, ")
loComandoSeleccionar.AppendLine(" COUNT(DISTINCT cod_tra) AS Trabajadores,")
loComandoSeleccionar.AppendLine(" (SELECT COUNT(DISTINCT Cod_Tra) FROM #tmpResumen) AS Integrantes,")
loComandoSeleccionar.AppendLine(" CAST(" & lcParametro1Desde & " AS DATETIME) AS Desde, ")
loComandoSeleccionar.AppendLine(" CAST(" & lcParametro1Hasta & " AS DATETIME) AS Hasta ")
loComandoSeleccionar.AppendLine("FROM #tmpResumen")
loComandoSeleccionar.AppendLine("GROUP BY Cod_Con, Nom_Con, Tipo")
loComandoSeleccionar.AppendLine("ORDER BY(CASE tipo")
loComandoSeleccionar.AppendLine(" WHEN 'Asignacion' THEN 0")
loComandoSeleccionar.AppendLine(" WHEN 'Deduccion' THEN 1")
loComandoSeleccionar.AppendLine(" WHEN 'Retencion' THEN 1")
loComandoSeleccionar.AppendLine(" ELSE 2 END) ASC, ")
loComandoSeleccionar.AppendLine(" cod_con ASC")
loComandoSeleccionar.AppendLine("")
'loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento)
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
Dim loServicios As New cusDatos.goDatos
'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString(), "curReportes")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rResumen_Conceptos_SID", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrResumen_Conceptos_SID.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: 13/06/13: Codigo inicial '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
Reportes - Nomina/rResumen_Conceptos_SID.aspx.vb
|
Visual Basic
|
mit
| 12,372
|
Imports System.IO
Imports System.Math
Imports System.Windows.Forms
Module Module1
Dim ProgramDefinedVariables As New Dictionary(Of String, String)
Dim ProgramDefinedvariablesTypes As New Dictionary(Of String, String)
Dim variablenametocreate, variablevalue, operationchoice, variabletoread, variabletype, workingfile, Line, Keyword, lastopenedfile, mainprogramname, activefunction As String
Dim LineNo As Integer = 1
Dim ErrorLineNo As Integer = 0
Dim multipleerrors As Boolean = False
Dim condition As Boolean
Dim linenotoloopto As Integer = 0
Dim loopvariablename As String
Dim forloopset As Boolean = False
Dim exponents(255) As Integer
Dim exponentno As Integer
Dim exponentline As Boolean = False
Dim functiontriggered As Boolean = False
Dim linetomovetoafterfunctionexecution, firstparameterposshift As Integer
Dim functionoperandvalues(50) As String
Public StrictSyntax As Boolean = False
Dim gui As New HAL_Interpreter.GUI
Dim procedurelocations(300) 'length of string is 3 times amount of procedures allowed in program (realtime)
Declare Function AllocConsole Lib "kernel32" () As Int32
Declare Function FreeConsole Lib "kernel32" () As Int32
Dim builtinfunctiongenerated As Boolean = False
Dim defaultfunctions(10) As String
Sub Main()
LineNo = 1
'DisplayGUI() 'new gui
oldmain() '"classic" mode
'realtime()
End Sub
Sub oldmain()
Console.Title = "HAL/S Interpreter"
Logo()
workingfile = "TRIG2.HAL"
' realtime()
Readfromfile()
Parsefile(True)
Parsefile(False)
Console.ReadKey()
'##prompt for future##
'Console.WriteLine("Default file is test.txt")
'Dim quit As Boolean = False
'Dim prompt As String
'Do Until quit = True
' Console.WriteLine()
' Console.WriteLine("Enter what type of operation you want to perfom. Options are: (1) View Annotations, (2) Compile and Run, (3) View Code, (f) change file, (c) Credits and (q) Quit")
' prompt = Console.ReadLine
' If prompt = "1" Then
' parsefile(True)
' ElseIf prompt = "2" Then
' parsefile(False)
' ElseIf prompt = "3" Then
' readfromfile()
' ElseIf prompt = "c" Then
' tribute()
' ElseIf prompt = "f" Then
' workingfile = Console.ReadLine()
' If My.Computer.FileSystem.FileExists("C:\Users\Thomas\Documents\Visual Studio 2017\Projects\HAL Interpreter\HAL Interpreter\bin\Debug\" & workingfile) Then
' Else
' Console.WriteLine("File does not exist")
' workingfile = "test.txt"
' End If
' ElseIf prompt = "q" Then
' quit = True
' End If
'Loop
End Sub
Sub realtime()
Dim currentarraypos As Integer = 3
Using file As New StreamReader(workingfile)
Do Until file.EndOfStream
Line = file.ReadLine
Dim components() As String = Line.Split(New Char() {" "c})
If Line.Contains("SIMPLE:") Then
procedurelocations(0) = Removesemicolon(components(3)) 'check if this is the right position (should be name of program)
procedurelocations(1) = Convert.ToInt64(LineNo)
End If
If Line.Contains("CLOSE SIMPLE") Then procedurelocations(2) = Convert.ToInt64(LineNo)
LineNo = LineNo + 1
Loop
End Using
LineNo = 1
Using file As New StreamReader(workingfile)
Do Until file.EndOfStream
Line = file.ReadLine
Dim components() As String = Line.Split(New Char() {" "c})
Try
If components(3).Contains("FUNCTION(") Then
procedurelocations(currentarraypos) = components(2)
Dim currentfunction = components(2)
currentarraypos = currentarraypos + 1
procedurelocations(currentarraypos) = Convert.ToInt64(LineNo)
currentarraypos = currentarraypos + 1
End If
Catch
End Try
Try
If components(2) = "CLOSE" Then
procedurelocations(currentarraypos) = Convert.ToInt64(LineNo)
currentarraypos = currentarraypos + 1
End If
Catch
End Try
LineNo = LineNo + 1
Loop
End Using
Dim Thread1 As New System.Threading.Thread(AddressOf mainthreadsub)
Thread1.Start()
LineNo = 1
End Sub
Sub mainthreadsub()
LineNo = procedurelocations(1)
Parsefile(False)
Console.ReadKey()
End Sub
Sub DisplayGUI()
Console.Title = "Hal Interpreter"
FreeConsole() 'hide console
'gui.Size = New System.Drawing.Size(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
GUI.Size = SystemInformation.PrimaryMonitorSize
gui.Location = New Drawing.Point(0, 0)
gui.WindowState = FormWindowState.Maximized
Try
If File.Exists("D:\owin31.wav") Then
'My.Computer.Audio.Play("D:\owin31.wav")
End If
Catch
End Try
If File.Exists("temp.tmp") Then
Try
gui.startopenfile()
Catch
File.Delete("temp.tmp")
End Try
If System.IO.File.Exists("temp.tmp") = True Then
System.IO.File.Delete("temp.tmp")
End If
End If
gui.ShowDialog()
End Sub
Sub guiexecute(filepath)
workingfile = filepath
AllocConsole()
Console.Title = "HAL/S Interpreter"
Try
Console.WriteLine("") 'if it crashes on this line its probably because the console is not properly opened
Parsefile(False)
Console.ReadKey()
FreeConsole()
Catch ex As Exception
If TypeOf ex Is NullReferenceException Then
MsgBox("Please remove all blank lines and properly finish programs and procedures (CLOSE not END). (Try adding 'CLOSE SIMPLE;') Line: " & LineNo, MsgBoxStyle.Critical, "NullReferenceError")
Else
If TypeOf ex Is FormatException Then
MsgBox("Incorrect format (Are your EMSCD's right?) Line: " & LineNo, MsgBoxStyle.Critical, "FormatException")
ElseIf TypeOf ex Is IO.IOException Then
' MsgBox("System.Console Output Error:" & Chr(10) & ex.ToString() & Chr(10) & "Please save your work and restart the program.", MsgBoxStyle.Critical, "Error")
'savelastopenedfile
Dim fs As FileStream = File.Create("temp.tmp")
fs.Close()
Using file As StreamWriter = New StreamWriter("temp.tmp")
file.Write(filepath)
End Using
Application.Restart()
'gui.Close()
'guiexecute(filepath)
Else
End If
End If
FreeConsole()
End Try
End Sub
Sub setworkingfile(filenametosetto)
workingfile = filenametosetto
End Sub
Sub Readfromfile()
Dim displaylineno As Integer = 1
'Console.WriteLine("Enter the filename to open")
'workingfile = Console.ReadLine()
Console.WriteLine("Contents of file '" & workingfile & "':")
Console.WriteLine()
Using file As New StreamReader(workingfile)
'output contents of workingfile (to check the file reads properly)
Do Until file.EndOfStream = True
Line = file.ReadLine()
'output line no
Console.ForegroundColor = ConsoleColor.DarkMagenta
Console.Write(displaylineno & " ")
Console.ForegroundColor = ConsoleColor.Gray
displaylineno = displaylineno + 1
Dim components() As String = Line.Split(New Char() {" "c})
For i As Integer = 0 To (components.Length() - 1)
Console.Write(components(i) & " ")
Next
Console.WriteLine()
Loop
End Using
End Sub
Sub Parsefile(DisplayInterpreterComments)
Dim linetype As String
LineNo = 1 'not for real time
Dim endofprogram As Boolean = False
Console.WriteLine()
Console.WriteLine("Interpreter output:")
Console.WriteLine()
'check for semicolons - mean syntax mode
If StrictSyntax = True Then
Dim semicolonline As Integer = 0
Using f As New StreamReader(workingfile)
Do Until f.EndOfStream = True
semicolonline = semicolonline + 1
Dim newline As String = f.ReadLine()
If Not (newline.Contains(";")) Then
If Not newline.Contains("C ") Then
MsgBox($"Semicolon missing on line {semicolonline}.", MsgBoxStyle.Critical, "Syntax Error.")
Exit Sub
Exit Sub
End If
End If
Loop
End Using
End If
'move to correct line
endofprogram = False
Do Until endofprogram = True
Using file As New StreamReader(workingfile)
For i = 1 To LineNo
Using fileline As New StreamReader(workingfile)
Line = file.ReadLine()
End Using
Next
'output line number
If DisplayInterpreterComments = True Then
Console.ForegroundColor = ConsoleColor.DarkMagenta
Console.Write(LineNo & " ")
Console.ForegroundColor = ConsoleColor.Gray
End If
Dim components() As String
Try
components = Line.Split(New Char() {" "c})
Catch
Errorupdate(LineNo)
End Try
linetype = Getlinetype(Line)
If linetype = "NORMAL" Then
Keyword = Getkeyword(Line)
ElseIf linetype = "EXPONENT" Then
Keyword = "EXPONENT"
ElseIf linetype = "SUBSCRIPT" Then
Keyword = "SUBSCRIPT"
ElseIf linetype = "MAIN" Then
Keyword = "ASSIGNMENT"
Else
Keyword = "SPECIAL"
End If
If DisplayInterpreterComments = True Then
For i As Integer = 0 To (components.Length() - 1)
'Console.Write(components(i) & " ")
If components(i).Contains(";") Then
'newline
Console.Write(Removesemicolon(Line))
Else
Console.Write(components(i) & " ")
End If
Next
End If
If Keyword = "ERROR" Then
If DisplayInterpreterComments = True Then
Console.ForegroundColor = ConsoleColor.DarkYellow
Console.Write(" " & linetype)
Console.ForegroundColor = ConsoleColor.Red
Console.Write(" " & Keyword)
Console.ForegroundColor = ConsoleColor.Gray
End If
If ErrorLineNo = 0 Then
ErrorLineNo = LineNo
Else
multipleerrors = True
End If
ElseIf Keyword = "N/A" Then
If DisplayInterpreterComments = True Then
Console.ForegroundColor = ConsoleColor.DarkYellow
Console.Write(" " & linetype)
Console.ForegroundColor = ConsoleColor.Yellow
Console.Write(" " & Keyword)
Console.ForegroundColor = ConsoleColor.Gray
End If
Else
If DisplayInterpreterComments = True Then
Console.ForegroundColor = ConsoleColor.DarkYellow
Console.Write(" " & linetype)
Console.ForegroundColor = ConsoleColor.Green
Console.Write(" " & Keyword)
Console.ForegroundColor = ConsoleColor.Gray
End If
End If
If DisplayInterpreterComments = True Then
Console.WriteLine()
End If
'### interpret line of code ###
If DisplayInterpreterComments = False And (linetype = "NORMAL" Or linetype = "EXPONENT" Or linetype = "SUBSCRIPT" Or linetype = "MAIN") Then
Try
SendLineToSub(Keyword)
Catch e As Exception
MsgBox($"The interpreter encountered an error. The interpreter may not function correctly.
Line: {LineNo}
Error: {e}", MsgBoxStyle.Exclamation, "Interpreter Error")
End Try
End If
LineNo = LineNo + 1
If Keyword = "END OF PROGRAM" Then
endofprogram = True
End If
End Using
Loop
Console.WriteLine()
Console.WriteLine("Error Summary:")
If ErrorLineNo <> 0 And multipleerrors = False Then
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Syntax error; Line: " & ErrorLineNo)
Console.ForegroundColor = ConsoleColor.Gray
ElseIf ErrorLineNo <> 0 And multipleerrors = True Then
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Multiple Errors. First Error: Line: " & ErrorLineNo)
Console.ForegroundColor = ConsoleColor.Gray
ElseIf ErrorLineNo = 0 Then
Console.ForegroundColor = ConsoleColor.Green
Console.WriteLine("No Errors.")
Console.ForegroundColor = ConsoleColor.Gray
End If
End Sub
Sub SetLineNo(line)
LineNo = line
End Sub
Sub SendLineToSub(Keyword)
'setup components
Dim components() As String = Line.Split(New Char() {" "c})
For i As Integer = 0 To (components.Length() - 1)
'Console.Write(components(i) & " ")
If components(i).Contains(";") Then
components(i) = (Removesemicolon(Line))
End If
Next
'split brackets
For i As Integer = 0 To (components.Length() - 1)
Try
If components(i).Contains("(") Then
Dim tempvalue(components.Length + 2) As String
For x As Integer = i To (components.Length - 1)
tempvalue(x + 1) = components(x)
Next
If ReturnOperator(Line, "(") <> Nothing Then
ReDim Preserve components(components.Length + 1) 'this was originally on line 193
components(i) = (ReturnOperator(Line, "("))
components(i + 1) = ReturnOperand(Line)
For x As Integer = i + 2 To (components.Length - 1)
components(x) = tempvalue(x)
x = x + 1
Next
Else
components(i) = (ReturnOperand(Line))
End If
End If
Catch 'do nothing
End Try
Next
Select Case Keyword
Case "DECLARATION"
'string
Dim debugvariablename As String = components(3) 'only for a watch (code watch, not a timepiece!)
Try
If components(5).Contains("'") Then 'turn this into a proper sub once it works
Dim noofparts = (components.Length) - 5
Dim declaredstring As String = ""
For i = 0 To noofparts - 1
declaredstring = declaredstring & " " & components(i + 5)
Next
Dim declaredstringchars() As Char = declaredstring.ToCharArray()
For i = 0 To declaredstringchars.Length - 3
declaredstringchars(i) = declaredstringchars(i + 2)
Next
declaredstring = ""
For i = 0 To declaredstringchars.Length - 3
declaredstring = declaredstring & declaredstringchars(i)
Next
DeclareHALVariable(components(3), "STRING", declaredstring)
End If
Catch
End Try
'notstring
Try
If components(5) <> Nothing Then
Dim possiblefunctionname As String = components(5)
Dim functionexists As Boolean = False
Dim functionoutput As String
Try
If ProgramDefinedvariablesTypes(possiblefunctionname) = "FUNCTION" Then
functionexists = True
If functiontriggered = False Then
dofunction(possiblefunctionname, 5)
firstparameterposshift = 5
linetomovetoafterfunctionexecution = linetomovetoafterfunctionexecution - 1
Console.ForegroundColor = ConsoleColor.DarkCyan
Console.WriteLine("Function '" & possiblefunctionname & "'")
Console.ForegroundColor = ConsoleColor.Gray
Else
functionoutput = ProgramDefinedVariables(possiblefunctionname)
DeclareHALVariable(components(3), components(4), functionoutput)
End If
End If
Catch
'function does not exist
End Try
If functionexists = False Then
DeclareHALVariable(components(3), components(4), components(5))
End If
functionexists = False
Else
DeclareHALVariable(components(3), components(4), "0")
End If
If components(3) = "" Then
If multipleerrors = False Then
ErrorLineNo = LineNo
Else
multipleerrors = True
End If
End If
Catch
Try
DeclareHALVariable(components(3), components(4), "0")
Catch
If multipleerrors = False Then
ErrorLineNo = LineNo
Else
multipleerrors = True
End If
End Try
End Try
Case "READ"
Try
If ProgramDefinedvariablesTypes(components(4)) <> "CONSTANT" Then
Console.WriteLine("Channel " & components(3) & " requires input")
Dim inputstring As String = Console.ReadLine()
ProgramDefinedVariables(components(4)) = inputstring
Console.WriteLine("Variable '" & components(4) & "' set to " & ProgramDefinedVariables(components(4)))
Else
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Variable " & components(4) & " cannot be changed as it is a constant.")
Console.ForegroundColor = ConsoleColor.Gray
If ErrorLineNo = 0 Then
ErrorLineNo = LineNo
Else
multipleerrors = True
End If
End If
Catch
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Variable " & components(4) & " does not exist")
Console.ForegroundColor = ConsoleColor.Gray
If ErrorLineNo = 0 Then
ErrorLineNo = LineNo
Else
multipleerrors = True
End If
End Try
Case "WRITE"
Dim newcomponents() As String = Line.Split(New Char() {" "c})
If newcomponents(3).Contains("'") Then
Dim noofparts = (newcomponents.Length) - 3
Dim declaredstring As String = ""
For i = 0 To (noofparts - 1)
If newcomponents(i + 3).Contains(";") Then newcomponents(i + 3) = Removesemicolon(newcomponents(i + 3))
declaredstring = declaredstring & " " & newcomponents(i + 3)
Next
Dim declaredstringchars() As Char = declaredstring.ToCharArray()
For i = 0 To declaredstringchars.Length - 3
declaredstringchars(i) = declaredstringchars(i + 2)
Next
declaredstring = ""
For i = 0 To declaredstringchars.Length - 3
declaredstring = declaredstring & declaredstringchars(i)
Next
If declaredstring.Contains("'") Then
Dim declaredstringchararray As Char() = declaredstring.ToCharArray()
declaredstring = ""
For i = 0 To declaredstringchararray.Length - 2
declaredstring = declaredstring & declaredstringchararray(i)
Next
End If
HALwrite(components(3), declaredstring, "string")
Else
Try
Dim writecomponents() As String = Line.Split(New Char() {" "c})
HALwrite(components(3), Newarithmetic(Removesemicolon(writecomponents(3))), "normal")
Catch
Dim writecomponents() As String = Line.Split(New Char() {" "c})
Dim argumentno As Integer = 0
For i As Integer = 3 To writecomponents.Length - 1
If writecomponents(i) <> Nothing Then
argumentno = argumentno + 1
End If
Next
If argumentno = 1 Then
HALwrite(components(3), components(4), "normal")
ElseIf argumentno = 0 Then
If ErrorLineNo = 0 Then
ErrorLineNo = LineNo
Else
multipleerrors = True
End If
Else
'convert to literal //Not Needed anymore
End If
End Try
End If
Case "ASSIGNMENT"
Try
Dim assignmentcomponents() As String = Line.Split(New Char() {" "c})
' original line: ProgramDefinedVariables(assignmentcomponents(2)) = Removesemicolon(assignmentcomponents(4))
assignmentcomponents(4) = Removesemicolon(assignmentcomponents(4))
Try
ProgramDefinedVariables(assignmentcomponents(2)) = Newarithmetic(assignmentcomponents(4)) ' was = Newarithmetic(ProgramDefinedVariables(assignmentcomponents(2)))
Console.WriteLine("Variable '" & assignmentcomponents(2) & "' set to '" & ProgramDefinedVariables(assignmentcomponents(2)) & "'")
Catch
End Try
Catch
Errorupdate(LineNo)
End Try
Case "CONDITIONAL EXECUTION"
Dim elseexists As Boolean = True
Conditionalexecution(components(3), components(5), components(4))
Console.WriteLine("Comparison '" & components(3) & " " & components(4) & " " & components(5) & "' = " & condition)
If condition = True Then
ElseIf condition = False Then
Dim lineamounttochange As Integer = LineNo
Dim linecontainselse As Boolean = False
Using fileline As New StreamReader(workingfile)
Do Until linecontainselse
Dim line As String = "placeholder" 'sort out null reference
For i = 1 To lineamounttochange
line = fileline.ReadLine() ' sort out loop
Next
Try
If line.Contains("ELSE;") Then
linecontainselse = True
LineNo = LineNo + 1
Else
lineamounttochange = 1
End If
Catch
elseexists = False
Exit Do
End Try
Loop
End Using
If elseexists = False Then movelinetokeyword("END")
End If
Case "ELSE"
If condition = True Then
'move to "END;"
Dim lineamounttochange As Integer = LineNo
Dim linecontainsend As Boolean = False
Dim totallineschanged As Integer = 0
Using fileline As New StreamReader(workingfile)
Do Until linecontainsend
Dim line As String = "placeholder" 'stop null reference exceptions
For i = 1 To lineamounttochange
line = fileline.ReadLine() ' sort out loop
Next
If line.Contains("END;") Then
linecontainsend = True
LineNo = LineNo + totallineschanged
Else
lineamounttochange = 1
totallineschanged = totallineschanged + 1
End If
Loop
End Using
End If
Case "DO"
linenotoloopto = LineNo
If components(3) = "FOR" Then 'do for loop
If forloopset = False Then
ProgramDefinedVariables(components(4)) = components(6)
loopvariablename = components(4)
forloopset = True
End If
If ProgramDefinedVariables(components(4)) = components(8) Then
linenotoloopto = 0
Dim lineamounttochange As Integer = LineNo '##### For 1 To 10 would generate i = 1 To 9, but still sdet i To 10 aafterwards
Dim linecontainsend As Boolean = False
Dim totallineschanged As Integer = 0
Using fileline As New StreamReader(workingfile)
Do Until linecontainsend
Dim line As String = "placeholder" 'stop null reference exception
For i = 1 To lineamounttochange
line = fileline.ReadLine() ' sort out loop
Next
If line.Contains("END;") Then
linecontainsend = True
LineNo = LineNo + totallineschanged
linenotoloopto = LineNo
Else
lineamounttochange = 1
totallineschanged = totallineschanged + 1
End If
Loop
End Using
Else
If forloopset = True Then
ProgramDefinedVariables(components(4)) = ProgramDefinedVariables(components(4)) + 1
End If
End If
End If
Case "END"
If condition = False Then
If linenotoloopto = 0 Then
LineNo = LineNo + 1
Else
LineNo = linenotoloopto - 1
End If
End If
linenotoloopto = 0
Case "EXPONENT"
Exponentiate(Line)
Case "FUNCTION"
If functiontriggered = False Then 'create namespace for function
If ProgramDefinedVariables.ContainsKey(Removechar(components(2), ":")) Then
Else
DeclareHALVariable(Removechar(components(2), ":"), "FUNCTION", "NULL")
End If 'move to end of function
movelinetokeyword("CLOSE")
Else
Try 'if there are parameters this won't catch
Dim variablestype As String = components(components.Length - 2)
Dim parameters As String = components(4)
Dim functionoperands() As String = parameters.Split(",")
If functionoperands.Length > 1 Then
For i = 0 To functionoperands.Length - 1
Try
functionoperandvalues(i + firstparameterposshift) = Convert.ToInt64(functionoperandvalues(i + firstparameterposshift))
Catch
End Try
DeclareHALVariable(functionoperands(i), variablestype, functionoperandvalues(i + firstparameterposshift))
Next
Else
Try
functionoperandvalues(0 + firstparameterposshift) = Convert.ToDouble(functionoperandvalues(0 + firstparameterposshift))
Catch
End Try
DeclareHALVariable(functionoperands(0), variablestype, functionoperandvalues(0 + firstparameterposshift))
End If
Catch 'no parameters for this function
End Try
End If 'else don't do anything (skip to next line ignoring this one)
Case "FUNCTION INVOCATION"
dofunction(components(2), 2)
firstparameterposshift = 2
Console.ForegroundColor = ConsoleColor.DarkCyan
Console.WriteLine("Function '" & components(2) & "'")
Console.ForegroundColor = ConsoleColor.Gray
Case "END OF FUNCTION"
If functiontriggered = True Then
LineNo = linetomovetoafterfunctionexecution
Console.ForegroundColor = ConsoleColor.DarkCyan
Console.WriteLine("End Of Function")
Console.ForegroundColor = ConsoleColor.Gray
End If
Case "FUNCTION RETURN"
Try
ProgramDefinedVariables(activefunction) = ProgramDefinedVariables(components(3)) 'returning value of a variable
Catch
Try
ProgramDefinedVariables(activefunction) = Convert.ToDouble(components(3)) 'returning a number
Catch
Try
ProgramDefinedVariables(activefunction) = Newarithmetic(components(3)) 'returning an arithmetic operation
Catch
ProgramDefinedVariables(activefunction) = components(3) ' returning a string
End Try
End Try
End Try
Console.WriteLine("Value of function '" & activefunction & "' set to " & ProgramDefinedVariables(activefunction))
Case "SCHEDULE"
'Console.Write("Scheduling is currently in Beta.")
Dim schedulecomponents() As String = Line.Split(New Char() {" "c})
Dim schedulepriority = Convert.ToInt64(ReturnOperand(Removechar(schedulecomponents(4), ",")))
Dim repeattime As Double = 1 / Convert.ToDouble(Removechar(schedulecomponents(7), ";"))
Dim functionnamearraypos As Integer
Dim functionnamefound As Boolean = False
Dim x As Integer = 0
Try
Do Until functionnamefound
If procedurelocations(x) = schedulecomponents(3) Then
functionnamearraypos = x
End If
x = x + 1
Loop
Catch
Console.WriteLine("Realtime mode not initialised.")
Errorupdate(LineNo)
End Try
Case "PROGRAM DECLARATION"
Console.ForegroundColor = ConsoleColor.DarkBlue
Console.WriteLine("Program '" & mainprogramname & "'")
Console.ForegroundColor = ConsoleColor.Gray
Case "END OF PROGRAM"
Console.ForegroundColor = ConsoleColor.DarkBlue
Console.WriteLine("End Of Program")
Console.ForegroundColor = ConsoleColor.Gray
Case Else
'do nothing
End Select
End Sub
Sub BuiltInFunctions()
builtinfunctiongenerated = True
defaultfunctions(0) = "SIN"
defaultfunctions(1) = "COS"
defaultfunctions(2) = "TAN"
For i = 0 To defaultfunctions.Length - 1
If defaultfunctions(i) <> Nothing Then
DeclareHALVariable(defaultfunctions(i), "FUNCTION", "NULL")
End If
Next
End Sub
Function Newarithmetic(inputstring)
If builtinfunctiongenerated = False Then
BuiltInFunctions()
End If
Dim chararray() As Char = inputstring.ToCharArray()
'convert from hal/s to standard notation (** -> ^)
Dim charnotoremove As Integer = 0 'chars to remove from end
For i = 0 To chararray.Length - 2
If chararray(i) = "*" And chararray(i + 1) = "*" Then
chararray(i) = "^"
For x = (i + 2) To chararray.Length - 1
chararray(x - 1) = chararray(x)
Next
charnotoremove = charnotoremove + 1
End If
Next
ReDim Preserve chararray(chararray.Length - (1 + charnotoremove))
'cluster operands together i.e. from ("3", ".", "1", "4", "+", "3", "3") to ("3.14", "+", "33")
Dim linecomponentsarray(chararray.Length) As String
Dim firstoperandlength As Integer
'firstoperand
If Not (chararray(0) = "+" Or chararray(0) = "-" Or chararray(0) = "*" Or chararray(0) = "/" Or chararray(0) = "^" Or chararray(0) = "(") Then
Dim reachedterminator As Boolean = False
Dim firstoperand As String = ""
Dim x As Integer = 0
Do Until reachedterminator
Try
If chararray(x) = "+" Or chararray(x) = "-" Or chararray(x) = "*" Or chararray(x) = "/" Or chararray(x) = "^" Or chararray(x) = "(" Or x = chararray.Length Then 'or x = chararray.Length -1
reachedterminator = True
Else
firstoperand = firstoperand & chararray(x)
x = x + 1
End If
Catch 'end of inputstring
reachedterminator = True
End Try
Loop
firstoperandlength = x
linecomponentsarray(0) = firstoperand
Else
linecomponentsarray(0) = chararray(0)
End If
'all other operands (and operators)
For i = (firstoperandlength) To chararray.Length - 1
Dim reachedterminator As Boolean = False
Dim operand As String = ""
Dim x As Integer = 0
If chararray(i) = "+" Or chararray(i) = "-" Or chararray(i) = "*" Or chararray(i) = "/" Or chararray(i) = "^" Or chararray(i) = "(" Or chararray(i) = ")" Then
x = i + 1
Do Until reachedterminator
Try
If chararray(x) = "+" Or chararray(x) = "-" Or chararray(x) = "*" Or chararray(x) = "/" Or chararray(x) = "^" Or chararray(x) = "(" Or chararray(x) = ")" Then
reachedterminator = True
Else
operand = operand & chararray(x)
x = x + 1
End If
Catch
reachedterminator = True
End Try
Loop
linecomponentsarray(i) = chararray(i)
If operand <> "" Then
linecomponentsarray(i + 1) = operand
End If
i = x - 1
Else
linecomponentsarray(i) = chararray(i)
End If
Next
'remove blank spaces in array
Dim noofdata As Integer = 0
For i As Integer = 0 To linecomponentsarray.Length - 1
If linecomponentsarray(i) <> Nothing Then
noofdata = noofdata + 1
End If
Next
Dim dataarray(noofdata) As String
For i As Integer = 0 To linecomponentsarray.Length - 1
If linecomponentsarray(i) <> Nothing Then
For x = 0 To noofdata - 1
If dataarray(x) = Nothing Then
dataarray(x) = linecomponentsarray(i)
Exit For
End If
Next
End If
Next
ReDim Preserve dataarray(noofdata - 1)
ReDim linecomponentsarray(noofdata - 1)
For i = 0 To noofdata - 1
linecomponentsarray(i) = dataarray(i)
Next
'###CONVERT VARIABLE NAMES TO NUMBERS HERE### (in hal/s interpreter)
For i = 0 To linecomponentsarray.Length - 1
If ProgramDefinedVariables.ContainsKey(linecomponentsarray(i)) Then
If ProgramDefinedvariablesTypes(linecomponentsarray(i)) <> "FUNCTION" Then
linecomponentsarray(i) = ProgramDefinedVariables(linecomponentsarray(i))
Else
'function
End If
End If
Next
'###ADD FUNCTION SUPPORT HERE
Dim functionno As Integer
'create list of function to reset later (and no of functions to do)
Dim linefunctions As New List(Of String)
For i = 0 To linecomponentsarray.Length - 1
If ProgramDefinedVariables.ContainsKey(linecomponentsarray(i)) Then
If ProgramDefinedvariablesTypes(linecomponentsarray(i)) = "FUNCTION" Then
functionno = functionno + 1
linefunctions.Add(linecomponentsarray(i))
End If
End If
Next
Do Until functionno = 0
Try
For i = 0 To linecomponentsarray.Length - 1
If ProgramDefinedVariables.ContainsKey(linecomponentsarray(i)) Then
If ProgramDefinedvariablesTypes(linecomponentsarray(i)) = "FUNCTION" Then
If ProgramDefinedVariables(linecomponentsarray(i)) = "NULL" Then
doarithmeticfunction(linecomponentsarray(i), i, linecomponentsarray) '###Need to send the value of the function back to this thread.
Console.ForegroundColor = ConsoleColor.DarkCyan
Console.WriteLine("Function '" & linecomponentsarray(i) & "'")
Console.ForegroundColor = ConsoleColor.Gray
functionno = functionno - 1
Exit Do
Else
linecomponentsarray(i) = ProgramDefinedVariables(linecomponentsarray(i))
For x As Integer = i + 1 To linecomponentsarray.Length - 4
linecomponentsarray(x) = linecomponentsarray(x + 3)
Next
functionno = functionno - 1
ReDim Preserve linecomponentsarray(linecomponentsarray.Length - 4)
End If
End If
End If
Next
Catch
End Try
Loop
For Each item In linefunctions
ProgramDefinedVariables(item) = "NULL"
Next
'###Shunting Yard Algorithm###
Dim input(linecomponentsarray.Length - 1) As String
'change linecomponents over to input (to make debugging easier)
For i = 0 To linecomponentsarray.Length - 1
input(i) = linecomponentsarray(i)
Next
Dim token As String
Dim output As New List(Of String)
Dim operatorstack As Stack = New Stack
Dim operatorprecedence As Integer
Dim lastoperatorprecendence As Integer
Dim spacejunk As New List(Of String)
For i = 0 To input.Length - 1
token = input(i)
Dim isoperator As Boolean
Try
token = Convert.ToDouble(token)
isoperator = False
Catch
isoperator = True
End Try
If isoperator = False Then output.Add(token)
If isoperator = True Then
Try
operatorprecedence = getoperatorprecedence(token)
Catch
Console.WriteLine("Invalid algebraic string")
End Try
Dim stoploop As Boolean = False
Dim lastoperatorassociativity As String
Do Until stoploop
Try
lastoperatorprecendence = getoperatorprecedence(operatorstack(0))
lastoperatorassociativity = getassociation(operatorstack(0))
Catch 'no operators
lastoperatorprecendence = -1 'not 0 as that would mess up '('
lastoperatorassociativity = "L"
End Try
If lastoperatorprecendence >= operatorprecedence And operatorstack(0) <> "(" And operatorstack(0) <> ")" And lastoperatorassociativity = "L" Then
output.Add(operatorstack.Pop())
ElseIf token = "(" Then
operatorstack.Push(token)
stoploop = True
ElseIf token = ")" Then
While operatorstack(0) <> "("
output.Add(operatorstack.Pop())
End While
spacejunk.Add(operatorstack.Pop())
stoploop = True
ElseIf lastoperatorprecendence < operatorprecedence And token = "^" Then
operatorstack.Push(token)
stoploop = True
ElseIf lastoperatorprecendence >= operatorprecedence And operatorstack(0) <> "(" And operatorstack(0) <> ")" Then
output.Add(operatorstack.Pop())
Else
operatorstack.Push(token)
stoploop = True
End If
Loop
End If
Next
'move remaining operators
Do Until operatorstack(0) = Nothing
output.Add(operatorstack.Pop())
Loop
'Console.Write("RPN: ") 'output rpn
'For Each item In output
' Console.Write(item & ", ")
'Next
'work out value of rpn
Dim RPNstack(output.Count - 1)
Dim transferloopcount As Integer = 0
Dim operationpoint As Integer = 0
For Each item In output
Select Case item
Case "+"
RPNstack(transferloopcount - 2) = Convert.ToDouble(RPNstack(transferloopcount - 2)) + Convert.ToDouble(RPNstack(transferloopcount - 1))
RPNstack(transferloopcount - 1) = Nothing
operationpoint = transferloopcount
transferloopcount = transferloopcount - 1
Case "-"
RPNstack(transferloopcount - 2) = Convert.ToDouble(RPNstack(transferloopcount - 2)) - Convert.ToDouble(RPNstack(transferloopcount - 1))
RPNstack(transferloopcount - 1) = Nothing
operationpoint = transferloopcount
transferloopcount = transferloopcount - 1
Case "/"
RPNstack(transferloopcount - 2) = Convert.ToDouble(RPNstack(transferloopcount - 2)) / Convert.ToDouble(RPNstack(transferloopcount - 1))
RPNstack(transferloopcount - 1) = Nothing
operationpoint = transferloopcount
transferloopcount = transferloopcount - 1
Case "*"
RPNstack(transferloopcount - 2) = Convert.ToDouble(RPNstack(transferloopcount - 2)) * Convert.ToDouble(RPNstack(transferloopcount - 1))
RPNstack(transferloopcount - 1) = Nothing
operationpoint = transferloopcount
transferloopcount = transferloopcount - 1
Case "^"
RPNstack(transferloopcount - 2) = Convert.ToDouble(RPNstack(transferloopcount - 2)) ^ Convert.ToDouble(RPNstack(transferloopcount - 1))
RPNstack(transferloopcount - 1) = Nothing
operationpoint = transferloopcount
transferloopcount = transferloopcount - 1
Case Else
RPNstack(transferloopcount) = item
transferloopcount = transferloopcount + 1
End Select
For i = operationpoint To RPNstack.Length - 1
If RPNstack(i) = Nothing Then
Try
RPNstack(i) = RPNstack(i + 1)
Catch
End Try
End If
Next
Next
Console.WriteLine("Arithmetic Operation Returned: " & RPNstack(0))
Return RPNstack(0)
End Function
Function getoperatorprecedence(token)
Select Case token
Case "+"
Return 2
Case "-"
Return 2
Case "/"
Return 3
Case "*"
Return 3
Case "^"
Return 4
Case "("
Return 9
Case ")"
Return 0
Case Else
Return "ERROR"
End Select
End Function
Function getassociation(token)
If token = "^" Then
Return "R"
Else
Return "L"
End If
End Function
Sub movelinetokeyword(keywordtofind)
Dim lineamounttochange As Integer = LineNo
Dim linecontainsend As Boolean = False
Dim totallineschanged As Integer = 0
Using fileline As New StreamReader(workingfile)
Do Until linecontainsend
Dim line As String = "placeholder" 'stop null reference exceptions
For i = 1 To lineamounttochange
line = fileline.ReadLine() ' sort out loop
Next
If line.Contains(keywordtofind) Then
linecontainsend = True
LineNo = LineNo + totallineschanged
Else
lineamounttochange = 1
totallineschanged = totallineschanged + 1
End If
Loop
End Using
End Sub
Sub Conditionalexecution(value1, value2, comparator)
Try
value1 = Newarithmetic(value1)
Catch
value1 = ProgramDefinedVariables(value1)
End Try
Try
value2 = Newarithmetic(value1)
Catch
value2 = ProgramDefinedVariables(value2)
End Try
If comparator = "=" Then
If value1 = value2 Then
condition = True
Else
condition = False
End If
ElseIf comparator = ">" Then
If value1 > value2 Then
condition = True
Else
condition = False
End If
ElseIf comparator = "<" Then
If value1 < value2 Then
condition = True
Else
condition = False
End If
ElseIf comparator = ">=" Then
If value1 >= value2 Then
condition = True
Else
condition = False
End If
ElseIf comparator = "<=" Then
If value1 <= value2 Then
condition = True
Else
condition = False
End If
End If
End Sub
Sub HALwrite(channel As Integer, identifier As String, type As String)
Try
If identifier <> Nothing Then
Console.WriteLine("Channel " & channel & ": ")
If type = "string" Then Console.ForegroundColor = ConsoleColor.DarkMagenta
Console.WriteLine(identifier)
Console.ForegroundColor = ConsoleColor.Gray
End If
Catch
If ErrorLineNo = 0 Then
ErrorLineNo = LineNo
Else
multipleerrors = True
End If
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Variable '" & identifier & "' has not been declared or has null value")
Console.ForegroundColor = ConsoleColor.Gray
End Try
End Sub
Function Trig(expression, trigfunction)
Select Case trigfunction
Case "SIN"
Return Math.Sin(expression)
Case "COS"
Return Math.Cos(expression)
Case "TAN"
Return Math.Tan(expression)
Case Else
Return "ERROR"
End Select
End Function
Sub Exponentiate(line)
exponentline = True
line = line.ToString
Dim components() As Char = line.tochararray()
exponentno = 0
Dim tempvalue As Integer
For i = 0 To components.Length - 1
If components(i) <> " " And components(i) <> "E" Then
tempvalue = Convert.ToInt16(components(i).ToString)
exponents(i) = tempvalue
exponentno = exponentno + 1
End If
Next
End Sub
Sub DeclareHALVariable(identifier, type, value)
Dim isdefaultFunction As Boolean = False
For i = 0 To defaultfunctions.Length - 1
If defaultfunctions(i) = identifier Then isdefaultFunction = True
Next
If value <> "" Then
Try
If value.contains(";") Then value = Removesemicolon(value)
value = Newarithmetic(value)
Catch
End Try
ProgramDefinedVariables(identifier) = value
ProgramDefinedvariablesTypes(identifier) = type
If type = "STRING" Then
Console.WriteLine("Variable '" & identifier & "' of type '" & ProgramDefinedvariablesTypes(identifier) & "' created with value '" & ProgramDefinedVariables(identifier) & "'")
Else
If isdefaultFunction = False Then
Console.WriteLine("Variable '" & identifier & "' of type '" & ProgramDefinedvariablesTypes(identifier) & "' created with value " & ProgramDefinedVariables(identifier))
End If
End If
Else
ProgramDefinedVariables(identifier) = "0"
ProgramDefinedvariablesTypes(identifier) = type
If type <> "" Then
Console.WriteLine("Variable '" & identifier & "' of type '" & ProgramDefinedvariablesTypes(identifier) & "' created and unassigned.")
End If
End If
End Sub
Function Removesemicolon(line)
Dim lastword As String = ""
Dim components() As String = line.Split(New Char() {" "c})
For i As Integer = 0 To (components.Length - 1)
If components(i).Contains(";") Then
Dim charArray() As Char = components(i).ToCharArray
For x As Integer = 0 To (charArray.Length - 2)
lastword = lastword & charArray(x)
Next
End If
Next
Return lastword
End Function
Function Removechar(line, chartoremove)
Dim lastword As String = ""
Dim components() As String = line.Split(New Char() {" "c})
For i As Integer = 0 To (components.Length - 1)
If components(i).Contains(chartoremove) Then
Dim charArray() As Char = components(i).ToCharArray
For x As Integer = 0 To (charArray.Length - 2)
lastword = lastword & charArray(x)
Next
End If
Next
Return lastword
End Function
Sub dofunction(functionname, firstparameterpos)
activefunction = functionname
linetomovetoafterfunctionexecution = LineNo
LineNo = -1
movelinetokeyword(functionname)
functiontriggered = True
Dim newcomponents() As String = Line.Split(New Char() {" "c})
For i As Integer = 0 To (newcomponents.Length() - 1)
'Console.Write(components(i) & " ")
If newcomponents(i).Contains(";") Then
newcomponents(i) = (Removesemicolon(Line))
End If
Next
newcomponents(firstparameterpos) = ReturnOperand(newcomponents(firstparameterpos) & ")") 'trick returnoperand into allowing the broken input
If newcomponents(firstparameterpos).Contains(",") Then newcomponents(firstparameterpos) = Removechar(newcomponents(firstparameterpos), ",")
If ProgramDefinedVariables.ContainsKey(newcomponents(firstparameterpos)) Then
functionoperandvalues(firstparameterpos) = ProgramDefinedVariables(newcomponents(firstparameterpos))
Else
functionoperandvalues(firstparameterpos) = newcomponents(firstparameterpos)
End If
For i = (firstparameterpos + 1) To newcomponents.Length - 1 'sort out so it allocates the operands for the function ###########
If newcomponents(i).Contains(",") Then
Try
functionoperandvalues(i) = ProgramDefinedVariables(Removechar(newcomponents(i), ","))
Catch
functionoperandvalues(i) = Removechar(newcomponents(i), ",")
End Try
ElseIf newcomponents(i).Contains(")") Then
Try
functionoperandvalues(i) = ProgramDefinedVariables(Removechar(newcomponents(i), ")"))
Catch
functionoperandvalues(i) = Removechar(newcomponents(i), ")")
End Try
Else
Try
functionoperandvalues(i) = ProgramDefinedVariables(newcomponents(i))
Catch
functionoperandvalues(i) = newcomponents(i)
End Try
End If
Next
End Sub
Sub doarithmeticfunction(functionname, functionpos, linecomponentsarray())
activefunction = functionname
Dim isdefaultfunction As Boolean = False
For j = 0 To defaultfunctions.Length - 1
If activefunction = defaultfunctions(j) Then isdefaultfunction = True
Next
If isdefaultfunction = False Then
linetomovetoafterfunctionexecution = LineNo - 1
LineNo = -1
movelinetokeyword(functionname)
functiontriggered = True
Dim parameterstring As String = linecomponentsarray(functionpos + 2)
Dim charparameters() As Char = parameterstring.ToCharArray()
Dim commasremoved As Integer = 0
Dim parameters As New List(Of String)
Dim currentoperand As String = ""
For i = 0 To charparameters.Length - 1
If charparameters(i) = "," Then
parameters.Add(currentoperand)
currentoperand = ""
commasremoved = commasremoved + 1
Else
currentoperand = currentoperand & charparameters(i)
End If
Next
parameters.Add(currentoperand)
If parameters.Count > 1 Then
Dim finalparameters(parameters.Count - 1)
For i = 0 To parameters.Count - commasremoved
Try
finalparameters(i) = parameters(i)
Catch
End Try
Next
For i = 0 To finalparameters.Length - 1
functionoperandvalues(i) = finalparameters(i)
Next
Else
functionoperandvalues(0) = parameters(0)
End If
Else 'default functions
LineNo = LineNo - 1
End If
End Sub
Function ReturnOperator(line, charactertoremove)
Dim operatorhalf As String = Nothing
Dim components() As String = line.Split(New Char() {" "c})
For i As Integer = 0 To (components.Length - 1)
If components(i).Contains(charactertoremove) Then
Dim charArray() As Char = components(i).ToCharArray
Dim leftbracket As Boolean = False
Dim x As Integer = 0
Do Until leftbracket = True
If charArray(x) <> charactertoremove Then
operatorhalf = operatorhalf & charArray(x)
Else
leftbracket = True
End If
x = x + 1
Loop
End If
Next
Return operatorhalf
End Function
Function ReturnOperand(line)
Dim operand As String = ""
Dim components() As String = line.Split(New Char() {" "c})
For i As Integer = 0 To (components.Length - 1)
If components(i).Contains("(") Then
Dim charArray() As Char = components(i).ToCharArray
Dim leftbracket As Boolean = False
Dim rightbracket As Boolean = False
Dim x As Integer = 0
Do Until leftbracket = True
If charArray(x) = "(" Then
Do Until rightbracket = True
If charArray(x) <> ")" And charArray(x) <> "(" Then
operand = operand & charArray(x)
ElseIf charArray(x) = ")" Then
rightbracket = True
End If 'fix so it doesn't output write6
If charArray(x) = ")" Then
rightbracket = True
End If
x = x + 1
Loop
leftbracket = True
End If
x = x + 1
Loop
End If
Next
Return operand
End Function
Function Getkeyword(line)
Dim firstpart As String = "NULL"
Dim components() As String = line.Split(New Char() {" "c})
For i = 0 To components.Length - 1
If components(i).Contains("(") Then
components(i) = ReturnOperator(line, "(")
End If
Next
Try
If components(2).Contains(":") And components(3) = "FUNCTION" Then Return "FUNCTION"
Catch
End Try
Dim istext As Boolean = False
Dim x As Integer = -1
Do Until istext
x = x + 1
If components(x) <> Nothing Then
istext = True
End If
Loop
firstpart = components(x)
Try
Select Case firstpart
'E, M, S, C, D
'Case "E" 'ignore
'Case "M"
'Case "S"
'Case "C"
' Return "COMMENT"
'Case "D"
Case "DECLARE"
Return "DECLARATION"
Case "SIMPLE:"
mainprogramname = Removesemicolon(components(3))
Return "PROGRAM DECLARATION"
Case "CLOSE"
If Removesemicolon(components(3)) = "SIMPLE" Then
Return "END OF PROGRAM"
Else
Return "END OF FUNCTION"
functiontriggered = False
End If
Case "READ"
Return "READ"
Case "WRITE"
Return "WRITE"
Case "IF"
Return "CONDITIONAL EXECUTION"
Case "ELSE;"
Return "ELSE"
Case "END"
Return "END"
Case "END;"
Return "END"
Case "DO"
Return "DO"
Case ProgramDefinedVariables.ContainsKey(firstpart)
'Console.WriteLine("assignment")
Return "ASSIGNMENT"
Case "FUNCTION"
Return "FUNCTION PARAMETERS"
Case "RETURN"
Return "FUNCTION RETURN"
Case "SCHEDULE"
Return "SCHEDULE"
Case Else
If ProgramDefinedVariables.ContainsKey(firstpart) Then
'Console.WriteLine("assignment")
If ProgramDefinedvariablesTypes(firstpart) = "FUNCTION" Then
Return "FUNCTION INVOCATION"
Else
Return "ASSIGNMENT"
End If
Else
Return "N/A"
End If
End Select
Catch
Return "Error"
End Try
End Function
Function Getlinetype(line)
Dim components() As String = line.Split(New Char() {" "c})
Select Case components(0)
'line is marked
Case "E"
Return "EXPONENT"
Case "M"
Return "MAIN"
Case "S"
Return "SUBSCRIPT"
Case "C"
Return "COMMENT"
Case "D"
Return "OTHER"
Case Else
Return "NORMAL"
End Select
End Function
Sub Userinput()
Dim quit As Boolean = False
Do Until quit
Console.WriteLine("Do you want To view(v), create(c) variables Or quit(q)")
operationchoice = Console.ReadLine()
If operationchoice = "c" Then
Console.WriteLine("Enter a variable name")
variablenametocreate = Console.ReadLine()
Console.WriteLine("Enter the variable type")
variabletype = Console.ReadLine()
Console.WriteLine("Enter variable value (variable Is a " & variabletype & ")")
variablevalue = Console.ReadLine()
ProgramDefinedVariables(variablenametocreate) = variablevalue
ProgramDefinedvariablesTypes(variablenametocreate) = variabletype
ElseIf operationchoice = "v" Then
Console.WriteLine("Enter a variable To read")
variabletoread = Console.ReadLine()
Console.WriteLine("Showing variable '" & variabletoread & "' of type " & ProgramDefinedvariablesTypes(variabletoread))
Try
If ProgramDefinedVariables(variabletoread) = "" Then
Console.WriteLine("Value: Null Value")
Else
Console.WriteLine("Value: " & ProgramDefinedVariables(variabletoread))
End If
Catch
Console.WriteLine("Value: Null Value")
End Try
ElseIf operationchoice = "q" Then
quit = True
End If
Loop
End Sub
Sub Errorupdate(lineno)
If ErrorLineNo = 0 Then
ErrorLineNo = lineno
Else
multipleerrors = True
End If
End Sub
Sub Logo()
Console.WriteLine(" _ _ __ __ __ ____")
Console.WriteLine("| |__| | //\\ | | / / | __|")
Console.WriteLine("| __ | //__\\ | |__ / / |__ |")
Console.WriteLine("|_| |_| // \\ |____| /_/ |____|")
Console.WriteLine()
End Sub
Sub Tribute()
Console.WriteLine("Written entirely by Thomas Curry with extensive reference to NASA's 'Programming in HAL /S' (1978) By Michael J Ryer.")
Console.WriteLine("Dedicated to the crews of STS-51-L Challenger and STS-107 Columbia.")
Console.WriteLine("STS-51-L:")
Console.WriteLine("Commander Dick Scobee")
Console.WriteLine("Pilot Michael Smith")
Console.WriteLine("Gregory Jarvis")
Console.WriteLine("Elison Onazuka")
Console.WriteLine("Judith Resnick")
Console.WriteLine("Ronald Mcnair")
Console.WriteLine("Christa Mcaulife")
Console.WriteLine("STS-107:")
Console.WriteLine("Commander Rick Husband")
Console.WriteLine("Pilot William McCool")
Console.WriteLine("David Brown")
Console.WriteLine("Kalpana Chawla")
Console.WriteLine("Michael Anderson")
Console.WriteLine("Laurel Clark")
Console.WriteLine("Ilan Ramon")
End Sub
End Module
|
TWCurry/HAL-S-Interpreter
|
HAL Interpreter/Module1.vb
|
Visual Basic
|
mit
| 69,352
|
Partial Class Termsand_Conditions
Inherits System.Web.UI.Page
Dim cf As New comonfunctions
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
tdip.InnerHtml = "We Track Each and Every Visitor Your Ip Address is " & Request.ServerVariables("REMOTE_ADDR")
Label1.Text = cf.websitename
End Sub
End Class
|
aminnagpure/matrimonydatingcommunity1.0
|
lovenmarry - EmptyFreeCode/Termsand Conditions.aspx.vb
|
Visual Basic
|
mit
| 377
|
'*******************************************************************************************'
' '
' 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.Data.OleDb
Imports System.Globalization
Imports System.IO
Imports Bytescout.PDFExtractor
Namespace ConsoleApplication1
Class Program
Shared Sub Main(ByVal args As String())
Dim inputDocument As String = Path.GetFullPath(".\UnicodeSample.pdf")
Dim csvFilePath As String = Path.ChangeExtension(inputDocument, ".csv")
Dim csvFileName As String = Path.GetFileName(csvFilePath)
Dim csvDirectory As String = Path.GetDirectoryName(Path.GetFullPath(csvFilePath))
' Create Bytescout.PDFExtractor.CSVExtractor instance
Using extractor As CSVExtractor = New CSVExtractor("demo", "demo")
extractor.LoadDocumentFromFile(inputDocument)
extractor.CSVSeparatorSymbol = ","
Dim csvText As String = extractor.GetCSV()
' Save csv text in UTF-8 encoding without BOM (byte order mark):
File.WriteAllText(csvFilePath, csvText)
End Using
' Please Note: Target the project to x86 because Microsoft.Jet.OLEDB.4.0 driver is 32-bit only.
Using connection As OleDbConnection = New OleDbConnection($"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""{csvDirectory}"";Extended Properties=""Text;FMT=$;HDR=No;CharacterSet=65001""")
Using command As OleDbCommand = New OleDbCommand($"select * from [{csvFileName}]", connection)
Using adapter As OleDbDataAdapter = New OleDbDataAdapter(command)
Dim table As DataTable = New DataTable()
table.Locale = CultureInfo.CurrentCulture
adapter.Fill(table)
Console.WriteLine($"Loaded {table.Rows.Count} lines.")
End Using
End Using
End Using
Console.ReadKey()
End Sub
End Class
End Namespace
|
bytescout/ByteScout-SDK-SourceCode
|
PDF Extractor SDK/VB.NET/Load Unicode CSV to DataTable using OLEDB/Module1.vb
|
Visual Basic
|
apache-2.0
| 2,932
|
' ******************************************************************************
' **
' ** 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.Weather
Public Class LocationInfo
Private mCityName, mRegion, mCountry As String
Public Property City() As String
Get
Return mCityName
End Get
Set(ByVal value As String)
mCityName = value
End Set
End Property
Public Property Region() As String
Get
Return mRegion
End Get
Set(ByVal value As String)
mRegion = value
End Set
End Property
Public Property Country() As String
Get
Return mCountry
End Get
Set(ByVal value As String)
mCountry = value
End Set
End Property
End Class
End Namespace
|
agassan/YahooManaged
|
MaasOne.YahooManaged/YahooManaged/Weather/LocationInfo.vb
|
Visual Basic
|
apache-2.0
| 1,976
|
Partial MustInherit Class GeoJsonGeometry(Of T)
Inherits GeoJsonElement(Of T)
Public MustOverride Sub CreateFromDbGeometry(inp As Spatial.DbGeometry)
Public Shared Function FromDbGeometry(inp As Spatial.DbGeometry, Optional withBoundingBox As Boolean = True) As GeoJsonGeometry(Of T)
Dim obj As GeoJsonGeometry(Of T) = CTypeDynamic(Activator.CreateInstance(Of T)(), GetType(T))
If withBoundingBox Then
obj.WithBoundingBox = True
obj.BoundingBox = New Double() {
inp.Envelope.PointAt(1).YCoordinate,
inp.Envelope.PointAt(1).XCoordinate,
inp.Envelope.PointAt(3).YCoordinate,
inp.Envelope.PointAt(3).XCoordinate
}
End If
obj.CreateFromDbGeometry(inp)
Return obj
End Function
End Class
|
jumpinjackie/GeoJSON4EntityFramework
|
GeoJSON4EntityFramework5/Base/GeoJsonGeometryEF5.vb
|
Visual Basic
|
apache-2.0
| 825
|
' 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
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Debugging
Friend Partial Class VisualBasicProximityExpressionsService
Public Class RelevantExpressionsCollector
Inherits VisualBasicSyntaxWalker
Private ReadOnly _includeDeclarations As Boolean
Private ReadOnly _expressions As IList(Of ExpressionSyntax)
Public Sub New(includeDeclarations As Boolean, expressions As IList(Of ExpressionSyntax))
MyBase.New(SyntaxWalkerDepth.Node)
_includeDeclarations = includeDeclarations
_expressions = expressions
End Sub
Private Sub AddExpression(node As ExpressionSyntax)
If node.IsRightSideOfDotOrBang() OrElse
TypeOf node.Parent Is TypeArgumentListSyntax OrElse
TypeOf node.Parent Is AsClauseSyntax OrElse
(node.Parent.Parent IsNot Nothing AndAlso TypeOf node.Parent.Parent Is AsClauseSyntax) OrElse
TypeOf node.Parent Is ImplementsClauseSyntax Then
Return
End If
If node.Parent.IsKind(SyntaxKind.NameColonEquals) Then
Return
End If
_expressions.Add(node)
End Sub
Public Overrides Sub VisitIdentifierName(node As IdentifierNameSyntax)
AddExpression(node)
MyBase.VisitIdentifierName(node)
End Sub
Public Overrides Sub VisitModifiedIdentifier(node As ModifiedIdentifierSyntax)
If _includeDeclarations Then
_expressions.Add(SyntaxFactory.IdentifierName(node.Identifier))
End If
MyBase.VisitModifiedIdentifier(node)
End Sub
Public Overrides Sub VisitQualifiedName(node As QualifiedNameSyntax)
AddExpression(node)
MyBase.VisitQualifiedName(node)
End Sub
Public Overrides Sub VisitMemberAccessExpression(node As MemberAccessExpressionSyntax)
_expressions.Add(node)
MyBase.VisitMemberAccessExpression(node)
End Sub
End Class
End Class
End Namespace
|
abock/roslyn
|
src/Features/VisualBasic/Portable/Debugging/ProximityExpressionsGetter.RelevantExpressionsCollector.vb
|
Visual Basic
|
mit
| 2,635
|
Imports SistFoncreagro.BussinessEntities
Public Interface IFormacionRequeridaRepository
Function GetAllFromFORMACIONREQUERIDA() As List(Of FormacionRequerida)
Function SaveFORMACIONREQUERIDA(ByVal formacionRequerida As FormacionRequerida) As Int32
Function GetFORMACIONREQUERIDAByIdFormacionAndIdPosicion(ByVal IdFormacion As Int32, ByVal IdPosicion As Int32) As FormacionRequerida
Function GetFORMACIONREQUERIDAByIdPosicion(ByVal IdPosicion As Int32) As List(Of FormacionRequerida)
Sub DeleteREQUISITOADICIONAL(ByVal IdFormacion As Int32, ByVal IdPosicion As Int32)
End Interface
|
crackper/SistFoncreagro
|
SistFoncreagro.DataAccess/My Project/IFormacionRequeridaRepository.vb
|
Visual Basic
|
mit
| 605
|
' 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.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer
Friend Module UseInitializerHelpers
Public Function GetNewObjectCreation(
objectCreation As ObjectCreationExpressionSyntax,
initializer As ObjectCreationInitializerSyntax) As ObjectCreationExpressionSyntax
If objectCreation.ArgumentList IsNot Nothing AndAlso
objectCreation.ArgumentList.Arguments.Count = 0 Then
objectCreation = objectCreation.WithType(objectCreation.Type.WithTrailingTrivia(objectCreation.ArgumentList.GetTrailingTrivia())).
WithArgumentList(Nothing)
End If
Return objectCreation.WithoutTrailingTrivia().
WithInitializer(initializer).
WithTrailingTrivia(objectCreation.GetTrailingTrivia())
End Function
Public Sub AddExistingItems(objectCreation As ObjectCreationExpressionSyntax, nodesAndTokens As ArrayBuilder(Of SyntaxNodeOrToken))
If TypeOf objectCreation.Initializer Is ObjectMemberInitializerSyntax Then
Dim memberInitializer = DirectCast(objectCreation.Initializer, ObjectMemberInitializerSyntax)
nodesAndTokens.AddRange(memberInitializer.Initializers.GetWithSeparators())
ElseIf TypeOf objectCreation.Initializer Is ObjectCOllectioninitializersyntax Then
Dim collectionInitializer = DirectCast(objectCreation.Initializer, ObjectCollectionInitializerSyntax)
nodesAndTokens.AddRange(collectionInitializer.Initializer.Initializers.GetWithSeparators())
End If
' If we have an odd number of elements already, add a comma at the end so that we can add the rest of the
' items afterwards without a syntax issue.
If nodesAndTokens.Count Mod 2 = 1 Then
Dim last = nodesAndTokens.Last()
nodesAndTokens.RemoveLast()
nodesAndTokens.Add(last.WithTrailingTrivia())
nodesAndTokens.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(last.GetTrailingTrivia()))
End If
End Sub
End Module
End Namespace
|
CyrusNajmabadi/roslyn
|
src/Analyzers/VisualBasic/CodeFixes/UseObjectInitializer/UseInitializerHelpers.vb
|
Visual Basic
|
mit
| 2,563
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
''' <summary>
''' Represents a method of a generic type instantiation.
''' e.g.
''' A{int}.M()
''' A.B{int}.C.M()
''' </summary>
Friend Class SpecializedMethodReference
Inherits MethodReference
Implements Microsoft.Cci.ISpecializedMethodReference
Public Sub New(underlyingMethod As MethodSymbol)
MyBase.New(underlyingMethod)
End Sub
Public Overrides Sub Dispatch(visitor As Microsoft.Cci.MetadataVisitor)
visitor.Visit(DirectCast(Me, Microsoft.Cci.ISpecializedMethodReference))
End Sub
Private ReadOnly Property ISpecializedMethodReferenceUnspecializedVersion As Microsoft.Cci.IMethodReference Implements Microsoft.Cci.ISpecializedMethodReference.UnspecializedVersion
Get
Return m_UnderlyingMethod.OriginalDefinition
End Get
End Property
Public Overrides ReadOnly Property AsSpecializedMethodReference As Microsoft.Cci.ISpecializedMethodReference
Get
Return Me
End Get
End Property
End Class
End Namespace
|
jmarolf/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/SpecializedMethodReference.vb
|
Visual Basic
|
mit
| 1,610
|
' 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 ModuleKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleInFileTest() As Task
Await VerifyRecommendationsContainAsync(<File>|</File>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotInMethodDeclarationTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>|</MethodBody>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleInNamespaceTest() As Task
Await VerifyRecommendationsContainAsync(<NamespaceDeclaration>|</NamespaceDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotInInterfaceTest() As Task
Await VerifyRecommendationsMissingAsync(<InterfaceDeclaration>|</InterfaceDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotInEnumTest() As Task
Await VerifyRecommendationsMissingAsync(<EnumDeclaration>|</EnumDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotInStructureTest() As Task
Await VerifyRecommendationsMissingAsync(<StructureDeclaration>|</StructureDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotInModuleTest() As Task
Await VerifyRecommendationsMissingAsync(<ModuleDeclaration>|</ModuleDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleAfterPartialTest() As Task
Await VerifyRecommendationsContainAsync(<File>Partial |</File>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleAfterPublicTest() As Task
Await VerifyRecommendationsContainAsync(<File>Public |</File>, "Module")
End Function
<Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleAfterEndModuleTest() As Task
Dim code =
<File>
Module M1
End Module
|
</File>
Await VerifyRecommendationsContainAsync(code, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleFollowsDelegateDeclarationTest() As Task
Dim code =
<File>
Delegate Sub DelegateType()
|
</File>
Await VerifyRecommendationsContainAsync(code, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterPublicInClassDeclarationTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Public |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterProtectedInFileTest() As Task
Await VerifyRecommendationsMissingAsync(<File>Protected |</File>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterProtectedInClassDeclarationTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Protected |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleAfterFriendInFileTest() As Task
Await VerifyRecommendationsContainAsync(<File>Friend |</File>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterFriendInClassDeclarationTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Friend |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterPrivateInFileTest() As Task
Await VerifyRecommendationsMissingAsync(<File>Private |</File>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterPrivateInNestedClassTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Private |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterPrivateInNamespaceTest() As Task
Await VerifyRecommendationsMissingAsync(<NamespaceDeclaration>Private |</NamespaceDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterProtectedFriendInFileTest() As Task
Await VerifyRecommendationsMissingAsync(<File>Protected Friend |</File>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterProtectedFriendInClassTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterOverloadsTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Overloads |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterOverridesTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Overrides |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterOverridableTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Overridable |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterNotOverridableTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterMustOverrideTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterMustOverrideOverridesTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>MustOverride Overrides |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterNotOverridableOverridesTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>NotOverridable Overrides |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterConstTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Const |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterDefaultTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Default |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterMustInheritTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterNotInheritableTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterNarrowingTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterWideningTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Widening |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterReadOnlyTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterWriteOnlyTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterCustomTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Custom |</ClassDeclaration>, "Module")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function ModuleNotAfterSharedTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Shared |</ClassDeclaration>, "Module")
End Function
End Class
End Namespace
|
jmarolf/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ModuleKeywordRecommenderTests.vb
|
Visual Basic
|
mit
| 11,263
|
' 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.CompilerServices
Imports CompilationCreationTestHelpers
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Imports Roslyn.Test.Utilities
Namespace CompilationCreationTestHelpers
Friend Module Helpers
<Extension()>
Friend Function BoundReferences(this As AssemblySymbol) As AssemblySymbol()
Return (From m In this.Modules, ref In m.GetReferencedAssemblySymbols() Select ref).ToArray()
End Function
<Extension()>
Friend Function Length(Of T)(this As ImmutableArray(Of T)) As Integer
Return this.Length
End Function
<Extension()>
Friend Function SourceAssembly(this As VisualBasicCompilation) As SourceAssemblySymbol
Return DirectCast(this.Assembly, SourceAssemblySymbol)
End Function
<Extension()>
Private Function HasUnresolvedReferencesByComparisonTo(this As AssemblySymbol, that As AssemblySymbol) As Boolean
Dim thisRefs = this.BoundReferences()
Dim thatRefs = that.BoundReferences()
For i As Integer = 0 To Math.Max(thisRefs.Length, thatRefs.Length) - 1
If thisRefs(i).IsMissing AndAlso Not thatRefs(i).IsMissing Then
Return True
End If
Next
Return False
End Function
<Extension()>
Friend Function RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(this As AssemblySymbol, that As AssemblySymbol) As Boolean
Dim thisPEAssembly = TryCast(this, PEAssemblySymbol)
If thisPEAssembly IsNot Nothing Then
Dim thatPEAssembly = TryCast(that, PEAssemblySymbol)
Return thatPEAssembly IsNot Nothing AndAlso
thisPEAssembly.Assembly Is thatPEAssembly.Assembly AndAlso this.HasUnresolvedReferencesByComparisonTo(that)
End If
Dim thisRetargetingAssembly = TryCast(this, RetargetingAssemblySymbol)
If thisRetargetingAssembly IsNot Nothing Then
Dim thatRetargetingAssembly = TryCast(that, RetargetingAssemblySymbol)
If thatRetargetingAssembly IsNot Nothing Then
Return thisRetargetingAssembly.UnderlyingAssembly Is thatRetargetingAssembly.UnderlyingAssembly AndAlso
this.HasUnresolvedReferencesByComparisonTo(that)
End If
Dim thatSourceAssembly = TryCast(that, SourceAssemblySymbol)
Return thatSourceAssembly IsNot Nothing AndAlso thisRetargetingAssembly.UnderlyingAssembly Is thatSourceAssembly AndAlso
this.HasUnresolvedReferencesByComparisonTo(that)
End If
Return False
End Function
End Module
End Namespace
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CompilationCreationTests : Inherits BasicTestBase
<Fact()>
Public Sub CorLibTypes()
Dim mdTestLib1 = TestReferences.SymbolsTests.MDTestLib1
Dim c1 = VisualBasicCompilation.Create("Test", references:={MscorlibRef_v4_0_30316_17626, mdTestLib1})
Dim c107 As TypeSymbol = c1.GlobalNamespace.GetTypeMembers("C107").Single()
Assert.Equal(SpecialType.None, c107.SpecialType)
For i As Integer = 1 To SpecialType.Count Step 1
Dim type As NamedTypeSymbol = c1.Assembly.GetSpecialType(CType(i, SpecialType))
Assert.NotEqual(type.Kind, SymbolKind.ErrorType)
Assert.Equal(CType(i, SpecialType), type.SpecialType)
Next
Assert.Equal(SpecialType.None, c107.SpecialType)
Dim arrayOfc107 = ArrayTypeSymbol.CreateVBArray(c107, Nothing, 1, c1)
Assert.Equal(SpecialType.None, arrayOfc107.SpecialType)
Dim c2 = VisualBasicCompilation.Create("Test", references:={mdTestLib1})
Assert.Equal(SpecialType.None, c2.GlobalNamespace.GetTypeMembers("C107").Single().SpecialType)
End Sub
<Fact()>
Public Sub RootNamespace_WithFiles_Simple()
Dim sourceTree = ParserTestUtilities.Parse(
<text>
Namespace XYZ
Public Class Clazz
End Class
End Namespace
</text>.Value)
Dim c1 = VisualBasicCompilation.Create("Test", {sourceTree}, DefaultVbReferences, TestOptions.ReleaseDll.WithRootNamespace("A.B.C"))
Dim root As NamespaceSymbol = c1.RootNamespace
Assert.NotNull(root)
Assert.Equal("C", root.Name)
Assert.Equal("B", root.ContainingNamespace.Name)
Assert.Equal("A", root.ContainingNamespace.ContainingNamespace.Name)
Assert.False(root.IsGlobalNamespace)
End Sub
<Fact()>
Public Sub RootNamespace_WithFiles_UpdateCompilation()
Dim sourceTree = ParserTestUtilities.Parse(
<text>
Namespace XYZ
Public Class Clazz
End Class
End Namespace
</text>.Value)
Dim c1 = VisualBasicCompilation.Create("Test", {sourceTree}, DefaultVbReferences, TestOptions.ReleaseDll)
Dim root As NamespaceSymbol = c1.RootNamespace
Assert.NotNull(root)
Assert.Equal("", root.Name)
Assert.True(root.IsGlobalNamespace)
c1 = c1.WithOptions(TestOptions.ReleaseDll.WithRootNamespace("A.B"))
root = c1.RootNamespace
Assert.NotNull(root)
Assert.Equal("B", root.Name)
Assert.Equal("A", root.ContainingNamespace.Name)
Assert.False(root.IsGlobalNamespace)
c1 = c1.WithOptions(TestOptions.ReleaseDll.WithRootNamespace(""))
root = c1.RootNamespace
Assert.NotNull(root)
Assert.Equal("", root.Name)
Assert.True(root.IsGlobalNamespace)
End Sub
<Fact()>
Public Sub RootNamespace_NoFiles_UpdateCompilation()
Dim c1 = VisualBasicCompilation.Create("Test", references:=DefaultVbReferences, options:=TestOptions.ReleaseDll)
Dim root As NamespaceSymbol = c1.RootNamespace
Assert.NotNull(root)
Assert.Equal("", root.Name)
Assert.True(root.IsGlobalNamespace)
c1 = c1.WithOptions(TestOptions.ReleaseDll.WithRootNamespace("A.B"))
root = c1.RootNamespace
Assert.NotNull(root)
Assert.Equal("B", root.Name)
Assert.Equal("A", root.ContainingNamespace.Name)
Assert.False(root.IsGlobalNamespace)
c1 = c1.WithOptions(TestOptions.ReleaseDll.WithRootNamespace(""))
root = c1.RootNamespace
Assert.NotNull(root)
Assert.Equal("", root.Name)
Assert.True(root.IsGlobalNamespace)
End Sub
Private Sub VerifyNamespaceShape(c1 As VisualBasicCompilation)
Dim globalNs = c1.GlobalNamespace
Assert.Equal(1, globalNs.GetNamespaceMembers().Count())
Dim globalsChild = globalNs.GetNamespaceMembers().Single()
Assert.Equal("FromOptions", globalsChild.Name)
Assert.Equal(1, globalsChild.GetNamespaceMembers().Count())
Assert.Equal("InSource", globalsChild.GetNamespaceMembers().Single.Name)
End Sub
<WorkItem(753078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/753078")>
<Fact()>
Public Sub RootNamespaceUpdateViaChangeInCompilationOptions()
Dim sourceTree = ParserTestUtilities.Parse(
<text>
Namespace InSource
End Namespace
</text>.Value)
Dim c1 = VisualBasicCompilation.Create("Test", {sourceTree}, options:=TestOptions.ReleaseDll.WithRootNamespace("FromOptions"))
VerifyNamespaceShape(c1)
c1 = VisualBasicCompilation.Create("Test", {sourceTree}, options:=TestOptions.ReleaseDll)
c1 = c1.WithOptions(c1.Options.WithRootNamespace("FromOptions"))
VerifyNamespaceShape(c1)
End Sub
<Fact()>
Public Sub CyclicReference()
Dim mscorlibRef = TestReferences.NetFx.v4_0_30319.mscorlib
Dim cyclic2Ref = TestReferences.SymbolsTests.Cyclic.Cyclic2.dll
Dim tc1 = VisualBasicCompilation.Create("Cyclic1", references:={mscorlibRef, cyclic2Ref})
Assert.NotNull(tc1.Assembly) ' force creation of SourceAssemblySymbol
Dim cyclic1Asm = DirectCast(tc1.Assembly, SourceAssemblySymbol)
Dim cyclic1Mod = DirectCast(cyclic1Asm.Modules(0), SourceModuleSymbol)
Dim cyclic2Asm = DirectCast(tc1.GetReferencedAssemblySymbol(cyclic2Ref), PEAssemblySymbol)
Dim cyclic2Mod = DirectCast(cyclic2Asm.Modules(0), PEModuleSymbol)
Assert.Same(cyclic2Mod.GetReferencedAssemblySymbols(1), cyclic1Asm)
Assert.Same(cyclic1Mod.GetReferencedAssemblySymbols(1), cyclic2Asm)
End Sub
<Fact()>
Public Sub MultiTargeting1()
Dim varV1MTTestLib2Path = TestReferences.SymbolsTests.V1.MTTestLib2.dll
Dim asm1 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
varV1MTTestLib2Path
})
Assert.Equal("mscorlib", asm1(0).Identity.Name)
Assert.Equal(0, asm1(0).BoundReferences().Length)
Assert.Equal("MTTestLib2", asm1(1).Identity.Name)
Assert.Equal(1, (From a In asm1(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm1(1).BoundReferences() Where a Is asm1(0) Select a).Count())
Assert.Equal(SymbolKind.ErrorType, asm1(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType.Kind)
Dim asm2 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
varV1MTTestLib2Path,
TestReferences.SymbolsTests.V1.MTTestLib1.dll
})
Assert.Same(asm2(0), asm1(0))
Assert.Equal("MTTestLib2", asm2(1).Identity.Name)
Assert.NotSame(asm2(1), asm1(1))
Assert.Same((DirectCast(asm2(1), PEAssemblySymbol)).[Assembly], (DirectCast(asm1(1), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, (From a In asm2(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(1).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Equal(1, (From a In asm2(1).BoundReferences() Where a Is asm2(2) Select a).Count())
Dim retval1 = asm2(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind)
Assert.Same(retval1, asm2(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm2(2).Identity.Name)
Assert.Equal(1, asm2(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where a Is asm2(0) Select a).Count())
Dim varV2MTTestLib3Path = TestReferences.SymbolsTests.V2.MTTestLib3.dll
Dim asm3 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
varV1MTTestLib2Path,
TestReferences.SymbolsTests.V2.MTTestLib1.dll,
varV2MTTestLib3Path
})
Assert.Same(asm3(0), asm1(0))
Assert.Equal("MTTestLib2", asm3(1).Identity.Name)
Assert.NotSame(asm3(1), asm1(1))
Assert.NotSame(asm3(1), asm2(1))
Assert.Same((DirectCast(asm3(1), PEAssemblySymbol)).[Assembly], (DirectCast(asm1(1), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, (From a In asm3(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(1).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(1, (From a In asm3(1).BoundReferences() Where a Is asm3(2) Select a).Count())
Dim retval2 = asm3(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind)
Assert.Same(retval2, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm3(2).Identity.Name)
Assert.NotSame(asm3(2), asm2(2))
Assert.NotSame((DirectCast(asm3(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm2(2), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, asm3(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal("MTTestLib3", asm3(3).Identity.Name)
Assert.Equal(3, (From a In asm3(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(1) Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(2) Select a).Count())
Dim type1 = asm3(3).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval3 = type1.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind)
Assert.Same(retval3, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval4 = type1.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind)
Assert.Same(retval4, asm3(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval5 = type1.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind)
Assert.Same(retval5, asm3(1).GlobalNamespace.GetMembers("Class4").Single())
Dim varV3MTTestLib4Path = TestReferences.SymbolsTests.V3.MTTestLib4.dll
Dim asm4 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
varV1MTTestLib2Path,
TestReferences.SymbolsTests.V3.MTTestLib1.dll,
varV2MTTestLib3Path,
varV3MTTestLib4Path
})
Assert.Same(asm3(0), asm1(0))
Assert.Equal("MTTestLib2", asm4(1).Identity.Name)
Assert.NotSame(asm4(1), asm1(1))
Assert.NotSame(asm4(1), asm2(1))
Assert.NotSame(asm4(1), asm3(1))
Assert.Same((DirectCast(asm4(1), PEAssemblySymbol)).[Assembly], (DirectCast(asm1(1), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, (From a In asm4(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(1).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(1).BoundReferences() Where a Is asm4(2) Select a).Count())
Dim retval6 = asm4(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind)
Assert.Same(retval6, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm4(2).Identity.Name)
Assert.NotSame(asm4(2), asm2(2))
Assert.NotSame(asm4(2), asm3(2))
Assert.NotSame((DirectCast(asm4(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm2(2), PEAssemblySymbol)).[Assembly])
Assert.NotSame((DirectCast(asm4(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm3(2), PEAssemblySymbol)).[Assembly])
Assert.Equal(3, asm4(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal("MTTestLib3", asm4(3).Identity.Name)
Assert.NotSame(asm4(3), asm3(3))
Assert.Same((DirectCast(asm4(3), PEAssemblySymbol)).[Assembly], (DirectCast(asm3(3), PEAssemblySymbol)).[Assembly])
Assert.Equal(3, (From a In asm4(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(2) Select a).Count())
Dim type2 = asm4(3).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval7 = type2.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind)
Assert.Same(retval7, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval8 = type2.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind)
Assert.Same(retval8, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval9 = type2.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind)
Assert.Same(retval9, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm4(4).Identity.Name)
Assert.Equal(4, (From a In asm4(4).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(2) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(3) Select a).Count())
Dim type3 = asm4(4).GlobalNamespace.GetTypeMembers("Class6").Single()
Dim retval10 = type3.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind)
Assert.Same(retval10, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval11 = type3.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind)
Assert.Same(retval11, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval12 = type3.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind)
Assert.Same(retval12, asm4(2).GlobalNamespace.GetMembers("Class3").Single())
Dim retval13 = type3.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind)
Assert.Same(retval13, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Dim retval14 = type3.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind)
Assert.Same(retval14, asm4(3).GlobalNamespace.GetMembers("Class5").Single())
Dim asm5 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
TestReferences.SymbolsTests.V2.MTTestLib3.dll
})
Assert.Same(asm5(0), asm1(0))
Assert.True(asm5(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3(3)))
Dim asm6 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib2.dll
})
Assert.Same(asm6(0), asm1(0))
Assert.Same(asm6(1), asm1(1))
Dim asm7 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib2.dll,
TestReferences.SymbolsTests.V2.MTTestLib3.dll,
TestReferences.SymbolsTests.V3.MTTestLib4.dll
})
Assert.Same(asm7(0), asm1(0))
Assert.Same(asm7(1), asm1(1))
Assert.NotSame(asm7(2), asm3(3))
Assert.NotSame(asm7(2), asm4(3))
Assert.NotSame(asm7(3), asm4(4))
Assert.Equal("MTTestLib3", asm7(2).Identity.Name)
Assert.Same((DirectCast(asm7(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm3(3), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, (From a In asm7(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm7(2).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(1, (From a In asm7(2).BoundReferences() Where a Is asm7(1) Select a).Count())
Dim type4 = asm7(2).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval15 = type4.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval15.Kind)
Dim retval16 = type4.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval16.Kind)
Dim retval17 = type4.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind)
Assert.Same(retval17, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm7(3).Identity.Name)
Assert.Same((DirectCast(asm7(3), PEAssemblySymbol)).[Assembly], (DirectCast(asm4(4), PEAssemblySymbol)).[Assembly])
Assert.Equal(3, (From a In asm7(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(1) Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(2) Select a).Count())
Dim type5 = asm7(3).GlobalNamespace.GetTypeMembers("Class6").Single()
Dim retval18 = type5.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval18.Kind)
Dim retval19 = type5.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval19.Kind)
Dim retval20 = type5.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval20.Kind)
Dim retval21 = type5.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind)
Assert.Same(retval21, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Dim retval22 = type5.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind)
Assert.Same(retval22, asm7(2).GlobalNamespace.GetMembers("Class5").Single())
' This test shows that simple reordering of references doesn't pick different set of assemblies
Dim asm8 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
TestReferences.SymbolsTests.V3.MTTestLib4.dll,
TestReferences.SymbolsTests.V1.MTTestLib2.dll,
TestReferences.SymbolsTests.V2.MTTestLib3.dll
})
Assert.Same(asm8(0), asm1(0))
Assert.Same(asm8(0), asm1(0))
Assert.Same(asm8(2), asm7(1))
Assert.True(asm8(3).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(3)))
Assert.Same(asm8(3), asm7(2))
Assert.True(asm8(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(4)))
Assert.Same(asm8(1), asm7(3))
Dim asm9 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
TestReferences.SymbolsTests.V3.MTTestLib4.dll
})
Assert.Same(asm9(0), asm1(0))
Assert.True(asm9(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(4)))
Dim asm10 = GetSymbolsForReferences(
{
TestReferences.NetFx.v4_0_21006.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib2.dll,
TestReferences.SymbolsTests.V3.MTTestLib1.dll,
TestReferences.SymbolsTests.V2.MTTestLib3.dll,
TestReferences.SymbolsTests.V3.MTTestLib4.dll
})
Assert.Same(asm10(0), asm1(0))
Assert.Same(asm10(1), asm4(1))
Assert.Same(asm10(2), asm4(2))
Assert.Same(asm10(3), asm4(3))
Assert.Same(asm10(4), asm4(4))
Assert.Equal("MTTestLib2", asm1(1).Identity.Name)
Assert.Equal(1, (From a In asm1(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm1(1).BoundReferences() Where a Is asm1(0) Select a).Count())
Assert.Equal(SymbolKind.ErrorType, asm1(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType.Kind)
Assert.Same(asm2(0), asm1(0))
Assert.Equal("MTTestLib2", asm2(1).Identity.Name)
Assert.NotSame(asm2(1), asm1(1))
Assert.Same((DirectCast(asm2(1), PEAssemblySymbol)).[Assembly], (DirectCast(asm1(1), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, (From a In asm2(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(1).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Equal(1, (From a In asm2(1).BoundReferences() Where a Is asm2(2) Select a).Count())
retval1 = asm2(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind)
Assert.Same(retval1, asm2(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm2(2).Identity.Name)
Assert.Equal(1, asm2(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Same(asm3(0), asm1(0))
Assert.Equal("MTTestLib2", asm3(1).Identity.Name)
Assert.NotSame(asm3(1), asm1(1))
Assert.NotSame(asm3(1), asm2(1))
Assert.Same((DirectCast(asm3(1), PEAssemblySymbol)).[Assembly], (DirectCast(asm1(1), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, (From a In asm3(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(1).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(1, (From a In asm3(1).BoundReferences() Where a Is asm3(2) Select a).Count())
retval2 = asm3(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind)
Assert.Same(retval2, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm3(2).Identity.Name)
Assert.NotSame(asm3(2), asm2(2))
Assert.NotSame((DirectCast(asm3(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm2(2), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, asm3(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal("MTTestLib3", asm3(3).Identity.Name)
Assert.Equal(3, (From a In asm3(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(1) Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(2) Select a).Count())
type1 = asm3(3).GlobalNamespace.GetTypeMembers("Class5").Single()
retval3 = type1.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind)
Assert.Same(retval3, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
retval4 = type1.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind)
Assert.Same(retval4, asm3(2).GlobalNamespace.GetMembers("Class2").Single())
retval5 = type1.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind)
Assert.Same(retval5, asm3(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Same(asm3(0), asm1(0))
Assert.Equal("MTTestLib2", asm4(1).Identity.Name)
Assert.NotSame(asm4(1), asm1(1))
Assert.NotSame(asm4(1), asm2(1))
Assert.NotSame(asm4(1), asm3(1))
Assert.Same((DirectCast(asm4(1), PEAssemblySymbol)).[Assembly], (DirectCast(asm1(1), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, (From a In asm4(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(1).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(1).BoundReferences() Where a Is asm4(2) Select a).Count())
retval6 = asm4(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind)
Assert.Same(retval6, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm4(2).Identity.Name)
Assert.NotSame(asm4(2), asm2(2))
Assert.NotSame(asm4(2), asm3(2))
Assert.NotSame((DirectCast(asm4(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm2(2), PEAssemblySymbol)).[Assembly])
Assert.NotSame((DirectCast(asm4(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm3(2), PEAssemblySymbol)).[Assembly])
Assert.Equal(3, asm4(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal("MTTestLib3", asm4(3).Identity.Name)
Assert.NotSame(asm4(3), asm3(3))
Assert.Same((DirectCast(asm4(3), PEAssemblySymbol)).[Assembly], (DirectCast(asm3(3), PEAssemblySymbol)).[Assembly])
Assert.Equal(3, (From a In asm4(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(2) Select a).Count())
type2 = asm4(3).GlobalNamespace.GetTypeMembers("Class5").Single()
retval7 = type2.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind)
Assert.Same(retval7, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
retval8 = type2.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind)
Assert.Same(retval8, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
retval9 = type2.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind)
Assert.Same(retval9, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm4(4).Identity.Name)
Assert.Equal(4, (From a In asm4(4).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(2) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(3) Select a).Count())
type3 = asm4(4).GlobalNamespace.GetTypeMembers("Class6").Single()
retval10 = type3.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind)
Assert.Same(retval10, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
retval11 = type3.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind)
Assert.Same(retval11, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
retval12 = type3.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind)
Assert.Same(retval12, asm4(2).GlobalNamespace.GetMembers("Class3").Single())
retval13 = type3.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind)
Assert.Same(retval13, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
retval14 = type3.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind)
Assert.Same(retval14, asm4(3).GlobalNamespace.GetMembers("Class5").Single())
Assert.Same(asm7(0), asm1(0))
Assert.Same(asm7(1), asm1(1))
Assert.NotSame(asm7(2), asm3(3))
Assert.NotSame(asm7(2), asm4(3))
Assert.NotSame(asm7(3), asm4(4))
Assert.Equal("MTTestLib3", asm7(2).Identity.Name)
Assert.Same((DirectCast(asm7(2), PEAssemblySymbol)).Assembly, (DirectCast(asm3(3), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, (From a In asm7(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm7(2).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(1, (From a In asm7(2).BoundReferences() Where a Is asm7(1) Select a).Count())
type4 = asm7(2).GlobalNamespace.GetTypeMembers("Class5").Single()
retval15 = type4.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval15.Kind)
retval16 = type4.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval16.Kind)
retval17 = type4.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind)
Assert.Same(retval17, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm7(3).Identity.Name)
Assert.Same((DirectCast(asm7(3), PEAssemblySymbol)).Assembly, (DirectCast(asm4(4), PEAssemblySymbol)).[Assembly])
Assert.Equal(3, (From a In asm7(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(1) Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(2) Select a).Count())
type5 = asm7(3).GlobalNamespace.GetTypeMembers("Class6").Single()
retval18 = type5.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval18.Kind)
retval19 = type5.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval19.Kind)
retval20 = type5.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal(SymbolKind.ErrorType, retval20.Kind)
retval21 = type5.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind)
Assert.Same(retval21, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
retval22 = type5.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind)
Assert.Same(retval22, asm7(2).GlobalNamespace.GetMembers("Class5").Single())
End Sub
#If Retargeting Then
<Fact(skip:=SkipReason.AlreadyTestingRetargeting)>
Public Sub MultiTargeting2()
#Else
<Fact()>
Public Sub MultiTargeting2()
#End If
Dim varMTTestLib1_V1_Name = New AssemblyIdentity("MTTestLib1", New Version("1.0.0.0"))
Dim varC_MTTestLib1_V1 = CreateCompilation(varMTTestLib1_V1_Name, New String() {<text>
Public Class Class1
End Class
</text>.Value}, {TestReferences.NetFx.v4_0_30319.mscorlib})
Dim asm_MTTestLib1_V1 = varC_MTTestLib1_V1.SourceAssembly().BoundReferences()
Dim varMTTestLib2_Name = New AssemblyIdentity("MTTestLib2")
Dim varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, New String() {<text>
Public Class Class4
Function Foo() As Class1
Return Nothing
End Function
Public Bar As Class1
End Class
</text>.Value}, {TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib1_V1.ToMetadataReference()})
Dim asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences()
Assert.Same(asm_MTTestLib2(0), asm_MTTestLib1_V1(0))
Assert.Same(asm_MTTestLib2(1), varC_MTTestLib1_V1.SourceAssembly())
Dim c2 = CreateCompilation(New AssemblyIdentity("c2"), Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V1.ToMetadataReference()})
Dim asm2 = c2.SourceAssembly().BoundReferences()
Assert.Same(asm2(0), asm_MTTestLib1_V1(0))
Assert.Same(asm2(1), varC_MTTestLib2.SourceAssembly())
Assert.Same(asm2(2), varC_MTTestLib1_V1.SourceAssembly())
Assert.Equal("MTTestLib2", asm2(1).Identity.Name)
Assert.Equal(2, (From a In asm2(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(1).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Equal(1, (From a In asm2(1).BoundReferences() Where a Is asm2(2) Select a).Count())
Dim retval1 = asm2(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind)
Assert.Same(retval1, asm2(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm2(2).Identity.Name)
Assert.Equal(1, asm2(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where a Is asm2(0) Select a).Count())
Dim varMTTestLib1_V2_Name = New AssemblyIdentity("MTTestLib1", New Version("2.0.0.0"))
Dim varC_MTTestLib1_V2 = CreateCompilation(varMTTestLib1_V2_Name, New String() {<text>
Public Class Class1
End Class
Public Class Class2
End Class
</text>.Value}, {TestReferences.NetFx.v4_0_30319.mscorlib})
Dim asm_MTTestLib1_V2 = varC_MTTestLib1_V2.SourceAssembly().BoundReferences()
Dim varMTTestLib3_Name = New AssemblyIdentity("MTTestLib3")
Dim varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, New String() {<text>
Public Class Class5
Function Foo1() As Class1
Return Nothing
End Function
Function Foo2() As Class2
Return Nothing
End Function
Function Foo3() As Class4
Return Nothing
End Function
Public Bar1 As Class1
Public Bar2 As Class2
Public Bar3 As Class4
End Class
</text>.Value}, {TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference()})
Dim asm_MTTestLib3 = varC_MTTestLib3.SourceAssembly().BoundReferences()
Assert.Same(asm_MTTestLib3(0), asm_MTTestLib1_V1(0))
Assert.NotSame(asm_MTTestLib3(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm_MTTestLib3(2), varC_MTTestLib1_V1.SourceAssembly())
Dim c3 = CreateCompilation(New AssemblyIdentity("c3"), Nothing, {TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference()})
Dim asm3 = c3.SourceAssembly().BoundReferences()
Assert.Same(asm3(0), asm_MTTestLib1_V1(0))
Assert.Same(asm3(1), asm_MTTestLib3(1))
Assert.Same(asm3(2), asm_MTTestLib3(2))
Assert.Same(asm3(3), varC_MTTestLib3.SourceAssembly())
Assert.Equal("MTTestLib2", asm3(1).Identity.Name)
Assert.Same((DirectCast(asm3(1), RetargetingAssemblySymbol)).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly())
Assert.Equal(2, (From a In asm3(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(1).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(1, (From a In asm3(1).BoundReferences() Where a Is asm3(2) Select a).Count())
Dim retval2 = asm3(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind)
Assert.Same(retval2, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm3(2).Identity.Name)
Assert.NotSame(asm3(2), asm2(2))
Assert.NotSame(asm3(2).DeclaringCompilation, asm2(2).DeclaringCompilation)
Assert.Equal(2, asm3(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal("MTTestLib3", asm3(3).Identity.Name)
Assert.Equal(3, (From a In asm3(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(1) Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(2) Select a).Count())
Dim type1 = asm3(3).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval3 = type1.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind)
Assert.Same(retval3, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval4 = type1.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind)
Assert.Same(retval4, asm3(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval5 = type1.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind)
Assert.Same(retval5, asm3(1).GlobalNamespace.GetMembers("Class4").Single())
Dim varMTTestLib1_V3_Name = New AssemblyIdentity("MTTestLib1", New Version("3.0.0.0"))
Dim varC_MTTestLib1_V3 = CreateCompilation(varMTTestLib1_V3_Name, New String() {<text>
Public Class Class1
End Class
Public Class Class2
End Class
Public Class Class3
End Class
</text>.Value}, {TestReferences.NetFx.v4_0_30319.mscorlib})
Dim asm_MTTestLib1_V3 = varC_MTTestLib1_V3.SourceAssembly().BoundReferences()
Dim varMTTestLib4_Name = New AssemblyIdentity("MTTestLib4")
Dim varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, New String() {<text>
Public Class Class6
Function Foo1() As Class1
Return Nothing
End Function
Function Foo2() As Class2
Return Nothing
End Function
Function Foo3() As Class3
Return Nothing
End Function
Function Foo4() As Class4
Return Nothing
End Function
Function Foo5() As Class5
Return Nothing
End Function
Public Bar1 As Class1
Public Bar2 As Class2
Public Bar3 As Class3
Public Bar4 As Class4
Public Bar5 As Class5
End Class
</text>.Value}, {TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference()})
Dim asm_MTTestLib4 = varC_MTTestLib4.SourceAssembly().BoundReferences()
Assert.Same(asm_MTTestLib4(0), asm_MTTestLib1_V1(0))
Assert.NotSame(asm_MTTestLib4(1), varC_MTTestLib2.SourceAssembly())
Assert.Same(asm_MTTestLib4(2), varC_MTTestLib1_V3.SourceAssembly())
Assert.NotSame(asm_MTTestLib4(3), varC_MTTestLib3.SourceAssembly())
Dim c4 = CreateCompilation(New AssemblyIdentity("c4"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
varC_MTTestLib2.ToMetadataReference(),
varC_MTTestLib1_V3.ToMetadataReference(),
varC_MTTestLib3.ToMetadataReference(),
varC_MTTestLib4.ToMetadataReference()})
Dim asm4 = c4.SourceAssembly().BoundReferences()
Assert.Same(asm4(0), asm_MTTestLib1_V1(0))
Assert.Same(asm4(1), asm_MTTestLib4(1))
Assert.Same(asm4(2), asm_MTTestLib4(2))
Assert.Same(asm4(3), asm_MTTestLib4(3))
Assert.Same(asm4(4), varC_MTTestLib4.SourceAssembly())
Assert.Equal("MTTestLib2", asm4(1).Identity.Name)
Assert.NotSame(asm4(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm4(1), asm2(1))
Assert.NotSame(asm4(1), asm3(1))
Assert.Same((DirectCast(asm4(1), RetargetingAssemblySymbol)).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly())
Assert.Equal(2, (From a In asm4(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(1).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(1).BoundReferences() Where a Is asm4(2) Select a).Count())
Dim retval6 = asm4(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind)
Assert.Same(retval6, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm4(2).Identity.Name)
Assert.NotSame(asm4(2), asm2(2))
Assert.NotSame(asm4(2), asm3(2))
Assert.NotSame(asm4(2).DeclaringCompilation, asm2(2).DeclaringCompilation)
Assert.NotSame(asm4(2).DeclaringCompilation, asm3(2).DeclaringCompilation)
Assert.Equal(3, asm4(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal("MTTestLib3", asm4(3).Identity.Name)
Assert.NotSame(asm4(3), asm3(3))
Assert.Same((DirectCast(asm4(3), RetargetingAssemblySymbol)).UnderlyingAssembly, asm3(3))
Assert.Equal(3, (From a In asm4(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(2) Select a).Count())
Dim type2 = asm4(3).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval7 = type2.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind)
Assert.Same(retval7, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval8 = type2.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind)
Assert.Same(retval8, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval9 = type2.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind)
Assert.Same(retval9, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm4(4).Identity.Name)
Assert.Equal(4, (From a In asm4(4).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(2) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(3) Select a).Count())
Dim type3 = asm4(4).GlobalNamespace.GetTypeMembers("Class6").Single()
Dim retval10 = type3.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind)
Assert.Same(retval10, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval11 = type3.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind)
Assert.Same(retval11, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval12 = type3.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind)
Assert.Same(retval12, asm4(2).GlobalNamespace.GetMembers("Class3").Single())
Dim retval13 = type3.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind)
Assert.Same(retval13, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Dim retval14 = type3.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind)
Assert.Same(retval14, asm4(3).GlobalNamespace.GetMembers("Class5").Single())
Dim c5 = CreateCompilation(New AssemblyIdentity("c5"), Nothing, {TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib3.ToMetadataReference()})
Dim asm5 = c5.SourceAssembly().BoundReferences()
Assert.Same(asm5(0), asm2(0))
Assert.True(asm5(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3(3)))
Dim c6 = CreateCompilation(New AssemblyIdentity("c6"), Nothing, {TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib2.ToMetadataReference()})
Dim asm6 = c6.SourceAssembly().BoundReferences()
Assert.Same(asm6(0), asm2(0))
Assert.True(asm6(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly()))
Dim c7 = CreateCompilation(New AssemblyIdentity("c6"), Nothing, {TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference()})
Dim asm7 = c7.SourceAssembly().BoundReferences()
Assert.Same(asm7(0), asm2(0))
Assert.True(asm7(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly()))
Assert.NotSame(asm7(2), asm3(3))
Assert.NotSame(asm7(2), asm4(3))
Assert.NotSame(asm7(3), asm4(4))
Assert.Equal("MTTestLib3", asm7(2).Identity.Name)
Assert.Same((DirectCast(asm7(2), RetargetingAssemblySymbol)).UnderlyingAssembly, asm3(3))
Assert.Equal(2, (From a In asm7(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm7(2).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(1, (From a In asm7(2).BoundReferences() Where a Is asm7(1) Select a).Count())
Dim type4 = asm7(2).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval15 = type4.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name)
Assert.Equal(0, (From a In asm7 Where a IsNot Nothing AndAlso a.Name = "MTTestLib1" Select a).Count())
Dim retval16 = type4.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name)
Dim retval17 = type4.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind)
Assert.Same(retval17, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm7(3).Identity.Name)
Assert.Same((DirectCast(asm7(3), RetargetingAssemblySymbol)).UnderlyingAssembly, asm4(4))
Assert.Equal(3, (From a In asm7(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(1) Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(2) Select a).Count())
Dim type5 = asm7(3).GlobalNamespace.GetTypeMembers("Class6").Single()
Dim retval18 = type5.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name)
Dim retval19 = type5.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name)
Dim retval20 = type5.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name)
Dim retval21 = type5.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind)
Assert.Same(retval21, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Dim retval22 = type5.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind)
Assert.Same(retval22, asm7(2).GlobalNamespace.GetMembers("Class5").Single())
' This test shows that simple reordering of references doesn't pick different set of assemblies
Dim c8 = CreateCompilation(New AssemblyIdentity("c8"), Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
varC_MTTestLib4.ToMetadataReference(),
varC_MTTestLib2.ToMetadataReference(),
varC_MTTestLib3.ToMetadataReference()})
Dim asm8 = c8.SourceAssembly().BoundReferences()
Assert.Same(asm8(0), asm2(0))
Assert.True(asm8(2).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(1)))
Assert.Same(asm8(2), asm7(1))
Assert.True(asm8(3).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(3)))
Assert.Same(asm8(3), asm7(2))
Assert.True(asm8(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(4)))
Assert.Same(asm8(1), asm7(3))
Dim c9 = CreateCompilation(New AssemblyIdentity("c9"), Nothing, {TestReferences.NetFx.v4_0_30319.mscorlib, varC_MTTestLib4.ToMetadataReference()})
Dim asm9 = c9.SourceAssembly().BoundReferences()
Assert.Same(asm9(0), asm2(0))
Assert.True(asm9(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(4)))
Dim c10 = CreateCompilation(New AssemblyIdentity("c10"), Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
varC_MTTestLib2.ToMetadataReference(),
varC_MTTestLib1_V3.ToMetadataReference(),
varC_MTTestLib3.ToMetadataReference(),
varC_MTTestLib4.ToMetadataReference()})
Dim asm10 = c10.SourceAssembly().BoundReferences()
Assert.Same(asm10(0), asm2(0))
Assert.Same(asm10(1), asm4(1))
Assert.Same(asm10(2), asm4(2))
Assert.Same(asm10(3), asm4(3))
Assert.Same(asm10(4), asm4(4))
Assert.Same(asm2(0), asm_MTTestLib1_V1(0))
Assert.Equal("MTTestLib2", asm2(1).Identity.Name)
Assert.Equal(2, (From a In asm2(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(1).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Equal(1, (From a In asm2(1).BoundReferences() Where a Is asm2(2) Select a).Count())
retval1 = asm2(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind)
Assert.Same(retval1, asm2(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm2(2).Identity.Name)
Assert.Equal(1, asm2(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Same(asm_MTTestLib3(0), asm_MTTestLib1_V1(0))
Assert.NotSame(asm_MTTestLib3(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm_MTTestLib3(2), varC_MTTestLib1_V1.SourceAssembly())
Assert.Same(asm3(0), asm_MTTestLib1_V1(0))
Assert.Same(asm3(1), asm_MTTestLib3(1))
Assert.Same(asm3(2), asm_MTTestLib3(2))
Assert.Same(asm3(3), varC_MTTestLib3.SourceAssembly())
Assert.Equal("MTTestLib2", asm3(1).Identity.Name)
Assert.Same((DirectCast(asm3(1), RetargetingAssemblySymbol)).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly())
Assert.Equal(2, (From a In asm3(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(1).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(1, (From a In asm3(1).BoundReferences() Where a Is asm3(2) Select a).Count())
retval2 = asm3(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind)
Assert.Same(retval2, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm3(2).Identity.Name)
Assert.NotSame(asm3(2), asm2(2))
Assert.NotSame(asm3(2).DeclaringCompilation, asm2(2).DeclaringCompilation)
Assert.Equal(2, asm3(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal("MTTestLib3", asm3(3).Identity.Name)
Assert.Equal(3, (From a In asm3(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(1) Select a).Count())
Assert.Equal(1, (From a In asm3(3).BoundReferences() Where a Is asm3(2) Select a).Count())
type1 = asm3(3).GlobalNamespace.GetTypeMembers("Class5").Single()
retval3 = type1.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind)
Assert.Same(retval3, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
retval4 = type1.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind)
Assert.Same(retval4, asm3(2).GlobalNamespace.GetMembers("Class2").Single())
retval5 = type1.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind)
Assert.Same(retval5, asm3(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Same(asm4(0), asm_MTTestLib1_V1(0))
Assert.Same(asm4(1), asm_MTTestLib4(1))
Assert.Same(asm4(2), asm_MTTestLib4(2))
Assert.Same(asm4(3), asm_MTTestLib4(3))
Assert.Same(asm4(4), varC_MTTestLib4.SourceAssembly())
Assert.Equal("MTTestLib2", asm4(1).Identity.Name)
Assert.NotSame(asm4(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm4(1), asm2(1))
Assert.NotSame(asm4(1), asm3(1))
Assert.Same((DirectCast(asm4(1), RetargetingAssemblySymbol)).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly())
Assert.Equal(2, (From a In asm4(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(1).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(1).BoundReferences() Where a Is asm4(2) Select a).Count())
retval6 = asm4(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind)
Assert.Same(retval6, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm4(2).Identity.Name)
Assert.NotSame(asm4(2), asm2(2))
Assert.NotSame(asm4(2), asm3(2))
Assert.NotSame(asm4(2).DeclaringCompilation, asm2(2).DeclaringCompilation)
Assert.NotSame(asm4(2).DeclaringCompilation, asm3(2).DeclaringCompilation)
Assert.Equal(3, asm4(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal("MTTestLib3", asm4(3).Identity.Name)
Assert.NotSame(asm4(3), asm3(3))
Assert.Same((DirectCast(asm4(3), RetargetingAssemblySymbol)).UnderlyingAssembly, asm3(3))
Assert.Equal(3, (From a In asm4(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(1, (From a In asm4(3).BoundReferences() Where a Is asm4(2) Select a).Count())
type2 = asm4(3).GlobalNamespace.GetTypeMembers("Class5").Single()
retval7 = type2.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind)
Assert.Same(retval7, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
retval8 = type2.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind)
Assert.Same(retval8, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
retval9 = type2.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind)
Assert.Same(retval9, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm4(4).Identity.Name)
Assert.Equal(4, (From a In asm4(4).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(2) Select a).Count())
Assert.Equal(1, (From a In asm4(4).BoundReferences() Where a Is asm4(3) Select a).Count())
type3 = asm4(4).GlobalNamespace.GetTypeMembers("Class6").Single()
retval10 = type3.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind)
Assert.Same(retval10, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
retval11 = type3.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind)
Assert.Same(retval11, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
retval12 = type3.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind)
Assert.Same(retval12, asm4(2).GlobalNamespace.GetMembers("Class3").Single())
retval13 = type3.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind)
Assert.Same(retval13, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
retval14 = type3.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind)
Assert.Same(retval14, asm4(3).GlobalNamespace.GetMembers("Class5").Single())
Assert.Same(asm5(0), asm2(0))
Assert.True(asm5(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3(3)))
Assert.Same(asm6(0), asm2(0))
Assert.True(asm6(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly()))
Assert.Same(asm7(0), asm2(0))
Assert.True(asm7(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly()))
Assert.NotSame(asm7(2), asm3(3))
Assert.NotSame(asm7(2), asm4(3))
Assert.NotSame(asm7(3), asm4(4))
Assert.Equal("MTTestLib3", asm7(2).Identity.Name)
Assert.Same((DirectCast(asm7(2), RetargetingAssemblySymbol)).UnderlyingAssembly, asm3(3))
Assert.Equal(2, (From a In asm7(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm7(2).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(1, (From a In asm7(2).BoundReferences() Where a Is asm7(1) Select a).Count())
type4 = asm7(2).GlobalNamespace.GetTypeMembers("Class5").Single()
retval15 = type4.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name)
Assert.Equal(0, (From a In asm7 Where a IsNot Nothing AndAlso a.Name = "MTTestLib1" Select a).Count())
retval16 = type4.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name)
retval17 = type4.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind)
Assert.Same(retval17, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm7(3).Identity.Name)
Assert.Same((DirectCast(asm7(3), RetargetingAssemblySymbol)).UnderlyingAssembly, asm4(4))
Assert.Equal(3, (From a In asm7(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(1) Select a).Count())
Assert.Equal(1, (From a In asm7(3).BoundReferences() Where a Is asm7(2) Select a).Count())
type5 = asm7(3).GlobalNamespace.GetTypeMembers("Class6").Single()
retval18 = type5.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name)
retval19 = type5.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name)
retval20 = type5.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name)
retval21 = type5.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind)
Assert.Same(retval21, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
retval22 = type5.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind)
Assert.Same(retval22, asm7(2).GlobalNamespace.GetMembers("Class5").Single())
End Sub
#If Retargeting Then
<Fact(skip:=SkipReason.AlreadyTestingRetargeting)>
Public Sub MultiTargeting3()
#Else
<Fact()>
Public Sub MultiTargeting3()
#End If
Dim varMTTestLib2_Name = New AssemblyIdentity("MTTestLib2")
Dim varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name,
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib1.dll,
TestReferences.SymbolsTests.V1.MTTestModule2.netmodule})
Dim asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences()
Dim c2 = CreateCompilation(New AssemblyIdentity("c2"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib1.dll,
New VisualBasicCompilationReference(varC_MTTestLib2)})
Dim asm2Prime = c2.SourceAssembly().BoundReferences()
Dim asm2 = New AssemblySymbol() {asm2Prime(0), asm2Prime(2), asm2Prime(1)}
Assert.Same(asm2(0), asm_MTTestLib2(0))
Assert.Same(asm2(1), varC_MTTestLib2.SourceAssembly())
Assert.Same(asm2(2), asm_MTTestLib2(1))
Assert.Equal("MTTestLib2", asm2(1).Identity.Name)
Assert.Equal(4, (From a In asm2(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm2(1).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Equal(2, (From a In asm2(1).BoundReferences() Where a Is asm2(2) Select a).Count())
Dim retval1 = asm2(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Same(retval1, asm2(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Bar").OfType(Of FieldSymbol)().Single().[Type])
Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind)
Assert.Same(retval1, asm2(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm2(2).Identity.Name)
Assert.Equal(1, asm2(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where a Is asm2(0) Select a).Count())
Dim varMTTestLib3_Name = New AssemblyIdentity("MTTestLib3")
Dim varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name,
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.V2.MTTestLib1.dll,
New VisualBasicCompilationReference(varC_MTTestLib2),
TestReferences.SymbolsTests.V2.MTTestModule3.netmodule})
Dim asm_MTTestLib3Prime = varC_MTTestLib3.SourceAssembly().BoundReferences()
Dim asm_MTTestLib3 = New AssemblySymbol() {asm_MTTestLib3Prime(0), asm_MTTestLib3Prime(2), asm_MTTestLib3Prime(1)}
Assert.Same(asm_MTTestLib3(0), asm_MTTestLib2(0))
Assert.NotSame(asm_MTTestLib3(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm_MTTestLib3(2), asm_MTTestLib2(1))
Dim c3 = CreateCompilation(New AssemblyIdentity("c3"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.V2.MTTestLib1.dll,
New VisualBasicCompilationReference(varC_MTTestLib2),
New VisualBasicCompilationReference(varC_MTTestLib3)})
Dim asm3Prime = c3.SourceAssembly().BoundReferences()
Dim asm3 = New AssemblySymbol() {asm3Prime(0), asm3Prime(2), asm3Prime(1), asm3Prime(3)}
Assert.Same(asm3(0), asm_MTTestLib2(0))
Assert.Same(asm3(1), asm_MTTestLib3(1))
Assert.Same(asm3(2), asm_MTTestLib3(2))
Assert.Same(asm3(3), varC_MTTestLib3.SourceAssembly())
Assert.Equal("MTTestLib2", asm3(1).Identity.Name)
Assert.Same((DirectCast(asm3(1), RetargetingAssemblySymbol)).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly())
Assert.Equal(4, (From a In asm3(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm3(1).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(2, (From a In asm3(1).BoundReferences() Where a Is asm3(2) Select a).Count())
Dim retval2 = asm3(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Same(retval2, asm3(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Bar").OfType(Of FieldSymbol)().Single().[Type])
Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind)
Assert.Same(retval2, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm3(2).Identity.Name)
Assert.NotSame(asm3(2), asm2(2))
Assert.NotSame(asm3(2), asm2(2))
Assert.NotSame((DirectCast(asm3(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm2(2), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, asm3(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal("MTTestLib3", asm3(3).Identity.Name)
Assert.Equal(6, (From a In asm3(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm3(3).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(2, (From a In asm3(3).BoundReferences() Where a Is asm3(1) Select a).Count())
Assert.Equal(2, (From a In asm3(3).BoundReferences() Where a Is asm3(2) Select a).Count())
Dim type1 = asm3(3).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval3 = type1.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind)
Assert.Same(retval3, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval4 = type1.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind)
Assert.Same(retval4, asm3(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval5 = type1.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind)
Assert.Same(retval5, asm3(1).GlobalNamespace.GetMembers("Class4").Single())
Dim varMTTestLib4_Name = New AssemblyIdentity("MTTestLib4")
Dim varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name,
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.V3.MTTestLib1.dll,
New VisualBasicCompilationReference(varC_MTTestLib2),
New VisualBasicCompilationReference(varC_MTTestLib3),
TestReferences.SymbolsTests.V3.MTTestModule4.netmodule})
Dim asm_MTTestLib4Prime = varC_MTTestLib4.SourceAssembly().BoundReferences()
Dim asm_MTTestLib4 = New AssemblySymbol() {asm_MTTestLib4Prime(0), asm_MTTestLib4Prime(2), asm_MTTestLib4Prime(1), asm_MTTestLib4Prime(3)}
Assert.Same(asm_MTTestLib4(0), asm_MTTestLib2(0))
Assert.NotSame(asm_MTTestLib4(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm_MTTestLib4(2), asm3(2))
Assert.NotSame(asm_MTTestLib4(2), asm2(2))
Assert.NotSame(asm_MTTestLib4(3), varC_MTTestLib3.SourceAssembly())
Dim c4 = CreateCompilation(New AssemblyIdentity("c4"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.V3.MTTestLib1.dll,
New VisualBasicCompilationReference(varC_MTTestLib2),
New VisualBasicCompilationReference(varC_MTTestLib3),
New VisualBasicCompilationReference(varC_MTTestLib4)})
Dim asm4Prime = c4.SourceAssembly().BoundReferences()
Dim asm4 = New AssemblySymbol() {asm4Prime(0), asm4Prime(2), asm4Prime(1), asm4Prime(3), asm4Prime(4)}
Assert.Same(asm4(0), asm_MTTestLib2(0))
Assert.Same(asm4(1), asm_MTTestLib4(1))
Assert.Same(asm4(2), asm_MTTestLib4(2))
Assert.Same(asm4(3), asm_MTTestLib4(3))
Assert.Same(asm4(4), varC_MTTestLib4.SourceAssembly())
Assert.Equal("MTTestLib2", asm4(1).Identity.Name)
Assert.NotSame(asm4(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm4(1), asm2(1))
Assert.NotSame(asm4(1), asm3(1))
Assert.Same((DirectCast(asm4(1), RetargetingAssemblySymbol)).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly())
Assert.Equal(4, (From a In asm4(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm4(1).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(2, (From a In asm4(1).BoundReferences() Where a Is asm4(2) Select a).Count())
Dim retval6 = asm4(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind)
Assert.Same(retval6, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm4(2).Identity.Name)
Assert.NotSame(asm4(2), asm2(2))
Assert.NotSame(asm4(2), asm3(2))
Assert.NotSame((DirectCast(asm4(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm2(2), PEAssemblySymbol)).[Assembly])
Assert.NotSame((DirectCast(asm4(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm3(2), PEAssemblySymbol)).[Assembly])
Assert.Equal(3, asm4(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal("MTTestLib3", asm4(3).Identity.Name)
Assert.NotSame(asm4(3), asm3(3))
Assert.Same((DirectCast(asm4(3), RetargetingAssemblySymbol)).UnderlyingAssembly, asm3(3))
Assert.Equal(6, (From a In asm4(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm4(3).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(2, (From a In asm4(3).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(2, (From a In asm4(3).BoundReferences() Where a Is asm4(2) Select a).Count())
Dim type2 = asm4(3).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval7 = type2.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind)
Assert.Same(retval7, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval8 = type2.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind)
Assert.Same(retval8, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval9 = type2.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind)
Assert.Same(retval9, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm4(4).Identity.Name)
Assert.Equal(8, (From a In asm4(4).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm4(4).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(2, (From a In asm4(4).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(2, (From a In asm4(4).BoundReferences() Where a Is asm4(2) Select a).Count())
Assert.Equal(2, (From a In asm4(4).BoundReferences() Where a Is asm4(3) Select a).Count())
Dim type3 = asm4(4).GlobalNamespace.GetTypeMembers("Class6").Single()
Dim retval10 = type3.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind)
Assert.Same(retval10, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Dim retval11 = type3.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind)
Assert.Same(retval11, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
Dim retval12 = type3.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind)
Assert.Same(retval12, asm4(2).GlobalNamespace.GetMembers("Class3").Single())
Dim retval13 = type3.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind)
Assert.Same(retval13, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Dim retval14 = type3.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind)
Assert.Same(retval14, asm4(3).GlobalNamespace.GetMembers("Class5").Single())
Dim c5 = CreateCompilation(New AssemblyIdentity("c5"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
New VisualBasicCompilationReference(varC_MTTestLib3)})
Dim asm5 = c5.SourceAssembly().BoundReferences()
Assert.Same(asm5(0), asm2(0))
Assert.True(asm5(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3(3)))
Dim c6 = CreateCompilation(New AssemblyIdentity("c6"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
New VisualBasicCompilationReference(varC_MTTestLib2)})
Dim asm6 = c6.SourceAssembly().BoundReferences()
Assert.Same(asm6(0), asm2(0))
Assert.True(asm6(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly()))
Dim c7 = CreateCompilation(New AssemblyIdentity("c7"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
New VisualBasicCompilationReference(varC_MTTestLib2),
New VisualBasicCompilationReference(varC_MTTestLib3),
New VisualBasicCompilationReference(varC_MTTestLib4)})
Dim asm7 = c7.SourceAssembly().BoundReferences()
Assert.Same(asm7(0), asm2(0))
Assert.True(asm7(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly()))
Assert.NotSame(asm7(2), asm3(3))
Assert.NotSame(asm7(2), asm4(3))
Assert.NotSame(asm7(3), asm4(4))
Assert.Equal("MTTestLib3", asm7(2).Identity.Name)
Assert.Same((DirectCast(asm7(2), RetargetingAssemblySymbol)).UnderlyingAssembly, asm3(3))
Assert.Equal(4, (From a In asm7(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm7(2).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(2, (From a In asm7(2).BoundReferences() Where a Is asm7(1) Select a).Count())
Dim type4 = asm7(2).GlobalNamespace.GetTypeMembers("Class5").Single()
Dim retval15 = type4.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Dim missingAssembly As AssemblySymbol
missingAssembly = retval15.ContainingAssembly
Assert.True(missingAssembly.IsMissing)
Assert.Equal("MTTestLib1", missingAssembly.Identity.Name)
Dim retval16 = type4.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Same(missingAssembly, retval16.ContainingAssembly)
Dim retval17 = type4.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind)
Assert.Same(retval17, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm7(3).Identity.Name)
Assert.Same((DirectCast(asm7(3), RetargetingAssemblySymbol)).UnderlyingAssembly, asm4(4))
Assert.Equal(6, (From a In asm7(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm7(3).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(2, (From a In asm7(3).BoundReferences() Where a Is asm7(1) Select a).Count())
Assert.Equal(2, (From a In asm7(3).BoundReferences() Where a Is asm7(2) Select a).Count())
Dim type5 = asm7(3).GlobalNamespace.GetTypeMembers("Class6").Single()
Dim retval18 = type5.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", (DirectCast(retval18, MissingMetadataTypeSymbol)).ContainingAssembly.Identity.Name)
Dim retval19 = type5.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly)
Dim retval20 = type5.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly)
Dim retval21 = type5.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind)
Assert.Same(retval21, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Dim retval22 = type5.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind)
Assert.Same(retval22, asm7(2).GlobalNamespace.GetMembers("Class5").Single())
' This test shows that simple reordering of references doesn't pick different set of assemblies
Dim c8 = CreateCompilation(New AssemblyIdentity("c8"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
New VisualBasicCompilationReference(varC_MTTestLib4),
New VisualBasicCompilationReference(varC_MTTestLib2),
New VisualBasicCompilationReference(varC_MTTestLib3)})
Dim asm8 = c8.SourceAssembly().BoundReferences()
Assert.Same(asm8(0), asm2(0))
Assert.True(asm8(2).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(1)))
Assert.Same(asm8(2), asm7(1))
Assert.True(asm8(3).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(3)))
Assert.Same(asm8(3), asm7(2))
Assert.True(asm8(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(4)))
Assert.Same(asm8(1), asm7(3))
Dim c9 = CreateCompilation(New AssemblyIdentity("c9"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
New VisualBasicCompilationReference(varC_MTTestLib4)})
Dim asm9 = c9.SourceAssembly().BoundReferences()
Assert.Same(asm9(0), asm2(0))
Assert.True(asm9(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4(4)))
Dim c10 = CreateCompilation(New AssemblyIdentity("c10"),
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.V3.MTTestLib1.dll,
New VisualBasicCompilationReference(varC_MTTestLib2),
New VisualBasicCompilationReference(varC_MTTestLib3),
New VisualBasicCompilationReference(varC_MTTestLib4)})
Dim asm10Prime = c10.SourceAssembly().BoundReferences()
Dim asm10 = New AssemblySymbol() {asm10Prime(0), asm10Prime(2), asm10Prime(1), asm10Prime(3), asm10Prime(4)}
Assert.Same(asm10(0), asm2(0))
Assert.Same(asm10(1), asm4(1))
Assert.Same(asm10(2), asm4(2))
Assert.Same(asm10(3), asm4(3))
Assert.Same(asm10(4), asm4(4))
Assert.Same(asm2(0), asm_MTTestLib2(0))
Assert.Equal("MTTestLib2", asm2(1).Identity.Name)
Assert.Equal(4, (From a In asm2(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm2(1).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Equal(2, (From a In asm2(1).BoundReferences() Where a Is asm2(2) Select a).Count())
retval1 = asm2(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind)
Assert.Same(retval1, asm2(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm2(2).Identity.Name)
Assert.Equal(1, asm2(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm2(2).BoundReferences() Where a Is asm2(0) Select a).Count())
Assert.Same(asm_MTTestLib3(0), asm_MTTestLib2(0))
Assert.NotSame(asm_MTTestLib3(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm_MTTestLib3(2), asm_MTTestLib2(1))
Assert.Same(asm3(0), asm_MTTestLib2(0))
Assert.Same(asm3(1), asm_MTTestLib3(1))
Assert.Same(asm3(2), asm_MTTestLib3(2))
Assert.Same(asm3(3), varC_MTTestLib3.SourceAssembly())
Assert.Equal("MTTestLib2", asm3(1).Identity.Name)
Assert.Same((DirectCast(asm3(1), RetargetingAssemblySymbol)).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly())
Assert.Equal(4, (From a In asm3(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm3(1).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(2, (From a In asm3(1).BoundReferences() Where a Is asm3(2) Select a).Count())
retval2 = asm3(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind)
Assert.Same(retval2, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm3(2).Identity.Name)
Assert.NotSame(asm3(2), asm2(2))
Assert.NotSame((DirectCast(asm3(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm2(2), PEAssemblySymbol)).[Assembly])
Assert.Equal(2, asm3(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm3(2).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal("MTTestLib3", asm3(3).Identity.Name)
Assert.Equal(6, (From a In asm3(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm3(3).BoundReferences() Where a Is asm3(0) Select a).Count())
Assert.Equal(2, (From a In asm3(3).BoundReferences() Where a Is asm3(1) Select a).Count())
Assert.Equal(2, (From a In asm3(3).BoundReferences() Where a Is asm3(2) Select a).Count())
type1 = asm3(3).GlobalNamespace.GetTypeMembers("Class5").Single()
retval3 = type1.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind)
Assert.Same(retval3, asm3(2).GlobalNamespace.GetMembers("Class1").Single())
retval4 = type1.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind)
Assert.Same(retval4, asm3(2).GlobalNamespace.GetMembers("Class2").Single())
retval5 = type1.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind)
Assert.Same(retval5, asm3(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Same(asm4(0), asm_MTTestLib2(0))
Assert.Same(asm4(1), asm_MTTestLib4(1))
Assert.Same(asm4(2), asm_MTTestLib4(2))
Assert.Same(asm4(3), asm_MTTestLib4(3))
Assert.Same(asm4(4), varC_MTTestLib4.SourceAssembly())
Assert.Equal("MTTestLib2", asm4(1).Identity.Name)
Assert.NotSame(asm4(1), varC_MTTestLib2.SourceAssembly())
Assert.NotSame(asm4(1), asm2(1))
Assert.NotSame(asm4(1), asm3(1))
Assert.Same((DirectCast(asm4(1), RetargetingAssemblySymbol)).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly())
Assert.Equal(4, (From a In asm4(1).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm4(1).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(2, (From a In asm4(1).BoundReferences() Where a Is asm4(2) Select a).Count())
retval6 = asm4(1).GlobalNamespace.GetTypeMembers("Class4").Single().GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind)
Assert.Same(retval6, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
Assert.Equal("MTTestLib1", asm4(2).Identity.Name)
Assert.NotSame(asm4(2), asm2(2))
Assert.NotSame(asm4(2), asm3(2))
Assert.NotSame((DirectCast(asm4(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm2(2), PEAssemblySymbol)).[Assembly])
Assert.NotSame((DirectCast(asm4(2), PEAssemblySymbol)).[Assembly], (DirectCast(asm3(2), PEAssemblySymbol)).[Assembly])
Assert.Equal(3, asm4(2).Identity.Version.Major)
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(1, (From a In asm4(2).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal("MTTestLib3", asm4(3).Identity.Name)
Assert.NotSame(asm4(3), asm3(3))
Assert.Same((DirectCast(asm4(3), RetargetingAssemblySymbol)).UnderlyingAssembly, asm3(3))
Assert.Equal(6, (From a In asm4(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm4(3).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(2, (From a In asm4(3).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(2, (From a In asm4(3).BoundReferences() Where a Is asm4(2) Select a).Count())
type2 = asm4(3).GlobalNamespace.GetTypeMembers("Class5").Single()
retval7 = type2.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind)
Assert.Same(retval7, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
retval8 = type2.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind)
Assert.Same(retval8, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
retval9 = type2.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind)
Assert.Same(retval9, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm4(4).Identity.Name)
Assert.Equal(8, (From a In asm4(4).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm4(4).BoundReferences() Where a Is asm4(0) Select a).Count())
Assert.Equal(2, (From a In asm4(4).BoundReferences() Where a Is asm4(1) Select a).Count())
Assert.Equal(2, (From a In asm4(4).BoundReferences() Where a Is asm4(2) Select a).Count())
Assert.Equal(2, (From a In asm4(4).BoundReferences() Where a Is asm4(3) Select a).Count())
type3 = asm4(4).GlobalNamespace.GetTypeMembers("Class6").Single()
retval10 = type3.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind)
Assert.Same(retval10, asm4(2).GlobalNamespace.GetMembers("Class1").Single())
retval11 = type3.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind)
Assert.Same(retval11, asm4(2).GlobalNamespace.GetMembers("Class2").Single())
retval12 = type3.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind)
Assert.Same(retval12, asm4(2).GlobalNamespace.GetMembers("Class3").Single())
retval13 = type3.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind)
Assert.Same(retval13, asm4(1).GlobalNamespace.GetMembers("Class4").Single())
retval14 = type3.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind)
Assert.Same(retval14, asm4(3).GlobalNamespace.GetMembers("Class5").Single())
Assert.Same(asm5(0), asm2(0))
Assert.True(asm5(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3(3)))
Assert.Same(asm6(0), asm2(0))
Assert.True(asm6(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly()))
Assert.Same(asm7(0), asm2(0))
Assert.True(asm7(1).RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly()))
Assert.NotSame(asm7(2), asm3(3))
Assert.NotSame(asm7(2), asm4(3))
Assert.NotSame(asm7(3), asm4(4))
Assert.Equal("MTTestLib3", asm7(2).Identity.Name)
Assert.Same((DirectCast(asm7(2), RetargetingAssemblySymbol)).UnderlyingAssembly, asm3(3))
Assert.Equal(4, (From a In asm7(2).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm7(2).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(2, (From a In asm7(2).BoundReferences() Where a Is asm7(1) Select a).Count())
type4 = asm7(2).GlobalNamespace.GetTypeMembers("Class5").Single()
retval15 = type4.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
missingAssembly = retval15.ContainingAssembly
Assert.True(missingAssembly.IsMissing)
Assert.Equal("MTTestLib1", missingAssembly.Identity.Name)
retval16 = type4.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Same(missingAssembly, retval16.ContainingAssembly)
retval17 = type4.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind)
Assert.Same(retval17, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
Assert.Equal("MTTestLib4", asm7(3).Identity.Name)
Assert.Same((DirectCast(asm7(3), RetargetingAssemblySymbol)).UnderlyingAssembly, asm4(4))
Assert.Equal(6, (From a In asm7(3).BoundReferences() Where Not a.IsMissing Select a).Count())
Assert.Equal(2, (From a In asm7(3).BoundReferences() Where a Is asm7(0) Select a).Count())
Assert.Equal(2, (From a In asm7(3).BoundReferences() Where a Is asm7(1) Select a).Count())
Assert.Equal(2, (From a In asm7(3).BoundReferences() Where a Is asm7(2) Select a).Count())
type5 = asm7(3).GlobalNamespace.GetTypeMembers("Class6").Single()
retval18 = type5.GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("MTTestLib1", (DirectCast(retval18, MissingMetadataTypeSymbol)).ContainingAssembly.Identity.Name)
retval19 = type5.GetMembers("Foo2").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly)
retval20 = type5.GetMembers("Foo3").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly)
retval21 = type5.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind)
Assert.Same(retval21, asm7(1).GlobalNamespace.GetMembers("Class4").Single())
retval22 = type5.GetMembers("Foo5").OfType(Of MethodSymbol)().Single().ReturnType
Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind)
Assert.Same(retval22, asm7(2).GlobalNamespace.GetMembers("Class5").Single())
End Sub
#If Retargeting Then
<Fact(skip:=SkipReason.AlreadyTestingRetargeting)>
Public Sub MultiTargeting4()
#Else
<Fact()>
Public Sub MultiTargeting4()
#End If
'"Class C1(Of T)" & vbCrLf &
'" Class C2(Of S)" & vbCrLf &
'" End Class" & vbCrLf &
'"End Class" & vbCrLf &
'"" & vbCrLf &
'"Class C3" & vbCrLf &
'" Function Foo() As C1(Of C3).C2(Of C4)" & vbCrLf &
'" End Function" & vbCrLf &
'"End Class" & vbCrLf &
'"" & vbCrLf &
'"Class C4" & vbCrLf &
'"End Class"
Dim source1 =
<s1>
Public Class C1(Of T)
Public Class C2(Of S)
Public Function Foo() As C1(Of T).C2(Of S)
Return Nothing
End Function
End Class
End Class
</s1>
Dim c1_V1_Name = New AssemblyIdentity("c1", New Version("1.0.0.0"))
Dim c1_V1 As VisualBasicCompilation = CreateCompilation(c1_V1_Name,
{source1.Value},
{TestReferences.NetFx.v4_0_30319.mscorlib})
Dim asm1_V1 = c1_V1.SourceAssembly
Dim c1_V2_Name = New AssemblyIdentity("c1", New Version("2.0.0.0"))
Dim c1_V2 As VisualBasicCompilation = CreateCompilation(c1_V2_Name,
{source1.Value},
{TestReferences.NetFx.v4_0_30319.mscorlib})
Dim asm1_V2 = c1_V2.SourceAssembly
Dim source4 =
<s4>
Public Class C4
End Class
</s4>
Dim c4_V1_Name = New AssemblyIdentity("c4", New Version("1.0.0.0"))
Dim c4_V1 As VisualBasicCompilation = CreateCompilation(c4_V1_Name,
{source4.Value},
{TestReferences.NetFx.v4_0_30319.mscorlib})
Dim asm4_V1 = c4_V1.SourceAssembly
Dim c4_V2_Name = New AssemblyIdentity("c4", New Version("2.0.0.0"))
Dim c4_V2 As VisualBasicCompilation = CreateCompilation(c4_V2_Name,
{source4.Value},
{TestReferences.NetFx.v4_0_30319.mscorlib})
Dim asm4_V2 = c4_V2.SourceAssembly
Dim source7 =
<s3>
Public Class C7
End Class
Public Class C8(Of T)
End Class
</s3>
Dim c7 As VisualBasicCompilation = CreateCompilation(New AssemblyIdentity("C7"),
{source7.Value},
{TestReferences.NetFx.v4_0_30319.mscorlib})
Dim asm7 = c7.SourceAssembly
Dim source3 =
<s3>
Public Class C3
Public Function Foo() As C1(Of C3).C2(Of C4)
Return Nothing
End Function
Public Shared Function Bar() As C6(Of C4)
Return Nothing
End Function
Public Function Foo1() As C8(Of C7)
Return Nothing
End Function
Public Sub Foo2(ByRef x1(,) As C300,
<System.Runtime.InteropServices.Out()> ByRef x2 As C4,
ByRef x3() As C7,
Optional ByVal x4 As C4 = Nothing)
End Sub
Friend Overridable Function Foo3(Of TFoo3 As C4)() As TFoo3
Return Nothing
End Function
Public Function Foo4() As C8(Of C4)
Return Nothing
End Function
Public MustInherit Class C301
Implements I1
End Class
Friend Class C302
End Class
End Class
Public Class C6(Of T As New)
End Class
Public Class C300
End Class
Public Interface I1
End Interface
Namespace ns1
Namespace ns2
Public Class C303
End Class
End Namespace
Public Class C304
Public Class C305
End Class
End Class
End Namespace
</s3>
Dim c3 As VisualBasicCompilation = CreateCompilation(New AssemblyIdentity("C3"),
{source3.Value},
{TestReferences.NetFx.v4_0_30319.mscorlib,
New VisualBasicCompilationReference(c1_V1),
New VisualBasicCompilationReference(c4_V1),
New VisualBasicCompilationReference(c7)})
Dim asm3 = c3.SourceAssembly
Dim localC3Foo2 = asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetMembers("Foo2").OfType(Of MethodSymbol)().Single()
Dim source5 =
<s5>
Public Class C5
Inherits ns1.C304.C305
End Class
</s5>
Dim c5 As VisualBasicCompilation = CreateCompilation(New AssemblyIdentity("C5"),
{source5.Value},
{TestReferences.NetFx.v4_0_30319.mscorlib,
New VisualBasicCompilationReference(c3),
New VisualBasicCompilationReference(c1_V2),
New VisualBasicCompilationReference(c4_V2),
New VisualBasicCompilationReference(c7)})
Dim asm5 = c5.SourceAssembly.BoundReferences
Assert.NotSame(asm5(1), asm3)
Assert.Same(DirectCast(asm5(1), RetargetingAssemblySymbol).UnderlyingAssembly, asm3)
Assert.Same(asm5(2), asm1_V2)
Assert.Same(asm5(3), asm4_V2)
Assert.Same(asm5(4), asm7)
Dim type3 = asm5(1).GlobalNamespace.GetTypeMembers("C3").Single()
Dim type1 = asm1_V2.GlobalNamespace.GetTypeMembers("C1").Single()
Dim type2 = type1.GetTypeMembers("C2").Single()
Dim type4 = asm4_V2.GlobalNamespace.GetTypeMembers("C4").Single()
Dim retval1 = DirectCast(type3.GetMembers("Foo").OfType(Of MethodSymbol)().Single().ReturnType, NamedTypeSymbol)
Assert.Equal("C1(Of C3).C2(Of C4)", retval1.ToTestDisplayString())
Assert.Same(retval1.OriginalDefinition, type2)
Dim args1 = retval1.ContainingType.TypeArguments.Concat(retval1.TypeArguments)
Dim params1 = retval1.ContainingType.TypeParameters.Concat(retval1.TypeParameters)
Assert.Same(params1(0), type1.TypeParameters(0))
Assert.Same(params1(1).OriginalDefinition, type2.TypeParameters(0).OriginalDefinition)
Assert.Same(args1(0), type3)
Assert.Same(args1(0).ContainingAssembly, asm5(1))
Assert.Same(args1(1), type4)
Dim retval2 = retval1.ContainingType
Assert.Equal("C1(Of C3)", retval2.ToTestDisplayString())
Assert.Same(retval2.OriginalDefinition, type1)
Dim bar = type3.GetMembers("Bar").OfType(Of MethodSymbol)().Single()
Dim retval3 = DirectCast(bar.ReturnType, NamedTypeSymbol)
Dim type6 = asm5(1).GlobalNamespace.GetTypeMembers("C6").Single()
Assert.Equal("C6(Of C4)", retval3.ToTestDisplayString())
Assert.Same(retval3.OriginalDefinition, type6)
Assert.Same(retval3.ContainingAssembly, asm5(1))
Dim args3 = retval3.TypeArguments
Dim params3 = retval3.TypeParameters
Assert.Same(params3(0), type6.TypeParameters(0))
Assert.Same(params3(0).ContainingAssembly, asm5(1))
Assert.Same(args3(0), type4)
Dim foo1 = type3.GetMembers("Foo1").OfType(Of MethodSymbol)().Single()
Dim retval4 = foo1.ReturnType
Assert.Equal("C8(Of C7)", retval4.ToTestDisplayString())
Assert.Same(retval4, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetMembers("Foo1").OfType(Of MethodSymbol)().Single().ReturnType)
Dim foo1Params = foo1.Parameters
Assert.Equal(0, foo1Params.Length)
Dim foo2 = type3.GetMembers("Foo2").OfType(Of MethodSymbol)().Single()
Assert.NotEqual(localC3Foo2, foo2)
Assert.Same(localC3Foo2, (DirectCast(foo2, RetargetingMethodSymbol)).UnderlyingMethod)
Assert.Equal(1, ((DirectCast(foo2, RetargetingMethodSymbol)).Locations).Length)
Dim foo2Params = foo2.Parameters
Assert.Equal(4, foo2Params.Length)
Assert.Same(localC3Foo2.Parameters(0), (DirectCast(foo2Params(0), RetargetingParameterSymbol)).UnderlyingParameter)
Assert.Same(localC3Foo2.Parameters(1), (DirectCast(foo2Params(1), RetargetingParameterSymbol)).UnderlyingParameter)
Assert.Same(localC3Foo2.Parameters(2), (DirectCast(foo2Params(2), RetargetingParameterSymbol)).UnderlyingParameter)
Assert.Same(localC3Foo2.Parameters(3), (DirectCast(foo2Params(3), RetargetingParameterSymbol)).UnderlyingParameter)
Dim x1 = foo2Params(0)
Dim x2 = foo2Params(1)
Dim x3 = foo2Params(2)
Dim x4 = foo2Params(3)
Assert.Equal("x1", x1.Name)
Assert.NotEqual(localC3Foo2.Parameters(0).[Type], x1.[Type])
Assert.Equal(localC3Foo2.Parameters(0).ToTestDisplayString(), x1.ToTestDisplayString())
Assert.Same(asm5(1), x1.ContainingAssembly)
Assert.Same(foo2, x1.ContainingSymbol)
Assert.[False](x1.HasExplicitDefaultValue)
Assert.[False](x1.IsOptional)
Assert.True(x1.IsByRef)
Assert.Equal(2, (DirectCast(x1.[Type], ArrayTypeSymbol)).Rank)
Assert.Equal("x2", x2.Name)
Assert.NotEqual(localC3Foo2.Parameters(1).[Type], x2.[Type])
Assert.True(x2.IsByRef)
Assert.Equal("x3", x3.Name)
Assert.Same(localC3Foo2.Parameters(2).[Type], x3.[Type])
Assert.Equal("x4", x4.Name)
Assert.True(x4.HasExplicitDefaultValue)
Assert.[True](x4.IsOptional)
Assert.Equal("Foo2", foo2.Name)
Assert.Equal(localC3Foo2.ToTestDisplayString(), foo2.ToTestDisplayString())
Assert.Same(asm5(1), foo2.ContainingAssembly)
Assert.Same(type3, foo2.ContainingSymbol)
Assert.Equal(Accessibility.[Public], foo2.DeclaredAccessibility)
Assert.False(foo2.IsOverloads)
Assert.[False](foo2.IsMustOverride)
Assert.[False](foo2.IsExternalMethod)
Assert.[False](foo2.IsGenericMethod)
Assert.[False](foo2.IsOverrides)
Assert.[False](foo2.IsNotOverridable)
Assert.[False](foo2.IsShared)
Assert.[False](foo2.IsVararg)
Assert.[False](foo2.IsOverridable)
Assert.[True](foo2.IsSub)
Assert.Equal(0, foo2.TypeParameters.Length)
Assert.Equal(0, foo2.TypeArguments.Length)
Assert.[True](bar.IsShared)
Assert.[False](bar.IsSub)
Dim foo3 = type3.GetMembers("Foo3").OfType(Of MethodSymbol)().Single()
Assert.Equal(Accessibility.Friend, foo3.DeclaredAccessibility)
Assert.[True](foo3.IsGenericMethod)
Assert.[True](foo3.IsOverridable)
Dim foo3TypeParams = foo3.TypeParameters
Assert.Equal(1, foo3TypeParams.Length)
Assert.Equal(1, foo3.TypeArguments.Length)
Assert.Same(foo3TypeParams(0), foo3.TypeArguments(0))
Dim typeC301 = type3.GetTypeMembers("C301").Single()
Dim typeC302 = type3.GetTypeMembers("C302").Single()
Dim typeC6 = asm5(1).GlobalNamespace.GetTypeMembers("C6").Single()
Assert.Equal(typeC301.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetTypeMembers("C301").Single().ToTestDisplayString())
Assert.Equal(typeC6.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToTestDisplayString())
Assert.Equal(typeC301.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetTypeMembers("C301").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat))
Assert.Equal(typeC6.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat))
Assert.Equal(type3.GetMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetMembers().Length)
Assert.Equal(type3.GetTypeMembers().Length(), asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetTypeMembers().Length())
Assert.Same(typeC301, type3.GetTypeMembers("C301", 0).Single())
Assert.Equal(0, type3.Arity)
Assert.Equal(1, typeC6.Arity)
Assert.NotNull(type3.BaseType)
Assert.Equal("System.Object", type3.BaseType.ToTestDisplayString())
Assert.Equal(Accessibility.[Public], type3.DeclaredAccessibility)
Assert.Equal(Accessibility.Friend, typeC302.DeclaredAccessibility)
Assert.Equal(0, type3.Interfaces.Length)
Assert.Equal(1, typeC301.Interfaces.Length)
Assert.Equal("I1", typeC301.Interfaces.Single().Name)
Assert.[False](type3.IsMustInherit)
Assert.[True](typeC301.IsMustInherit)
Assert.[False](type3.IsNotInheritable)
Assert.[False](type3.IsShared)
Assert.Equal(0, type3.TypeArguments.Length)
Assert.Equal(0, type3.TypeParameters.Length)
Dim localC6Params = typeC6.TypeParameters
Assert.Equal(1, localC6Params.Length)
Assert.Equal(1, typeC6.TypeArguments.Length)
Assert.Same(localC6Params(0), typeC6.TypeArguments(0))
Assert.Same((DirectCast(type3, RetargetingNamedTypeSymbol)).UnderlyingNamedType, asm3.GlobalNamespace.GetTypeMembers("C3").Single())
Assert.Equal(1, ((DirectCast(type3, RetargetingNamedTypeSymbol)).Locations).Length)
Assert.Equal(TypeKind.[Class], type3.TypeKind)
Assert.Equal(TypeKind.[Interface], asm5(1).GlobalNamespace.GetTypeMembers("I1").Single().TypeKind)
Dim localC6_T = localC6Params(0)
Dim foo3TypeParam = foo3TypeParams(0)
Assert.Equal(0, localC6_T.ConstraintTypes.Length)
Assert.Equal(1, foo3TypeParam.ConstraintTypes.Length)
Assert.Same(type4, foo3TypeParam.ConstraintTypes(0))
Assert.Same(typeC6, localC6_T.ContainingSymbol)
Assert.[False](foo3TypeParam.HasConstructorConstraint)
Assert.[True](localC6_T.HasConstructorConstraint)
Assert.[False](foo3TypeParam.HasReferenceTypeConstraint)
Assert.[False](foo3TypeParam.HasValueTypeConstraint)
Assert.Equal("TFoo3", foo3TypeParam.Name)
Assert.Equal("T", localC6_T.Name)
Assert.Equal(0, foo3TypeParam.Ordinal)
Assert.Equal(0, localC6_T.Ordinal)
Assert.Equal(VarianceKind.None, foo3TypeParam.Variance)
Assert.Same((DirectCast(localC6_T, RetargetingTypeParameterSymbol)).UnderlyingTypeParameter, asm3.GlobalNamespace.GetTypeMembers("C6").Single().TypeParameters(0))
Dim ns1 = asm5(1).GlobalNamespace.GetMembers("ns1").OfType(Of NamespaceSymbol)().Single()
Dim ns2 = ns1.GetMembers("ns2").OfType(Of NamespaceSymbol)().Single()
Assert.Equal("ns1.ns2", ns2.ToTestDisplayString())
Assert.Equal(2, ns1.GetMembers().Length)
Assert.Equal(1, ns1.GetTypeMembers().Length())
Assert.Same(ns1.GetTypeMembers("C304").Single(), ns1.GetTypeMembers("C304", 0).Single())
Assert.Same(asm5(1).Modules(0), asm5(1).Modules(0).GlobalNamespace.ContainingSymbol)
Assert.Same(asm5(1).Modules(0).GlobalNamespace, ns1.ContainingSymbol)
Assert.Same(asm5(1).Modules(0), ns1.Extent.[Module])
Assert.Equal(1, ns1.ConstituentNamespaces.Length)
Assert.Same(ns1, ns1.ConstituentNamespaces(0))
Assert.[False](ns1.IsGlobalNamespace)
Assert.Equal(DirectCast(ns2, RetargetingNamespaceSymbol).DeclaredAccessibilityOfMostAccessibleDescendantType, ns2.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.[True](asm5(1).Modules(0).GlobalNamespace.IsGlobalNamespace)
Assert.Same(asm3.Modules(0).GlobalNamespace, (DirectCast(asm5(1).Modules(0).GlobalNamespace, RetargetingNamespaceSymbol)).UnderlyingNamespace)
Assert.Same(asm3.Modules(0).GlobalNamespace.GetMembers("ns1").Single(), (DirectCast(ns1, RetargetingNamespaceSymbol)).UnderlyingNamespace)
Dim module3 = DirectCast(asm5(1).Modules(0), RetargetingModuleSymbol)
Assert.Equal("C3.exe", module3.ToTestDisplayString())
Assert.Equal("C3.exe", module3.Name)
Assert.Same(asm5(1), module3.ContainingSymbol)
Assert.Same(asm5(1), module3.ContainingAssembly)
Assert.Null(module3.ContainingType)
Dim retval5 = type3.GetMembers("Foo4").OfType(Of MethodSymbol)().Single().ReturnType
Assert.Equal("C8(Of C4)", retval5.ToTestDisplayString())
Dim typeC5 = c5.[Assembly].GlobalNamespace.GetTypeMembers("C5").Single()
Assert.Same(asm5(1), typeC5.BaseType.ContainingAssembly)
Assert.Equal("ns1.C304.C305", typeC5.BaseType.ToTestDisplayString())
Assert.NotEqual(SymbolKind.ErrorType, typeC5.Kind)
End Sub
<Fact()>
Public Sub MultiTargeting5()
Dim c1_Name = New AssemblyIdentity("c1")
Dim compilationDef =
<compilation name="Dummy">
<file name="Dummy.vb">
class Module1
Function M1() As Class4
End Function
Function M2() As Class4.Class4_1
End Function
Function M3() As Class4
End Function
End Class
</file>
</compilation>
Dim refs = New List(Of MetadataReference)()
refs.Add(TestReferences.SymbolsTests.V1.MTTestLib1.dll)
refs.Add(TestReferences.SymbolsTests.V1.MTTestModule2.netmodule)
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib(compilationDef)
c1 = c1.AddReferences(refs)
Dim c2_Name = New AssemblyIdentity("MTTestLib2")
Dim c2 = CreateCompilation(c2_Name,
Nothing,
{TestReferences.NetFx.v4_0_30319.mscorlib,
TestReferences.SymbolsTests.V2.MTTestLib1.dll,
New VisualBasicCompilationReference(c1)})
Dim c1AsmSource As SourceAssemblySymbol = DirectCast(c1.[Assembly], SourceAssemblySymbol)
Dim Lib1_V1 As PEAssemblySymbol = DirectCast(c1AsmSource.Modules(0).GetReferencedAssemblySymbols()(1), PEAssemblySymbol)
Dim module1 As PEModuleSymbol = DirectCast(c1AsmSource.Modules(1), PEModuleSymbol)
Dim c2AsmSource As SourceAssemblySymbol = DirectCast(c2.[Assembly], SourceAssemblySymbol)
Dim c1AsmRef As RetargetingAssemblySymbol = DirectCast(c2AsmSource.Modules(0).GetReferencedAssemblySymbols()(2), RetargetingAssemblySymbol)
Dim Lib1_V2 As PEAssemblySymbol = DirectCast(c2AsmSource.Modules(0).GetReferencedAssemblySymbols()(1), PEAssemblySymbol)
Dim module2 As PEModuleSymbol = DirectCast(c1AsmRef.Modules(1), PEModuleSymbol)
Assert.Equal(1, Lib1_V1.Identity.Version.Major)
Assert.Equal(2, Lib1_V2.Identity.Version.Major)
Assert.NotEqual(module1, module2)
Assert.Same(module1.[Module], module2.[Module])
Dim classModule1 As NamedTypeSymbol = c1AsmRef.Modules(0).GlobalNamespace.GetTypeMembers("Module1").Single()
Dim m1 As MethodSymbol = classModule1.GetMembers("M1").OfType(Of MethodSymbol)().Single()
Dim m2 As MethodSymbol = classModule1.GetMembers("M2").OfType(Of MethodSymbol)().Single()
Dim m3 As MethodSymbol = classModule1.GetMembers("M3").OfType(Of MethodSymbol)().Single()
Assert.Same(module2, m1.ReturnType.ContainingModule)
Assert.Same(module2, m2.ReturnType.ContainingModule)
Assert.Same(module2, m3.ReturnType.ContainingModule)
End Sub
' Very simplistic test if a compilation has a single type with the given full name. Does NOT handle generics.
Private Function HasSingleTypeOfKind(c As VisualBasicCompilation, kind As TypeKind, fullName As String) As Boolean
Dim names As String() = fullName.Split("."c)
Dim current As NamespaceOrTypeSymbol = c.GlobalNamespace
For Each name In names
Dim matchingSym = current.GetMembers(name)
If (matchingSym.Length() <> 1) Then
Return False
End If
current = DirectCast(matchingSym.First(), NamespaceOrTypeSymbol)
Next
Return (TypeOf current Is TypeSymbol AndAlso DirectCast(current, TypeSymbol).TypeKind = kind)
End Function
<Fact()>
Public Sub AddRemoveReferences()
Dim mscorlibRef = TestReferences.NetFx.v4_0_30319.mscorlib
Dim systemCoreRef = TestReferences.NetFx.v4_0_30319.System_Core
Dim systemRef = TestReferences.NetFx.v4_0_30319.System
Dim c = VisualBasicCompilation.Create("Test")
Assert.False(HasSingleTypeOfKind(c, TypeKind.Structure, "System.Int32"))
c = c.AddReferences(mscorlibRef)
Assert.True(HasSingleTypeOfKind(c, TypeKind.Structure, "System.Int32"))
Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable"))
c = c.AddReferences(systemCoreRef)
Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable"))
Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri"))
c = c.ReplaceReference(systemCoreRef, systemRef)
Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable"))
Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri"))
c = c.RemoveReferences(systemRef)
Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri"))
Assert.True(HasSingleTypeOfKind(c, TypeKind.Structure, "System.Int32"))
c = c.RemoveReferences(mscorlibRef)
Assert.False(HasSingleTypeOfKind(c, TypeKind.Structure, "System.Int32"))
End Sub
<Fact()>
Public Sub SyntaxTreeOrderConstruct()
Dim tree1 = CreateSyntaxTree("A")
Dim tree2 = CreateSyntaxTree("B")
Dim treeOrder1 = {tree1, tree2}
Dim compilation1 = VisualBasicCompilation.Create("Compilation1", syntaxTrees:=treeOrder1)
CheckCompilationSyntaxTrees(compilation1, treeOrder1)
Dim treeOrder2 = {tree2, tree1}
Dim compilation2 = VisualBasicCompilation.Create("Compilation2", syntaxTrees:=treeOrder2)
CheckCompilationSyntaxTrees(compilation2, treeOrder2)
End Sub
<Fact()>
Public Sub SyntaxTreeOrderAdd()
Dim tree1 = CreateSyntaxTree("A")
Dim tree2 = CreateSyntaxTree("B")
Dim tree3 = CreateSyntaxTree("C")
Dim tree4 = CreateSyntaxTree("D")
Dim treeList1 = {tree1, tree2}
Dim compilation1 = VisualBasicCompilation.Create("Compilation1", syntaxTrees:=treeList1)
CheckCompilationSyntaxTrees(compilation1, treeList1)
Dim treeList2 = {tree3, tree4}
Dim compilation2 = compilation1.AddSyntaxTrees(treeList2)
CheckCompilationSyntaxTrees(compilation1, treeList1) ' compilation1 untouched
CheckCompilationSyntaxTrees(compilation2, treeList1.Concat(treeList2).ToArray())
Dim treeList3 = {tree4, tree3}
Dim compilation3 = VisualBasicCompilation.Create("Compilation3", syntaxTrees:=treeList3)
CheckCompilationSyntaxTrees(compilation3, treeList3)
Dim treeList4 = {tree2, tree1}
Dim compilation4 = compilation3.AddSyntaxTrees(treeList4)
CheckCompilationSyntaxTrees(compilation3, treeList3) ' compilation3 untouched
CheckCompilationSyntaxTrees(compilation4, treeList3.Concat(treeList4).ToArray())
End Sub
<Fact()>
Public Sub SyntaxTreeOrderRemove()
Dim tree1 = CreateSyntaxTree("A")
Dim tree2 = CreateSyntaxTree("B")
Dim tree3 = CreateSyntaxTree("C")
Dim tree4 = CreateSyntaxTree("D")
Dim treeList1 = {tree1, tree2, tree3, tree4}
Dim compilation1 = VisualBasicCompilation.Create("Compilation1", syntaxTrees:=treeList1)
CheckCompilationSyntaxTrees(compilation1, treeList1)
Dim treeList2 = {tree3, tree1}
Dim compilation2 = compilation1.RemoveSyntaxTrees(treeList2)
CheckCompilationSyntaxTrees(compilation1, treeList1) ' compilation1 untouched
CheckCompilationSyntaxTrees(compilation2, tree2, tree4)
Dim treeList3 = {tree4, tree3, tree2, tree1}
Dim compilation3 = VisualBasicCompilation.Create("Compilation3", syntaxTrees:=treeList3)
CheckCompilationSyntaxTrees(compilation3, treeList3)
Dim treeList4 = {tree3, tree1}
Dim compilation4 = compilation3.RemoveSyntaxTrees(treeList4)
CheckCompilationSyntaxTrees(compilation3, treeList3) ' compilation3 untouched
CheckCompilationSyntaxTrees(compilation4, tree4, tree2)
End Sub
<Fact()>
Public Sub SyntaxTreeOrderReplace()
Dim tree1 = CreateSyntaxTree("A")
Dim tree2 = CreateSyntaxTree("B")
Dim tree3 = CreateSyntaxTree("C")
Dim treeList1 = {tree1, tree2}
Dim compilation1 = VisualBasicCompilation.Create("Compilation1", syntaxTrees:=treeList1)
CheckCompilationSyntaxTrees(compilation1, treeList1)
Dim compilation2 = compilation1.ReplaceSyntaxTree(tree1, tree3)
CheckCompilationSyntaxTrees(compilation1, treeList1) ' compilation1 untouched
CheckCompilationSyntaxTrees(compilation2, tree3, tree2)
Dim treeList3 = {tree2, tree1}
Dim compilation3 = VisualBasicCompilation.Create("Compilation3", syntaxTrees:=treeList3)
CheckCompilationSyntaxTrees(compilation3, treeList3)
Dim compilation4 = compilation3.ReplaceSyntaxTree(tree1, tree3)
CheckCompilationSyntaxTrees(compilation3, treeList3) ' compilation3 untouched
CheckCompilationSyntaxTrees(compilation4, tree2, tree3)
End Sub
<WorkItem(578706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578706")>
<Fact>
Public Sub DeclaringCompilationOfAddedModule()
Dim source1 =
<compilation name="Lib1">
<file name="a.vb">
Class C1
End Class
</file>
</compilation>
Dim source2 =
<compilation name="Lib2">
<file name="a.vb">
Class C2
End Class
</file>
</compilation>
Dim lib1 = CreateCompilationWithMscorlib(source1, OutputKind.NetModule)
Dim ref1 = lib1.EmitToImageReference()
Dim lib2 = CreateCompilationWithMscorlibAndReferences(source2, {ref1})
lib2.VerifyDiagnostics()
Dim sourceAssembly = lib2.Assembly
Dim sourceModule = sourceAssembly.Modules(0)
Dim sourceType = sourceModule.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C2")
Assert.IsType(Of SourceAssemblySymbol)(sourceAssembly)
Assert.Equal(lib2, sourceAssembly.DeclaringCompilation)
Assert.IsType(Of SourceModuleSymbol)(sourceModule)
Assert.Equal(lib2, sourceModule.DeclaringCompilation)
Assert.IsType(Of SourceNamedTypeSymbol)(sourceType)
Assert.Equal(lib2, sourceType.DeclaringCompilation)
Dim addedModule = sourceAssembly.Modules(1)
Dim addedModuleAssembly = addedModule.ContainingAssembly
Dim addedModuleType = addedModule.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C1")
Assert.IsType(Of SourceAssemblySymbol)(addedModuleAssembly)
Assert.Equal(lib2, addedModuleAssembly.DeclaringCompilation) ' NB: not lib1, not null
Assert.IsType(Of PEModuleSymbol)(addedModule)
Assert.Null(addedModule.DeclaringCompilation)
Assert.IsType(Of PENamedTypeSymbol)(addedModuleType)
Assert.Null(addedModuleType.DeclaringCompilation)
End Sub
Private Shared Function CreateSyntaxTree(className As String) As SyntaxTree
Dim text = String.Format("Public Partial Class {0}{1}End Class", className, Environment.NewLine)
Dim path = String.Format("{0}.vb", className)
Return VisualBasicSyntaxTree.ParseText(text, path:=path)
End Function
Private Shared Sub CheckCompilationSyntaxTrees(compilation As VisualBasicCompilation, ParamArray expectedSyntaxTrees As SyntaxTree())
Dim actualSyntaxTrees = compilation.SyntaxTrees
Dim numTrees = expectedSyntaxTrees.Length
Assert.Equal(numTrees, actualSyntaxTrees.Length)
For i = 0 To numTrees - 1
Assert.Equal(expectedSyntaxTrees(i), actualSyntaxTrees(i))
Next
For i = 0 To numTrees - 1
For j = 0 To numTrees - 1
Assert.Equal(Math.Sign(compilation.CompareSyntaxTreeOrdering(expectedSyntaxTrees(i), expectedSyntaxTrees(j))), Math.Sign(i.CompareTo(j)))
Next
Next
Dim types = expectedSyntaxTrees.Select(Function(tree) compilation.GetSemanticModel(tree).GetDeclaredSymbol(tree.GetCompilationUnitRoot().Members.Single())).ToArray()
For i = 0 To numTrees - 1
For j = 0 To numTrees - 1
Assert.Equal(Math.Sign(compilation.CompareSourceLocations(types(i).Locations(0), types(j).Locations(0))), Math.Sign(i.CompareTo(j)))
Next
Next
End Sub
End Class
End Namespace
|
ericfe-ms/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CompilationCreationTests.vb
|
Visual Basic
|
apache-2.0
| 137,640
|
#Region "Microsoft.VisualBasic::51914b6e60badcfe0e9403b8bfd5eada, src\visualize\plot\StandardCurvesPlot.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Module StandardCurvesPlot
'
' Function: StandardCurves
'
' /********************************************************************************/
#End Region
Imports System.Drawing
Imports System.Runtime.CompilerServices
Imports BioNovoGene.Analytical.MassSpectrometry.Math.LinearQuantitative
Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel
Imports Microsoft.VisualBasic.Data.ChartPlots.Statistics
Imports Microsoft.VisualBasic.Imaging.Driver
Imports Microsoft.VisualBasic.MIME.Html.CSS
Public Module StandardCurvesPlot
<MethodImpl(MethodImplOptions.AggressiveInlining)>
<Extension>
Public Function StandardCurves(model As StandardCurve,
Optional samples As IEnumerable(Of NamedValue(Of Double)) = Nothing,
Optional name$ = "",
Optional size$ = "1600,1200",
Optional margin$ = "padding: 100px 100px 100px 200px",
Optional factorFormat$ = "G4",
Optional sampleLabelFont$ = CSSFont.Win10Normal,
Optional labelerIterations% = 1000,
Optional gridFill$ = NameOf(Color.LightGray),
Optional showLegend As Boolean = True,
Optional showYFitPoints As Boolean = True) As GraphicsData
If model.requireISCalibration Then
' 如果进行内标校正的话,则应该是[峰面积比, 浓度比]之间的线性关系
Return model _
.linear _
.Plot(xLabel:="(CIS/Cti u mol/L) ratio",
yLabel:="Peak area ratio (AIS/Ati)",
size:=size,
predictedX:=samples,
xAxisTickFormat:="F2",
yAxisTickFormat:="F2",
showErrorBand:=False,
title:=name,
margin:=margin,
factorFormat:=factorFormat,
pointLabelFontCSS:=sampleLabelFont,
labelerIterations:=labelerIterations,
gridFill:=gridFill,
showLegend:=showLegend,
showYFitPoints:=showYFitPoints
)
Else
' 如果不做内标校正的话,则是直接[峰面积, 浓度]之间的线性关系了
Return model _
.linear _
.Plot(xLabel:="Cti u mol/L",
yLabel:="Peak area(Ati)",
size:=size,
predictedX:=samples,
xAxisTickFormat:="G2",
yAxisTickFormat:="G2",
showErrorBand:=False,
title:=name,
margin:=margin,
factorFormat:=factorFormat,
pointLabelFontCSS:=sampleLabelFont,
labelerIterations:=labelerIterations,
gridFill:=gridFill,
showLegend:=showLegend,
showYFitPoints:=showYFitPoints
)
End If
End Function
End Module
|
xieguigang/MassSpectrum-toolkits
|
src/visualize/plot/StandardCurvesPlot.vb
|
Visual Basic
|
mit
| 4,886
|
Imports System.Data
Partial Class rCuentas_Gastos
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
Dim lcComandoSelect As String
Try
lcComandoSelect = "SELECT Cod_Gas, " _
& "Nom_Gas, " _
& "Status, " _
& "(Case When Status = 'A' Then 'Activo' Else 'Inactivo' End) as Status_Cuentas_Gastos " _
& "FROM Cuentas_Gastos " _
& "WHERE Cod_Gas between '" & cusAplicacion.goReportes.paParametrosIniciales(0) & "'" _
& " And '" & cusAplicacion.goReportes.paParametrosFinales(0) & "'" _
& " And Status between '" & cusAplicacion.goReportes.paParametrosIniciales(1) & "'" _
& " And '" & cusAplicacion.goReportes.paParametrosFinales(1) & "'" _
& " ORDER BY Cod_Gas, " _
& " Nom_Gas "
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(lcComandoSelect, "curReportes")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rCuentas_Gastos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrCuentas_Gastos.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
'-------------------------------------------------------------------------------------------'
' MJP : 15/07/08 : Codigo inicial
'-------------------------------------------------------------------------------------------'
' MVP: 05/08/08: Cambios para multi idioma, mensaje de error y clase padre.
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
Reportes - Contabilidad/rCuentas_Gastos.aspx.vb
|
Visual Basic
|
mit
| 2,505
|
Namespace My
' The following events are available for MyApplication:
'
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
Private Sub StartFromFile(sender As Object, e As ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
ClipboardSaver.ShowClipboardSaver()
For Each s As String In e.CommandLine
If s.ToLower.StartsWith("hide") Then
ClipboardSaver.HideClipboardSaver()
End If
If s.ToLower.StartsWith("changecheckstate") Then
ClipboardSaver.StartStop()
End If
Next
End Sub
End Class
End Namespace
|
Walkman100/Clipboard-Projects
|
ApplicationEvents.vb
|
Visual Basic
|
mit
| 1,208
|
Imports DTIServerControls
''' <summary>
''' A control to handle file uploads.
''' </summary>
''' <remarks></remarks>
#If DEBUG Then
Public Class DTIUploaderControl
Inherits DTIServerBase
#Else
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never), ComponentModel.ToolboxItem(False)> _
Public Class DTIUploaderControl
Inherits DTIServerBase
#End If
Public Event handleFile(ByRef file As HttpPostedFile)
Public Event handleWebFile(ByVal path As String)
Friend WithEvents myUploaderControl As DTIUploaderUserControl
Public Enum FileFilters
All
Images
Videos
ImagesAndVideo
End Enum
#Region "Properties"
'Public Property maxFileSize() As Integer
' Get
' Return myUploaderControl.maxFileSize
' End Get
' Set(ByVal value As Integer)
' myUploaderControl.maxFileSize = value
' End Set
'End Property
Private _fileFilter As FileFilters = FileFilters.All
Public Property FileFilter() As FileFilters
Get
Return _fileFilter
End Get
Set(ByVal value As FileFilters)
_fileFilter = value
End Set
End Property
Private _cssFile As String = ""
Public Property CssFile() As String
Get
Return _cssFile
End Get
Set(ByVal value As String)
_cssFile = value
End Set
End Property
Public Property selectFilesButtonCssClass() As String
Get
Return myUploaderControl.selectFilesButtonCssClass
End Get
Set(ByVal value As String)
myUploaderControl.selectFilesButtonCssClass = value
End Set
End Property
Public Property uploadFilesButtonCssClass() As String
Get
Return myUploaderControl.uploadFilesButtonCssClass
End Get
Set(ByVal value As String)
myUploaderControl.uploadFilesButtonCssClass = value
End Set
End Property
Public Property clearFilesButtonCssClass() As String
Get
Return myUploaderControl.clearFilesButtonCssClass
End Get
Set(ByVal value As String)
myUploaderControl.clearFilesButtonCssClass = value
End Set
End Property
Public Property selectFilesDivCssClass() As String
Get
Return myUploaderControl.selectFilesDivCssClass
End Get
Set(ByVal value As String)
myUploaderControl.selectFilesDivCssClass = value
End Set
End Property
'Public Property uploadFilesDivCssClass() As String
' Get
' Return myUploaderControl.uploadFilesDivCssClass
' End Get
' Set(ByVal value As String)
' myUploaderControl.uploadFilesDivCssClass = value
' End Set
'End Property
Public Property fileSizeWarningCssClass() As String
Get
Return myUploaderControl.fileSizeWarningCssClass
End Get
Set(ByVal value As String)
myUploaderControl.fileSizeWarningCssClass = value
End Set
End Property
'Private _mySkin As Skins = Skins.VirtuConnect
'Public Property Skin() As Skins
' Get
' Return _mySkin
' End Get
' Set(ByVal value As Skins)
' _mySkin = value
' End Set
'End Property
Public Property AllowUploadsOver2Gigs() As Boolean
Get
Return myUploaderControl.allowOver2GigUploads
End Get
Set(ByVal value As Boolean)
myUploaderControl.allowOver2GigUploads = value
End Set
End Property
Private _redirectURL As String = ""
Public Property RedirectURL() As String
Get
Return _redirectURL
End Get
Set(ByVal value As String)
_redirectURL = value
End Set
End Property
#End Region
'Public Class applicationlistener
' Shared listener As New applicationlistener
' Public Shared Sub intialize()
' SyncLock listener
' 'If listener Is Nothing Then
' 'listener = New applicationlistener
' listener.app = HttpContext.Current.ApplicationInstance
' 'End If
' End SyncLock
' End Sub
' Public WithEvents app As HttpApplication
' Private Sub app_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs) Handles app.BeginRequest
' Try
' Dim session_cookie_name As String = "ASP.NET_SESSIONID"
' Dim session_value As String = HttpContext.Current.Request.QueryString("sid")
' If session_value IsNot Nothing Then
' UpdateCookie(session_cookie_name, session_value)
' End If
' Catch ex As Exception
' End Try
' End Sub
' Private Sub UpdateCookie(ByVal cookie_name As String, ByVal cookie_value As String)
' Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies.[Get](cookie_name)
' If cookie Is Nothing Then
' Dim cookie1 As New HttpCookie(cookie_name, cookie_value)
' HttpContext.Current.Response.Cookies.Add(cookie1)
' Else
' cookie.Value = cookie_value
' HttpContext.Current.Request.Cookies.[Set](cookie)
' End If
' End Sub
'End Class
Public Shared Sub correctCookie()
Try
Dim session_cookie_name As String = "ASP.NET_SESSIONID"
Dim session_value As String = HttpContext.Current.Request.QueryString("sid")
If session_value IsNot Nothing Then
UpdateCookie(session_cookie_name, session_value)
End If
Catch ex As Exception
End Try
End Sub
Private Shared Sub UpdateCookie(ByVal cookie_name As String, ByVal cookie_value As String)
Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies.[Get](cookie_name)
If cookie Is Nothing Then
Dim cookie1 As New HttpCookie(cookie_name, cookie_value)
HttpContext.Current.Response.Cookies.Add(cookie1)
Else
cookie.Value = cookie_value
HttpContext.Current.Request.Cookies.[Set](cookie)
End If
End Sub
Private Sub DTIUploaderControl_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
correctCookie()
'this is to fix a bug in Flash where it only sends IE cookies
'applicationlistener.intialize()
Me.Controls.Clear()
myUploaderControl = DirectCast(Page.LoadControl("~/res/DTIUploader/DTIUploaderUserControl.ascx"), DTIUploaderUserControl)
myUploaderControl.ID = "jsFileUploader_" & ClientID
myUploaderControl.RedirectURL = RedirectURL
Me.Controls.Add(myUploaderControl)
End Sub
Private Sub DTIUploaderControl_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If Not CssFile Is Nothing AndAlso CssFile <> "" Then
registerClientScriptBlock("interfacestyle", "<link rel=""stylesheet"" type=""text/css"" href=""" & CssFile & """ />")
'Else
' jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/interfacestyle.css", "text/css")
'registerClientScriptBlock("interfacestyle", "<link rel=""stylesheet"" type=""text/css"" href=""/res/BaseClasses/Scripts.aspx?f=res/DTIUploader/interfacestyle.css"" />")
End If
If myUploaderControl.UploadMode = DTIUploaderUserControl.UploadModes.JS Then
'jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/fonts-min.css", "text/css")
'jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/datatable.css", "text/css")
jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/yahoo-dom-event.js")
jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/element-min.js")
jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/uploader.js")
jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/datasource-min.js")
jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/datatable-min.js")
jQueryLibrary.jQueryInclude.addScriptFile(Page, "/DTIUploader/YahooUploader.js")
'registerClientScriptBlock("yahooFonts", "<link rel=""stylesheet"" type=""text/css"" href=""/res/DTIUploader/fonts-min.css"" />")
'registerClientScriptBlock("yahooSkins", "<link rel=""stylesheet"" type=""text/css"" href=""/res/DTIUploader/datatable.css"" />")
'registerClientScriptFile("yahooEvents", "/res/DTIUploader/yahoo-dom-event.js")
'registerClientScriptFile("yahooElement", "/res/DTIUploader/element-min.js")
'registerClientScriptFile("yahooUploader", "/res/DTIUploader/uploader.js")
'registerClientScriptFile("yahooDatasource", "/res/DTIUploader/datasource-min.js")
'registerClientScriptFile("yahooDatatable", "/res/DTIUploader/datatable-min.js")
'registerClientScriptFile("localUploaderHandler", "/res/DTIUploader/YahooUploader.js")
Dim uploadOverlayId As String = myUploaderControl.jsUploader.uploadOverlayId
Dim dataTableContainerId As String = myUploaderControl.jsUploader.dataTableContainerId
Dim selectFilesButtonId As String = myUploaderControl.jsUploader.selectFilesButtonId
Dim uploadFilesId As String = myUploaderControl.jsUploader.uploadFilesButtonId
Dim clearFilesId As String = myUploaderControl.jsUploader.clearFilesButtonId
Dim errorMessageId As String = myUploaderControl.fileSizeErrorId
Dim queryChanger As New BaseClasses.QueryStringChanger
queryChanger.Add("fp", uploadOverlayId)
queryChanger.Add("sid", Session.SessionID)
Dim uploadPath = queryChanger.FullUrl
Dim initializeScript As String = "initialize('" & uploadOverlayId & "', '" & uploadPath & _
"', '" & dataTableContainerId & "', '" & selectFilesButtonId & "', '" & uploadFilesId & "', '" & _
FileFilter.ToString & "', '" & clearFilesId & "', '" & RedirectURL & "', '" & errorMessageId & "');"
registerClientStartupScriptBlock("initializeUploader_" & ClientID, initializeScript, True)
End If
End Sub
Private Sub myUploaderControl_handleFile(ByRef file As System.Web.HttpPostedFile) Handles myUploaderControl.handleFile
RaiseEvent handleFile(file)
End Sub
Private Sub myUploaderControl_handleWebFile(ByVal path As String) Handles myUploaderControl.handleWebFile
RaiseEvent handleWebFile(path)
End Sub
End Class
|
Micmaz/DTIControls
|
DTIContentManagement/DTIUploader/DTIUploaderControl.vb
|
Visual Basic
|
mit
| 11,655
|
' 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
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp
Public Class RootCodeModelTests
Inherits AbstractRootCodeModelTests
#Region "CodeElements tests"
' This test depends On the version Of mscorlib used by the TestWorkspace And may
' change in the future
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCodeElements1()
Dim code =
<code>
class Goo { }
</code>
TestChildren(code,
"Goo",
"System",
"Microsoft",
"FxResources")
End Sub
#End Region
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDotNetNameFromLanguageSpecific1()
Dim code =
<code>
using N.M;
namespace N
{
namespace M
{
class Generic<T> { }
}
}
</code>
TestRootCodeModelWithCodeFile(code,
Sub(rootCodeModel)
Dim dotNetName = rootCodeModel.DotNetNameFromLanguageSpecific("N.M.Generic<string>")
Assert.Equal("N.M.Generic`1[System.String]", dotNetName)
End Sub)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDotNetNameFromLanguageSpecific2()
TestRootCodeModelWithCodeFile(<code></code>,
Sub(rootCodeModel)
Dim dotNetName = rootCodeModel.DotNetNameFromLanguageSpecific("System.Collections.Generic.Dictionary<int, string>")
Assert.Equal("System.Collections.Generic.Dictionary`2[System.Int32,System.String]", dotNetName)
End Sub)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDotNetNameFromLanguageSpecificWithAssemblyQualifiedName()
TestRootCodeModelWithCodeFile(<code></code>,
Sub(rootCodeModel)
Assert.Throws(Of ArgumentException)(Sub() rootCodeModel.DotNetNameFromLanguageSpecific("System.Collections.Generic.Dictionary<int, string>, mscorlib"))
End Sub)
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestExternalNamespaceChildren()
Dim code =
<code>
class Goo { }
</code>
TestRootCodeModelWithCodeFile(code,
Sub(rootCodeModel)
Dim systemNamespace = rootCodeModel.CodeElements.Find(Of EnvDTE.CodeNamespace)("System")
Assert.NotNull(systemNamespace)
Dim collectionsNamespace = systemNamespace.Members.Find(Of EnvDTE.CodeNamespace)("Collections")
Assert.NotNull(collectionsNamespace)
Dim genericNamespace = collectionsNamespace.Members.Find(Of EnvDTE.CodeNamespace)("Generic")
Assert.NotNull(genericNamespace)
Dim listClass = genericNamespace.Members.Find(Of EnvDTE.CodeClass)("List")
Assert.NotNull(listClass)
End Sub)
End Sub
#Region "CreateCodeTypeRef"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCreateCodeTypeRef_Int32()
TestCreateCodeTypeRef("System.Int32",
New CodeTypeRefData With {
.AsString = "int",
.AsFullName = "System.Int32",
.CodeTypeFullName = "System.Int32",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt
})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCreateCodeTypeRef_System_Text_StringBuilder()
TestCreateCodeTypeRef("System.Text.StringBuilder",
New CodeTypeRefData With {
.AsString = "System.Text.StringBuilder",
.AsFullName = "System.Text.StringBuilder",
.CodeTypeFullName = "System.Text.StringBuilder",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCreateCodeTypeRef_NullableInteger()
TestCreateCodeTypeRef("int?",
New CodeTypeRefData With {
.AsString = "int?",
.AsFullName = "System.Nullable<System.Int32>",
.CodeTypeFullName = "System.Int32?",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCreateCodeTypeRef_ListOfInt()
TestCreateCodeTypeRef("System.Collections.Generic.List<int>",
New CodeTypeRefData With {
.AsString = "System.Collections.Generic.List<int>",
.AsFullName = "System.Collections.Generic.List<System.Int32>",
.CodeTypeFullName = "System.Collections.Generic.List<System.Int32>",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
})
End Sub
#End Region
#Region "CodeTypeFromFullName"
<WorkItem(1107453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107453")>
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCodeTypeFromFullName_NonGenerated()
Dim workspace = <Workspace>
<Project Language=<%= LanguageName %> CommonReferences="true">
<Document FilePath="C.cs"><![CDATA[
namespace N
{
class C
{
}
}
]]></Document>
</Project>
</Workspace>
TestCodeTypeFromFullName(workspace, "N.C",
Sub(codeType)
Assert.NotNull(codeType)
Assert.Equal("N.C", codeType.FullName)
Dim codeNamespace = TryCast(codeType.Parent, EnvDTE.CodeNamespace)
Assert.NotNull(codeNamespace)
Dim fileCodeModel = TryCast(codeNamespace.Parent, EnvDTE.FileCodeModel)
Assert.NotNull(fileCodeModel)
Dim underlyingFileCodeModel = ComAggregate.GetManagedObject(Of FileCodeModel)(fileCodeModel)
Assert.NotNull(underlyingFileCodeModel)
Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId())
Assert.Equal("C.cs", filePath)
End Sub)
End Sub
<WorkItem(1107453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107453")>
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCodeTypeFromFullName_Generated()
Dim workspace = <Workspace>
<Project Language=<%= LanguageName %> CommonReferences="true">
<Document FilePath="C.g.cs"><![CDATA[
namespace N
{
class C
{
}
}
]]></Document>
</Project>
</Workspace>
TestCodeTypeFromFullName(workspace, "N.C",
Sub(codeType)
Assert.NotNull(codeType)
Assert.Equal("N.C", codeType.FullName)
Dim codeNamespace = TryCast(codeType.Parent, EnvDTE.CodeNamespace)
Assert.NotNull(codeNamespace)
Dim fileCodeModel = TryCast(codeNamespace.Parent, EnvDTE.FileCodeModel)
Assert.NotNull(fileCodeModel)
Dim underlyingFileCodeModel = ComAggregate.GetManagedObject(Of FileCodeModel)(fileCodeModel)
Assert.NotNull(underlyingFileCodeModel)
Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId())
Assert.Equal("C.g.cs", filePath)
End Sub)
End Sub
<WorkItem(1107453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107453")>
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCodeTypeFromFullName_NonGenerated_Generated()
Dim workspace = <Workspace>
<Project Language=<%= LanguageName %> CommonReferences="true">
<Document FilePath="C.cs"><![CDATA[
namespace N
{
partial class C
{
}
}
]]></Document>
<Document FilePath="C.g.cs"><![CDATA[
namespace N
{
partial class C
{
}
}
]]></Document>
</Project>
</Workspace>
TestCodeTypeFromFullName(workspace, "N.C",
Sub(codeType)
Assert.NotNull(codeType)
Assert.Equal("N.C", codeType.FullName)
Dim codeNamespace = TryCast(codeType.Parent, EnvDTE.CodeNamespace)
Assert.NotNull(codeNamespace)
Dim fileCodeModel = TryCast(codeNamespace.Parent, EnvDTE.FileCodeModel)
Assert.NotNull(fileCodeModel)
Dim underlyingFileCodeModel = ComAggregate.GetManagedObject(Of FileCodeModel)(fileCodeModel)
Assert.NotNull(underlyingFileCodeModel)
Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId())
Assert.Equal("C.cs", filePath)
End Sub)
End Sub
<WorkItem(1107453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107453")>
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCodeTypeFromFullName_Generated_NonGenerated()
Dim workspace = <Workspace>
<Project Language=<%= LanguageName %> CommonReferences="true">
<Document FilePath="C.g.cs"><![CDATA[
namespace N
{
partial class C
{
}
}
]]></Document>
<Document FilePath="C.cs"><![CDATA[
namespace N
{
partial class C
{
}
}
]]></Document>
</Project>
</Workspace>
TestCodeTypeFromFullName(workspace, "N.C",
Sub(codeType)
Assert.NotNull(codeType)
Assert.Equal("N.C", codeType.FullName)
Dim codeNamespace = TryCast(codeType.Parent, EnvDTE.CodeNamespace)
Assert.NotNull(codeNamespace)
Dim fileCodeModel = TryCast(codeNamespace.Parent, EnvDTE.FileCodeModel)
Assert.NotNull(fileCodeModel)
Dim underlyingFileCodeModel = ComAggregate.GetManagedObject(Of FileCodeModel)(fileCodeModel)
Assert.NotNull(underlyingFileCodeModel)
Dim filePath = underlyingFileCodeModel.Workspace.GetFilePath(underlyingFileCodeModel.GetDocumentId())
Assert.Equal("C.cs", filePath)
End Sub)
End Sub
#End Region
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.CSharp
End Get
End Property
End Class
End Namespace
|
diryboy/roslyn
|
src/VisualStudio/Core/Test/CodeModel/CSharp/RootCodeModelTests.vb
|
Visual Basic
|
mit
| 12,737
|
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim refPlanes As SolidEdgePart.RefPlanes = Nothing
Dim profileSets As SolidEdgePart.ProfileSets = Nothing
Dim profileSet As SolidEdgePart.ProfileSet = Nothing
Dim profiles As SolidEdgePart.Profiles = Nothing
Dim profile As SolidEdgePart.Profile = Nothing
Dim arcs2d As SolidEdgeFrameworkSupport.Arcs2d = Nothing
Dim arc2d As SolidEdgeFrameworkSupport.Arc2d = Nothing
Dim linearStyles As SolidEdgeFramework.LinearStyles = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
documents = application.Documents
partDocument = CType(documents.Add("SolidEdge.PartDocument"), SolidEdgePart.PartDocument)
refPlanes = partDocument.RefPlanes
linearStyles = CType(partDocument.LinearStyles, SolidEdgeFramework.LinearStyles)
profileSets = partDocument.ProfileSets
profileSet = profileSets.Add()
profiles = profileSet.Profiles
profile = profiles.Add(refPlanes.Item(1))
arcs2d = profile.Arcs2d
arc2d = arcs2d.AddByCenterStartEnd(0, 0, 0.15, 0, 0, 0.15)
arc2d.AddSegmentedStyle(0.15, 0, 0.14309, 0.045, linearStyles.Item(4))
arc2d.AddSegmentedStyle(0.14309, 0.045, 0.10905, 0.103, linearStyles.Item(3))
arc2d.RemoveSegmentedStyle(1)
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFrameworkSupport.Arc2d.RemoveSegmentedStyle.vb
|
Visual Basic
|
mit
| 2,365
|
Imports Microsoft.Phone.Reactive
Imports Microsoft.Devices.Sensors
Public Module ShakeObserver
Const MinimumOffset = 1.44
Const TimeThreshold = 200
Public Function GetShakeObserver(ByVal accel As Accelerometer) As IObservable(Of Unit)
Dim query = From start In Observable.FromEvent(Of AccelerometerReadingEventArgs)(accel, "ReadingChanged")
Where (start.EventArgs.X ^ 2 + start.EventArgs.Y ^ 2) > MinimumOffset
Select start
Dim shake = From interval In query.TimeInterval
Where interval.Interval.TotalMilliseconds < MinimumOffset
Select New Unit
Return shake
End Function
'Public Function GetShakeObserver(ByVal accel As Accelerometer) As IObservable(Of Unit)
' Dim query =
' From interval In
' (From startEvent In Observable.FromEvent(Of AccelerometerReadingEventArgs)(accel, "ReadingChanged")
' Where (startEvent.EventArgs.X * startEvent.EventArgs.X +
' startEvent.EventArgs.Y * startEvent.EventArgs.Y) > MinimumOffset
' Select startEvent).TimeInterval
' Where interval.Interval.TotalMilliseconds < TimeThreshold
' Select New Unit
' Return query
'End Function
End Module
|
jwooley/RxSamples
|
Dice/RxWp7Dice/Gestures/ShakeObserver.vb
|
Visual Basic
|
mit
| 1,313
|
Imports SignWriterStudio.General.All
Imports SignWriterStudio.SymbolCache
<Serializable()> Public Class SWSymbol
Implements ICloneable
' In this section you can add your own using directives
' section 127-0-0-1-12759f70:11b4c9e83f8:-8000:0000000000000844 begin
' section 127-0-0-1-12759f70:11b4c9e83f8:-8000:0000000000000844 end
' *
' * A class that represents ...
' * All rights Reserved Copyright(c) 2008
' * @see OtherClasses
' * @author Jonathan Duncan
' */
' Attributes
Public Sub SetIds(ByVal code As Integer, ByVal id As String)
_Code = code
_ID = id
End Sub
Private _LoadImage As Boolean
'Public Property LoadImage() As Boolean
' Get
' Return _LoadImage
' End Get
' Set(ByVal value As Boolean)
' _LoadImage = value
' End Set
'End Property
Private _code As Integer
Public Property Code() As Integer
Get
Return _Code
End Get
Set(ByVal value As Integer)
_Code = value
_LoadImage = True
Me._ID = String.Empty
Me.Update()
End Set
End Property
Public Property CodeNotLoadImage As Integer
Get
Return _Code
End Get
Set(ByVal value As Integer)
_Code = value
_LoadImage = False
Me._ID = String.Empty
Me.Update()
End Set
End Property
Private _ID As String
Public Property Id() As String
Get
Return _ID
End Get
Set(ByVal value As String)
_ID = value
_LoadImage = True
Me._Code = 0
Me.Update()
End Set
End Property
Public Property IdNotLoadImage As String
Get
Return _ID
End Get
Set(ByVal value As String)
_ID = value
_LoadImage = False
Me._Code = 0
Me.Update()
End Set
End Property
Private _isValid As Boolean '= False
Public ReadOnly Property IsValid() As Boolean
Get
Return _isValid
End Get
End Property
Private _baseGroup As Integer
Public Property BaseGroup() As Integer
Get
Return _baseGroup
End Get
Set(ByVal value As Integer)
_baseGroup = value
'Me.ResetPreviousId()
End Set
End Property
Private _group As Integer
Public Property Group() As Integer
Get
Return _group
End Get
Set(ByVal value As Integer)
_group = value
Me.ResetPreviousId()
End Set
End Property
Private _category As Integer
Public Property Category() As Integer
Get
Return _category
End Get
Set(ByVal value As Integer)
_category = value
Me.ResetPreviousId()
End Set
End Property
Private _symbol As Integer
Public Property Symbol() As Integer
Get
Return _symbol
End Get
Set(ByVal value As Integer)
_symbol = value
Me.ResetPreviousId()
End Set
End Property
Private _variation As Integer
Public Property Variation() As Integer
Get
Return _variation
End Get
Set(ByVal value As Integer)
_variation = value
Me.ResetPreviousId()
End Set
End Property
Private _fill As Integer
Public Property Fill() As Integer
Get
Return _fill
End Get
Set(ByVal value As Integer)
_fill = value
Me.ResetPreviousId()
End Set
End Property
Private _rotation As Integer
Public Property Rotation() As Integer
Get
Return _rotation
End Get
Set(ByVal value As Integer)
_rotation = value
Me.ResetPreviousId()
End Set
End Property
Private _width As Integer
Public Property Width() As Integer
Get
Return _width
End Get
Set(ByVal value As Integer)
_width = value
End Set
End Property
Private _height As Integer
Public Property Height() As Integer
Get
Return _height
End Get
Set(ByVal value As Integer)
_height = value
End Set
End Property
Private _baseName As String
Public Property BaseName() As String
Get
Return _BaseName
End Get
Set(ByVal value As String)
_BaseName = value
End Set
End Property
Private _standardColor As Color
Public Property StandardColor() As Color
Get
Return _standardColor
End Get
Set(ByVal value As Color)
_standardColor = value
End Set
End Property
Private _symImage As Image
Public Property SymImage() As Image
Get
Return _SymImage
End Get
Set(ByVal value As Image)
_SymImage = value
End Set
End Property
Private _illusImage As Image
Public Property Illustration() As Image
Get
Return _IllusImage
End Get
Set(ByVal value As Image)
_IllusImage = value
End Set
End Property
Private _sortWeight As String
Public Property SortWeight() As String
Get
Return _sortWeight
End Get
Set(ByVal value As String)
_sortWeight = value
End Set
End Property
Public Shared Function CodefromId(ByVal id As String) As Integer
Dim symbol As New SWSymbol With {.IdNotLoadImage = id}
Return symbol.Code
End Function
Public Shared Function Fills(ByVal code As Integer) As Integer
Return SC.GetFills(code)
End Function
Public Shared Function Rotations(ByVal code As Integer) As Integer
Return SC.GetRotations(code)
End Function
Public Function Fills() As Integer
Return Fills(Me.Code)
End Function
Public Function Rotations() As Integer
Return Rotations(Me.Code)
End Function
Public Sub FromDataRow(ByVal tempDataRow() As SymbolCache.ISWA2010DataSet.cacheRow)
' section 127-0-0-1-fe1248e:11b50ee3448:-8000:0000000000000985 begin
If tempDataRow IsNot Nothing AndAlso tempDataRow.Length > 0 Then
Dim cacheRow As SymbolCache.ISWA2010DataSet.cacheRow = tempDataRow(0)
If CInt(cacheRow.sym_code) > 0 Then
Me.Category = cacheRow.sg_cat_num
Me.Group = cacheRow.sg_grp_num
Me.Symbol = cacheRow.bs_bas_num
Me.Variation = cacheRow.bs_var_num
Me.Fill = cacheRow.sym_fill
Me.Rotation = cacheRow.sym_rot
Me.Height = cacheRow.sym_h
Me.Width = cacheRow.sym_w
Me.StandardColor = Color.FromArgb(Convert.ToInt32("FF" & cacheRow.sg_color, 16))
If _LoadImage Then
Dim image = SymbolImageCache(cacheRow.sym_code)
If image IsNot Nothing Then
Me.SymImage = image
Else
Me.SymImage = ByteArraytoImage(cacheRow.sym_png)
SymbolImageCache(cacheRow.sym_code) = Me.SymImage
End If
Me.Illustration = ByteArraytoImage(cacheRow.sym_illus)
End If
Me.BaseName = cacheRow.bs_name
Me.BaseGroup = cacheRow.sym_bs_code
Me.SortWeight = cacheRow.sort_weight
Me.SetIds(cacheRow.sym_code, cacheRow.sym_id)
Me._isValid = True
End If
Else
Me._isValid = False
End If
' section 127-0-0-1-fe1248e:11b50ee3448:-8000:0000000000000985 end
End Sub
Private Sub Update()
' section 127-0-0-1-fe1248e:11b50ee3448:-8000:0000000000000989 begin
If Me.Code > 0 Then
Me.FromDataRow(SymbolCache.Iswa2010.SC.GetCode(Me.Code))
ElseIf CheckId(Me.Id) Then
Me.FromDataRow(SymbolCache.Iswa2010.SC.GetId(Me.Id))
End If
' section 127-0-0-1-fe1248e:11b50ee3448:-8000:0000000000000989 end
End Sub
Public Sub MakeId()
Dim SSS As New System.Text.StringBuilder
If Not (Me.Category = 0 And Me.Group = 0 And Me.Symbol = 0 And Me.Variation = 0 And Me.Fill = 0 And Me.Rotation = 0) Then
SSS.Append(Format(Me.Category, "00"))
SSS.Append("-")
SSS.Append(Format(Me.Group, "00"))
SSS.Append("-")
SSS.Append(Format(Me.Symbol, "000"))
SSS.Append("-")
SSS.Append(Format(Me.Variation, "00"))
SSS.Append("-")
SSS.Append(Format(Me.Fill, "00"))
SSS.Append("-")
SSS.Append(Format(Me.Rotation, "00"))
Me._Code = 0
Me._ID = SSS.ToString
Update()
End If
End Sub
Public Function CharacterCodeToString() As String
' section 127-0-0-1--489ad8bc:11b55ce357a:-8000:0000000000000957 begin
Return Me.Code.ToString(Globalization.CultureInfo.InvariantCulture)
' section 127-0-0-1--489ad8bc:11b55ce357a:-8000:0000000000000957 end
End Function
Public Function CharacterCodetoStringHex() As String
' section 127-0-0-1--489ad8bc:11b55ce357a:-8000:0000000000000959 begin
'TODO Check that this is working to Hex
Return Me.Code.ToString("X")
' section 127-0-0-1--489ad8bc:11b55ce357a:-8000:0000000000000959 end
End Function
Public Function GetID(basegroup As Integer, fill As Integer, rotation As Integer) As String
Dim result As ISWA2010DataSet.cacheRow = SC.GetSymbol(basegroup, fill, rotation).FirstOrDefault()
If result IsNot Nothing Then
Return result.sym_id
End If
Return String.Empty
End Function
Public Shared Function GetCode(basegroup As Integer, fill As Integer, rotation As Integer) As Integer
Dim result As ISWA2010DataSet.cacheRow = SC.GetSymbol(basegroup, fill, rotation).FirstOrDefault()
If result IsNot Nothing Then
Return result.sym_code
End If
Return 0
End Function
Public Sub ResetPreviousId()
Me._ID = String.Empty
Me._Code = 0
Me._isValid = False
End Sub
Public Shadows Function Clone() As Object Implements System.ICloneable.Clone
' section 127-0-0-1--6e0e347d:11b574a5270:-8000:0000000000000A0A begin
' Performs a shallow copy of Me and assign it to Newclone.
Dim Newclone As SWSymbol = CType(Me.MemberwiseClone(), SWSymbol)
'Newclone.Sss = CType(Me.Clone, SssDetails)
'Newclone.mySWSymbol = Newclone
Return Newclone
' section 127-0-0-1--6e0e347d:11b574a5270:-8000:0000000000000A0A end
End Function
End Class
|
JonathanDDuncan/SignWriterStudio
|
SWS/SWS.vb
|
Visual Basic
|
mit
| 11,113
|
' 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.Reflection.Metadata
Imports System.Reflection.PortableExecutable
Imports System.Text
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Debugging
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.PDB
Public Class VisualBasicDeterministicBuildCompilationTests
Inherits BasicTestBase
Implements IEnumerable(Of Object())
Private Sub VerifyCompilationOptions(originalOptions As VisualBasicCompilationOptions, compilationOptionsBlobReader As BlobReader, emitOptions As EmitOptions, compilation As VisualBasicCompilation)
Dim pdbOptions = DeterministicBuildCompilationTestHelpers.ParseCompilationOptions(compilationOptionsBlobReader)
DeterministicBuildCompilationTestHelpers.AssertCommonOptions(emitOptions, originalOptions, compilation, pdbOptions)
' See VisualBasicCompilation.SerializeForPdb for options that are added
Assert.Equal(originalOptions.CheckOverflow.ToString(), pdbOptions("checked"))
Assert.Equal(originalOptions.OptionStrict.ToString(), pdbOptions("strict"))
Assert.Equal(originalOptions.ParseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(), pdbOptions("language-version"))
Dim preprocessorStrings = originalOptions.ParseOptions.PreprocessorSymbols.Select(Function(p)
If (p.Value Is Nothing) Then
Return p.Key
End If
Return p.Key + "=" + p.Value.ToString()
End Function)
Assert.Equal(String.Join(",", preprocessorStrings), pdbOptions("define"))
End Sub
Private Sub TestDeterministicCompilationVB(syntaxTrees As SyntaxTree(), compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions, ParamArray metadataReferences() As TestMetadataReferenceInfo)
Dim originalCompilation = CreateCompilation(
syntaxTrees,
references:=metadataReferences.SelectAsArray(Of MetadataReference)(Function(r) r.MetadataReference),
options:=compilationOptions,
targetFramework:=TargetFramework.NetStandard20)
Dim peBlob = originalCompilation.EmitToArray(emitOptions)
Using peReader As PEReader = New PEReader(peBlob)
Dim entries = peReader.ReadDebugDirectory()
AssertEx.Equal({DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb}, entries.Select(Of DebugDirectoryEntryType)(Function(e) e.Type))
Dim codeView = entries(0)
Dim checksum = entries(1)
Dim reproducible = entries(2)
Dim embedded = entries(3)
Using embeddedPdb As MetadataReaderProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded)
Dim pdbReader = embeddedPdb.GetMetadataReader()
Dim metadataReferenceReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationMetadataReferences, pdbReader)
Dim compilationOptionsReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationOptions, pdbReader)
VerifyCompilationOptions(compilationOptions, compilationOptionsReader, emitOptions, originalCompilation)
DeterministicBuildCompilationTestHelpers.VerifyReferenceInfo(metadataReferences, metadataReferenceReader)
End Using
End Using
End Sub
<Theory>
<ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))>
Public Sub PortablePdb_DeterministicCompilation(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions)
Dim sourceOne = Parse("
Class C1
End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8)
Dim sourceTwo = Parse("
Class C2
End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False))
Dim referenceSourceOne =
<compilation>
<file name="b.vb">
Public Class SomeClass
End Class
Public Class SomeOtherClass
End Class
</file>
</compilation>
Dim referenceSourceTwo =
<compilation>
<file name="b.vb">
Public Class SomeClass
End Class
Public Class SomeOtherClass
End Class
</file>
</compilation>
Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll)
Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll)
Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default)
Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default)
TestDeterministicCompilationVB({sourceOne, sourceTwo}, compilationOptions, emitOptions, referenceOne, referenceTwo)
End Using
End Using
End Sub
<ConditionalTheory(GetType(DesktopOnly))>
<ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))>
Public Sub PortablePdb_DeterministicCompilationWithSJIS(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions)
Dim sourceOne = Parse("
Class C1
End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8)
Dim sourceTwo = Parse("
Class C2
End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False))
Dim sourceThree = Parse("
Class C3
End Class", fileName:="three.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.GetEncoding(932)) ' SJIS encoding
Dim referenceSourceOne =
<compilation>
<file name="b.vb">
Public Class SomeClass
End Class
Public Class SomeOtherClass
End Class
</file>
</compilation>
Dim referenceSourceTwo =
<compilation>
<file name="b.vb">
Public Class SomeClass
End Class
Public Class SomeOtherClass
End Class
</file>
</compilation>
Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll)
Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll)
Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default)
Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default)
TestDeterministicCompilationVB({sourceOne, sourceTwo, sourceThree}, compilationOptions, emitOptions, referenceOne, referenceTwo)
End Using
End Using
End Sub
Public Iterator Function GetEnumerator() As IEnumerator(Of Object()) Implements IEnumerable(Of Object()).GetEnumerator
For Each compilationOptions As VisualBasicCompilationOptions In GetCompilationOptions()
For Each emitOptions As EmitOptions In GetEmitOptions()
Yield {compilationOptions, emitOptions}
Next
Next
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return GetEnumerator()
End Function
Private Iterator Function GetEmitOptions() As IEnumerable(Of EmitOptions)
Dim emitOptions = New EmitOptions(debugInformationFormat:=DebugInformationFormat.Embedded)
Yield emitOptions
Yield emitOptions.WithDefaultSourceFileEncoding(Encoding.UTF8)
End Function
Private Iterator Function GetCompilationOptions() As IEnumerable(Of VisualBasicCompilationOptions)
For Each parseOption As VisualBasicParseOptions In GetParseOptions()
' Provide non default options for to test that they are being serialized
' to the pdb correctly. It needs to produce a compilation to be emitted, but otherwise
' everything should be non-default if possible. Diagnostic settings are ignored
' because they won't be serialized.
' Use constructor that requires all arguments. If New arguments are added, it's possible they need to be
' included in the pdb serialization And added to tests here
Dim defaultOptions = New VisualBasicCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
moduleName:=Nothing,
mainTypeName:=Nothing,
scriptClassName:=WellKnownMemberNames.DefaultScriptClassName,
globalImports:={GlobalImport.Parse("System")},
rootNamespace:=Nothing,
optionStrict:=OptionStrict.Off,
optionInfer:=True,
optionExplicit:=True,
optionCompareText:=False,
parseOptions:=parseOption,
embedVbCoreRuntime:=False,
optimizationLevel:=OptimizationLevel.Debug,
checkOverflow:=True,
cryptoKeyContainer:=Nothing,
cryptoKeyFile:=Nothing,
cryptoPublicKey:=Nothing,
delaySign:=Nothing,
platform:=Platform.AnyCpu,
generalDiagnosticOption:=ReportDiagnostic.Default,
specificDiagnosticOptions:=Nothing,
concurrentBuild:=True,
deterministic:=True,
xmlReferenceResolver:=Nothing,
sourceReferenceResolver:=Nothing,
metadataReferenceResolver:=Nothing,
assemblyIdentityComparer:=Nothing,
strongNameProvider:=Nothing,
publicSign:=False,
reportSuppressedDiagnostics:=False,
metadataImportOptions:=MetadataImportOptions.Public)
Yield defaultOptions
Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release)
Yield defaultOptions.WithDebugPlusMode(True)
Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release).WithDebugPlusMode(True)
Next
End Function
Private Iterator Function GetParseOptions() As IEnumerable(Of VisualBasicParseOptions)
Dim parseOptions As New VisualBasicParseOptions()
Yield parseOptions
Yield parseOptions.WithLanguageVersion(LanguageVersion.VisualBasic15_3)
' https://github.com/dotnet/roslyn/issues/44802 tracks
' enabling preprocessor symbol validation for VB
' Yield parseOptions.WithPreprocessorSymbols({New KeyValuePair(Of String, Object)("TestPre", True), New KeyValuePair(Of String, Object)("TestPreTwo", True)})
End Function
End Class
|
davkean/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/VisualBasicDeterministicBuildCompilationTests.vb
|
Visual Basic
|
apache-2.0
| 12,094
|
Option Strict Off
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.GenerateFromMembers.GenerateEqualsAndGetHashCode
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.GenerateFromMembers
Public Class GenerateEqualsAndGetHashCodeTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace) As Object
Return New GenerateEqualsAndGetHashCodeCodeRefactoringProvider()
End Function
<WorkItem(541991)>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestEqualsOnSingleField() As Task
Await TestAsync(
NewLines("Class Z \n [|Private a As Integer|] \n End Class"),
NewLines("Imports System.Collections.Generic \n Class Z \n Private a As Integer \n Public Overrides Function Equals(obj As Object) As Boolean \n Dim z = TryCast(obj, Z) \n Return z IsNot Nothing AndAlso EqualityComparer(Of Integer).Default.Equals(a, z.a) \n End Function \n End Class"),
index:=0)
End Function
<WorkItem(541991)>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestGetHashCodeOnSingleField() As Task
Await TestAsync(
NewLines("Class Z \n [|Private a As Integer|] \n End Class"),
NewLines("Imports System.Collections.Generic \n Class Z \n Private a As Integer \n Public Overrides Function GetHashCode() As Integer \n Return EqualityComparer(Of Integer).Default.GetHashCode(a) \n End Function \n End Class"),
index:=1)
End Function
<WorkItem(541991)>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestBothOnSingleField() As Task
Await TestAsync(
NewLines("Class Z \n [|Private a As Integer|] \n End Class"),
NewLines("Imports System.Collections.Generic \n Class Z \n Private a As Integer \n Public Overrides Function Equals(obj As Object) As Boolean \n Dim z = TryCast(obj, Z) \n Return z IsNot Nothing AndAlso EqualityComparer(Of Integer).Default.Equals(a, z.a) \n End Function \n Public Overrides Function GetHashCode() As Integer \n Return EqualityComparer(Of Integer).Default.GetHashCode(a) \n End Function \n End Class"),
index:=2)
End Function
<WorkItem(545205)>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)>
Public Async Function TestTypeWithNumberInName() As Task
Await TestAsync(
NewLines("Partial Class c1(Of V As {New}, U) \n [|Dim x As New V|] \n End Class"),
NewLines("Imports System.Collections.Generic \n Partial Class c1(Of V As {New}, U) \n Dim x As New V \n Public Overrides Function Equals(obj As Object) As Boolean \n Dim c = TryCast(obj, c1(Of V, U)) \n Return c IsNot Nothing AndAlso EqualityComparer(Of V).Default.Equals(x, c.x) \n End Function \n End Class"))
End Function
End Class
End Namespace
|
mseamari/Stuff
|
src/EditorFeatures/VisualBasicTest/CodeActions/GenerateFromMembers/GenerateEqualsAndGetHashCode/GenerateEqualsAndGetHashCodeTests.vb
|
Visual Basic
|
apache-2.0
| 3,430
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18033
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("WindowsApplication1.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
farizluqman/simple-sha1-tool
|
My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,728
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Friend Module CompletionUtilities
Private ReadOnly s_commitChars As Char() = {" "c, ";"c, "("c, ")"c, "["c, "]"c, "{"c, "}"c, "."c, ","c, ":"c, "+"c, "-"c, "*"c, "/"c, "\"c, "^"c, "<"c, ">"c, "'"c, "="c, "?"c}
Private ReadOnly s_defaultTriggerChars As Char() = {"."c, "["c, "#"c, " "c, "="c, "<"c, "{"c}
Public Function GetTextChangeSpan(text As SourceText, position As Integer) As TextSpan
Return CommonCompletionUtilities.GetTextChangeSpan(
text, position,
AddressOf IsTextChangeSpanStartCharacter,
AddressOf IsTextChangeSpanEndCharacter)
End Function
Private Function IsWordStartCharacter(ch As Char) As Boolean
Return SyntaxFacts.IsIdentifierStartCharacter(ch)
End Function
Private Function IsWordCharacter(ch As Char) As Boolean
Return SyntaxFacts.IsIdentifierStartCharacter(ch) OrElse SyntaxFacts.IsIdentifierPartCharacter(ch)
End Function
Private Function IsTextChangeSpanStartCharacter(ch As Char) As Boolean
Return ch = "#"c OrElse ch = "["c OrElse IsWordCharacter(ch)
End Function
Private Function IsTextChangeSpanEndCharacter(ch As Char) As Boolean
Return ch = "]"c OrElse IsWordCharacter(ch)
End Function
Public Function IsCommitCharacter(completionItem As CompletionItem, ch As Char, textTypedSoFar As String) As Boolean
Return s_commitChars.Contains(ch)
End Function
Public Function IsDefaultTriggerCharacter(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Dim ch = text(characterPosition)
If s_defaultTriggerChars.Contains(ch) Then
Return True
End If
Return IsStartingNewWord(text, characterPosition, options)
End Function
Public Function IsDefaultTriggerCharacterOrParen(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Dim ch = text(characterPosition)
Return _
ch = "("c OrElse
s_defaultTriggerChars.Contains(ch) OrElse
IsStartingNewWord(text, characterPosition, options)
End Function
Public Function IsTriggerAfterSpaceOrStartOfWordCharacter(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
' Bring up on space or at the start of a word.
Dim ch = text(characterPosition)
Return ch = " "c OrElse IsStartingNewWord(text, characterPosition, options)
End Function
Public Function SendEnterThroughToEditor(completionItem As CompletionItem, textTypedSoFar As String) As Boolean
' In VB we always send enter through to the editor.
Return True
End Function
Private Function IsStartingNewWord(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
If Not options.GetOption(CompletionOptions.TriggerOnTypingLetters, LanguageNames.VisualBasic) Then
Return False
End If
Return CommonCompletionUtilities.IsStartingNewWord(
text, characterPosition, AddressOf IsWordStartCharacter, AddressOf IsWordCharacter)
End Function
Public Function GetDisplayAndInsertionText(
symbol As ISymbol,
isAttributeNameContext As Boolean, isAfterDot As Boolean, isWithinAsyncMethod As Boolean,
syntaxFacts As ISyntaxFactsService
) As ValueTuple(Of String, String)
Dim name As String = Nothing
If Not CommonCompletionUtilities.TryRemoveAttributeSuffix(symbol, isAttributeNameContext, syntaxFacts, name) Then
name = symbol.Name
End If
Dim insertionText = GetInsertionText(name, symbol, isAfterDot, isWithinAsyncMethod)
Dim displayText = GetDisplayText(name, symbol)
If symbol.GetArity() > 0 Then
Const UnicodeEllipsis = ChrW(&H2026)
displayText += " " & UnicodeEllipsis & ")"
End If
Return ValueTuple.Create(displayText, insertionText)
End Function
Public Function GetDisplayText(name As String, symbol As ISymbol) As String
If symbol.IsConstructor() Then
name = "New"
ElseIf symbol.GetArity() > 0 Then
name += "(Of"
End If
Return name
End Function
Public Function GetInsertionText(
name As String, symbol As ISymbol,
isAfterDot As Boolean, isWithinAsyncMethod As Boolean,
Optional typedChar As Char? = Nothing
) As String
name = name.EscapeIdentifier(afterDot:=isAfterDot, symbol:=symbol, withinAsyncMethod:=isWithinAsyncMethod)
If symbol.IsConstructor() Then
name = "New"
ElseIf symbol.GetArity() > 0 Then
name += GetOfText(symbol, typedChar.GetValueOrDefault())
End If
If typedChar.HasValue AndAlso typedChar = "]"c AndAlso name(0) <> "["c Then
name = String.Format("[{0}", name)
End If
Return name
End Function
Private Function GetOfText(symbol As ISymbol, typedChar As Char) As String
If symbol.Kind = SymbolKind.NamedType Then
If typedChar = "("c Then
Return "("
Else
Return "(Of"
End If
End If
If typedChar = " "c Then
Return "(Of"
End If
Return ""
End Function
Public Function GetInsertionTextAtInsertionTime(symbol As ISymbol, context As AbstractSyntaxContext, ch As Char) As String
Dim name As String = Nothing
If Not CommonCompletionUtilities.TryRemoveAttributeSuffix(symbol, context.IsAttributeNameContext, context.GetLanguageService(Of ISyntaxFactsService), name) Then
name = symbol.Name
End If
Return GetInsertionText(name, symbol, context.IsRightOfNameSeparator, DirectCast(context, VisualBasicSyntaxContext).WithinAsyncMethod, ch)
End Function
Public Function GetTextChange(symbolItem As SymbolCompletionItem, Optional ch As Char? = Nothing, Optional textTypedSoFar As String = Nothing) As TextChange
Dim insertionText As String = If(ch Is Nothing,
symbolItem.InsertionText,
GetInsertionTextAtInsertionTime(
symbolItem.Symbols.First(),
symbolItem.Context,
ch.Value))
Return New TextChange(symbolItem.FilterSpan, insertionText)
End Function
End Module
End Namespace
|
KashishArora/Roslyn
|
src/Features/VisualBasic/Completion/CompletionProviders/CompletionUtilities.vb
|
Visual Basic
|
apache-2.0
| 7,661
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Completion.FileSystem
Imports Microsoft.VisualStudio.InteractiveWindow
Imports Microsoft.VisualStudio.Text.Editor
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Completion.CompletionProviders
<ExportCompletionProvider("ReferenceDirectiveCompletionProvider", LanguageNames.VisualBasic)>
<TextViewRole(PredefinedInteractiveTextViewRoles.InteractiveTextViewRole)>
Friend Class ReferenceDirectiveCompletionProvider : Inherits AbstractReferenceDirectiveCompletionProvider
Protected Overrides Function TryGetStringLiteralToken(tree As SyntaxTree, position As Integer, ByRef stringLiteral As SyntaxToken, cancellationToken As CancellationToken) As Boolean
If tree.IsEntirelyWithinStringLiteral(position, cancellationToken) Then
Dim token = tree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True)
' Verifies that the string literal under caret is the path token.
If token.IsKind(SyntaxKind.StringLiteralToken) AndAlso token.Parent.IsKind(SyntaxKind.ReferenceDirectiveTrivia) Then
stringLiteral = token
Return True
End If
End If
stringLiteral = Nothing
Return False
End Function
End Class
End Namespace
|
HellBrick/roslyn
|
src/Interactive/EditorFeatures/VisualBasic/Interactive/FileSystem/ReferenceDirectiveCompletionProvider.vb
|
Visual Basic
|
apache-2.0
| 1,610
|
' 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.ObjectModel
Imports Microsoft.CodeAnalysis.Editor.Commands
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags
Imports Microsoft.CodeAnalysis.Editor.Shared.Tagging
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Text.Tagging
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
Public Class RenameTagProducerTests
Private Sub VerifyEmptyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService)
VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, SpecializedCollections.EmptyEnumerable(Of Span))
End Sub
Private Sub VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService)
Dim expectedSpans = actualWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan())
VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans)
End Sub
Private Sub VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace)
Dim expectedSpans = expectedTaggedWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan())
VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans)
End Sub
Private Sub VerifyAnnotatedTaggedSpans(tagType As TextMarkerTag, annotationString As String, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace)
Dim annotatedDocument = expectedTaggedWorkspace.Documents.SingleOrDefault(Function(d) d.AnnotatedSpans.Any())
Dim expectedSpans As IEnumerable(Of Span)
If annotatedDocument Is Nothing Then
expectedSpans = SpecializedCollections.EmptyEnumerable(Of Span)
Else
expectedSpans = GetAnnotatedSpans(annotationString, annotatedDocument)
End If
VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans)
End Sub
Private Shared Function GetAnnotatedSpans(annotationString As String, annotatedDocument As TestHostDocument) As IEnumerable(Of Span)
Return annotatedDocument.AnnotatedSpans.SelectMany(Function(kvp)
If kvp.Key = annotationString Then
Return kvp.Value.Select(Function(ts) ts.ToSpan())
End If
Return SpecializedCollections.EmptyEnumerable(Of Span)
End Function)
End Function
Private Sub VerifySpansBeforeConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService)
' Verify no fixup/resolved non-reference conflict span.
VerifyEmptyTaggedSpans(HighlightTags.FixupTag.Instance, actualWorkspace, renameService)
' Verify valid reference tags.
VerifyTaggedSpans(HighlightTags.ValidTag.Instance, actualWorkspace, renameService)
End Sub
Private Sub VerifySpansAndBufferForConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService, resolvedConflictWorkspace As TestWorkspace,
session As IInlineRenameSession, Optional sessionCommit As Boolean = False, Optional sessionCancel As Boolean = False)
WaitForRename(actualWorkspace)
' Verify fixup/resolved conflict spans.
VerifyAnnotatedTaggedSpans(HighlightTags.FixupTag.Instance, "Complexified", actualWorkspace, renameService, resolvedConflictWorkspace)
' Verify valid reference tags.
VerifyTaggedSpans(HighlightTags.ValidTag.Instance, actualWorkspace, renameService, resolvedConflictWorkspace)
VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace)
If sessionCommit Or sessionCancel Then
Assert.True(Not sessionCommit Or Not sessionCancel)
If sessionCancel Then
session.Cancel()
VerifyBufferContentsInWorkspace(actualWorkspace, actualWorkspace)
ElseIf sessionCommit Then
session.Commit()
VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace)
End If
End If
End Sub
Private Sub VerifyTaggedSpansCore(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedSpans As IEnumerable(Of Span))
Dim taggedSpans = GetTagsOfType(tagType, actualWorkspace, renameService)
Assert.Equal(expectedSpans, taggedSpans)
End Sub
Private Sub VerifyBufferContentsInWorkspace(actualWorkspace As TestWorkspace, expectedWorkspace As TestWorkspace)
Dim actualDocs = actualWorkspace.Documents
Dim expectedDocs = expectedWorkspace.Documents
Assert.Equal(expectedDocs.Count, actualDocs.Count)
For i = 0 To actualDocs.Count - 1
Dim actualDocument = actualDocs(i)
Dim expectedDocument = expectedDocs(i)
Dim actualText = actualDocument.TextBuffer.CurrentSnapshot.GetText().Trim()
Dim expectedText = expectedDocument.TextBuffer.CurrentSnapshot.GetText().Trim()
Assert.Equal(expectedText, actualText)
Next
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ValidTagsDuringSimpleRename()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Foo|]
{
void Blah()
{
[|Foo|] f = new [|Foo|]();
}
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
VerifyTaggedSpans(HighlightTags.ValidTag.Instance, workspace, renameService)
session.Cancel()
End Using
End Sub
<Fact>
<WorkItem(922197)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub UnresolvableConflictInModifiedDocument()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] {|conflict:args|}, int $$foo)
{
Foo(c => IsInt({|conflict:foo|}, c));
}
private static void Foo(Func<char, bool> p) { }
private static void Foo(Func<int, bool> p) { }
private static bool IsInt(int foo, char c) { }
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim document = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue)
Dim location = document.CursorPosition.Value
Dim session = StartSession(workspace)
document.TextBuffer.Replace(New Span(location, 3), "args")
WaitForRename(workspace)
Using renamedWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] {|conflict:args|}, int args)
{
Foo(c => IsInt({|conflict:args|}, c));
}
private static void Foo(Func<char, bool> p) { }
private static void Foo(Func<int, bool> p) { }
private static bool IsInt(int foo, char c) { }
}
</Document>
</Project>
</Workspace>)
Dim renamedDocument = renamedWorkspace.Documents.Single()
Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument)
Dim taggedSpans = GetTagsOfType(ConflictTag.Instance, renameService, document.TextBuffer)
Assert.Equal(expectedSpans, taggedSpans)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyLinkedFiles_InterleavedResolvedConflicts()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs">
public class Class1
{
#if Proj2
int fieldclash;
#endif
int field$$;
void M()
{
int fieldclash = 8;
#if Proj1
var a = [|field|];
#elif Proj2
var a = [|field|];
#elif Proj3
var a = field;
#endif
#if Proj1
var b = [|field|];
#elif Proj2
var b = [|field|];
#elif Proj3
var b = field;
#endif
}
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim location = document.CursorPosition.Value
Dim session = StartSession(workspace)
document.TextBuffer.Insert(location, "clash")
WaitForRename(workspace)
Using renamedWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs">
public class Class1
{
#if Proj2
int fieldclash;
#endif
int {|valid:fieldclash|};
void M()
{
int fieldclash = 8;
#if Proj1
{|resolved:var a = this.{|valid:fieldclash|};|}
#elif Proj2
var a = {|conflict:fieldclash|};
#elif Proj3
var a = field;
#endif
#if Proj1
{|resolved:var b = this.{|valid:fieldclash|};|}
#elif Proj2
var b = {|conflict:fieldclash|};
#elif Proj3
var b = field;
#endif
}
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>
)
Dim renamedDocument = renamedWorkspace.Documents.First()
Dim expectedSpans = GetAnnotatedSpans("resolved", renamedDocument)
Dim taggedSpans = GetTagsOfType(FixupTag.Instance, renameService, document.TextBuffer)
Assert.Equal(expectedSpans, taggedSpans)
expectedSpans = GetAnnotatedSpans("conflict", renamedDocument)
taggedSpans = GetTagsOfType(ConflictTag.Instance, renameService, document.TextBuffer)
Assert.Equal(expectedSpans, taggedSpans)
expectedSpans = GetAnnotatedSpans("valid", renamedDocument)
taggedSpans = GetTagsOfType(ValidTag.Instance, renameService, document.TextBuffer)
Assert.Equal(expectedSpans, taggedSpans)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyLinkedFiles_UnresolvableConflictComments()
Dim originalDocument = "
public class Class1
{
#if Proj1
void Test(double x) { }
#elif Proj2
void Test(long x) { }
#endif
void Tes$$(int i) { }
void M()
{
Test(5);
}
}"
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><%= originalDocument %></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim location = document.CursorPosition.Value
Dim session = StartSession(workspace)
document.TextBuffer.Insert(location, "t")
WaitForRename(workspace)
Dim expectedDocument = $"
public class Class1
{{
#if Proj1
void Test(double x) {{ }}
#elif Proj2
void Test(long x) {{ }}
#endif
void Test(int i) {{ }}
void M()
{{
{{|conflict:{{|conflict:/* {String.Format(WorkspacesResources.UnmergedChangeFromProject, "CSharpAssembly1")}
{WorkspacesResources.BeforeHeader}
Test(5);
{WorkspacesResources.AfterHeader}
Test((long)5);
*|}}|}}/
Test((double)5);
}}
}}"
Using renamedWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><%= expectedDocument %></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>
)
Dim renamedDocument = renamedWorkspace.Documents.First()
Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument)
Dim taggedSpans = GetTagsOfType(ConflictTag.Instance, renameService, document.TextBuffer)
Assert.Equal(expectedSpans, taggedSpans)
End Using
End Using
End Sub
<Fact>
<WorkItem(922197)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub UnresolvableConflictInUnmodifiedDocument()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$A|]
{
}
</Document>
<Document FilePath="B.cs">
class {|conflict:B|}
{
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).TextBuffer
Dim session = StartSession(workspace)
textBuffer.Replace(New Span(location, 1), "B")
WaitForRename(workspace)
Dim conflictDocument = workspace.Documents.Single(Function(d) d.FilePath = "B.cs")
Dim expectedSpans = GetAnnotatedSpans("conflict", conflictDocument)
Dim taggedSpans = GetTagsOfType(ConflictTag.Instance, renameService, conflictDocument.TextBuffer)
Assert.Equal(expectedSpans, taggedSpans)
End Using
End Sub
<Fact>
<WorkItem(847467)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ValidStateWithEmptyReplacementTextAfterConflictResolution()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$T|]
{
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim session = StartSession(workspace)
textBuffer.Replace(New Span(location, 1), "this")
' Verify @ escaping
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class @[|this|]
{
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
textBuffer.Delete(New Span(location + 1, 4))
WaitForRename(workspace)
' Verify no escaping
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class
{
}
</Document>
</Project>
</Workspace>)
VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace)
End Using
session.Commit()
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class T
{
}
</Document>
</Project>
</Workspace>)
VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(812789)>
Public Sub RenamingEscapedIdentifiers()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void @$$as() { }
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
' Verify @ escaping is still present
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void @[|as|]() { }
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
textBuffer.Replace(New Span(location, 2), "bar")
' Verify @ escaping is removed
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|bar|]() { }
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
End Using
End Sub
<Fact>
<WorkItem(812795)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BackspacingAfterConflictResolutionPreservesTrackingSpans()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Method()
{
$$Bar(0);
}
void Foo(int i) { }
void Bar(double d) { }
}
</Document>
</Project>
</Workspace>)
Dim view = workspace.Documents.Single().GetTextView()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view)
Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IWaitIndicator))
Dim session = StartSession(workspace)
textBuffer.Replace(New Span(location, 3), "Foo")
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Method()
{
{|Complexified:[|Foo|]((double)0);|}
}
void Foo(int i) { }
void [|Foo|](double d) { }
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Delete Foo and type "as"
commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace())
commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace())
commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace())
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "a"c), Sub() editorOperations.InsertText("a"))
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "s"c), Sub() editorOperations.InsertText("s"))
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Method()
{
@[|as|](0);
}
void Foo(int i) { }
void @[|as|](double d) { }
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharp_FixupSpanDuringResolvableConflict_NonReferenceConflict()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int bar;
void M(int [|$$foo|])
{
var x = [|foo|];
bar = 23;
}
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved non-reference conflict.
textBuffer.Replace(New Span(location, 3), "bar")
' Verify fixup/resolved non-reference conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int bar;
void M(int [|bar|])
{
var x = [|bar|];
{|Complexified:this.{|Resolved:bar|} = 23;|}
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit so that we have no more conflicts.
location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
textBuffer.Replace(New Span(location, 3), "baR")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int bar;
void M(int [|$$baR|])
{
var x = [|baR|];
bar = 23;
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VisualBasic_FixupSpanDuringResolvableConflict_NonReferenceConflict()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim bar As Integer
Sub M([|$$foo|] As Integer)
Dim x = [|foo|]
BAR = 23
End Sub
End Class
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved non-reference conflict.
textBuffer.Replace(New Span(location, 3), "bar")
' Verify fixup/resolved non-reference conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim bar As Integer
Sub M([|bar|] As Integer)
Dim x = [|bar|]
{|Complexified:Me.{|Resolved:BAR|} = 23|}
End Sub
End Class
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit so that we have no more conflicts.
location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
textBuffer.Replace(New Span(location, 3), "boo")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim bar As Integer
Sub M([|$$boo|] As Integer)
Dim x = [|boo|]
BAR = 23
End Sub
End Class
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharp_FixupSpanDuringResolvableConflict_ReferenceConflict()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int [|$$foo|];
void M(int bar)
{
[|foo|] = [|foo|] + bar;
}
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 3), "bar")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int [|bar|];
void M(int bar)
{
{|Complexified:this.{|Resolved:[|bar|]|} = this.{|Resolved:[|bar|]|} + bar;|}
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
textBuffer.Replace(New Span(location, 3), "ba")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int [|$$ba|];
void M(int bar)
{
[|ba|] = [|ba|] + bar;
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VisualBasic_FixupSpanDuringResolvableConflict_ReferenceConflict()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim [|$$foo|] As Integer
Sub M(bar As Integer)
[|foo|] = [|foo|] + bar
End Sub
End Class
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 3), "bar")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim [|bar|] As Integer
Sub M(bar As Integer)
{|Complexified:Me.{|Resolved:[|bar|]|} = Me.{|Resolved:[|bar|]|} + bar|}
End Sub
End Class
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit so that we have no more conflicts.
textBuffer.Replace(New Span(location, 3), "ba")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim [|$$ba|] As Integer
Sub M(bar As Integer)
[|ba|] = [|ba|] + bar
End Sub
End Class
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharp_FixupSpanDuringResolvableConflict_NeedsEscaping()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int @int;
void M(int [|$$foo|])
{
var x = [|foo|];
@int = 23;
}
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved escaping conflict.
textBuffer.Replace(New Span(location, 3), "int")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int @int;
void M(int {|Resolved:@[|int|]|})
{
var x = {|Resolved:@[|int|]|};
{|Complexified:this.{|Resolved:@int|} = 23;|}
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit to change "int" to "@in" so that we have no more conflicts, just escaping.
textBuffer.Replace(New Span(location + 1, 3), "in")
' Verify resolved escaping conflict spans.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int @int;
void M(int {|Resolved:@[|in|]|})
{
var x = {|Resolved:@[|in|]|};
@int = 23;
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VisualBasic_FixupSpanDuringResolvableConflict_NeedsEscaping()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim [New] As Integer
Sub M([|$$foo|] As Integer)
Dim x = [|foo|]
[NEW] = 23
End Sub
End Class
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved escaping conflict.
textBuffer.Replace(New Span(location, 3), "New")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim [New] As Integer
Sub M({|Resolved:[[|New|]]|} As Integer)
Dim x = {|Resolved:[[|New|]]|}
{|Complexified:Me.{|Resolved:[NEW]|} = 23|}
End Sub
End Class
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit to change "New" to "[Do]" so that we have no more conflicts, just escaping.
textBuffer.Replace(New Span(location + 1, 3), "Do")
' Verify resolved escaping conflict spans.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Dim [New] As Integer
Sub M({|Resolved:[[|Do|]]|} As Integer)
Dim x = {|Resolved:[[|Do|]]|}
[NEW] = 23
End Sub
End Class
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub FixupSpanDuringResolvableConflict_VerifyCaret()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub [|N$$w|](foo As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>)
Dim view = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view)
Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IWaitIndicator))
Dim textViewService = New TextBufferAssociatedViewService()
Dim buffers = New Collection(Of ITextBuffer)
buffers.Add(view.TextBuffer)
DirectCast(textViewService, IWpfTextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
VerifySpansBeforeConflictResolution(workspace, renameService)
' Type first in the main identifier
view.Selection.Clear()
view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value))
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"))
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub [[|Ne$$w|]](foo As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
Dim location = view.Caret.Position.BufferPosition.Position
Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Assert.Equal(expectedLocation, location)
End Using
' Make another edit to change "New" to "Nexw" so that we have no more conflicts or escaping.
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "x"c), Sub() editorOperations.InsertText("x"))
' Verify resolved escaping conflict spans.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub [|Nex$$w|](foo As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
Dim location = view.Caret.Position.BufferPosition.Position
Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Assert.Equal(expectedLocation, location)
End Using
End Using
End Sub
<Fact>
<WorkItem(771743)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyNoSelectionAfterCommit()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub [|M$$ain|](foo As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>)
Dim view = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view)
Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IWaitIndicator))
Dim textViewService = New TextBufferAssociatedViewService()
Dim buffers = New Collection(Of ITextBuffer)
buffers.Add(view.TextBuffer)
DirectCast(textViewService, IWpfTextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers)
Dim location = view.Caret.Position.BufferPosition.Position
view.Selection.Select(New SnapshotSpan(view.Caret.Position.BufferPosition, 2), False)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
VerifySpansBeforeConflictResolution(workspace, renameService)
' Type few characters.
view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value))
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"))
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "f"c), Sub() editorOperations.InsertText("f"))
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "g"c), Sub() editorOperations.InsertText("g"))
session.Commit()
Dim selectionLength = view.Selection.End.Position - view.Selection.Start.Position
Assert.Equal(0, selectionLength)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharp_FixupSpanDuringResolvableConflict_ComplexificationOutsideConflict()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int x = [|$$Bar|](Foo([|Bar|](0)));
}
static int Foo(int i)
{
return 0;
}
static int [|Bar|](double d)
{
return 1;
}
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 3), "Foo")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
{|Complexified:int x = {|Resolved:[|Foo|]|}((double)Foo({|Resolved:[|Foo|]|}((double)0)));|}
}
static int Foo(int i)
{
return 0;
}
static int [|Foo|](double d)
{
return 1;
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit so that we have no more conflicts.
textBuffer.Replace(New Span(location, 3), "FOO")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int x = [|$$FOO|](Foo([|FOO|](0)));
}
static int Foo(int i)
{
return 0;
}
static int [|FOO|](double d)
{
return 1;
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharp_FixupSpanDuringResolvableConflict_ContainedComplexifiedSpan()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Foo(T x) { }
class B<S> : A<B<S>>
{
class [|$$C|]<U> : B<[|C|]<U>> // Rename C to A
{
public override void Foo(A<A<T>.B<S>>.B<A<T>.B<S>.[|C|]<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 1), "A")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Foo(T x) { }
class B<S> : A<B<S>>
{
class [|A|]<U> : B<[|A|]<U>> // Rename C to A
{
public override void Foo({|Complexified:N.{|Resolved:A|}<N.{|Resolved:A|}<T>.B<S>>|}.B<{|Complexified:N.{|Resolved:A|}<T>|}.B<S>.[|A|]<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharp_FixupSpanDuringResolvableConflict_ComplexificationReordersReferenceSpans()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class E
{
public static C [|$$Foo|](this C x, int tag) { return new C(); }
}
class C
{
C Bar(int tag)
{
return this.[|Foo|](1).[|Foo|](2);
}
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 3), "Bar")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class E
{
public static C [|Bar|](this C x, int tag) { return new C(); }
}
class C
{
C Bar(int tag)
{
{|Complexified:return E.{|Resolved:[|Bar|]|}(E.{|Resolved:[|Bar|]|}(this,1),2);|}
}
}
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharp_FixupSpanDuringResolvableConflict_WithinCrefs()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Foo();
}
}
class C
{
class E : F.I
{
/// <summary>
/// This is a function <see cref="F.I.Foo"/>
/// </summary>
public void Foo() { }
}
class [|$$K|]
{
}
}
]]>
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 1), "F")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Foo();
}
}
class C
{
class E : {|Complexified:{|Resolved:N|}|}.I
{
/// <summary>
/// This is a function <see cref="{|Complexified:{|Resolved:N|}|}.I.Foo"/>
/// </summary>
public void Foo() { }
}
class [|$$F|]
{
}
}
]]>
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharp_FixupSpanDuringResolvableConflict_OverLoadResolutionChangesInEnclosingInvocations()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
< { } // Rename Ex to Foo
}
]]>
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().TextBuffer
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 2), "Foo")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
< { } // Rename Ex to Foo
}
]]>
</Document>
</Project>
</Workspace>)
VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Sub
<Fact>
<WorkItem(530817)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CSharpShowDeclarationConflictsImmediately()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
const int {|valid:$$V|} = 5;
int {|conflict:V|} = 99;
}
}
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim validTaggedSpans = GetTagsOfType(HighlightTags.ValidTag.Instance, workspace, renameService)
Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan())
Dim conflictTaggedSpans = GetTagsOfType(ConflictTag.Instance, workspace, renameService)
Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan())
session.Cancel()
AssertEx.Equal(validExpectedSpans, validTaggedSpans)
AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans)
End Using
End Sub
<Fact>
<WorkItem(530817)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VBShowDeclarationConflictsImmediately()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Bar()
Dim {|valid:$$V|} as Integer
Dim {|conflict:V|} as String
End Sub
End Class
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim validTaggedSpans = GetTagsOfType(HighlightTags.ValidTag.Instance, workspace, renameService)
Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan())
Dim conflictTaggedSpans = GetTagsOfType(ConflictTag.Instance, workspace, renameService)
Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan())
session.Cancel()
AssertEx.Equal(validExpectedSpans, validTaggedSpans)
AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ActiveSpanInSecondaryView()
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class [|$$Foo|]
End Class
</Document>
<Document>
' [|Foo|]
</Document>
</Project>
</Workspace>)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents(0).TextBuffer
Dim session = StartSession(workspace)
session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=True)
WaitForRename(workspace)
session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=False)
WaitForRename(workspace)
textBuffer.Replace(New Span(location, 3), "Bar")
WaitForRename(workspace)
End Using
End Sub
Private Function GetTagsOfType(expectedTagType As ITextMarkerTag, workspace As TestWorkspace, renameService As InlineRenameService) As IEnumerable(Of Span)
Dim textBuffer = workspace.Documents.Single().TextBuffer
WaitForRename(workspace)
Return GetTagsOfType(expectedTagType, renameService, textBuffer)
End Function
Private Shared Function GetTagsOfType(expectedTagType As ITextMarkerTag, renameService As InlineRenameService, textBuffer As ITextBuffer) As IEnumerable(Of Span)
Dim tagger = New RenameTagger(textBuffer, renameService)
Dim snapshotSpan = New SnapshotSpan(textBuffer.CurrentSnapshot, 0, textBuffer.CurrentSnapshot.Length)
Dim tags = tagger.GetTags(New NormalizedSnapshotSpanCollection(snapshotSpan))
Return (From tag In tags
Where tag.Tag Is expectedTagType
Order By tag.Span.Start
Select tag.Span.Span).ToList()
End Function
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb
|
Visual Basic
|
apache-2.0
| 69,905
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class DocumentationCommentIdVisitor
Inherits VisualBasicSymbolVisitor(Of StringBuilder, Object)
Public Shared ReadOnly Instance As New DocumentationCommentIdVisitor()
Private Sub New()
End Sub
Public Overrides Function DefaultVisit(symbol As Symbol, builder As StringBuilder) As Object
Return Nothing
End Function
Public Overrides Function VisitNamespace(symbol As NamespaceSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "N:")
End Function
Public Overrides Function VisitEvent(symbol As EventSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "E:")
End Function
Public Overrides Function VisitMethod(symbol As MethodSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "M:")
End Function
Public Overrides Function VisitField(symbol As FieldSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "F:")
End Function
Public Overrides Function VisitProperty(symbol As PropertySymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "P:")
End Function
Public Overrides Function VisitNamedType(symbol As NamedTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "T:")
End Function
Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "T:")
End Function
Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "!:")
End Function
Public Overrides Function VisitErrorType(symbol As ErrorTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "!:")
End Function
Private Shared Function VisitSymbolUsingPrefix(symbol As Symbol, builder As StringBuilder, prefix As String) As Object
builder.Append(prefix)
PartVisitor.Instance.Visit(symbol, builder)
Return Nothing
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Portable/DocumentationComments/DocumentationCommentIDVisitor.vb
|
Visual Basic
|
apache-2.0
| 2,763
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "CGS_rCompras_Articulos_ADM"
'-------------------------------------------------------------------------------------------'
Partial Class CGS_rCompras_Articulos_ADM
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine("DECLARE @lcCodArt_Desde AS VARCHAR(8) = " & lcParametro0Desde)
loComandoSeleccionar.AppendLine("DECLARE @lcCodArt_Hasta AS VARCHAR(8) = " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine("DECLARE @ldFecha_Desde AS DATETIME = " & lcParametro1Desde)
loComandoSeleccionar.AppendLine("DECLARE @ldFecha_Hasta AS DATETIME = " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine("DECLARE @lcCodPro_Desde AS VARCHAR(10) = " & lcParametro2Desde)
loComandoSeleccionar.AppendLine("DECLARE @lcCodPro_Hasta AS VARCHAR(10) = " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine("DECLARE @lcCodDep_Desde AS VARCHAR(2) = " & lcParametro3Desde)
loComandoSeleccionar.AppendLine("DECLARE @lcCodDep_Hasta AS VARCHAR(2) = " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine("DECLARE @lcCodSec_Desde AS VARCHAR(2) = " & lcParametro4Desde)
loComandoSeleccionar.AppendLine("DECLARE @lcCodSec_Hasta AS VARCHAR(2) = " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("SELECT Articulos.Cod_Art, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art,")
loComandoSeleccionar.AppendLine(" Compras.Documento, ")
loComandoSeleccionar.AppendLine(" Compras.Cod_Pro, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Compras.Factura, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Notas, ")
loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro,")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Can_Art1, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Cod_Uni, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Precio1, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Mon_Net,")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Tip_Ori,")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Doc_Ori,")
loComandoSeleccionar.AppendLine(" CASE Renglones_Compras.Tip_Ori ")
loComandoSeleccionar.AppendLine(" WHEN 'recepciones' THEN")
loComandoSeleccionar.AppendLine(" (SELECT Fec_Ini FROM Recepciones WHERE Documento = Renglones_Compras.Doc_Ori)")
loComandoSeleccionar.AppendLine(" WHEN 'ordenes_compras' THEN")
loComandoSeleccionar.AppendLine(" (SELECT Fec_Ini FROM Ordenes_Compras WHERE Documento = Renglones_Compras.Doc_Ori)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Fec_Ori,")
loComandoSeleccionar.AppendLine(" Articulos.Generico,")
loComandoSeleccionar.AppendLine(" CONCAT(CONVERT(VARCHAR(12),CAST(@ldFecha_Desde AS DATE),103), ' - ', CONVERT(VARCHAR(12),CAST(@ldFecha_Hasta AS DATE),103)) AS Fecha,")
loComandoSeleccionar.AppendLine(" CASE WHEN @lcCodArt_Desde <> ''")
loComandoSeleccionar.AppendLine(" THEN (SELECT Nom_Art FROM Articulos WHERE Cod_Art = @lcCodArt_Desde)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Art_Desde,")
loComandoSeleccionar.AppendLine(" CASE WHEN @lcCodArt_Hasta <> 'zzzzzzz'")
loComandoSeleccionar.AppendLine(" THEN (SELECT Nom_Art FROM Articulos WHERE Cod_Art = @lcCodArt_Hasta)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Art_Hasta,")
loComandoSeleccionar.AppendLine(" CASE WHEN @lcCodDep_Desde <> ''")
loComandoSeleccionar.AppendLine(" THEN (SELECT Nom_Dep FROM Departamentos WHERE Cod_Dep = @lcCodDep_Desde)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Dep_Desde,")
loComandoSeleccionar.AppendLine(" CASE WHEN @lcCodDep_Hasta <> 'zzzzzzz'")
loComandoSeleccionar.AppendLine(" THEN (SELECT Nom_Dep FROM Departamentos WHERE Cod_Dep = @lcCodDep_Hasta)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Dep_Hasta,")
loComandoSeleccionar.AppendLine(" CASE WHEN @lcCodSec_Desde <> ''")
loComandoSeleccionar.AppendLine(" THEN (SELECT Nom_Sec FROM Secciones WHERE Cod_Sec = @lcCodSec_Desde)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Sec_Desde,")
loComandoSeleccionar.AppendLine(" CASE WHEN @lcCodSec_Hasta <> 'zzzzzzz'")
loComandoSeleccionar.AppendLine(" THEN (SELECT Nom_Sec FROM Secciones WHERE Cod_Sec = @lcCodSec_Hasta)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Sec_Hasta,")
loComandoSeleccionar.AppendLine(" CASE WHEN @lcCodPro_Desde <> ''")
loComandoSeleccionar.AppendLine(" THEN (SELECT Nom_Pro FROM Proveedores WHERE Cod_Pro = @lcCodPro_Desde)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Pro_Desde,")
loComandoSeleccionar.AppendLine(" CASE WHEN @lcCodPro_Hasta <> 'zzzzzzz'")
loComandoSeleccionar.AppendLine(" THEN (SELECT Nom_Pro FROM Proveedores WHERE Cod_Pro = @lcCodPro_Hasta)")
loComandoSeleccionar.AppendLine(" ELSE '' END AS Pro_Hasta")
loComandoSeleccionar.AppendLine("FROM Articulos")
loComandoSeleccionar.AppendLine(" JOIN Renglones_Compras ON Renglones_Compras.Cod_Art = Articulos.Cod_Art")
loComandoSeleccionar.AppendLine(" JOIN Compras ON Compras.Documento = Renglones_Compras.Documento")
loComandoSeleccionar.AppendLine(" JOIN Proveedores ON Compras.Cod_Pro = Proveedores.Cod_Pro")
loComandoSeleccionar.AppendLine("WHERE Renglones_Compras.Cod_Art BETWEEN @lcCodArt_Desde AND @lcCodArt_Hasta")
loComandoSeleccionar.AppendLine(" AND Compras.Fec_Ini BETWEEN @ldFecha_Desde AND @ldFecha_Hasta")
loComandoSeleccionar.AppendLine(" AND Compras.Cod_Pro BETWEEN @lcCodPro_Desde AND @lcCodPro_Hasta")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN @lcCodDep_Desde AND @lcCodDep_Hasta")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN @lcCodSec_Desde AND @lcCodSec_Hasta")
If lcParametro5Desde = "GEN" Then
loComandoSeleccionar.AppendLine(" AND Articulos.Generico = 1")
End If
loComandoSeleccionar.AppendLine("ORDER BY Renglones_Compras.Cod_Art")
'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("CGS_rCompras_Articulos_ADM", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvCGS_rCompras_Articulos_ADM.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: 09/10/08: Codigo inicial
'-------------------------------------------------------------------------------------------'
' YJP: 14/05/09: Agregar filtro Revisión
'-------------------------------------------------------------------------------------------'
' CMS: 22/06/09: Agregar filtro Revisión
'-------------------------------------------------------------------------------------------'
' AAP: 01/07/09: Filtro "Sucursal:"
'-------------------------------------------------------------------------------------------'
' CMS: 04/08/09: Secciones.Cod_Dep = Departamentos.Cod_Dep
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
CGS_rCompras_Articulos_ADM.aspx.vb
|
Visual Basic
|
mit
| 11,306
|
Imports System.Runtime.InteropServices
Namespace NativeRoutines.Interfaces
<ComImport, Guid("0000010B-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface IPersistFile
Inherits IPersist
Shadows Sub GetClassID(ByRef pClassID As Guid)
<PreserveSig> Function IsDirty() As Integer
<PreserveSig> Sub Load(<[In], MarshalAs(UnmanagedType.LPWStr)> pszFileName As String, dwMode As UInteger)
<PreserveSig> Sub Save(<[In], MarshalAs(UnmanagedType.LPWStr)> pszFileName As String, <[In], MarshalAs(UnmanagedType.Bool)> fRemember As Boolean)
<PreserveSig> Sub SaveCompleted(<[In], MarshalAs(UnmanagedType.LPWStr)> pszFileName As String)
<PreserveSig> Sub GetCurFile(<[In], MarshalAs(UnmanagedType.LPWStr)> ppszFileName As String)
End Interface
End Namespace
|
nublet/APRBase
|
APRBase/NativeRoutines/Interfaces/IPersistFile.vb
|
Visual Basic
|
mit
| 866
|
Option Explicit On
'Title: Running total & Avg
'Author: Miguel Rodriguez
'Date: 2/16/2016
'Course: CSC 162
'Section: 001
'Description: This program demonstrates how to keep track
' of a running total of numbers and it computes the avg
'
'Initial Algorithm:
' 1. Get Number Entered by User
' 2. Add to running total
' 3. count by one each time the user enters a number
' 4. Display running total
' 5. Display the total average
'
'Data Requirements:
' Input:
' Number entered by user: NumEntered
' Output:
' Running Total (sum of all numbers entered): RunTotal
' Average (RunTotal / count): totalAvg
' Additional:
' None
'
'Formulas:
' RunTotal = RunTotal + NumEntered
' totalAvg = RunTotal / count
'
'Refined Algorithm:
' 1. Get Number Entered by User
' 2. Add to running total
' RunTotal = RunTotal + NumEntered
' 3. Compute the total average
' totalAvg = RunTotal / count
' 4. Display running total
' 5. Display the total Average
Public Class frmRunningTotal
Inherits System.Windows.Forms.Form
'Global Variable Section
Dim RunTotal As Integer 'Running Total
Dim count As Integer 'counts everytime the user enters a number
Private Sub cmdAdd_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdAdd.Click
'This command button adds the number entered to the running total
'Declare local variables
Dim NumEntered As Integer 'Number entered by user
'Get number entered into text box and put into variable
NumEntered = Val(txtNumEntered.Text)
'Calculate running total
RunTotal = RunTotal + NumEntered
'Place new total into label
txtRunTotal.Text = RunTotal
count = count + 1 'counts and increases by one
'Clear out text box for next number
txtNumEntered.Text = ""
'Return cursor to text box for next number
txtNumEntered.Focus()
End Sub
Private Sub cmdClear_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdClear.Click
'This button clears out all text boxes and count
txtNumEntered.Text = ""
txtRunTotal.Text = ""
txtDisplayAvg.Text = ""
'Re-initialize RunTotal
RunTotal = 0
'reinitialize count
count = 0
'Set focus back to text box
txtNumEntered.Focus()
End Sub
Private Sub cmdEnd_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdEnd.Click
'This command button ends the program
Me.Close() 'Remove active window
End 'End program
End Sub
Private Sub frmRunningTotal_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
'Initialize Text Boxes, labels, and variables to zero when form is loaded
txtNumEntered.Text = ""
txtRunTotal.Text = ""
txtDisplayAvg.Text = ""
RunTotal = 0
lblInfo.Text = "Adds up numbers and Computes average"
End Sub
Private Sub cdmAvg_Click(sender As Object, e As EventArgs) Handles cdmAvg.Click
Dim totalAvg As Double 'stores the total avg computed
totalAvg = RunTotal / count 'computes the avg and stores it in totalAvg
'Place average into the lbl
txtDisplayAvg.Text = totalAvg
End Sub
End Class
|
miguel2192/CSC-162
|
Rodriguez_runTotalAvg/runningTotal/Rodriguez_RnAvg.vb
|
Visual Basic
|
mit
| 3,479
|
Namespace Assets
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [Asset]
'''<summary>Indicates if an asset was already depreciated before registering it in Exact Online</summary>
Public Property [AlreadyDepreciated] As Byte
'''<summary>In case of a transfer or a split, the original asset ID is saved in this field. This is done to provide tracability of the Asset</summary>
Public Property [AssetFrom] As Guid?
'''<summary>Description of AssetFrom</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AssetFromDescription] As String
'''<summary>Asset group identifies GLAccounts to be used for Asset transactions</summary>
Public Property [AssetGroup] As Guid?
'''<summary>Code of the asset group</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AssetGroupCode] As String
'''<summary>Description of the asset group</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AssetGroupDescription] As String
'''<summary>The catalogue value of the asset</summary>
Public Property [CatalogueValue] As Double?
'''<summary>Code of the asset</summary>
Public Property [Code] As String
'''<summary>Assets can be linked to a cost center</summary>
Public Property [Costcenter] As String
'''<summary>Description of Costcenter</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CostcenterDescription] As String
'''<summary>Assets can be linked to a cost unit</summary>
Public Property [Costunit] As String
'''<summary>Description of Costunit</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CostunitDescription] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Used for Belgium legislation. Used to produce the official 'Investment deduction' report</summary>
Public Property [DeductionPercentage] As Double?
'''<summary>Amount that is already depreciated when adding an existing asset. Can only be filled when 'Alreadydepreciated' is on</summary>
Public Property [DepreciatedAmount] As Double?
'''<summary>Number of periods that already have been depreciated for the asset. Can only be filled when 'Alreadydepreciated' is on</summary>
Public Property [DepreciatedPeriods] As Int32?
'''<summary>StartDate of depreciating. Can only be filled when 'Alreadydepreciated' is on</summary>
Public Property [DepreciatedStartDate] As DateTime?
'''<summary>This is the description of the Asset</summary>
Public Property [Description] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Asset EndDate is filled when asset is Sold or Inactive</summary>
Public Property [EndDate] As DateTime?
'''<summary>Engine emission of the asset, needed to calculate the co² report</summary>
Public Property [EngineEmission] As Int16?
'''<summary>Engine type of the asset, Needed to generate a co² report</summary>
Public Property [EngineType] As Int16?
'''<summary>Links to the gltransactions.id. GL transaction line based on which the asset is created</summary>
Public Property [GLTransactionLine] As Guid?
'''<summary>Description of GLTransactionLine</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [GLTransactionLineDescription] As String
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Supplier of the asset</summary>
Public Property [InvestmentAccount] As Guid?
'''<summary>Code of InvestmentAccount</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [InvestmentAccountCode] As String
'''<summary>Name of InvestmentAccount</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [InvestmentAccountName] As String
'''<summary>Investment amount in the default currency of the company</summary>
Public Property [InvestmentAmountDC] As Double?
'''<summary>Investment value of the asset. Currently the field is filled with the PurchasePriceLocal. Can be status 'Not used' after sources have been cleaned</summary>
Public Property [InvestmentAmountFC] As Double?
'''<summary>Indicates the currency of the investment amount</summary>
Public Property [InvestmentCurrency] As String
'''<summary>Description of InvestmentCurrency</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [InvestmentCurrencyDescription] As String
'''<summary>Refers to the original date when the asset was bought</summary>
Public Property [InvestmentDate] As DateTime?
'''<summary>Belgian functionality, to determine how a local legal report regarding investment deduction must be created</summary>
Public Property [InvestmentDeduction] As Int16?
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Extra remarks for the asset</summary>
Public Property [Notes] As String
'''<summary>Parent asset</summary>
Public Property [Parent] As Guid?
'''<summary>Code of Parent</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ParentCode] As String
'''<summary>Description of Parent</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ParentDescription] As String
'''<summary>Image for an asset</summary>
Public Property [Picture] As Byte()
'''<summary>Filename of the image</summary>
Public Property [PictureFileName] As String
'''<summary>First method of depreciation. Currently, it is the only one used</summary>
Public Property [PrimaryMethod] As Guid?
'''<summary>Code of PrimaryMethod</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PrimaryMethodCode] As String
'''<summary>Description of PrimaryMethod</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PrimaryMethodDescription] As String
'''<summary>Indicates the residual value of the asset at the end of the depreciation</summary>
Public Property [ResidualValue] As Double?
'''<summary>Asset Depreciation StartDate</summary>
Public Property [StartDate] As DateTime?
'''<summary>Identifies the status of the Asset. (see AssetStatus table to see the possibilities)</summary>
Public Property [Status] As Int16?
'''<summary>Reference to Transaction</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [TransactionEntryID] As Guid?
'''<summary>Entry number of transaction</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [TransactionEntryNo] As Int32?
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [AssetGroup]
'''<summary>Code of the asset group</summary>
Public Property [Code] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Default depreciation method of the assets in this asset group</summary>
Public Property [DepreciationMethod] As Guid?
'''<summary>Code of the depreciation method</summary>
Public Property [DepreciationMethodCode] As String
'''<summary>Description of the depreciation method</summary>
Public Property [DepreciationMethodDescription] As String
'''<summary>Description of the asset group</summary>
Public Property [Description] As String
'''<summary>Division code</summary>
Public Property [Division] As Int32?
'''<summary>GLAccount for the assets</summary>
Public Property [GLAccountAssets] As Guid?
'''<summary>Code of the GLAccount for the assets</summary>
Public Property [GLAccountAssetsCode] As String
'''<summary>Description of the GLAccount for the assets</summary>
Public Property [GLAccountAssetsDescription] As String
'''<summary>GLAccount for depreciation (Balance sheet)</summary>
Public Property [GLAccountDepreciationBS] As Guid?
'''<summary>Code of the GLAccount for depreciation (Balance sheet)</summary>
Public Property [GLAccountDepreciationBSCode] As String
'''<summary>Description of the GLAccount for depreciation (Balance sheet)</summary>
Public Property [GLAccountDepreciationBSDescription] As String
'''<summary>GLAccount for depreciation (Profit & Loss)</summary>
Public Property [GLAccountDepreciationPL] As Guid?
'''<summary>Code of the GLAccount for depreciation (Profit & Loss)</summary>
Public Property [GLAccountDepreciationPLCode] As String
'''<summary>Description of the GLAccount for depreciation (Profit & Loss)</summary>
Public Property [GLAccountDepreciationPLDescription] As String
'''<summary>GLAccount for revaluation (Balance sheet)</summary>
Public Property [GLAccountRevaluationBS] As Guid?
'''<summary>Code of the GLAccount for revaluation (Balance sheet)</summary>
Public Property [GLAccountRevaluationBSCode] As String
'''<summary>Description of the GLAccount for revaluation (Balance sheet)</summary>
Public Property [GLAccountRevaluationBSDescription] As String
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Notes</summary>
Public Property [Notes] As String
End Class
<SupportedActionsSDK(True, True, True, True)>
<DataServiceKey("ID")>
Public Class [DepreciationMethod]
'''<summary>When the method is fixed amount, this is the periodic depreciation amount</summary>
Public Property [Amount] As Double?
'''<summary>Code of the depreciation method</summary>
Public Property [Code] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Describes the periodic interval</summary>
Public Property [DepreciationInterval] As String
'''<summary>Description of the method</summary>
Public Property [Description] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Indicates the maximum value when using depreciation type degressive to linear</summary>
Public Property [MaxPercentage] As Double?
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Degressive percentage for methods: 10 - Degressive to linear, 11 - Degressive (fixed perc. of book value), 12 - Degressive to linear (Belgium & Luxembourg only). And interest percentage for method: 40 - Normal annuity method. On import: Can not be modified if depreciation method is already linked to an asset. For Belgium & Luxembourg the degressive percentage is calculated as double of the linear percentage</summary>
Public Property [Percentage] As Double?
'''<summary>Linear percentage for methods: 10 - Degressive to linear, 3 - Linear depreciation (Belgium & Luxembourg only), 12 - Degressive to linear (Belgium & Luxembourg only). On import: Can not be modified if depreciation method is already linked to an asset</summary>
Public Property [Percentage2] As Double?
'''<summary>The total number of periods for the depreciation method. Used in combination with depreciation interval: only used when interval is periodic</summary>
Public Property [Periods] As Int16?
'''<summary>The actual type of deprecation, such as lineair or degressive. The periodic amounts are based on this type, in combination with other fields, such as the interval and the periods</summary>
Public Property [Type] As Int32?
'''<summary>Description of Type</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [TypeDescription] As String
'''<summary>Determines the total number of years for the depreciation method. Used in combination with depreciation interval: only used when interval is yearly</summary>
Public Property [Years] As Int16?
End Class
End Namespace
|
shtrip/exactonline-api-dotnet-client
|
src/ExactOnline.Client.Models/Assets.vb
|
Visual Basic
|
mit
| 13,418
|
#Region "Microsoft.VisualBasic::c5f2dc4dc0981ce351355415b1773c00, src\visualize\plot\PeakAssign.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Class PeakAssign
'
' Constructor: (+1 Overloads) Sub New
'
' Function: DrawSpectrumPeaks, ResizeImages, ResizeThisWidth
'
' Sub: PlotInternal
'
' /********************************************************************************/
#End Region
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports Microsoft.VisualBasic.Data.ChartPlots.Graphic
Imports Microsoft.VisualBasic.Data.ChartPlots.Graphic.Axis
Imports Microsoft.VisualBasic.Data.ChartPlots.Graphic.Canvas
Imports Microsoft.VisualBasic.Imaging
Imports Microsoft.VisualBasic.Imaging.d3js.Layout
Imports Microsoft.VisualBasic.Imaging.Drawing2D
Imports Microsoft.VisualBasic.Imaging.Drawing2D.Text
Imports Microsoft.VisualBasic.Imaging.Driver
Imports Microsoft.VisualBasic.Imaging.Math2D
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.Math.LinearAlgebra
Imports Microsoft.VisualBasic.MIME.Html.CSS
''' <summary>
''' 通过KCF图模型为ms2二级质谱碎片鉴定分子碎片的具体的结构式
''' </summary>
Public Class PeakAssign : Inherits Plot
ReadOnly matrix As ms2()
ReadOnly title As String
ReadOnly barHighlight As String
ReadOnly images As Dictionary(Of String, Image)
ReadOnly labelIntensity As Double = 0.2
''' <summary>
'''
''' </summary>
''' <param name="title$"></param>
''' <param name="matrix"></param>
''' <param name="barHighlight"></param>
''' <param name="theme"></param>
''' <param name="images">the annotated molecular parts image</param>
Public Sub New(title$,
matrix As IEnumerable(Of ms2),
barHighlight As String,
labelIntensity As Double,
theme As Theme,
images As Dictionary(Of String, Image))
MyBase.New(theme)
Me.labelIntensity = labelIntensity
Me.title = title
Me.matrix = matrix.ToArray
Me.barHighlight = barHighlight
If images Is Nothing Then
Me.images = New Dictionary(Of String, Image)
Else
Me.images = images
End If
xlabel = "M/z ratio"
ylabel = "Relative Intensity (%)"
End Sub
Private Function ResizeThisWidth(original As Image, maxwidth As Integer) As Size
Dim intWidth As Integer = original.Width
Dim intHeight As Integer = original.Height
Dim newWidth, newHeight As Integer
If intWidth > maxwidth Then
newWidth = maxwidth
newHeight = maxwidth * (intHeight / intWidth)
Return New Size(newWidth, newHeight)
Else
Return original.Size
End If
End Function
Private Function ResizeImages(canvas As GraphicsRegion, ratio As Double) As Dictionary(Of String, (img As Image, size As Size))
Dim output As New Dictionary(Of String, (Image, Size))
Dim img As Image
Dim maxWidth As Integer = canvas.PlotRegion.Width * ratio
Dim maxHeight As Integer = canvas.PlotRegion.Height * ratio
For Each item In images
img = item.Value
If img.Width > img.Height Then
' via height
output(item.Key) = (img, ResizeThisWidth(img, maxwidth:=maxHeight / (img.Height / img.Width)))
Else
' via width
output(item.Key) = (img, ResizeThisWidth(img, maxWidth))
End If
Next
Return output
End Function
Protected Overrides Sub PlotInternal(ByRef g As IGraphics, canvas As GraphicsRegion)
Dim images = ResizeImages(canvas, ratio:=0.2)
If matrix.Length = 0 Then
Call "MS matrix is empty in peak assign plot!".Warning
Return
End If
Dim maxinto As Double = matrix.Select(Function(p) p.intensity).Max
Dim rect As RectangleF = canvas.PlotRegion.ToFloat
Dim xticks As Double() = (matrix.Select(Function(p) p.mz).Range * 1.125).CreateAxisTicks
Dim xscale = d3js.scale.linear().domain(xticks).range(values:={rect.Left, rect.Right})
Dim yscale = d3js.scale.linear().domain(New Double() {0, 100}).range(values:={rect.Top, rect.Bottom})
Dim scaler As New DataScaler() With {
.AxisTicks = (xticks.AsVector, New Vector(New Double() {0, 20, 40, 60, 80, 100})),
.region = canvas.PlotRegion,
.X = xscale,
.Y = yscale
}
Dim bottomY As Double = rect.Bottom
Dim text As New GraphicsText(DirectCast(g, Graphics2D).Graphics)
Dim labelFont As Font = CSSFont.TryParse(theme.tagCSS).GDIObject(g.Dpi)
Dim titleFont As Font = CSSFont.TryParse(theme.mainCSS).GDIObject(g.Dpi)
Call Axis.DrawAxis(
g, canvas, scaler,
showGrid:=True,
xlabel:=xlabel,
ylabel:=ylabel,
XtickFormat:="F4",
YtickFormat:="F0",
gridFill:=theme.gridFill,
xlayout:=XAxisLayoutStyles.None,
tickFontStyle:=theme.axisTickCSS,
gridX:=Nothing,
axisStroke:=theme.axisStroke,
htmlLabel:=False,
labelFont:=theme.axisLabelCSS
)
Dim ZERO As New PointF(rect.Left, rect.Bottom)
Dim RIGHT As New PointF(rect.Right, rect.Bottom)
Call g.DrawLine(Stroke.TryParse(theme.axisStroke), ZERO, RIGHT)
Dim labelSize As SizeF
Dim barStyle As Stroke = Stroke.TryParse(theme.lineStroke)
Dim barColor As Brush = barStyle.fill.GetBrush
Dim barHighlight As Brush = Me.barHighlight.GetBrush
Dim label As String
label = xlabel
labelSize = g.MeasureString(label, CSSFont.TryParse(theme.axisLabelCSS).GDIObject(g.Dpi))
RIGHT = New PointF(rect.Right - labelSize.Width, rect.Bottom + 5)
g.DrawString(label, CSSFont.TryParse(theme.axisLabelCSS).GDIObject(g.Dpi), Brushes.Black, RIGHT)
Dim labels As New List(Of Label)
Dim anchors As New List(Of Anchor)
For Each product As ms2 In matrix
Dim pt As PointF = scaler.Translate(product.mz, product.intensity / maxinto * 100)
Dim bar As New RectangleF With {
.X = pt.X - barStyle.width / 2,
.Y = pt.Y,
.Height = bottomY - pt.Y,
.Width = barStyle.width
}
Dim drawMzLabel As Boolean = product.intensity / maxinto >= labelIntensity
label = product.Annotation
If Not label.StringEmpty Then
If images.ContainsKey(label) Then
labelSize = images(label).size.SizeF
Else
' label = label.DoWordWrap(28, "")
labelSize = g.MeasureString(label, labelFont)
End If
If drawMzLabel Then
pt = New PointF(bar.X + bar.Width / 2, bar.Y - g.MeasureString(label, labelFont).Height)
Else
pt = bar.Location.OffSet2D(bar.Width / 2, 0)
End If
Call g.FillRectangle(barHighlight, bar)
If (Not images.ContainsKey(label)) AndAlso label.Length < 18 Then
pt = New PointF With {
.X = pt.X - labelSize.Width / 2,
.Y = pt.Y - labelSize.Height
}
g.DrawString(label, labelFont, Brushes.Black, pt)
Else
Call anchors.Add(pt)
If images.ContainsKey(label) Then
Call New Label With {
.text = label,
.X = pt.X - labelSize.Width / 2, .Y = 0,
.width = labelSize.Width,
.height = labelSize.Height,
.pinned = False
}.DoCall(AddressOf labels.Add)
Else
Call New Label With {
.text = label,
.X = pt.X - labelSize.Width / 2, .Y = pt.Y + labelSize.Height,
.width = labelSize.Width,
.height = labelSize.Height,
.pinned = False
}.DoCall(AddressOf labels.Add)
End If
End If
Else
Call g.FillRectangle(barColor, bar)
End If
labels.Add(New Label With {.height = bar.Height, .pinned = True, .width = bar.Width, .X = bar.X, .Y = bar.Y})
anchors.Add(New Anchor)
If drawMzLabel Then
label = product.mz.ToString("F2")
labelSize = g.MeasureString(label, labelFont)
pt = bar.Location
pt = New PointF With {
.X = pt.X - labelSize.Width / 2,
.Y = pt.Y - labelSize.Height
}
Call g.DrawString(label, labelFont, Brushes.Black, pt)
Call labels.Add(New Label With {.height = labelSize.Height, .pinned = True, .width = labelSize.Width, .X = pt.X, .Y = pt.Y})
Call anchors.Add(New Anchor)
End If
Next
labelSize = g.MeasureString(title, titleFont)
Dim location As New PointF With {
.X = (canvas.Width - labelSize.Width) / 2,
.Y = (rect.Top - labelSize.Height) / 2
}
Call g.DrawString(title, titleFont, Brushes.Black, location)
Call d3js.forcedirectedLabeler(
ejectFactor:=2,
dist:=$"50,{canvas.Width / 2}",
condenseFactor:=100,
avoidRegions:={}' {New RectangleF(rect.Left, rect.Bottom - rect.Height * 0.2, rect.Width, rect.Height * 0.2)}
) _
.Labels(labels) _
.Anchors(anchors) _
.Width(rect.Width) _
.Height(rect.Height) _
.WithOffset(rect.Location) _
.Start(showProgress:=False, nsweeps:=2500)
Dim labelBrush As Brush = theme.tagColor.GetBrush
Dim labelConnector As Pen = Stroke.TryParse(theme.tagLinkStroke)
Dim connectorLead As Pen = Stroke.TryParse(theme.tagLinkStroke)
labelConnector.EndCap = LineCap.ArrowAnchor
For Each i As SeqValue(Of Label) In labels.SeqIterator
If i.value.pinned Then
Continue For
End If
Dim a As PointF = i.value.GetTextAnchor(anchors(i))
Dim b As PointF = anchors(i)
Dim c As New PointF With {.X = a.X - (a.X - b.X) * 0.65, .Y = a.Y}
If a.Y >= i.value.rectangle.Bottom Then
Call g.DrawLine(labelConnector, a, b)
Else
Call g.DrawLine(connectorLead, a, c)
Call g.DrawLine(labelConnector, c, b)
End If
If images.ContainsKey(i.value.text) Then
Call g.DrawImage(images(i.value.text).img, i.value.rectangle)
Else
Call g.DrawString(i.value.text, labelFont, labelBrush, i.value)
End If
Next
End Sub
Public Shared Function DrawSpectrumPeaks(matrix As LibraryMatrix,
Optional size$ = "1280,900",
Optional padding$ = "padding:200px 100px 85px 125px;",
Optional bg$ = "white",
Optional gridFill$ = "white",
Optional barHighlight$ = NameOf(Color.DarkRed),
Optional barStroke$ = "stroke: steelblue; stroke-width: 5px; stroke-dash: solid;",
Optional titleCSS$ = "font-style: normal; font-size: 16; font-family: " & FontFace.MicrosoftYaHei & ";",
Optional labelCSS$ = "font-style: normal; font-size: 8; font-family: " & FontFace.MicrosoftYaHei & ";",
Optional axisLabelCSS$ = "font-style: normal; font-size: 10; font-family: " & FontFace.MicrosoftYaHei & ";",
Optional axisTicksCSS$ = "font-style: normal; font-size: 10; font-family: " & FontFace.SegoeUI & ";",
Optional axisStroke$ = Stroke.AxisStroke,
Optional connectorStroke$ = "stroke: gray; stroke-width: 3.5px; stroke-dash: dash;",
Optional labelIntensity As Double = 0.2,
Optional images As Dictionary(Of String, Image) = Nothing,
Optional xlabel$ = "M/z ratio",
Optional ylabel$ = "Relative Intensity (%)") As GraphicsData
Dim theme As New Theme With {
.padding = padding,
.background = bg,
.gridFill = gridFill,
.lineStroke = barStroke,
.mainCSS = titleCSS,
.tagCSS = labelCSS,
.axisTickCSS = axisTicksCSS,
.axisStroke = axisStroke,
.axisLabelCSS = axisLabelCSS,
.tagLinkStroke = connectorStroke
}
Dim app As New PeakAssign(
title:=matrix.name,
matrix:=matrix.ms2,
barHighlight:=barHighlight,
labelIntensity:=labelIntensity,
theme:=theme,
images:=images
) With {
.xlabel = xlabel,
.ylabel = ylabel
}
Return app.Plot(size, ppi:=200)
End Function
End Class
|
xieguigang/MassSpectrum-toolkits
|
src/visualize/plot/PeakAssign.vb
|
Visual Basic
|
mit
| 15,431
|
Option Strict On
Option Explicit On
Option Infer Off
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
''' <summary>
''' A highly customizable calendar control. For interaction with individual calendar days, handle the Click, MouseEnter and MouseLeave events.
''' </summary>
Public NotInheritable Class CustomCalendar
Inherits ContainerControl
Implements IDisposable
#Region "Fields"
Private WHeader As WeekHeader
Private MHeader As MonthHeader
Private Const MaxSquares As Integer = 42
Private M As Integer = Date.Now.Month
Private SquareArr(41) As CalendarDay
Protected Friend DaysOfWeek(), MonthNames() As String
Private RHeight, CWidth, varSpacingX, varSpacingY, varMargins(3) As Integer
Private ParentContainer As Control
Private varAutoShrink As Boolean = True, varHideEmptyRows As Boolean = True
Private DictCustomStates As New Dictionary(Of Integer, CalendarDayStyle)
Private AppliedStylesList As New List(Of DateStylePair)
Private PrevStyle, CurrStyle, NextStyle As CalendarDayStyle
Public Shadows Event MouseEnter(Sender As CalendarDay)
Public Shadows Event MouseLeave(Sender As CalendarDay)
Public Shadows Event Click(Sender As CalendarDay)
Private IsDisplayed As Boolean
#End Region
#Region "Classes"
Private NotInheritable Class DateStylePair
Private varDate As Date
Private varStyleKey As Integer
Public Property MyDate As Date
Get
Return varDate
End Get
Set(value As Date)
varDate = value
End Set
End Property
Public Property StyleKey As Integer
Get
Return varStyleKey
End Get
Set(value As Integer)
varStyleKey = value
End Set
End Property
Public Sub New(MyDate As Date, StyleKey As Integer)
varDate = MyDate
varStyleKey = StyleKey
End Sub
End Class
Private NotInheritable Class WeekHeader
Implements IDisposable
Private WeekDays() As Label = {New Label, New Label, New Label, New Label, New Label, New Label, New Label}
Private WeekDaysString() As String = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
Private WithEvents ParentContainer As CustomCalendar
Private H As Integer
Private ColWidth As Integer
Private Sub ParentBGChanged() Handles ParentContainer.BackColorChanged
Dim BG As Color = ParentContainer.BackColor
For Each Lab As Label In WeekDays
Lab.BackColor = BG
Next
End Sub
Public Property Parent As CustomCalendar
Get
Return ParentContainer
End Get
Set(value As CustomCalendar)
ParentContainer = value
For i As Integer = 0 To 6
WeekDays(i).Parent = value
Next
SetDayNames()
End Set
End Property
Public ReadOnly Property Height As Integer
Get
Return H
End Get
End Property
''' <summary>
''' Gets the header label displaying the name of the specified day of the week.
''' </summary>
''' <param name="DayOfTheWeek">Zero-based index of the day of the week (Monday = 0)</param>
Public Function GetLabel(ByVal DayOfTheWeek As Integer) As Label
Return WeekDays(DayOfTheWeek)
End Function
Public Sub SetDayNames()
WeekDaysString = ParentContainer.DaysOfWeek
For i As Integer = 1 To 6
WeekDays(i - 1).Text = WeekDaysString(i)
Next
WeekDays(6).Text = WeekDaysString(0)
End Sub
Public Sub New(Parent As CustomCalendar, Left As Integer, Top As Integer, Spacing As Integer, Optional Width As Integer = 100, Optional ByVal Height As Integer = 100)
ColWidth = Width
H = Height
For i As Integer = 0 To 6
With WeekDays(i)
.Parent = Parent
.AutoSize = False
.TextAlign = ContentAlignment.MiddleCenter
.BackColor = Parent.BackColor
.Text = WeekDaysString(i)
.Width = ColWidth
.Left = Left + i * (Width + Spacing)
.Top = Top
End With
Next
ParentContainer = Parent
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
For i As Integer = 0 To 6
WeekDays(i).Dispose()
ParentContainer = Nothing
Next
End If
End If
disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
End Sub
#End Region
End Class
Private NotInheritable Class MonthHeader
Implements IDisposable
Protected Friend Enum MonthArrow
Left = 0
Right = 1
End Enum
#Region "Fields"
Private MLabel As Label
Private WithEvents ArrowLeft, ArrowRight As PictureBox
Private ParentControl As CustomCalendar
Private PointsL(), PointsR() As Point
Private CArrowDefault As Color = Color.FromArgb(0, 173, 185)
Private CArrowHover As Color = Color.FromArgb(0, 123, 135)
Private BrushL, BrushR As Brush
Public Event ArrowClicked(ByVal Arrow As MonthArrow)
#End Region
Public Property ArrowColorDefault As Color
Get
Return CArrowDefault
End Get
Set(value As Color)
CArrowDefault = value
BrushL.Dispose()
BrushR.Dispose()
BrushL = New SolidBrush(value)
BrushR = New SolidBrush(value)
ArrowLeft.Invalidate()
ArrowRight.Invalidate()
End Set
End Property
Public Property ArrowColorHover As Color
Get
Return CArrowHover
End Get
Set(value As Color)
CArrowHover = value
End Set
End Property
Public Property MonthString As String
Get
Return MLabel.Text
End Get
Set(value As String)
MLabel.Text = value
End Set
End Property
Public Sub New(Parent As CustomCalendar, ByVal Left As Integer, ByVal Top As Integer, ByVal Width As Integer, ByVal Height As Integer)
ParentControl = Parent
BrushL = New SolidBrush(ArrowColorDefault)
BrushR = New SolidBrush(ArrowColorDefault)
MLabel = New Label
ArrowLeft = New PictureBox
ArrowRight = New PictureBox
With MLabel
.Location = New Point(Left, Top)
.Size = New Size(Width, Height)
.TextAlign = ContentAlignment.MiddleCenter
.BackColor = Parent.BackColor
.Parent = Parent
.Text = Parent.MonthNames(Date.Now.Month - 1)
End With
With ArrowLeft
.Size = New Size(16, 16)
.Location = New Point(Left + (Width \ 2) - (.Width \ 2) - 50, Top + (Height \ 2) - (.Height \ 2))
.Parent = Parent
.BringToFront()
End With
With ArrowRight
.Size = New Size(16, 16)
.Location = New Point(Left + (Width \ 2) - (.Width \ 2) + 50, Top + (Height \ 2) - (.Height \ 2))
.Parent = Parent
.BringToFront()
End With
PointsL = {New Point(ArrowLeft.Width - 4, 0), New Point(ArrowLeft.Width - 4, ArrowLeft.Height), New Point(4, (ArrowLeft.Height \ 2))}
PointsR = {New Point(4, 0), New Point(4, ArrowRight.Height), New Point(12, (ArrowRight.Height \ 2))}
End Sub
Private Sub PaintLeftArrow(Sender As Object, e As PaintEventArgs) Handles ArrowLeft.Paint
e.Graphics.FillPolygon(BrushL, PointsL)
End Sub
Private Sub PaintRightArrow(Sender As Object, e As PaintEventArgs) Handles ArrowRight.Paint
e.Graphics.FillPolygon(BrushR, PointsR)
End Sub
Private Sub EnterLeft() Handles ArrowLeft.MouseEnter
BrushL.Dispose()
BrushL = New SolidBrush(CArrowHover)
ArrowLeft.Refresh()
End Sub
Private Sub LeaveLeft() Handles ArrowLeft.MouseLeave
BrushL.Dispose()
BrushL = New SolidBrush(CArrowDefault)
ArrowLeft.Refresh()
End Sub
Private Sub EnterRight() Handles ArrowRight.MouseEnter
BrushR.Dispose()
BrushR = New SolidBrush(CArrowHover)
ArrowRight.Refresh()
End Sub
Private Sub LeaveRight() Handles ArrowRight.MouseLeave
BrushR.Dispose()
BrushR = New SolidBrush(CArrowDefault)
ArrowRight.Refresh()
End Sub
Private Sub ClickLeft() Handles ArrowLeft.MouseDown
RaiseEvent ArrowClicked(MonthArrow.Left)
End Sub
Private Sub ClickRight() Handles ArrowRight.MouseDown
RaiseEvent ArrowClicked(MonthArrow.Right)
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
MLabel.Dispose()
ArrowLeft.Dispose()
ArrowRight.Dispose()
BrushL.Dispose()
BrushR.Dispose()
End If
End If
disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
End Sub
#End Region
End Class
Public NotInheritable Class CalendarDay
Inherits Label
Private LabWeek As New Label
Private GB As LinearGradientBrush
Private myDate As Date
Private DrawGrad As Boolean
Private varAppliedStyle As CalendarDayStyle
Public Area As CalendarArea = CalendarArea.Undefined
Public Property LastStyleApplied As CalendarDayStyle
Get
Return varAppliedStyle
End Get
Set(value As CalendarDayStyle)
varAppliedStyle = value
End Set
End Property
Public Sub SetColors(ByRef Style As CalendarDayStyle)
varAppliedStyle = Style
If DrawGrad Then
If GB IsNot Nothing Then
GB.Dispose()
End If
GB = New LinearGradientBrush(DisplayRectangle, Color.FromArgb(70, ColorHelper.FillRemainingRGB(Style.BackgroundColor, 0.7)), Color.Transparent, LinearGradientMode.Vertical)
End If
With Style
MyBase.BackColor = .BackgroundColor
LabWeek.BackColor = .BackgroundColor
LabWeek.ForeColor = .DayOfWeekColor
ForeColor = .DayColor
End With
End Sub
Public Shadows Property Parent As CustomCalendar
Get
Return DirectCast(MyBase.Parent, CustomCalendar)
End Get
Set(Parent As CustomCalendar)
MyBase.Parent = Parent
End Set
End Property
Public Property Day As Date
Get
Return myDate
End Get
Set(value As Date)
myDate = value
Text = CStr(value.Day)
Dim DayToUpper As String = Parent.DaysOfWeek(value.DayOfWeek).ToUpper
If LabWeek.Text <> DayToUpper Then
LabWeek.Text = DayToUpper
End If
End Set
End Property
Public Overrides Property BackColor As Color
Get
Return MyBase.BackColor
End Get
Set(value As Color)
If MyBase.BackColor <> value Then
If DrawGrad Then
If GB IsNot Nothing Then
GB.Dispose()
End If
GB = New LinearGradientBrush(DisplayRectangle, Color.FromArgb(70, ColorHelper.FillRemainingRGB(value, 0.7)), Color.Transparent, LinearGradientMode.Vertical)
End If
MyBase.BackColor = value
LabWeek.BackColor = BackColor
End If
End Set
End Property
Public Property DayOfWeekColor As Color
Get
Return LabWeek.ForeColor
End Get
Set(value As Color)
If LabWeek.ForeColor <> value Then
LabWeek.ForeColor = value
End If
End Set
End Property
Public Property DrawGradient As Boolean
Get
Return DrawGrad
End Get
Set(value As Boolean)
If value <> DrawGrad Then
DrawGrad = value
If DrawGrad Then
If GB IsNot Nothing Then
GB.Dispose()
End If
GB = New LinearGradientBrush(DisplayRectangle, Color.FromArgb(70, ColorHelper.FillRemainingRGB(BackColor, 0.7)), Color.Transparent, LinearGradientMode.Vertical)
End If
Invalidate()
End If
End Set
End Property
Public Sub New(Width As Integer, Height As Integer)
SuspendLayout()
ResizeRedraw = False
SetStyle(ControlStyles.UserPaint, True)
SetStyle(ControlStyles.AllPaintingInWmPaint, True)
SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
DoubleBuffered = True
AutoSize = False
With Me
.Size = New Size(Width, Height)
.TextAlign = ContentAlignment.MiddleCenter
.Font = New Font(.Font.FontFamily, 20, FontStyle.Bold)
End With
With LabWeek
.Parent = Me
.BackColor = BackColor
.AutoSize = False
.Size = New Size(Width, Height \ 4)
.TextAlign = ContentAlignment.MiddleCenter
.Font = New Font(.Font.FontFamily, 6, FontStyle.Bold)
.BringToFront()
End With
ResumeLayout()
End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
If DrawGrad Then
e.Graphics.FillRectangle(GB, ClientRectangle)
End If
MyBase.OnPaint(e)
End Sub
Protected Overloads Overrides Sub Dispose(disposing As Boolean)
LabWeek.Dispose()
If GB IsNot Nothing Then
GB.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
End Class
Public Enum CalendarArea
Undefined = 0
PreviousMonth = 1
CurrentMonth = 2
NextMonth = 3
End Enum
Public Class CalendarDayStyle
Private DColor, BGColor, WColor As Color
Public Sub New(ByVal DayColor As Color, ByVal BackgroundColor As Color, ByVal DayOfWeekColor As Color)
DColor = DayColor
BGColor = BackgroundColor
WColor = DayOfWeekColor
End Sub
Public Property DayColor As Color
Get
Return DColor
End Get
Set(value As Color)
DColor = value
End Set
End Property
Public Property BackgroundColor As Color
Get
Return BGColor
End Get
Set(value As Color)
BGColor = value
End Set
End Property
Public Property DayOfWeekColor As Color
Get
Return WColor
End Get
Set(value As Color)
WColor = value
End Set
End Property
End Class
#End Region
''' <summary>
''' Replaces the default names for Monday through Sunday with the specified string array.
''' </summary>
''' <param name="Names">An array of string representing the days of the week, starting with Sunday and ending with Saturday.</param>
''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify False if several methods with this optional parameter are called in succession</param>
Public Sub SetDayNames(Names() As String, Optional Refresh As Boolean = True)
DaysOfWeek = Names
If Refresh Then
RefreshCalendar()
End If
End Sub
''' <summary>
''' Applies the specified custom style (that has been added using the
''' </summary>
''' <param name="Dates"></param>
''' <param name="StyleKey"></param>
''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify False if several methods with this optional parameter are called in succession</param>
Public Sub ApplyCustomStyle(Dates() As Date, StyleKey As Integer, Optional Refresh As Boolean = True)
For Each D As Date In Dates
AppliedStylesList.Add(New DateStylePair(D, StyleKey))
Next
If Refresh Then
RefreshCalendar()
End If
End Sub
''' <summary>
''' Use this method if all dates with a given custom style should be reset to the default style.
''' </summary>
''' <param name="StyleKey"></param>
''' <param name="RemoveFromDictionary">If true, removes the custom style from the dictionary. If the style is to be used again, it must be added again.</param>
''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify False if several methods with this optional parameter are called in succession</param>
Public Overloads Sub RemoveCustomStyle(StyleKey As Integer, Optional RemoveFromDictionary As Boolean = False, Optional Refresh As Boolean = True)
Dim iLast As Integer = AppliedStylesList.Count - 1
For i As Integer = iLast To 0 Step -1
With AppliedStylesList(i)
If .StyleKey = StyleKey Then
AppliedStylesList.RemoveAt(i)
End If
End With
Next
If RemoveFromDictionary Then
DictCustomStates.Remove(StyleKey)
End If
If Refresh Then
RefreshCalendar()
End If
End Sub
''' <summary>
''' Use this (slow) method if only some dates with a given style should be reset to the default style.
''' </summary>
''' <param name="Dates">The dates that have a custom style applied to them that should be removed.</param>
''' ''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify False if several methods with this optional parameter are called in succession</param>
Public Overloads Sub RemoveCustomStyle(Dates() As Date, Optional Refresh As Boolean = True)
Dim DatesList As List(Of Date) = Dates.ToList
DatesList.Capacity = Dates.Length
Dim Matches As List(Of DateStylePair) = AppliedStylesList.FindAll(Function(Pair As DateStylePair) As Boolean
Dim iLast As Integer = DatesList.Count - 1
For i As Integer = 0 To iLast
With Pair
If .MyDate.Date = DatesList(i).Date Then
DatesList.RemoveAt(i)
Return True
Exit For
End If
End With
Next
Return False
End Function)
If Matches IsNot Nothing Then
For Each Match As DateStylePair In Matches
Match = Nothing
Next
End If
Dim nLast As Integer = AppliedStylesList.Count - 1
If nLast >= 0 Then
For n As Integer = nLast To 0 Step -1
If AppliedStylesList(n) Is Nothing Then
AppliedStylesList.RemoveAt(n)
End If
Next
End If
If Refresh Then
RefreshCalendar()
End If
End Sub
''' <summary>
''' Shows the calendar without calling the Display method. Stylistic changes to the calendar only get applied if the Display method has been shown.
''' </summary>
''' <param name="Refresh">Specifies whether or not to call the RefreshCalendar method. Specify True if stylistic changes have been made to the calendar while it was hidden.</param>
''' <param name="SuppressDisplay">Specifies whether or not to display the form if it has not already been displayed (not recommended).</param>
Public Shadows Sub Show(Refresh As Boolean, Optional SuppressDisplay As Boolean = False)
If IsDisplayed Then
If Refresh Then
RefreshCalendar()
End If
MyBase.Show()
ElseIf Not SuppressDisplay Then
Display()
End If
End Sub
''' <summary>
''' If the Display method has not yet been called, displays the calendar. If the Display method has been called, shows the calendar without calling RefreshCalendar.
''' </summary>
Public Shadows Sub Show()
If IsDisplayed Then
MyBase.Show()
Else
Display()
End If
End Sub
''' <summary>
''' Applies changes and displays the calendar. Call this method the first time the calendar is shown. Changes to the calendar may not display correctly unless this method has been called.
''' </summary>
Public Sub Display()
IsDisplayed = True
RefreshCalendar()
MyBase.Show()
End Sub
Private Shadows Sub OnMouseEnter(Sender As Object, e As EventArgs)
RaiseEvent MouseEnter(DirectCast(Sender, CalendarDay))
End Sub
Private Shadows Sub OnMouseLeave(Sender As Object, e As EventArgs)
RaiseEvent MouseLeave(DirectCast(Sender, CalendarDay))
End Sub
Private Shadows Sub OnClick(Sender As Object, e As EventArgs)
RaiseEvent Click(DirectCast(Sender, CalendarDay))
End Sub
''' <summary>
''' Gets or sets the color of the next and previous buttons when they are not hovered.
''' </summary>
Public Property ArrowColorDefault As Color
Get
Return MHeader.ArrowColorDefault
End Get
Set(value As Color)
MHeader.ArrowColorDefault = value
End Set
End Property
''' <summary>
''' Gets or sets the color of the next and previous buttons when they are hovered.
''' </summary>
Public Property ArrowColorHover As Color
Get
Return MHeader.ArrowColorHover
End Get
Set(value As Color)
MHeader.ArrowColorHover = value
End Set
End Property
''' <summary>
''' Gets the number of the currently displaying month, or sets which month to display.
''' </summary>
''' <returns>An integer value between 1 and 12 (inclusive).</returns>
Public Property CurrentMonth As Integer
Get
Return M
End Get
Set(value As Integer)
If value >= 1 AndAlso value <= 12 Then
M = value
RefreshCalendar()
End If
End Set
End Property
Public Sub New(PreviousMonthStyle As CalendarDayStyle, CurrentMonthStyle As CalendarDayStyle, NextMonthStyle As CalendarDayStyle, Left As Integer, ByVal Top As Integer, Optional ByVal ColumnWidth As Integer = 100, Optional ByVal RowHeight As Integer = 100, Optional ByVal SpacingX As Integer = 20, Optional ByVal SpacingY As Integer = 20, Optional ByVal HeaderMarginBottom As Integer = 10, Optional ByVal HeaderHeight As Integer = 30, Optional WeekDays() As String = Nothing, Optional Months() As String = Nothing)
Hide()
Dim StylesArr(2) As CalendarDayStyle
StylesArr(0) = PreviousMonthStyle
StylesArr(1) = CurrentMonthStyle
StylesArr(2) = NextMonthStyle
Location = New Point(Left, Top)
CommonNew(ColumnWidth, SpacingX, SpacingY, RowHeight, HeaderHeight, StylesArr, WeekDays, Months)
End Sub
Public Sub New(Left As Integer, ByVal Top As Integer, Optional ByVal ColumnWidth As Integer = 100, Optional ByVal RowHeight As Integer = 100, Optional ByVal SpacingX As Integer = 20, Optional ByVal SpacingY As Integer = 20, Optional ByVal HeaderMarginBottom As Integer = 10, Optional ByVal HeaderHeight As Integer = 30, Optional WeekDays() As String = Nothing, Optional Months() As String = Nothing)
Hide()
Dim StylesArr(2) As CalendarDayStyle
StylesArr(0) = New CalendarDayStyle(Color.White, Color.LightGray, Color.White)
StylesArr(1) = New CalendarDayStyle(Color.White, Color.FromArgb(0, 173, 185), Color.White)
StylesArr(2) = New CalendarDayStyle(Color.White, Color.LightGray, Color.White)
Location = New Point(Left, Top)
CommonNew(ColumnWidth, SpacingX, SpacingY, RowHeight, HeaderHeight, StylesArr, WeekDays, Months)
End Sub
Private Sub CommonNew(ByVal ColumnWidth As Integer, ByVal SpacingX As Integer, ByVal SpacingY As Integer, ByVal RowHeight As Integer, ByVal HeaderHeight As Integer, Styles() As CalendarDayStyle, WeekDays() As String, Months() As String)
SetStyle(ControlStyles.UserPaint, True)
SetStyle(ControlStyles.AllPaintingInWmPaint, True)
SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
DoubleBuffered = True
ResizeRedraw = False
If WeekDays Is Nothing Then
WeekDays = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
End If
If Months Is Nothing Then
Months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
End If
PrevStyle = Styles(0)
CurrStyle = Styles(1)
NextStyle = Styles(2)
DaysOfWeek = WeekDays
MonthNames = Months
MHeader = New MonthHeader(Me, Left, Top, (ColumnWidth * 7) + (SpacingX * 6), 50)
AddHandler MHeader.ArrowClicked, AddressOf OnArrowClicked
WHeader = New WeekHeader(Me, Left, Top + 50, SpacingX, ColumnWidth, HeaderHeight) ' Legg til alle de andre parameterne også
RHeight = RowHeight
CWidth = ColumnWidth
varSpacingX = SpacingX
varSpacingY = SpacingY
BuildSquares()
End Sub
''' <summary>
''' Specifies whether or not the SizeToContent method should be automatically called as necessary.
''' </summary>
Public Property AutoShrink As Boolean
Get
Return varAutoShrink
End Get
Set(value As Boolean)
varAutoShrink = value
If value Then
SizeToContent()
End If
End Set
End Property
''' <summary>
''' Sets the width and height of the calendar to the right and bottom edges of its elements.
''' </summary>
Public Sub SizeToContent()
Dim CalcHeight As Integer
If varAutoShrink Then
With SquareArr(41)
If .Visible Then
CalcHeight = .Bottom
Else
CalcHeight = SquareArr(41 - 7).Bottom
End If
End With
Else
CalcHeight = SquareArr(41).Bottom
End If
With Me
.Width = SquareArr(6).Right
.Height = CalcHeight
End With
End Sub
Private Sub OnArrowClicked(Arrow As MonthHeader.MonthArrow)
Select Case Arrow
Case MonthHeader.MonthArrow.Left
PreviousMonth()
Case MonthHeader.MonthArrow.Right
NextMonth()
End Select
End Sub
''' <summary>
''' Applies changes to the calendar. Call this method only if exceptional circumstances causes the calendar to display incorrectly.
''' </summary>
Public Sub RefreshCalendar()
If IsDisplayed Then
SuspendLayout()
Hide()
MHeader.MonthString = MonthNames(M - 1)
Dim D As New Date(Date.Now.Year, M, 1)
Dim DInt As Integer = D.DayOfWeek
If DInt = 0 Then
DInt = 7
End If
Dim DaysInMonthPrevious As Integer
If D.Month > 1 Then
DaysInMonthPrevious = Date.DaysInMonth(D.Year, D.Month - 1)
Else
DaysInMonthPrevious = Date.DaysInMonth(D.Year - 1, 12)
End If
Dim DaysInMonthPreviousYear As Integer = Date.DaysInMonth(D.Year - 1, 12)
Dim DaysInMonthCurrent As Integer = Date.DaysInMonth(D.Year, M)
Dim DYear As Integer = D.Year
Dim DMonth As Integer = D.Month
Dim Day As Integer
For i As Integer = 1 To MaxSquares
If i < DInt Then
With SquareArr(i - 1)
.Area = CalendarArea.PreviousMonth
If D.Month > 1 Then
Day = DaysInMonthPrevious - DInt + i + 1
.Day = New Date(DYear, DMonth - 1, Day)
Else
Day = DaysInMonthPreviousYear - DInt + i + 1
.Day = New Date(DYear - 1, 12, Day)
End If
End With
ElseIf i - DInt < DaysInMonthCurrent Then
Day = i - DInt + 1
With SquareArr(i - 1)
.Area = CalendarArea.CurrentMonth
.Day = New Date(DYear, DMonth, Day)
End With
Else
Day = i - (DaysInMonthCurrent + DInt) + 1
With SquareArr(i - 1)
.Area = CalendarArea.NextMonth
If D.Month < 12 Then
.Day = New Date(DYear, DMonth + 1, Day)
Else
.Day = New Date(DYear + 1, 1, Day)
End If
End With
End If
Next
Dim LastRowStart As Integer = 7 * 5
Dim LastDayIndex As Integer = DInt + DaysInMonthCurrent - 2
If Not SquareArr(0).Visible Then
For i As Integer = 0 To LastRowStart - 1
SquareArr(i).Show()
Next
End If
If LastDayIndex < LastRowStart AndAlso varHideEmptyRows Then
For i As Integer = LastRowStart To MaxSquares - 1
SquareArr(i).Hide()
Next
ElseIf Not SquareArr(MaxSquares - 1).Visible Then
For i As Integer = LastRowStart To MaxSquares - 1
SquareArr(i).Show()
Next
End If
For i As Integer = 0 To 41
With SquareArr(i)
Select Case .Area
Case CalendarArea.CurrentMonth
.SetColors(CurrStyle)
Case CalendarArea.PreviousMonth
.SetColors(PrevStyle)
Case CalendarArea.NextMonth
.SetColors(NextStyle)
End Select
End With
Next
For i As Integer = 0 To 41
With SquareArr(i)
Dim SquareDate As Date = .Day
Dim Match As DateStylePair = AppliedStylesList.Find(Function(Pair As DateStylePair) As Boolean
With Pair.MyDate
If .Date = SquareDate.Date Then
Return True
Else
Return False
End If
End With
End Function)
If Match IsNot Nothing Then
Dim Style As CalendarDayStyle = DictCustomStates(Match.StyleKey)
If Style IsNot Nothing Then
.SetColors(Style)
End If
End If
End With
Next
WHeader.SetDayNames()
If varAutoShrink Then
SizeToContent()
End If
ResumeLayout(True)
Show()
Refresh()
End If
End Sub
Private Sub BuildSquares()
SuspendLayout()
Dim WHeight As Integer = WHeader.Height
Dim Counter As Integer = 0
For n As Integer = 0 To 5
For i As Integer = 0 To 6
Dim Square As New CalendarDay(CWidth, RHeight)
With Square
.Location = New Point(Left + i * (varSpacingX + CWidth), WHeight + Top + n * (varSpacingY + RHeight) + 50)
.Tag = (n + 1) * (i + 1)
.Parent = Me
End With
AddHandler Square.MouseEnter, AddressOf OnMouseEnter
AddHandler Square.MouseLeave, AddressOf OnMouseLeave
AddHandler Square.Click, AddressOf OnClick
SquareArr(Counter) = Square
Counter += 1
Next
Next
'RefreshCalendar()
ResumeLayout(True)
End Sub
''' <summary>
''' Specifies whether or not to draw subtle gradients on the Calendar's days. The initial and final color are determined by the CalendarDay's BackColor property. Default = False.
''' </summary>
Public WriteOnly Property DrawGradient As Boolean
Set(value As Boolean)
For i As Integer = 0 To 41
SquareArr(i).DrawGradient = value
Next
End Set
End Property
Private Sub NextMonth()
CurrentMonth += 1
End Sub
Private Sub PreviousMonth()
CurrentMonth -= 1
End Sub
''' <summary>
''' Gets the CalendarDay control currently representing the specified date.
''' </summary>
''' <returns>The CalendarDay displaying the specified date, or Nothing if the date is not included in the current view.</returns>
Public Overloads ReadOnly Property Day(ByVal DayDate As Date) As CalendarDay
Get
For i As Integer = 0 To 41
With SquareArr(i).Day
If .Date = DayDate.Date Then
Return SquareArr(i)
End If
End With
Next
Return Nothing
End Get
End Property
''' <summary>
''' Gets the CalendarDay at the specified index (going left to right, including days in the previous and next month's area, if any).
''' </summary>
''' <param name="Index">An integer value between 0 and 41 inclusive.</param>
''' <returns>The CalendarDay at the specified index (going left to right, including days in the previous and next month's area, if any).</returns>
Public Overloads ReadOnly Property Day(ByVal Index As Integer) As CalendarDay
Get
Return SquareArr(Index)
End Get
End Property
''' <summary>
''' Gets an array of all 42 CalendarDay controls, which include both visible and hidden days.
''' </summary>
''' <returns></returns>
Public ReadOnly Property Days As CalendarDay()
Get
Return SquareArr
End Get
End Property
''' <summary>
''' Adds the specified custom style to a dictionary, so that it can be applied with the specified key using the ApplyCustomStyle method.
''' </summary>
''' <param name="Key">A unique key that can be used to identify the style when it is applied.</param>
''' <param name="Style">The style to be applied to specific dates.</param>
Public Sub AddCustomStyle(Key As Integer, Style As CalendarDayStyle)
DictCustomStates.Add(Key, Style)
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean
Protected Overrides Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
RemoveHandler MHeader.ArrowClicked, AddressOf OnArrowClicked
MHeader.Dispose()
WHeader.Dispose()
For i As Integer = 0 To MaxSquares - 1
RemoveHandler SquareArr(i).MouseEnter, AddressOf OnMouseEnter
RemoveHandler SquareArr(i).MouseLeave, AddressOf OnMouseLeave
RemoveHandler SquareArr(i).Click, AddressOf OnClick
SquareArr(i).Dispose()
Next
SquareArr = Nothing
End If
End If
disposedValue = True
MyBase.Dispose(disposing)
End Sub
#End Region
End Class
|
Audiopolis/Gruppe21-prosjekt
|
AudiopoLib/AudiopoLib/CustomCalendar.vb
|
Visual Basic
|
mit
| 38,802
|
'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 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("AngleAngleVB")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("AngleAngleVB")>
<Assembly: AssemblyCopyright("Copyright © 2009")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(True)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("bbcb0f31-4207-4e0b-8229-0ead8f9a0eb9")>
' 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")>
|
Esri/arcobjects-sdk-community-samples
|
Net/Editing/AngleAngleConstructor/VBNet/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,695
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class CryptForm
Inherits DevExpress.XtraEditors.XtraForm
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.MemoEdit1 = New DevExpress.XtraEditors.MemoEdit()
CType(Me.MemoEdit1.Properties, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'MemoEdit1
'
Me.MemoEdit1.Location = New System.Drawing.Point(12, 12)
Me.MemoEdit1.Name = "MemoEdit1"
Me.MemoEdit1.Size = New System.Drawing.Size(400, 315)
Me.MemoEdit1.TabIndex = 0
'
'CryptForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(720, 433)
Me.Controls.Add(Me.MemoEdit1)
Me.Name = "CryptForm"
Me.Text = "CryptForm"
CType(Me.MemoEdit1.Properties, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents MemoEdit1 As MemoEdit
End Class
|
bigbhe/1310
|
SROI-SKRIPSI/Form/CryptForm.Designer.vb
|
Visual Basic
|
apache-2.0
| 1,784
|
Namespace Win32Manager
Public Class Win32ManageAdapter
Public Shared Function GetTargetAllInfo(ByVal target As String) As List(Of Dictionary(Of String, Object))
Dim listR As List(Of Dictionary(Of String, Object)) = Nothing
Using searcher As New Management.ManagementObjectSearcher()
searcher.Query.QueryString = "SELECT * FROM " & target.ToString()
Dim re As Management.ManagementObjectCollection = searcher.Get()
If (Not re Is Nothing AndAlso re.Count > 0) Then
listR = New List(Of Dictionary(Of String, Object))()
For Each o As Management.ManagementObject In re
Dim dic As New Dictionary(Of String, Object)
For Each p In o.Properties
dic.Add(p.Name, p.Value)
Next
listR.Add(dic)
Next
End If
End Using
Return listR
End Function
End Class
Namespace Win32Classes
Namespace ComputerSystemHardware
Public Class CoolingDevice
End Class
''' <summary>
''' 输入设备
''' </summary>
Public Class InputDevice
Public Const Win32_Keyboard = "Win32_Keyboard"
Public Const Win32_PointingDevice = "Win32_PointingDevice "
End Class
''' <summary>
''' Classes in the Mass Storage subcategory represent storage devices such as hard disk drives, CD-ROM drives, and tape drives.
''' </summary>
Public Class MassStorage
'' <summary>Represents the settings for the autocheck operation of a disk.</summary>
Public Const Win32_AutochkSetting = "Win32_AutochkSetting"
'' <summary>Represents a CD-ROM drive on a computer system running Windows.</summary>
Public Const Win32_CDROMDrive = "Win32_CDROMDrive"
'' <summary>Represents a physical disk drive as seen by a computer running the Windows operating system.</summary>
Public Const Win32_DiskDrive = "Win32_DiskDrive"
'' <summary>Manages the capabilities of a floppy disk drive.</summary>
Public Const Win32_FloppyDrive = "Win32_FloppyDrive"
'' <summary>Represents any type of documentation or storage medium.</summary>
Public Const Win32_PhysicalMedia = "Win32_PhysicalMedia"
'' <summary>Represents a tape drive on a computer system running Windows.</summary>
Public Const Win32_TapeDrive = "Win32_TapeDrive"
End Class
End Namespace
End Namespace
Public Class Win32Classess
Public Class ComputerSystemHardware
End Class
End Class
' Public Enum Win32Classes
' Win32_1394Controller
' Win32_1394ControllerDevice
' Win32_Fan
' Win32_HeatPipe
' Win32_Refrigeration
' Win32_TemperatureProbe
' Win32_AssociatedProcessorMemory
' Win32_AutochkSetting
' Win32_BaseBoard
' Win32_Battery
' Win32_BIOS
' Win32_Bus
' Win32_CacheMemory
' Win32_CDROMDrive
' Win32_CIMLogicalDeviceCIMDataFile
' Win32_ComputerSystemProcessor
' Win32_CurrentProbe
' Win32_DesktopMonitor
' Win32_DeviceBus
' Win32_DeviceChangeEvent
' Win32_DeviceMemoryAddress
' Win32_DeviceSettings
' Win32_DiskDrive
' Win32_DiskDriveToDiskPartition
' Win32_DiskPartition
' Win32_DisplayControllerConfiguration
' Win32_DMAChannel
' Win32_DriverForDevice
' Win32_FloppyController
' Win32_FloppyDrive
' Win32_IDEController
' Win32_IDEControllerDevice
' Win32_InfraredDevice
' Win32_IRQResource
' Win32_Keyboard
' Win32_LogicalDisk
' Win32_LogicalDiskRootDirectory
' Win32_LogicalDiskToPartition
' Win32_LogicalProgramGroup
' Win32_LogicalProgramGroupDirectory
' Win32_LogicalProgramGroupItem
' Win32_LogicalProgramGroupItemDataFile
' Win32_MappedLogicalDisk
' Win32_MemoryArray
' Win32_MemoryArrayLocation
' Win32_MemoryDevice
' Win32_MemoryDeviceArray
' Win32_MemoryDeviceLocation
' Win32_MotherboardDevice
' Win32_NetworkAdapter
' Win32_NetworkAdapterConfiguration
' Win32_NetworkAdapterSetting
' Win32_NetworkClient
' Win32_NetworkConnection
' Win32_NetworkLoginProfile
' Win32_NetworkProtocol
' Win32_OnBoardDevice
' Win32_ParallelPort
' Win32_PCMCIAController
' Win32_PhysicalMemory
' Win32_PhysicalMemoryArray
' Win32_PhysicalMemoryLocation
' Win32_PnPAllocatedResource
' Win32_PnPDevice
' Win32_PnPDeviceProperty
' Win32_PnPDevicePropertyUint8
' Win32_PnPDevicePropertyUint16
' Win32_PnPDevicePropertyUint32
' Win32_PnPDevicePropertyUint64
' Win32_PnPDevicePropertySint8
' Win32_PnPDevicePropertySint16
' Win32_PnPDevicePropertySint32
' Win32_PnPDevicePropertySint64
' Win32_PnPDevicePropertyString
' Win32_PnPDevicePropertyBoolean
' Win32_PnPDevicePropertyReal32
' Win32_PnPDevicePropertyReal64
' Win32_PnPDevicePropertyDateTime
' Win32_PnPDevicePropertySecurityDescriptor
' Win32_PnPDevicePropertyBinary
' Win32_PnPDevicePropertyUint16Array
' Win32_PnPDevicePropertyUint32Array
' Win32_PnPDevicePropertyUint64Array
' Win32_PnPDevicePropertySint8Array
' Win32_PnPDevicePropertySint16Array
' Win32_PnPDevicePropertySint32Array
' Win32_PnPDevicePropertySint64Array
' Win32_PnPDevicePropertyStringArray
' Win32_PnPDevicePropertyBooleanArray
' Win32_PnPDevicePropertyReal32Array
' Win32_PnPDevicePropertyReal64Array
' Win32_PnPDevicePropertyDateTimeArray
' Win32_PnPDevicePropertySecurityDescriptorArray
' Win32_PnPEntity
' Win32_PointingDevice
' Win32_PortableBattery
' Win32_PortConnector
' Win32_PortResource
' Win32_POTSModem
' Win32_POTSModemToSerialPort
' Win32_Printer
' Win32_PrinterConfiguration
' Win32_PrinterController
' Win32_PrinterDriver
' Win32_PrinterDriverDll
' Win32_PrinterSetting
' Win32_PrinterShare
' Win32_PrintJob
' Win32_Processor
' Win32_SCSIController
' Win32_SCSIControllerDevice
' Win32_SerialPort
' Win32_SerialPortConfiguration
' Win32_SerialPortSetting
' Win32_SMBIOSMemory
' Win32_SoundDevice
' Win32_TapeDrive
' Win32_TCPIPPrinterPort
' Win32_USBController
' Win32_USBControllerDevice
' Win32_VideoController
' Win32_VideoSettings
' Win32_VoltageProbe
'End Enum
End Namespace
|
sugartomato/AllProjects
|
ZS.Common/ZS.Common/Win32Manager.vb
|
Visual Basic
|
apache-2.0
| 7,128
|
Imports bv.winclient.Core
Imports System.Linq
Imports System.Collections.Generic
Imports System.ComponentModel
Imports EIDSS.model.Resources
Imports DevExpress.XtraGrid
Namespace ActiveSurveillance
Public Class AsSamplesPanel
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
If WinUtils.IsComponentInDesignMode(Me) Then
Return
End If
DbService = New AsSessionSamples_DB
' Add any initialization after the InitializeComponent() call.
Me.colSampleCondition.Visible = False
Me.colAnimal.Visible = False
Me.colSpecies.Visible = False
Me.colAccessionedDate.Visible = False
Me.colConditionReceived.Visible = False
Me.colVectorID.Visible = False
Me.colVectorType.Visible = False
SamplesView.OptionsView.ColumnAutoWidth = True
Me.SamplesGrid.Width = SamplesGrid.Parent.ClientSize.Width - SamplesGrid.Left - 4
Me.SamplesGrid.Height = SamplesGrid.Parent.ClientSize.Height - SamplesGrid.Top - 4
DefaultPartyID = Nothing
End Sub
Public Function CanDeleteParty(ByVal partyID As Object) As Boolean
If Utils.IsEmpty(partyID) Then
Return True
End If
If baseDataSet.Tables(CaseSamples_Db.TableSamples).Select(String.Format("idfParty = {0} and Used = 1", partyID.ToString)).Length > 0 Then
Return False
End If
Return True
End Function
Public Property SupressRowValidation As Boolean
Overrides Function IsCurrentSpecimenRowValid(Optional ByVal index As Integer = -1, Optional ByVal showError As Boolean = True) As Boolean
If SupressRowValidation Then
SupressRowValidation = False
Return True
End If
Dim row As DataRow
If index = -1 Then
row = SamplesGridView.GetFocusedDataRow()
Else
row = SamplesGridView.GetDataRow(index)
End If
If Not MyBase.IsCurrentSpecimenRowValid(index, showError) Then
InvalidSample = row
Return False
End If
If (index = GridControl.InvalidRowHandle) Then
Return True
End If
If Not row Is Nothing Then
If HasDuplicates(row) Then
If showError Then
MessageForm.Show(EidssMessages.Get("AsSession.DetailsTableView.DuplicateSample"))
End If
InvalidSample = row
Return False
End If
Dim errMsg As String = String.Empty
If Not AsSession.ValidateCollectionDate(row("datFieldCollectionDate"), errMsg, showError) Then
InvalidSample = row
Return False
End If
End If
Return True
End Function
Public Property InvalidSample As DataRow
Private Function HasDuplicates(ByVal samples As IEnumerable(Of DataRow)) As Boolean
Dim hash As New HashSet(Of DataRow)(New SampleComparer())
For Each sample As DataRow In samples
If Not hash.Add(sample) Then
InvalidSample = sample
Return True
End If
Next
Return False
End Function
Private Function HasDuplicates(ByVal sampleRow As DataRow) As Boolean
If sampleRow Is Nothing OrElse sampleRow.RowState = DataRowState.Deleted OrElse sampleRow.RowState = DataRowState.Detached Then
Return False
End If
If Utils.IsEmpty(sampleRow("strFieldBarcode")) Then
Return False
End If
If baseDataSet.Tables(CaseSamples_Db.TableSamples).Select( _
String.Format("idfParty = {0} and idfsSampleType={1} and strFieldBarcode = '{2}' and idfMaterial<> {3} ", _
sampleRow("idfParty"), sampleRow("idfsSampleType"), sampleRow("strFieldBarcode"), sampleRow("idfMaterial"))).Length > 0 Then
InvalidSample = sampleRow
Return True
End If
Return False
End Function
Public Overrides Function ValidateData() As Boolean
If MyBase.ValidateData() = False Then
Return False
End If
If HasDuplicates(baseDataSet.Tables(CaseSamples_Db.TableSamples).AsEnumerable()) Then
MessageForm.Show(EidssMessages.Get("AsSession.DetailsTableView.DuplicateSample"))
Return False
End If
Return True
End Function
Protected Overrides Function ShowEditor(ByVal row As DataRow) As Boolean
If (SamplesGridView.FocusedColumn.Name = Me.colSampleCondition.Name) Then
Return False
End If
Return MyBase.ShowEditor(row)
End Function
<Browsable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Overrides Property DefaultPartyID() As Object
Get
Return MyBase.DefaultPartyID
End Get
Set(ByVal Value As Object)
MyBase.DefaultPartyID = Value
UpdateButtons()
btnNewSpecimen.Enabled = Not [ReadOnly] AndAlso Not Utils.IsEmpty(Value)
End Set
End Property
Public Overrides Sub UpdateButtons()
Dim specimenSelected As Boolean = Not SamplesGridView.GetDataRow(SamplesGridView.FocusedRowHandle) Is Nothing
btnDeleteSpecimen.Enabled = Not [ReadOnly] AndAlso specimenSelected
EnableSampleAdding(Not [ReadOnly] AndAlso Not Utils.IsEmpty(DefaultPartyID) AndAlso IsCurrentSpecimenRowValid(, False))
End Sub
Private ReadOnly Property AsSession As AsSessionDetail
Get
Return CType(BaseForm.FindBaseForm(Me), AsSessionDetail)
End Get
End Property
Protected Overrides Sub UpdatePartyInfo(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
MyBase.UpdatePartyInfo(sender, e)
Dim materialRow As DataRow = e.Row
Dim animalRow As DataRow = FindRow(CType(cbAnimalLookup.DataSource, DataView).Table, materialRow("idfParty"), "idfAnimal")
If Not animalRow Is Nothing Then
materialRow("strFarmCode") = animalRow("strFarmCode")
End If
End Sub
Public Class SampleComparer
Implements IEqualityComparer(Of DataRow)
Public Overloads Function Equals(
ByVal x As DataRow,
ByVal y As DataRow
) As Boolean Implements IEqualityComparer(Of DataRow).Equals
' Check whether the compared objects reference the same data.
If x Is y Then Return True
If x.RowState = DataRowState.Deleted OrElse x.RowState = DataRowState.Detached OrElse y.RowState = DataRowState.Deleted OrElse y.RowState = DataRowState.Detached Then
Return False
End If
'Check whether any of the compared objects is null.
If x Is Nothing OrElse y Is Nothing Then Return False
If Utils.IsEmpty(x("strFieldBarcode")) OrElse Utils.IsEmpty(x("strFieldBarcode")) Then Return False
' Check whether the products' properties are equal.
Return x("idfParty").Equals(y("idfParty")) AndAlso x("idfsSampleType").Equals(y("idfsSampleType")) AndAlso x("strFieldBarcode").Equals(y("strFieldBarcode"))
End Function
Public Overloads Function GetHashCode(ByVal sample As DataRow) As Integer Implements IEqualityComparer(Of DataRow).GetHashCode
' Check whether the object is null.
If sample Is Nothing Then Return 0
If sample.RowState = DataRowState.Deleted OrElse sample.RowState = DataRowState.Detached Then
Return 0
End If
' Get hash code for the Name field if it is not null.
Return sample("idfParty").GetHashCode() Xor sample("idfsSampleType").GetHashCode() Xor sample("strFieldBarcode").GetHashCode()
End Function
End Class
End Class
End Namespace
|
EIDSS/EIDSS-Legacy
|
EIDSS v6/vb/EIDSS/EIDSS_Vet/ActiveSurveillance/AsSamplesPanel.vb
|
Visual Basic
|
bsd-2-clause
| 8,783
|
'*******************************************************************************************'
' '
' 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.PDF
''' <summary>
''' This example demonstrates how to add an audio annotaion.
''' </summary>
Class Program
Shared Sub Main()
' Create new document
Dim pdfDocument = New Document()
pdfDocument.RegistrationName = "demo"
pdfDocument.RegistrationKey = "demo"
' Add page
Dim page = New Page(PaperFormat.A4)
pdfDocument.Pages.Add(page)
' Add sound annotation
Dim sound = New Sound("sample.wav")
Dim soundAnnotation = New SoundAnnotation(sound, 20, 20, 20, 20)
page.Annotations.Add(soundAnnotation)
' Save document to file
pdfDocument.Save("result.pdf")
' Cleanup
pdfDocument.Dispose()
' Open document in default PDF viewer app
Process.Start("result.pdf")
End Sub
End Class
|
bytescout/ByteScout-SDK-SourceCode
|
Premium Suite/VB.NET/Add sound annotation to pdf with pdf sdk/Program.vb
|
Visual Basic
|
apache-2.0
| 1,806
|
' 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.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
Partial Public Class RenameEngineTest
Public Class CSharpConflicts
<WpfFact(Skip:="799977")>
<WorkItem(773543)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
class D { public int x = 1; }
Action<int> a = (int [|$$x|]) => // Rename x to y
{
var {|Conflict:y|} = new D();
Console.{|Conflict:WriteLine|}({|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<WorkItem(773534)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct y
{
public int x;
}
class C
{
class D { public int x = 1; }
Action<y> a = (y [|$$x|]) => // Rename x to y
{ var {|Conflict:y|} = new D();
Console.WriteLine(y.x);
Console.WriteLine({|Conflict:x|}.{|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<WorkItem(773435)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithInvocationOnDelegateInstance()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public delegate void Foo(int x);
public void FooMeth(int x)
{
}
public void Sub()
{
Foo {|Conflict:x|} = new Foo(FooMeth);
int [|$$z|] = 1; // Rename z to x
int y = {|Conflict:z|};
x({|Conflict:z|}); // Renamed to x(x)
}
}
</Document>
</Project>
</Workspace>, renameTo:="x")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<WorkItem(782020)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithSameClassInOneNamespace()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using K = N.{|Conflict:C|}; // No change, show compiler error
namespace N
{
class {|Conflict:C|}
{
}
}
namespace N
{
class {|Conflict:$$D|} // Rename D to C
{
}
}
</Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameCrossAssembly()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly1">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class D
Public Sub Boo()
Dim x = New {|Conflict:$$C|}()
End Sub
End Class
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document>
public class [|C|]
{
public static void Foo()
{
}
}
</Document>
</Project>
</Workspace>, renameTo:="D")
result.AssertLabeledSpansAre("Conflict", "D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideLambdaBody()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Proaasgram
{
object z;
public void masdain(string[] args)
{
Func<int, bool> sx = (int [|$$x|]) =>
{
{|resolve:z|} = null;
if (true)
{
bool y = foo([|x|]);
}
return true;
};
}
public bool foo(int bar)
{
return true;
}
public bool foo(object bar)
{
return true;
}
}
</Document>
</Project>
</Workspace>, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "this.z = null;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<WorkItem(1069237)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + this.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + this.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<WorkItem(1069237)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public static readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + B.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + B.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideMethodBody()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int Y(int [|$$y|])
{
[|y|] = 0;
return {|resolve:z|};
}
}
</Document>
</Project>
</Workspace>, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "return this.z;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner(x => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner((x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_3()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, renameTo:="Ex")
Dim outputResult = <code>Outer((y) => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_4()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_5()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code> z.Ex();</code>.Value + vbCrLf +
<code> x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|stmt2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|resolved:foo|} = 23;
{|resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolved", "this.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int @if;
void Blah(int {|Escape1:$$bar|})
{
{|Resolve:@if|} = 23;
{|Resolve2:@if|} = {|Escape2:bar|};
}
}
</Document>
</Project>
</Workspace>, renameTo:="if")
result.AssertLabeledSpansAre("Resolve", "this.@if = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpecialSpansAre("Escape1", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpecialSpansAre("Escape2", "this.@if = @if;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "this.@if = @if;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithStaticField()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
static int foo;
void Blah(int [|$$bar|])
{
{|Resolved:foo|} = 23;
{|Resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, renameTo:="foo")
result.AssertLabeledSpansAre("Resolved", "Foo.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("stmt1", "Foo.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolved2", "Foo.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithFieldFromAnotherLanguage()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<ProjectReference>VisualBasicAssembly</ProjectReference>
<Document>
class Foo : FooBase
{
void Blah(int bar)
{
{|Resolve:$$foo|} = bar;
}
}
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true">
<Document>
Public Class FooBase
Protected [|foo|] As Integer
End Class
</Document>
</Project>
</Workspace>, renameTo:="bar")
result.AssertLabeledSpansAre("Resolve", "base.bar = bar;", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact>
<WorkItem(539745)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingTypeDeclaration()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" LanguageVersion="CSharp6">
<Document>< { }
}
]]></Document>
</Project>
</Workspace>, renameTo:="Goo")
result.AssertLabeledSpansAre("ReplacementCInt", "C<int>.Goo(i, i);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("ReplacementCString", "C<string>.Goo(s, s);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, renameTo:="`")
result.AssertLabeledSpansAre("Invalid", "`", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>,
renameTo:="!")
result.AssertLabeledSpansAre("Invalid", "!", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<WpfFact>
<WorkItem(539636)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void F()
{
}
class Blah
{
void [|$$M|]()
{
{|Replacement:F|}();
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="F")
result.AssertLabeledSpansAre("Replacement", "Program.F();", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
int foo;
{|Replacement:Bar|}();
}
void [|$$Bar|]()
{
}
}
</Document>
</Project>
</Workspace>, renameTo:="foo")
result.AssertLabeledSpansAre("Replacement", "this.foo();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact>
<WorkItem(539733)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingTypeToConflictingMemberAndParentTypeName()
' It's important that we see conflicts for both simultaneously, so I do a single
' test for both cases.
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
class [|$$Bar|]
{
int {|Conflict:Foo|};
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<WorkItem(539733)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToNameConflictingWithParent()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
int [|$$Bar|];
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<WorkItem(540199)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToInvalidIdentifierName()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
}
</Document>
</Project>
</Workspace>, renameTo:="Foo@")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("Invalid", "Foo@", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class [|$$A|] { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class B { }
}
</Document>
</Project>
</Workspace>, renameTo:="B")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class A { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class [|$$B|] { }
}
</Document>
</Project>
</Workspace>, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "X.A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322)>
Public Sub EscapeIfKeywordWhenDoingTypeNameQualification()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class Foo
{
static void {|Escape:Method$$|}() { }
static void Test()
{
int @if;
{|Replacement:Method|}();
}
}
</Document>
</Project>
</Workspace>, renameTo:="if")
result.AssertLabeledSpecialSpansAre("Escape", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Replacement", "Foo.@if();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322)>
Public Sub EscapeUnboundGenericTypesInTypeOfContext()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S> { }
}
class Program
{
static void Main()
{
var type = typeof({|stmt1:C|}.B<>);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("stmt1", "var type = typeof(A<>.B<>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322)>
Public Sub EscapeUnboundGenericTypesInTypeOfContext2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322)>
Public Sub EscapeUnboundGenericTypesInTypeOfContext3()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|]
{
public class B<S>
{
public class E { }
}
}
}
]]></Document>
</Project>
</Workspace>,
renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651)>
Public Sub ReplaceAliasWithGenericTypeThatIncludesArrays()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int[]>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int[]>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651)>
Public Sub ReplaceAliasWithGenericTypeThatIncludesPointers()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int*>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int*>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651)>
Public Sub ReplaceAliasWithNestedGenericType()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>.E;
class A<T>
{
public class E { }
}
class B
{
{|Resolve:C|} x;
class [|D$$|] { } // Rename D to C
}
]]></Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int>.E", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact()>
<WorkItem(535068)>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542103)>
Public Sub RewriteConflictingExtensionMethodCallSite()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
C Bar(int tag)
{
return this.{|stmt1:Foo|}(1).{|stmt1:Foo|}(2);
}
}
static class E
{
public static C [|$$Foo|](this C x, int tag) { return new C(); }
}
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "return E.Bar(E.Bar(this,1),2);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068)>
<WorkItem(528902)>
<WorkItem(645152)>
Public Sub RewriteConflictingExtensionMethodCallSiteWithReturnTypeChange()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|$$Bar|](int tag)
{
this.{|Resolved:Foo|}(1).{|Resolved:Foo|}(2);
}
}
static class E
{
public static C Foo(this C x, int tag) { return x; }
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", "E.Foo(E.Foo(this,1),2);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact(Skip:="535068")>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068)>
<WorkItem(542821)>
Public Sub RewriteConflictingExtensionMethodCallSiteRequiringTypeArguments()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>()
{
{|Replacement:this.{|Resolved:Foo|}<int>()|};
}
}
static class E
{
public static void Foo<T>(this C x) { }
}
]]></Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo<int>(this)")
End Using
End Sub
<WpfFact(Skip:="535068")>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068)>
<WorkItem(542103)>
Public Sub RewriteConflictingExtensionMethodCallSiteInferredTypeArguments()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>(T y)
{
{|Replacement:this.{|Resolved:Foo|}(42)|};
}
}
static class E
{
public static void Foo<T>(this C x, T y) { }
}
]]></Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo(this, 42)")
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DoNotDetectQueryContinuationNamedTheSame()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C
{
static void Main(string[] args)
{
var temp = from {|stmt1:$$x|} in "abc"
select {|stmt1:x|} into y
select y;
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
' This may feel strange, but the "into" effectively splits scopes
' into two. There are no errors here.
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesUsingWithoutDeclaration()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
class Program
{
public static void Main(string[] args)
{
Stream {|stmt1:$$s|} = new Stream();
using ({|stmt2:s|})
{
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesForWithoutDeclaration()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
public static void Main(string[] args)
{
int {|stmt1:$$i|};
for ({|stmt2:i|} = 0; ; )
{
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeSuffix()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Special:Something|}()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, renameTo:="SpecialAttribute")
result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAddAttributeSuffix()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|Something|]()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, renameTo:="Special")
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameKeepAttributeSuffixOnUsages()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|SomethingAttribute|]()]
class Foo { }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|] { }
}
</Document>
</Project>
</Workspace>, renameTo:="FooAttribute")
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameToConflictWithValue()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
public int TestProperty
{
set
{
int [|$$x|];
[|x|] = {|Conflict:value|};
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="value")
' result.AssertLabeledSpansAre("stmt1", "value", RelatedLocationType.NoConflict)
' result.AssertLabeledSpansAre("stmt2", "value", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact>
<WorkItem(543482)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeWithConflictingUse()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
[Main()]
static void test() { }
}
class MainAttribute : System.Attribute
{
static void Main() { }
}
class [|$$Main|] : System.Attribute
{
}
</Document>
</Project>
</Workspace>, renameTo:="FooAttribute")
End Using
End Sub
<WpfFact>
<WorkItem(542649)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub QualifyTypeWithGlobalWhenConflicting()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class A { }
class B
{
{|Resolve:A|} x;
class [|$$C|] { }
}
</Document>
</Project>
</Workspace>, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "global::A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
End Class
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolConflictWithLocals()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
{ int x; }
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "this.x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(528738)>
Public Sub RenameAliasToCatchConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using [|$$A|] = X.Something;
using {|Conflict:B|} = X.SomethingElse;
namespace X
{
class Something { }
class SomethingElse { }
}
</Document>
</Project>
</Workspace>, renameTo:="B")
result.AssertLabeledSpansAre("Conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeToCreateConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Escape:Main|}]
class Some
{
}
class SpecialAttribute : Attribute
{
}
class [|$$Main|] : Attribute // Rename 'Main' to 'Special'
{
}
</Document>
</Project>
</Workspace>, renameTo:="Special")
result.AssertLabeledSpecialSpansAre("Escape", "@Special", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUsingToKeyword()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using [|$$S|] = System.Collections;
[A]
class A : {|Resolve:Attribute|}
{
}
class B
{
[|S|].ArrayList a;
}
</Document>
</Project>
</Workspace>, renameTo:="Attribute")
result.AssertLabeledSpansAre("Resolve", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16809)>
<WorkItem(535066)>
Public Sub RenameInNestedClasses()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Foo(T x) { }
class B<S> : A<B<S>>
{
class [|$$C|]<U> : B<{|Resolve1:C|}<U>> // Rename C to A
{
public override void Foo({|Resolve2:A|}<{|Resolve3:A|}<T>.B<S>>.B<{|Resolve4:A|}<T>.B<S>.{|Resolve1:C|}<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="A")
result.AssertLabeledSpansAre("Resolve1", "A", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve3", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve4", "N.A<T>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact()>
<WorkItem(535066)>
<WorkItem(531433)>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAndEscapeContextualKeywordsInCSharp()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System.Linq;
class [|t$$o|] // Rename 'to' to 'from'
{
object q = from x in "" select new {|resolved:to|}();
}
</Document>
</Project>
</Workspace>, renameTo:="from")
result.AssertLabeledSpansAre("resolved", "@from", RelatedLocationType.NoConflict)
End Using
End Sub
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(522774)>
Public Sub RenameCrefWithConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Foo();
}
}
class C
{
class E : {|Resolve:F|}.I
{
/// <summary>
/// This is a function <see cref="{|Resolve:F|}.I.Foo"/>
/// </summary>
public void Foo() { }
}
class [|$$K|]
{
}
}
]]></Document>
</Project>
</Workspace>, renameTo:="F")
result.AssertLabeledSpansAre("Resolve", "N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameClassContainingAlias()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using C = A<int,int>;
class A<T,U>
{
public class B<S>
{
}
}
class [|$$B|]
{
{|Resolve:C|}.B<int> cb;
}
]]></Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int, int>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionWithOverloadConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Bar
{
void Foo(int x) { }
void [|Boo|](object x) { }
void Some()
{
Foo(1);
{|Resolve:$$Boo|}(1);
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolve", "Foo((object)1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameActionWithFunctionConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class Program
{
static void doer(int x)
{
Console.WriteLine("Hey");
}
static void Main(string[] args)
{
Action<int> {|stmt1:$$action|} = delegate(int x) { Console.WriteLine(x); }; // Rename action to doer
{|stmt2:doer|}(3);
}
}
]]></Document>
</Project>
</Workspace>, renameTo:="doer")
result.AssertLabeledSpansAre("stmt1", "doer", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "Program.doer(3);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552522)>
Public Sub RenameFunctionNameToDelegateTypeConflict1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|Foo|]() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
{|Stmt2:$$Foo|}();
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="Del")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Del);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Del", RelatedLocationType.NoConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520)>
Public Sub RenameFunctionNameToDelegateTypeConflict2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|$$Foo|]() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Bar);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionNameToDelegateTypeConflict3()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
delegate void Del(Del a);
static void [|Bar|](Del a) { }
class B
{
Del Boo = new Del({|decl1:Bar|});
void Foo()
{
Boo({|Stmt2:Bar|});
{|Stmt3:$$Bar|}(Boo);
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="Boo")
result.AssertLabeledSpansAre("decl1", "new Del(A.Boo)", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Boo(A.Boo);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt3", "A.Boo(Boo);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520)>
Public Sub RenameFunctionNameToDelegateTypeConflict4()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void Foo(int i) { }
static void Foo(string s) { }
class B
{
delegate void Del(string s);
void [|$$Bar|](string s) { }
void Boo()
{
Del d = new Del({|stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Del d = new Del(A.Foo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722)>
Public Sub RenameActionTypeConflict()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class A
{
static Action<int> [|$$Baz|] = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Foo()
{
{|Stmt1:Baz|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "A.Bar(3);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722)>
Public Sub RenameConflictAttribute1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
[{|escape:Bar|}]
class Bar : System.Attribute
{ }
class [|$$FooAttribute|] : System.Attribute
{ }
]]>
</Document>
</Project>
</Workspace>, renameTo:="BarAttribute")
result.AssertLabeledSpansAre("escape", "@Bar", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameConflictAttribute2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Resolve:B|}]
class [|$$BAttribute|] : Attribute
{
}
class AAttributeAttribute : Attribute
{
}
</Document>
</Project>
</Workspace>, renameTo:="AAttribute")
result.AssertLabeledSpecialSpansAre("Resolve", "A", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(576573)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug576573_ConflictAttributeWithNamespace()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace X
{
class BAttribute
: System.Attribute
{ }
namespace Y.[|$$Z|]
{
[{|Resolve:B|}]
class Foo { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="BAttribute")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(579602)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug579602_RenameFunctionWithDynamicParameter()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
class B
{
public void [|Boo|](int d) { } //Line 1
}
void Bar()
{
B b = new B();
dynamic d = 1.5f;
b.{|stmt1:$$Boo|}(d); //Line 2 Rename Boo to Foo
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
End Using
End Sub
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub IdentifyConflictsWithVar()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class [|$$vor|]
{
static void Main(string[] args)
{
{|conflict:var|} x = 23;
}
}
</Document>
</Project>
</Workspace>, renameTo:="v\u0061r")
result.AssertLabeledSpansAre("conflict", "var", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(633180)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_DetectOverLoadResolutionChangesInEnclosingInvocations()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolved:Outer|}(y => {|resolved:Inner|}(x => x.Ex(), y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("resolved", "Outer((string y) => Inner(x => x.Ex(), y), 0);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(635622)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandingDynamicAddsObjectCast()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void [|$$Foo|](int x, Action y) { } // Rename Foo to Bar
static void Bar(dynamic x, Action y) { }
static void Main()
{
{|resolve:Bar|}(1, Console.WriteLine);
}
}
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("resolve", "Bar((object)1, Console.WriteLine);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673562)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameNamespaceConflictsAndResolves()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace N
{
class C
{
{|resolve:N|}.C x;
/// <see cref="{|resolve:N|}.C"/>
void Sub()
{ }
}
namespace [|$$K|] // Rename K to N
{
class C
{ }
}
}
</Document>
</Project>
</Workspace>, renameTo:="N")
result.AssertLabeledSpansAre("resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673667)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUnnecessaryExpansion()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
namespace N
{
using K = {|stmt1:N|}.C;
class C
{
}
class [|$$D|] // Rename D to N
{
class C
{
[|D|] x;
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="N")
result.AssertLabeledSpansAre("stmt1", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(768910)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInCrefPreservesWhitespaceTrivia()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
<![CDATA[
public class A
{
public class B
{
public class C
{
}
/// <summary>
/// <see cref=" {|Resolve:D|}"/>
/// </summary>
public static void [|$$foo|]() // Rename foo to D
{
}
}
public class D
{
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="D")
result.AssertLabeledSpansAre("Resolve", "A.D", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#Region "Type Argument Expand/Reduce for Generic Method Calls - 639136"
<WorkItem(639136)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void F<T>(Func<int, T> x) { }
static void [|$$B|](Func<int, int> x) { } // Rename Bar to Foo
static void Main()
{
{|stmt1:F|}(a => a);
}
}
</Document>
</Project>
</Workspace>, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F<int>(a => a);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WorkItem(725934)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_This()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void TestMethod()
{
int x = 1;
Func<int> y = delegate { return {|stmt1:Foo|}(x); };
}
int Foo<T>(T x) { return 1; }
int [|$$Bar|](int x) { return 1; }
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "return Foo<int>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_Nested()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public static void [|$$Foo|]<T>(T x) { }
public static void Bar(int x) { }
class D
{
void Bar<T>(T x) { }
void Bar(int x) { }
void sub()
{
{|stmt1:Foo|}(1);
}
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "C.Bar<int>(1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ReferenceType()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
string one = "1";
{|stmt1:Foo|}(one);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<string>(one);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConstructedTypeArgumentNonGenericContainer()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
D<int> x = new D<int>();
{|stmt1:Foo|}(x);
}
}
class D<T>
{}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<D<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_SameTypeParameter()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System.Linq.Expressions;
class C
{
public static int Foo<T>(T x) { return 1; }
public static int [|$$Bar|]<T>(Expression<Func<int, T>> x) { return 1; }
Expression<Func<int, int>> x = (y) => Foo(1);
public void sub()
{
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<Expression<Func<int, int>>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ArrayTypeParameter()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void [|$$Foo|]<S>(S x) { }
public void Bar(int[] x) { }
public void Sub()
{
var x = new int[] { 1, 2, 3 };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "Bar<int[]>(x);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultiDArrayTypeParameter()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
var x = new int[,] { { 1, 2 }, { 2, 3 } };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[,]>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedAsArgument()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Sub(int x) { }
public void Test()
{
Sub({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Sub(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInConstructorInitialization()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Test()
{
C c = new C({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C c = new C(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_CalledOnObject()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
C c = new C();
c.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "c.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInGenericDelegate()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel<int> foodel = new FooDel<int>({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel<int> foodel = new FooDel<int>(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInNonGenericDelegate()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel foodel = new FooDel({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel foodel = new FooDel(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultipleTypeParameters()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void Foo<T, S>(T x, S y) { }
public void [|$$Bar|]<U, P>(U[] x, P y) { }
public void Sub()
{
int[] x;
{|stmt1:Foo|}(x, new C());
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[], C>(x, new C());", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WorkItem(730781)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConflictInDerived()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "base.Foo(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728653)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameGenericInvocationWithDynamicArgument()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to F
public void sub()
{
dynamic x = 1;
{|stmt1:F|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(728646)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandInvocationInStaticMemberAccess()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
}
}
class D
{
public void Sub()
{
C.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728628)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RecursiveTypeParameterExpansionFail()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
C<int> x = new C<int>();
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<C<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728575)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameCrefWithProperBracesForTypeInferenceAdditionToMethod()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename to Zoo
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Zoo")
result.AssertLabeledSpansAre("cref1", "C.Zoo{T}", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_GenericBase()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
}
class D : C<int>
{
public void Test()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136)>
<WpfFact(Skip:="Story 736967"), Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_InErrorCode()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< // Rename Bar to Foo
{
x = 1;
}
public void Test()
{
int y = 1;
int x;
{|stmt1:Foo|}(y, x); // error in code, but Foo is bound to Foo<T>
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(y, x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#End Region
<WorkItem(1016652)>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_ConflictBetweenTypeNamesInTypeConstraintSyntax()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
// rename INamespaceSymbol to ISymbol
public interface {|unresolved1:$$INamespaceSymbol|} { }
public interface {|DeclConflict:ISymbol|} { }
public interface IReferenceFinder { }
internal abstract partial class AbstractReferenceFinder<TSymbol> : IReferenceFinder
where TSymbol : {|unresolved2:INamespaceSymbol|}
{
}]]></Document>
</Project>
</Workspace>, renameTo:="ISymbol")
result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_StaticReferencingInstance()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
static void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingStatic()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
static int zoo;
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingInstance()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfMethodInvocationUsesThisDot()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
int zoo;
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
void nameof(int x) { }
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(this.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInLambdaBodyExpression()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => 5;
static int N(long b) => 5;
System.Func<int, int> a = d => {|resolved:N|}(1);
System.Func<int> b = () => {|resolved:N|}(1);
}]]>
</Document>
</Project>
</Workspace>, renameTo:="N")
result.AssertLabeledSpansAre("resolved", "N((long)1)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInExpressionBodiedMembers()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => {|resolved2:N|}(0);
int N(long b) => [|M|](0);
int P => {|resolved2:N|}(0);
}]]>
</Document>
</Project>
</Workspace>, renameTo:="N")
result.AssertLabeledSpansAre("resolved1", "new C().N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1027506)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
interface [|$$I|] { }
]]>
</Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class [|$$C|] { }
interface {|conflict:I|} { }
]]>
</Document>
</Project>
</Workspace>, renameTo:="I")
result.AssertLabeledSpansAre("conflict", "I", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:$$C|} { }
namespace N { }
]]>
</Document>
</Project>
</Workspace>, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
namespace [|$$N|] { }
]]>
</Document>
</Project>
</Workspace>, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictBetweenTwoNamespaces()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
namespace [|$$N1|][ { }
namespace N2 { }
]]>
</Document>
</Project>
</Workspace>, renameTo:="N2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictWithParametersOrLocalsOfDelegateType()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M1(Action [|callback$$|])
{
[|callback|]();
}
void M2(Func<bool> callback)
{
callback();
}
void M3()
{
Action callback = () => { };
callback();
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="callback2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictWithLocalsOfDelegateTypeWhenBindingChangesToNonDelegateLocal()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M()
{
int [|x$$|] = 7; // Rename x to a. "a()" will bind to the first definition of a.
Action {|conflict:a|} = () => { };
{|conflict:a|}();
}
}
]]>
</Document>
</Project>
</Workspace>, renameTo:="a")
result.AssertLabeledSpansAre("conflict", "a", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(446, "https://github.com/dotnet/roslyn/issues/446")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoCrashOrConflictOnRenameWithNameOfInAttribute()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
static void [|T|]$$(int x) { }
[System.Obsolete(nameof(Test))]
static void Test() { }
}
</Document>
</Project>
</Workspace>, renameTo:="Test")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceDoesNotBindToAnyOriginalSymbols()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Test()
{
int [|T$$|];
var x = nameof({|conflict:Test|});
}
}
</Document>
</Project>
</Workspace>, renameTo:="Test")
result.AssertLabeledSpansAre("conflict", "Test", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceDoesNotBindToSomeOriginalSymbols()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|$$M|](int x) { }
void M() { var x = nameof(M); }
}
</Document>
</Project>
</Workspace>, renameTo:="X")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceBindsToSymbolForFirstTime()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|X$$|]() { }
void M() { var x = nameof(T); }
}
</Document>
</Project>
</Workspace>, renameTo:="T")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceChangesBindingFromMetadataToSource()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Program
{
static void M()
{
var [|Consol$$|] = 7;
var x = nameof({|conflict:Console|});
}
}
</Document>
</Project>
</Workspace>, renameTo:="Console")
result.AssertLabeledSpansAre("conflict", "Console", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_IntroduceQualifiedName()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, renameTo:="C.D")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", "C.D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_AccidentallyPasteLotsOfCode()
Dim renameTo = "class C { public void M() { for (int i = 0; i < 10; i++) { System.Console.Writeline(""This is a test""); } } }"
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, renameTo)
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", renameTo, RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_SameProject()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
internal void [|A$$|]() { }
internal void {|conflict:B|}() { }
}
</Document>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_DifferentProjects()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document FilePath="Test1.cs">
public class Program
{
public void [|A$$|]() { }
public void {|conflict:B|}() { }
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly2">
<ProjectReference>CSAssembly1</ProjectReference>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<WorkItem(3303, "https://github.com/dotnet/roslyn/issues/3303")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_PartialTypes()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
partial class C
{
private static void [|$$M|]()
{
{|conflict:M|}();
}
}
</Document>
<Document FilePath="Test2.cs">
partial class C
{
private static void {|conflict:Method|}()
{
}
}
</Document>
</Project>
</Workspace>, renameTo:="Method")
result.AssertLabeledSpansAre("conflict", "Method", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf1()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|}).ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field).ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf2()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|})?.ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field)?.ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf3()
Using result = RenameEngineResult.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
Program.nameof({|Conflict:field|}); // Should also expand to Program.field
}
static void nameof(string s) { }
}
</Document>
</Project>
</Workspace>, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="Program.nameof(Program.field);", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
End Class
End Namespace
|
VPashkov/roslyn
|
src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb
|
Visual Basic
|
apache-2.0
| 114,036
|
' 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.Globalization
Imports System.Reflection
Imports System.Reflection.Metadata
Imports System.Linq
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Imports TypeAttributes = System.Reflection.TypeAttributes
Imports FieldAttributes = System.Reflection.FieldAttributes
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
''' <summary>
''' The class to represent all types imported from a PE/module.
''' </summary>
''' <remarks></remarks>
Friend Class PENamedTypeSymbol
Inherits InstanceTypeSymbol
Private ReadOnly _container As NamespaceOrTypeSymbol
#Region "Metadata"
Private ReadOnly _handle As TypeDefinitionHandle
Private ReadOnly _genericParameterHandles As GenericParameterHandleCollection
Private ReadOnly _name As String
Private ReadOnly _flags As TypeAttributes
Private ReadOnly _arity As UShort
Private ReadOnly _mangleName As Boolean ' CONSIDER: combine with flags
#End Region
''' <summary>
''' A map of types immediately contained within this type
''' grouped by their name (case-insensitively).
''' </summary>
Private _lazyNestedTypes As Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol))
''' <summary>
''' A set of all the names of the members in this type.
''' </summary>
Private _lazyMemberNames As ICollection(Of String)
''' <summary>
''' A map of members immediately contained within this type
''' grouped by their name (case-insensitively).
''' </summary>
''' <remarks></remarks>
Private _lazyMembers As Dictionary(Of String, ImmutableArray(Of Symbol))
Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Private _lazyEnumUnderlyingType As NamedTypeSymbol
Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData)
Private _lazyConditionalAttributeSymbols As ImmutableArray(Of String)
Private _lazyAttributeUsageInfo As AttributeUsageInfo = AttributeUsageInfo.Null
Private _lazyCoClassType As TypeSymbol = ErrorTypeSymbol.UnknownResultType
''' <summary>
''' Lazily initialized by TypeKind property.
''' Using Integer type to make sure read/write operations are atomic.
''' </summary>
''' <remarks></remarks>
Private _lazyTypeKind As Integer
Private _lazyDocComment As Tuple(Of CultureInfo, String)
Private _lazyDefaultPropertyName As String
Private _lazyUseSiteErrorInfo As DiagnosticInfo = ErrorFactory.EmptyErrorInfo ' Indicates unknown state.
Private _lazyMightContainExtensionMethods As Byte = ThreeState.Unknown
Private _lazyHasEmbeddedAttribute As Integer = ThreeState.Unknown
Private _lazyObsoleteAttributeData As ObsoleteAttributeData = ObsoleteAttributeData.Uninitialized
Private _lazyIsExtensibleInterface As ThreeState = ThreeState.Unknown
Friend Sub New(
moduleSymbol As PEModuleSymbol,
containingNamespace As PENamespaceSymbol,
handle As TypeDefinitionHandle
)
Me.New(moduleSymbol, containingNamespace, 0, handle)
End Sub
Friend Sub New(
moduleSymbol As PEModuleSymbol,
containingType As PENamedTypeSymbol,
handle As TypeDefinitionHandle
)
Me.New(moduleSymbol, containingType, CUShort(containingType.MetadataArity), handle)
End Sub
Private Sub New(
moduleSymbol As PEModuleSymbol,
container As NamespaceOrTypeSymbol,
containerMetadataArity As UShort,
handle As TypeDefinitionHandle
)
Debug.Assert(Not handle.IsNil)
Debug.Assert(container IsNot Nothing)
_handle = handle
_container = container
Dim makeBad As Boolean = False
Dim name As String
Try
name = moduleSymbol.Module.GetTypeDefNameOrThrow(handle)
Catch mrEx As BadImageFormatException
name = String.Empty
makeBad = True
End Try
Try
_flags = moduleSymbol.Module.GetTypeDefFlagsOrThrow(handle)
Catch mrEx As BadImageFormatException
makeBad = True
End Try
Dim metadataArity As Integer
Try
_genericParameterHandles = moduleSymbol.Module.GetTypeDefGenericParamsOrThrow(handle)
metadataArity = _genericParameterHandles.Count
Catch mrEx As BadImageFormatException
_genericParameterHandles = Nothing
metadataArity = 0
makeBad = True
End Try
' Figure out arity from the language point of view
If metadataArity > containerMetadataArity Then
_arity = CType(metadataArity - containerMetadataArity, UShort)
End If
If _arity = 0 Then
_lazyTypeParameters = ImmutableArray(Of TypeParameterSymbol).Empty
_name = name
_mangleName = False
Else
' Unmangle name for a generic type.
_name = MetadataHelpers.UnmangleMetadataNameForArity(name, _arity)
_mangleName = (_name IsNot name)
End If
If makeBad OrElse metadataArity < containerMetadataArity Then
_lazyUseSiteErrorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, Me)
End If
Debug.Assert(Not _mangleName OrElse _name.Length < name.Length)
End Sub
Friend ReadOnly Property ContainingPEModule As PEModuleSymbol
Get
Dim s As Symbol = _container
While s.Kind <> SymbolKind.Namespace
s = s.ContainingSymbol
End While
Return DirectCast(s, PENamespaceSymbol).ContainingPEModule
End Get
End Property
Public Overrides ReadOnly Property ContainingModule As ModuleSymbol
Get
Return ContainingPEModule
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return _arity
End Get
End Property
Friend Overrides ReadOnly Property MangleName As Boolean
Get
Return _mangleName
End Get
End Property
Friend Overrides ReadOnly Property Layout As TypeLayout
Get
Return Me.ContainingPEModule.Module.GetTypeLayout(_handle)
End Get
End Property
Friend Overrides ReadOnly Property MarshallingCharSet As CharSet
Get
Dim result As CharSet = _flags.ToCharSet()
If result = 0 Then
Return CharSet.Ansi
End If
Return result
End Get
End Property
Friend Overrides ReadOnly Property IsSerializable As Boolean
Get
Return (_flags And TypeAttributes.Serializable) <> 0
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return (_flags And TypeAttributes.SpecialName) <> 0
End Get
End Property
Friend ReadOnly Property MetadataArity As Integer
Get
Return _genericParameterHandles.Count
End Get
End Property
Friend ReadOnly Property Handle As TypeDefinitionHandle
Get
Return _handle
End Get
End Property
Friend Overrides Function GetInterfacesToEmit() As IEnumerable(Of NamedTypeSymbol)
Return InterfacesNoUseSiteDiagnostics
End Function
Friend Overrides Function MakeDeclaredBase(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As NamedTypeSymbol
If (Me._flags And TypeAttributes.Interface) = 0 Then
Dim moduleSymbol As PEModuleSymbol = Me.ContainingPEModule
Try
Dim token As EntityHandle = moduleSymbol.Module.GetBaseTypeOfTypeOrThrow(Me._handle)
If Not token.IsNil Then
Dim decodedType = New MetadataDecoder(moduleSymbol, Me).GetTypeOfToken(token)
Return DirectCast(TupleTypeDecoder.DecodeTupleTypesIfApplicable(decodedType, _handle, moduleSymbol), NamedTypeSymbol)
End If
Catch mrEx As BadImageFormatException
Return New UnsupportedMetadataTypeSymbol(mrEx)
End Try
End If
Return Nothing
End Function
Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Try
Dim moduleSymbol As PEModuleSymbol = Me.ContainingPEModule
Dim interfaceImpls = moduleSymbol.Module.GetInterfaceImplementationsOrThrow(Me._handle)
If interfaceImpls.Count = 0 Then
Return ImmutableArray(Of NamedTypeSymbol).Empty
End If
Dim symbols As NamedTypeSymbol() = New NamedTypeSymbol(interfaceImpls.Count - 1) {}
Dim tokenDecoder As New MetadataDecoder(moduleSymbol, Me)
Dim i = 0
For Each interfaceImpl In interfaceImpls
Dim interfaceHandle As EntityHandle = moduleSymbol.Module.MetadataReader.GetInterfaceImplementation(interfaceImpl).Interface
Dim typeSymbol As TypeSymbol = tokenDecoder.GetTypeOfToken(interfaceHandle)
typeSymbol = DirectCast(TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeSymbol, interfaceImpl, moduleSymbol), NamedTypeSymbol)
'TODO: how to pass reason to unsupported
Dim namedTypeSymbol As NamedTypeSymbol = TryCast(typeSymbol, NamedTypeSymbol)
symbols(i) = If(namedTypeSymbol IsNot Nothing, namedTypeSymbol, New UnsupportedMetadataTypeSymbol()) ' "interface tmpList contains a bad type"
i = i + 1
Next
Return symbols.AsImmutableOrNull
Catch mrEx As BadImageFormatException
Return ImmutableArray.Create(Of NamedTypeSymbol)(New UnsupportedMetadataTypeSymbol(mrEx))
End Try
End Function
Private Shared Function CyclicInheritanceError(diag As DiagnosticInfo) As ErrorTypeSymbol
Return New ExtendedErrorTypeSymbol(diag, True)
End Function
Friend Overrides Function MakeAcyclicBaseType(diagnostics As DiagnosticBag) As NamedTypeSymbol
Dim diag = BaseTypeAnalysis.GetDependencyDiagnosticsForImportedClass(Me)
If diag IsNot Nothing Then
Return CyclicInheritanceError(diag)
End If
Return GetDeclaredBase(Nothing)
End Function
Friend Overrides Function MakeAcyclicInterfaces(diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Dim declaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing)
If (Not Me.IsInterface) Then
' only interfaces needs to check for inheritance cycles via interfaces.
Return declaredInterfaces
End If
Return (From t In declaredInterfaces
Let diag = BaseTypeAnalysis.GetDependencyDiagnosticsForImportedBaseInterface(Me, t)
Select If(diag Is Nothing, t, CyclicInheritanceError(diag))).AsImmutable
End Function
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _container
End Get
End Property
Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol
Get
Return TryCast(_container, NamedTypeSymbol)
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Dim access As Accessibility = Accessibility.Private
Select Case _flags And TypeAttributes.VisibilityMask
Case TypeAttributes.NestedAssembly
access = Accessibility.Friend
Case TypeAttributes.NestedFamORAssem
access = Accessibility.ProtectedOrFriend
Case TypeAttributes.NestedFamANDAssem
access = Accessibility.ProtectedAndFriend
Case TypeAttributes.NestedPrivate
access = Accessibility.Private
Case TypeAttributes.Public,
TypeAttributes.NestedPublic
access = Accessibility.Public
Case TypeAttributes.NestedFamily
access = Accessibility.Protected
Case TypeAttributes.NotPublic
access = Accessibility.Friend
Case Else
Debug.Assert(False, "Unexpected!!!")
End Select
Return access
End Get
End Property
Public Overrides ReadOnly Property EnumUnderlyingType As NamedTypeSymbol
Get
If _lazyEnumUnderlyingType Is Nothing AndAlso TypeKind = TypeKind.Enum Then
' From §8.5.2
' An enum is considerably more restricted than a true type, as
' follows:
' • It shall have exactly one instance field, and the type of that field defines the underlying type of
' the enumeration.
' • It shall not have any static fields unless they are literal. (see §8.6.1.2)
' The underlying type shall be a built-in integer type. Enums shall derive from System.Enum, hence they are
' value types. Like all value types, they shall be sealed (see §8.9.9).
Dim underlyingType As NamedTypeSymbol = Nothing
For Each member In GetMembers()
If (Not member.IsShared AndAlso member.Kind = SymbolKind.Field) Then
Dim type = DirectCast(member, FieldSymbol).Type
If (type.SpecialType.IsClrInteger()) Then
If (underlyingType Is Nothing) Then
underlyingType = DirectCast(type, NamedTypeSymbol)
Else
underlyingType = New UnsupportedMetadataTypeSymbol()
Exit For
End If
End If
End If
Next
Interlocked.CompareExchange(_lazyEnumUnderlyingType,
If(underlyingType, New UnsupportedMetadataTypeSymbol()),
Nothing)
End If
Return _lazyEnumUnderlyingType
End Get
End Property
Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
If _lazyCustomAttributes.IsDefault Then
If (_lazyTypeKind = TypeKind.Unknown AndAlso
((_flags And TypeAttributes.Interface) <> 0 OrElse Me.Arity <> 0 OrElse Me.ContainingType IsNot Nothing)) OrElse
Me.TypeKind <> TypeKind.Module Then
ContainingPEModule.LoadCustomAttributes(_handle, _lazyCustomAttributes)
Else
Dim stdModuleAttribute As CustomAttributeHandle
Dim attributes = ContainingPEModule.GetCustomAttributesForToken(
_handle,
stdModuleAttribute,
filterOut1:=AttributeDescription.StandardModuleAttribute)
Debug.Assert(Not stdModuleAttribute.IsNil)
ImmutableInterlocked.InterlockedInitialize(_lazyCustomAttributes, attributes)
End If
End If
Return _lazyCustomAttributes
End Function
Friend Overrides Iterator Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData)
For Each attribute In GetAttributes()
Yield attribute
Next
If Me.TypeKind = TypeKind.Module Then
Yield New PEAttributeData(ContainingPEModule,
ContainingPEModule.Module.GetAttributeHandle(Me._handle, AttributeDescription.StandardModuleAttribute))
End If
End Function
Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String)
Get
EnsureNonTypeMemberNamesAreLoaded()
Return _lazyMemberNames
End Get
End Property
Private Sub EnsureNonTypeMemberNamesAreLoaded()
If _lazyMemberNames Is Nothing Then
Dim peModule = ContainingPEModule.Module
Dim names = New HashSet(Of String)()
Try
For Each methodDef In peModule.GetMethodsOfTypeOrThrow(_handle)
Try
names.Add(peModule.GetMethodDefNameOrThrow(methodDef))
Catch mrEx As BadImageFormatException
End Try
Next
Catch mrEx As BadImageFormatException
End Try
Try
For Each propertyDef In peModule.GetPropertiesOfTypeOrThrow(_handle)
Try
names.Add(peModule.GetPropertyDefNameOrThrow(propertyDef))
Catch mrEx As BadImageFormatException
End Try
Next
Catch mrEx As BadImageFormatException
End Try
Try
For Each eventDef In peModule.GetEventsOfTypeOrThrow(_handle)
Try
names.Add(peModule.GetEventDefNameOrThrow(eventDef))
Catch mrEx As BadImageFormatException
End Try
Next
Catch mrEx As BadImageFormatException
End Try
Try
For Each fieldDef In peModule.GetFieldsOfTypeOrThrow(_handle)
Try
names.Add(peModule.GetFieldDefNameOrThrow(fieldDef))
Catch mrEx As BadImageFormatException
End Try
Next
Catch mrEx As BadImageFormatException
End Try
Interlocked.CompareExchange(Of ICollection(Of String))(
_lazyMemberNames,
SpecializedCollections.ReadOnlySet(names),
Nothing)
End If
End Sub
Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol)
EnsureNestedTypesAreLoaded()
EnsureNonTypeMembersAreLoaded()
Return _lazyMembers.Flatten(DeclarationOrderSymbolComparer.Instance)
End Function
Friend Overrides Function GetMembersUnordered() As ImmutableArray(Of Symbol)
EnsureNestedTypesAreLoaded()
EnsureNonTypeMembersAreLoaded()
Dim result = _lazyMembers.Flatten()
#If DEBUG Then
' In DEBUG, swap first and last elements so that use of Unordered in a place it isn't warranted is caught
' more obviously.
Return result.DeOrder()
#Else
Return result
#End If
End Function
Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
' If there are any fields, they are at the very beginning.
Return GetMembers(Of FieldSymbol)(GetMembers(), SymbolKind.Field, offset:=0)
End Function
Friend Overrides Iterator Function GetMethodsToEmit() As IEnumerable(Of MethodSymbol)
Dim members = GetMembers()
' Get to methods.
Dim index = GetIndexOfFirstMember(members, SymbolKind.Method)
If Not Me.IsInterfaceType() Then
While index < members.Length
Dim member = members(index)
If member.Kind <> SymbolKind.Method Then
Exit While
End If
Dim method = DirectCast(member, MethodSymbol)
' Don't emit the default value type constructor - the runtime handles that
If Not method.IsDefaultValueTypeConstructor() Then
Yield method
End If
index += 1
End While
Else
' We do not create symbols for v-table gap methods, let's figure out where the gaps go.
If index >= members.Length OrElse members(index).Kind <> SymbolKind.Method Then
' We didn't import any methods, it is Ok to return an empty set.
Return
End If
Dim method = DirectCast(members(index), PEMethodSymbol)
Dim [module] = ContainingPEModule.Module
Dim methodDefs = ArrayBuilder(Of MethodDefinitionHandle).GetInstance()
Try
For Each methodDef In [module].GetMethodsOfTypeOrThrow(_handle)
methodDefs.Add(methodDef)
Next
Catch mrEx As BadImageFormatException
End Try
For Each methodDef In methodDefs
If method.Handle = methodDef Then
Yield method
index += 1
If index = members.Length OrElse members(index).Kind <> SymbolKind.Method Then
' no need to return any gaps at the end.
methodDefs.Free()
Return
End If
method = DirectCast(members(index), PEMethodSymbol)
Else
' Encountered a gap.
Dim gapSize As Integer
Try
gapSize = ModuleExtensions.GetVTableGapSize([module].GetMethodDefNameOrThrow(methodDef))
Catch mrEx As BadImageFormatException
gapSize = 1
End Try
' We don't have a symbol to return, so, even if the name doesn't represent a gap, we still have a gap.
Do
Yield Nothing
gapSize -= 1
Loop While gapSize > 0
End If
Next
' Ensure we explicitly returned from inside loop.
Throw ExceptionUtilities.Unreachable
End If
End Function
Friend Overrides Function GetPropertiesToEmit() As IEnumerable(Of PropertySymbol)
Return GetMembers(Of PropertySymbol)(GetMembers(), SymbolKind.Property)
End Function
Friend Overrides Function GetEventsToEmit() As IEnumerable(Of EventSymbol)
Return GetMembers(Of EventSymbol)(GetMembers(), SymbolKind.Event)
End Function
Private Class DeclarationOrderSymbolComparer
Implements IComparer(Of ISymbol)
Public Shared ReadOnly Instance As New DeclarationOrderSymbolComparer()
Private Sub New()
End Sub
Public Function Compare(x As ISymbol, y As ISymbol) As Integer Implements IComparer(Of ISymbol).Compare
If x Is y Then
Return 0
End If
Dim cmp As Integer = x.Kind.ToSortOrder - y.Kind.ToSortOrder
If cmp <> 0 Then
Return cmp
End If
Select Case x.Kind
Case SymbolKind.Field
Return HandleComparer.Default.Compare(DirectCast(x, PEFieldSymbol).Handle, DirectCast(y, PEFieldSymbol).Handle)
Case SymbolKind.Method
If DirectCast(x, MethodSymbol).IsDefaultValueTypeConstructor() Then
Return -1
ElseIf DirectCast(y, MethodSymbol).IsDefaultValueTypeConstructor() Then
Return 1
End If
Return HandleComparer.Default.Compare(DirectCast(x, PEMethodSymbol).Handle, DirectCast(y, PEMethodSymbol).Handle)
Case SymbolKind.Property
Return HandleComparer.Default.Compare(DirectCast(x, PEPropertySymbol).Handle, DirectCast(y, PEPropertySymbol).Handle)
Case SymbolKind.Event
Return HandleComparer.Default.Compare(DirectCast(x, PEEventSymbol).Handle, DirectCast(y, PEEventSymbol).Handle)
Case SymbolKind.NamedType
Return HandleComparer.Default.Compare(DirectCast(x, PENamedTypeSymbol).Handle, DirectCast(y, PENamedTypeSymbol).Handle)
Case Else
Throw ExceptionUtilities.UnexpectedValue(x.Kind)
End Select
End Function
End Class
Private Sub EnsureNonTypeMembersAreLoaded()
If _lazyMembers Is Nothing Then
' A method may be referenced as an accessor by one or more properties. And,
' any of those properties may be "bogus" if one of the property accessors
' does not match the property signature. If the method is referenced by at
' least one non-bogus property, then the method is created as an accessor,
' and (for purposes of error reporting if the method is referenced directly) the
' associated property is set (arbitrarily) to the first non-bogus property found
' in metadata. If the method is not referenced by any non-bogus properties,
' then the method is created as a normal method rather than an accessor.
' Create a dictionary of method symbols indexed by metadata row id
' (to allow efficient lookup when matching property accessors).
Dim methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol) = CreateMethods()
Dim members = ArrayBuilder(Of Symbol).GetInstance()
Dim ensureParameterlessConstructor As Boolean = (TypeKind = TypeKind.Structure OrElse TypeKind = TypeKind.Enum) AndAlso Not IsShared
For Each member In methodHandleToSymbol.Values
members.Add(member)
If ensureParameterlessConstructor Then
ensureParameterlessConstructor = Not member.IsParameterlessConstructor()
End If
Next
If ensureParameterlessConstructor Then
members.Add(New SynthesizedConstructorSymbol(Nothing, Me, Me.IsShared, False, Nothing, Nothing))
End If
' CreateFields will add withEvent names here if there are any.
' Otherwise stays Nothing
Dim withEventNames As HashSet(Of String) = Nothing
CreateProperties(methodHandleToSymbol, members)
CreateFields(members, withEventNames)
CreateEvents(methodHandleToSymbol, members)
Dim membersDict As New Dictionary(Of String, ImmutableArray(Of Symbol))(CaseInsensitiveComparison.Comparer)
Dim groupedMembers = members.GroupBy(Function(m) m.Name, CaseInsensitiveComparison.Comparer)
For Each g In groupedMembers
membersDict.Add(g.Key, ImmutableArray.CreateRange(g))
Next
members.Free()
' tell WithEvents properties that they are WithEvents properties
If withEventNames IsNot Nothing Then
For Each withEventName In withEventNames
Dim weMembers As ImmutableArray(Of Symbol) = Nothing
If membersDict.TryGetValue(withEventName, weMembers) Then
' there must be only a single match for a given WithEvents name
If weMembers.Length <> 1 Then
Continue For
End If
' it must be a valid property
Dim asProperty = TryCast(weMembers(0), PEPropertySymbol)
If asProperty IsNot Nothing AndAlso IsValidWithEventsProperty(asProperty) Then
asProperty.SetIsWithEvents(True)
End If
End If
Next
End If
' Merge types into members
For Each typeSymbols In _lazyNestedTypes.Values
Dim name = typeSymbols(0).Name
Dim symbols As ImmutableArray(Of Symbol) = Nothing
If Not membersDict.TryGetValue(name, symbols) Then
membersDict.Add(name, StaticCast(Of Symbol).From(typeSymbols))
Else
membersDict(name) = symbols.Concat(StaticCast(Of Symbol).From(typeSymbols))
End If
Next
Dim exchangeResult = Interlocked.CompareExchange(_lazyMembers, membersDict, Nothing)
If exchangeResult Is Nothing Then
Dim memberNames = SpecializedCollections.ReadOnlyCollection(membersDict.Keys)
Interlocked.Exchange(Of ICollection(Of String))(_lazyMemberNames, memberNames)
End If
End If
End Sub
''' <summary>
''' Some simple sanity checks if a property can actually be a withevents property
''' </summary>
Private Function IsValidWithEventsProperty(prop As PEPropertySymbol) As Boolean
' NOTE: Dev10 does not make any checks. Just has comment that it could be a good idea to do in Whidbey.
' We will check, just to make stuff a bit more robust.
' It will be extremely rare that this function would fail though.
If prop.IsReadOnly Or prop.IsWriteOnly Then
Return False
End If
If Not prop.IsOverridable Then
Return False
End If
Return True
End Function
Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
EnsureNestedTypesAreLoaded()
EnsureNonTypeMembersAreLoaded()
Dim m As ImmutableArray(Of Symbol) = Nothing
If _lazyMembers.TryGetValue(name, m) Then
Return m
End If
Return ImmutableArray(Of Symbol).Empty
End Function
Friend Overrides Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol)
EnsureNestedTypesAreLoaded()
Return StaticCast(Of NamedTypeSymbol).From(_lazyNestedTypes.Flatten())
End Function
Public Overloads Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
EnsureNestedTypesAreLoaded()
Return StaticCast(Of NamedTypeSymbol).From(_lazyNestedTypes.Flatten(DeclarationOrderSymbolComparer.Instance))
End Function
Private Sub EnsureNestedTypesAreLoaded()
If _lazyNestedTypes Is Nothing Then
Dim typesDict = CreateNestedTypes()
Interlocked.CompareExchange(_lazyNestedTypes, typesDict, Nothing)
' Build cache of TypeDef Tokens
' Potentially this can be done in the background.
If _lazyNestedTypes Is typesDict Then
ContainingPEModule.OnNewTypeDeclarationsLoaded(typesDict)
End If
End If
End Sub
Public Overloads Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
EnsureNestedTypesAreLoaded()
Dim t As ImmutableArray(Of PENamedTypeSymbol) = Nothing
If _lazyNestedTypes.TryGetValue(name, t) Then
Return StaticCast(Of NamedTypeSymbol).From(t)
End If
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overloads Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
Return GetTypeMembers(name).WhereAsArray(Function(type) type.Arity = arity)
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return StaticCast(Of Location).From(ContainingPEModule.MetadataLocation)
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Friend ReadOnly Property TypeDefFlags As TypeAttributes
Get
Return _flags
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
EnsureTypeParametersAreLoaded()
Return _lazyTypeParameters
End Get
End Property
Private Sub EnsureTypeParametersAreLoaded()
If _lazyTypeParameters.IsDefault Then
Debug.Assert(_arity > 0)
Dim ownedParams(_arity - 1) As PETypeParameterSymbol
Dim moduleSymbol = ContainingPEModule
' If this is a nested type generic parameters in metadata include generic parameters of the outer types.
Dim firstIndex = _genericParameterHandles.Count - Arity
For i = 0 To ownedParams.Length - 1
ownedParams(i) = New PETypeParameterSymbol(moduleSymbol, Me, CUShort(i), _genericParameterHandles(firstIndex + i))
Next
ImmutableInterlocked.InterlockedCompareExchange(_lazyTypeParameters,
StaticCast(Of TypeParameterSymbol).From(ownedParams.AsImmutableOrNull),
Nothing)
End If
End Sub
Public Overrides ReadOnly Property IsMustInherit As Boolean
Get
Return (_flags And TypeAttributes.Abstract) <> 0 AndAlso
(_flags And TypeAttributes.Sealed) = 0
End Get
End Property
Friend Overrides ReadOnly Property IsMetadataAbstract As Boolean
Get
Return (_flags And TypeAttributes.Abstract) <> 0
End Get
End Property
Public Overrides ReadOnly Property IsNotInheritable As Boolean
Get
Return (_flags And TypeAttributes.Sealed) <> 0
End Get
End Property
Friend Overrides ReadOnly Property IsMetadataSealed As Boolean
Get
Return (_flags And TypeAttributes.Sealed) <> 0
End Get
End Property
Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean
Get
Return (_flags And TypeAttributes.WindowsRuntime) <> 0
End Get
End Property
Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean
Get
Return IsWindowsRuntimeImport
End Get
End Property
Friend Overrides Function GetGuidString(ByRef guidString As String) As Boolean
Return ContainingPEModule.Module.HasGuidAttribute(_handle, guidString)
End Function
Public NotOverridable Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
If _lazyMightContainExtensionMethods = ThreeState.Unknown Then
' Only top level non-generic types with an Extension attribute are
' valid containers of extension methods.
Dim result As Boolean = False
If _container.Kind = SymbolKind.Namespace AndAlso _arity = 0 Then
Dim containingModuleSymbol = Me.ContainingPEModule
If containingModuleSymbol.MightContainExtensionMethods AndAlso
containingModuleSymbol.Module.HasExtensionAttribute(Me._handle, ignoreCase:=True) Then
result = True
End If
End If
If result Then
_lazyMightContainExtensionMethods = ThreeState.True
Else
_lazyMightContainExtensionMethods = ThreeState.False
End If
End If
Return _lazyMightContainExtensionMethods = ThreeState.True
End Get
End Property
Friend Overrides ReadOnly Property HasEmbeddedAttribute As Boolean
Get
If Me._lazyHasEmbeddedAttribute = ThreeState.Unknown Then
Interlocked.CompareExchange(Me._lazyHasEmbeddedAttribute,
If(Me.ContainingPEModule.Module.HasVisualBasicEmbeddedAttribute(Me._handle),
ThreeState.True, ThreeState.False),
ThreeState.Unknown)
End If
Return Me._lazyHasEmbeddedAttribute = ThreeState.True
End Get
End Property
Friend Overrides Sub BuildExtensionMethodsMap(
map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)),
appendThrough As NamespaceSymbol
)
If Me.MightContainExtensionMethods Then
EnsureNestedTypesAreLoaded()
EnsureNonTypeMembersAreLoaded()
If Not appendThrough.BuildExtensionMethodsMap(map, _lazyMembers) Then
' Didn't find any extension methods, record the fact.
_lazyMightContainExtensionMethods = ThreeState.False
End If
End If
End Sub
Friend Overrides Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder,
appendThrough As NamedTypeSymbol)
If Me.MightContainExtensionMethods Then
EnsureNestedTypesAreLoaded()
EnsureNonTypeMembersAreLoaded()
If Not appendThrough.AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, _lazyMembers) Then
' Didn't find any extension methods, record the fact.
_lazyMightContainExtensionMethods = ThreeState.False
End If
End If
End Sub
Public Overrides ReadOnly Property TypeKind As TypeKind
Get
If _lazyTypeKind = TypeKind.Unknown Then
Dim result As TypeKind
If (_flags And TypeAttributes.Interface) <> 0 Then
result = TypeKind.Interface
Else
Dim base As TypeSymbol = GetDeclaredBase(Nothing)
result = TypeKind.Class
If base IsNot Nothing Then
' Code is cloned from MetaImport::DoImportBaseAndImplements()
Dim baseCorTypeId As SpecialType = base.SpecialType
If baseCorTypeId = SpecialType.System_Enum Then
' Enum
result = TypeKind.Enum
ElseIf baseCorTypeId = SpecialType.System_MulticastDelegate OrElse
(baseCorTypeId = SpecialType.System_Delegate AndAlso Me.SpecialType <> SpecialType.System_MulticastDelegate) Then
' Delegate
result = TypeKind.Delegate
ElseIf (baseCorTypeId = SpecialType.System_ValueType AndAlso
Me.SpecialType <> SpecialType.System_Enum) Then
' Struct
result = TypeKind.Structure
ElseIf Me.Arity = 0 AndAlso
Me.ContainingType Is Nothing AndAlso
ContainingPEModule.Module.HasAttribute(Me._handle, AttributeDescription.StandardModuleAttribute) Then
result = TypeKind.Module
End If
End If
End If
_lazyTypeKind = result
End If
Return CType(_lazyTypeKind, TypeKind)
End Get
End Property
Friend Overrides ReadOnly Property IsInterface As Boolean
Get
Return (_flags And TypeAttributes.Interface) <> 0
End Get
End Property
Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String
' Note: m_lazyDocComment is passed ByRef
Return PEDocumentationCommentUtils.GetDocumentationComment(
Me, ContainingPEModule, preferredCulture, cancellationToken, _lazyDocComment)
End Function
Friend Overrides ReadOnly Property IsComImport As Boolean
Get
Return (_flags And TypeAttributes.Import) <> 0
End Get
End Property
Friend Overrides ReadOnly Property CoClassType As TypeSymbol
Get
If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then
Interlocked.CompareExchange(_lazyCoClassType,
MakeComImportCoClassType(),
DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol))
End If
Return _lazyCoClassType
End Get
End Property
Private Function MakeComImportCoClassType() As TypeSymbol
If Not Me.IsInterface Then
Return Nothing
End If
Dim coClassTypeName As String = Nothing
If Not Me.ContainingPEModule.Module.HasStringValuedAttribute(Me._handle, AttributeDescription.CoClassAttribute, coClassTypeName) Then
Return Nothing
End If
Dim decoder As New MetadataDecoder(Me.ContainingPEModule)
Return decoder.GetTypeSymbolForSerializedType(coClassTypeName)
End Function
Friend Overrides ReadOnly Property DefaultPropertyName As String
Get
' Unset value is Nothing. No default member is String.Empty.
If _lazyDefaultPropertyName Is Nothing Then
Dim memberName = GetDefaultPropertyName()
Interlocked.CompareExchange(_lazyDefaultPropertyName, If(memberName, String.Empty), Nothing)
End If
' Return Nothing rather than String.Empty for no default member.
Return If(String.IsNullOrEmpty(_lazyDefaultPropertyName), Nothing, _lazyDefaultPropertyName)
End Get
End Property
Private Function GetDefaultPropertyName() As String
Dim memberName As String = Nothing
ContainingPEModule.Module.HasDefaultMemberAttribute(Me._handle, memberName)
If memberName IsNot Nothing Then
For Each member In GetMembers(memberName)
' Allow Default Shared properties for consistency with Dev10.
If member.Kind = SymbolKind.Property Then
Return memberName
End If
Next
End If
Return Nothing
End Function
Private Function CreateNestedTypes() As Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol))
Dim members = ArrayBuilder(Of PENamedTypeSymbol).GetInstance()
Dim moduleSymbol = Me.ContainingPEModule
Dim [module] = moduleSymbol.Module
Try
For Each nestedTypeDef In [module].GetNestedTypeDefsOrThrow(_handle)
If [module].ShouldImportNestedType(nestedTypeDef) Then
members.Add(New PENamedTypeSymbol(moduleSymbol, Me, nestedTypeDef))
End If
Next
Catch mrEx As BadImageFormatException
End Try
Dim children = members.GroupBy(Function(t) t.Name, IdentifierComparison.Comparer)
Dim types = New Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol))(IdentifierComparison.Comparer)
For Each c In children
types.Add(c.Key, c.ToArray().AsImmutableOrNull())
Next
members.Free()
Return types
End Function
Private Sub CreateFields(members As ArrayBuilder(Of Symbol),
<Out()> ByRef witheventPropertyNames As HashSet(Of String))
Dim moduleSymbol = Me.ContainingPEModule
Dim [module] = moduleSymbol.Module
Try
For Each fieldDef In [module].GetFieldsOfTypeOrThrow(_handle)
Dim import As Boolean
Try
import = [module].ShouldImportField(fieldDef, moduleSymbol.ImportOptions)
If Not import Then
Select Case Me.TypeKind
Case TypeKind.Structure
Dim specialType = Me.SpecialType
If specialType = SpecialType.None OrElse specialType = SpecialType.System_Nullable_T Then
' This is an ordinary struct
If ([module].GetFieldDefFlagsOrThrow(fieldDef) And FieldAttributes.Static) = 0 Then
import = True
End If
End If
Case TypeKind.Enum
If ([module].GetFieldDefFlagsOrThrow(fieldDef) And FieldAttributes.Static) = 0 Then
import = True
End If
End Select
End If
Catch mrEx As BadImageFormatException
End Try
If import Then
members.Add(New PEFieldSymbol(moduleSymbol, Me, fieldDef))
End If
Dim witheventPropertyName As String = Nothing
If [module].HasAccessedThroughPropertyAttribute(fieldDef, witheventPropertyName) Then
' Dev10 does not check if names are duplicated, but it does check
' that withevents names match some property name using identifier match
' So if names are duplicated they would refer to same property.
' We will just put names in a set.
If witheventPropertyNames Is Nothing Then
witheventPropertyNames = New HashSet(Of String)(IdentifierComparison.Comparer)
End If
witheventPropertyNames.Add(witheventPropertyName)
End If
Next
Catch mrEx As BadImageFormatException
End Try
End Sub
Private Function CreateMethods() As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol)
Dim methods = New Dictionary(Of MethodDefinitionHandle, PEMethodSymbol)()
Dim moduleSymbol = Me.ContainingPEModule
Dim [module] = moduleSymbol.Module
Try
For Each methodDef In [module].GetMethodsOfTypeOrThrow(_handle)
If [module].ShouldImportMethod(methodDef, moduleSymbol.ImportOptions) Then
methods.Add(methodDef, New PEMethodSymbol(moduleSymbol, Me, methodDef))
End If
Next
Catch mrEx As BadImageFormatException
End Try
Return methods
End Function
Private Sub CreateProperties(methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), members As ArrayBuilder(Of Symbol))
Dim moduleSymbol = Me.ContainingPEModule
Dim [module] = moduleSymbol.Module
Try
For Each propertyDef In [module].GetPropertiesOfTypeOrThrow(_handle)
Try
Dim methods = [module].GetPropertyMethodsOrThrow(propertyDef)
Dim getMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, methods.Getter)
Dim setMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, methods.Setter)
If (getMethod IsNot Nothing) OrElse (setMethod IsNot Nothing) Then
members.Add(PEPropertySymbol.Create(moduleSymbol, Me, propertyDef, getMethod, setMethod))
End If
Catch mrEx As BadImageFormatException
End Try
Next
Catch mrEx As BadImageFormatException
End Try
End Sub
Private Sub CreateEvents(methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), members As ArrayBuilder(Of Symbol))
Dim moduleSymbol = Me.ContainingPEModule
Dim [module] = moduleSymbol.Module
Try
For Each eventRid In [module].GetEventsOfTypeOrThrow(_handle)
Try
Dim methods = [module].GetEventMethodsOrThrow(eventRid)
' NOTE: C# ignores all other accessors (most notably, raise/fire).
Dim addMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, methods.Adder)
Dim removeMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, methods.Remover)
Dim raiseMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, methods.Raiser)
' VB ignores events that do not have both Add and Remove.
If (addMethod IsNot Nothing) AndAlso (removeMethod IsNot Nothing) Then
members.Add(New PEEventSymbol(moduleSymbol, Me, eventRid, addMethod, removeMethod, raiseMethod))
End If
Catch mrEx As BadImageFormatException
End Try
Next
Catch mrEx As BadImageFormatException
End Try
End Sub
Private Shared Function GetAccessorMethod(moduleSymbol As PEModuleSymbol, methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), methodDef As MethodDefinitionHandle) As PEMethodSymbol
If methodDef.IsNil Then
Return Nothing
End If
Dim method As PEMethodSymbol = Nothing
Dim found As Boolean = methodHandleToSymbol.TryGetValue(methodDef, method)
Debug.Assert(found OrElse Not moduleSymbol.Module.ShouldImportMethod(methodDef, moduleSymbol.ImportOptions))
Return method
End Function
Friend Overrides Function GetUseSiteErrorInfo() As DiagnosticInfo
If _lazyUseSiteErrorInfo Is ErrorFactory.EmptyErrorInfo Then
_lazyUseSiteErrorInfo = CalculateUseSiteErrorInfoImpl()
End If
Return _lazyUseSiteErrorInfo
End Function
Private Function CalculateUseSiteErrorInfoImpl() As DiagnosticInfo
Dim diagnostic = CalculateUseSiteErrorInfo()
If diagnostic Is Nothing Then
' Check if this type Is marked by RequiredAttribute attribute.
' If so mark the type as bad, because it relies upon semantics that are not understood by the VB compiler.
If Me.ContainingPEModule.Module.HasRequiredAttributeAttribute(Me.Handle) Then
Return ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, Me)
End If
Dim typeKind = Me.TypeKind
Dim specialtype = Me.SpecialType
If (typeKind = TypeKind.Class OrElse typeKind = TypeKind.Module) AndAlso
specialtype <> SpecialType.System_Enum AndAlso specialtype <> SpecialType.System_MulticastDelegate Then
Dim base As TypeSymbol = GetDeclaredBase(Nothing)
If base?.SpecialType = SpecialType.None AndAlso base.ContainingAssembly?.IsMissing Then
Dim missingType = TryCast(base, MissingMetadataTypeSymbol.TopLevel)
If missingType IsNot Nothing AndAlso missingType.Arity = 0 Then
Dim emittedName As String = MetadataHelpers.BuildQualifiedName(missingType.NamespaceName, missingType.MetadataName)
Select Case SpecialTypes.GetTypeFromMetadataName(emittedName)
Case SpecialType.System_Enum,
SpecialType.System_Delegate,
SpecialType.System_MulticastDelegate,
SpecialType.System_ValueType
' This might be a structure, an enum, or a delegate
Return missingType.GetUseSiteErrorInfo()
End Select
End If
End If
End If
' Verify type parameters for containing types
' match those on the containing types.
If Not MatchesContainingTypeParameters() Then
Return ErrorFactory.ErrorInfo(ERRID.ERR_NestingViolatesCLS1, Me)
End If
End If
Return diagnostic
End Function
''' <summary>
''' Return true if the type parameters specified on the nested type (Me),
''' that represent the corresponding type parameters on the containing
''' types, in fact match the actual type parameters on the containing types.
''' </summary>
Private Function MatchesContainingTypeParameters() As Boolean
If _genericParameterHandles.Count = 0 Then
Return True
End If
Dim container = ContainingType
If container Is Nothing Then
Return True
End If
Dim containingTypeParameters = container.GetAllTypeParameters()
Dim n = containingTypeParameters.Length
If n = 0 Then
Return True
End If
' Create an instance of PENamedTypeSymbol for the nested type, but
' with all type parameters, from the nested type and all containing
' types. The type parameters on this temporary type instance are used
' for comparison with those on the actual containing types. The
' containing symbol for the temporary type is the namespace directly.
Dim nestedType = New PENamedTypeSymbol(ContainingPEModule, DirectCast(ContainingNamespace, PENamespaceSymbol), _handle)
Dim nestedTypeParameters = nestedType.TypeParameters
Dim containingTypeMap = TypeSubstitution.Create(
container,
containingTypeParameters,
IndexedTypeParameterSymbol.Take(n).As(Of TypeSymbol))
Dim nestedTypeMap = TypeSubstitution.Create(
nestedType,
nestedTypeParameters,
IndexedTypeParameterSymbol.Take(nestedTypeParameters.Length).As(Of TypeSymbol))
For i = 0 To n - 1
Dim containingTypeParameter = containingTypeParameters(i)
Dim nestedTypeParameter = nestedTypeParameters(i)
If Not MethodSignatureComparer.HaveSameConstraints(
containingTypeParameter,
containingTypeMap,
nestedTypeParameter,
nestedTypeMap) Then
Return False
End If
Next
Return True
End Function
''' <summary>
''' Force all declaration errors to be generated.
''' </summary>
Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken)
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(_lazyObsoleteAttributeData, _handle, ContainingPEModule)
Return _lazyObsoleteAttributeData
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
If Me._lazyConditionalAttributeSymbols.IsDefault Then
Dim conditionalSymbols As ImmutableArray(Of String) = ContainingPEModule.Module.GetConditionalAttributeValues(_handle)
Debug.Assert(Not conditionalSymbols.IsDefault)
ImmutableInterlocked.InterlockedCompareExchange(_lazyConditionalAttributeSymbols, conditionalSymbols, Nothing)
End If
Return Me._lazyConditionalAttributeSymbols
End Function
Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo
If _lazyAttributeUsageInfo.IsNull Then
_lazyAttributeUsageInfo = DecodeAttributeUsageInfo()
End If
Debug.Assert(Not _lazyAttributeUsageInfo.IsNull)
Return _lazyAttributeUsageInfo
End Function
Private Function DecodeAttributeUsageInfo() As AttributeUsageInfo
Dim attributeUsageHandle = Me.ContainingPEModule.Module.GetAttributeUsageAttributeHandle(_handle)
If Not attributeUsageHandle.IsNil Then
Dim decoder = New MetadataDecoder(ContainingPEModule)
Dim positionalArgs As TypedConstant() = Nothing
Dim namedArgs As KeyValuePair(Of String, TypedConstant)() = Nothing
If decoder.GetCustomAttribute(attributeUsageHandle, positionalArgs, namedArgs) Then
Return AttributeData.DecodeAttributeUsageAttribute(positionalArgs(0), namedArgs.AsImmutableOrNull())
End If
End If
Dim baseType = Me.BaseTypeNoUseSiteDiagnostics
Return If(baseType IsNot Nothing, baseType.GetAttributeUsageInfo(), AttributeUsageInfo.Default)
End Function
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean
Get
If _lazyIsExtensibleInterface = ThreeState.Unknown Then
_lazyIsExtensibleInterface = DecodeIsExtensibleInterface().ToThreeState()
End If
Return _lazyIsExtensibleInterface.Value
End Get
End Property
Private Function DecodeIsExtensibleInterface() As Boolean
If Me.IsInterfaceType() Then
If Me.HasAttributeForExtensibleInterface() Then
Return True
End If
For Each [interface] In Me.AllInterfacesNoUseSiteDiagnostics
If [interface].IsExtensibleInterfaceNoUseSiteDiagnostics Then
Return True
End If
Next
End If
Return False
End Function
Private Function HasAttributeForExtensibleInterface() As Boolean
Dim metadataModule = Me.ContainingPEModule.Module
' Is interface marked with 'TypeLibTypeAttribute( flags w/o TypeLibTypeFlags.FNonExtensible )' attribute
Dim flags As Cci.TypeLibTypeFlags = Nothing
If metadataModule.HasTypeLibTypeAttribute(Me._handle, flags) AndAlso
(flags And Cci.TypeLibTypeFlags.FNonExtensible) = 0 Then
Return True
End If
' Is interface marked with 'InterfaceTypeAttribute( flags with ComInterfaceType.InterfaceIsIDispatch )' attribute
Dim interfaceType As ComInterfaceType = Nothing
If metadataModule.HasInterfaceTypeAttribute(Me._handle, interfaceType) AndAlso
(interfaceType And Cci.Constants.ComInterfaceType_InterfaceIsIDispatch) <> 0 Then
Return True
End If
Return False
End Function
''' <remarks>
''' This is for perf, not for correctness.
''' </remarks>
Friend NotOverridable Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation
Get
Return Nothing
End Get
End Property
''' <summary>
''' Returns the index of the first member of the specific kind.
''' Returns the number of members if not found.
''' </summary>
Private Shared Function GetIndexOfFirstMember(members As ImmutableArray(Of Symbol), kind As SymbolKind) As Integer
Dim n = members.Length
For i = 0 To n - 1
If members(i).Kind = kind Then
Return i
End If
Next
Return n
End Function
''' <summary>
''' Returns all members of the specific kind, starting at the optional offset.
''' Members of the same kind are assumed to be contiguous.
''' </summary>
Private Overloads Shared Iterator Function GetMembers(Of TSymbol As Symbol)(members As ImmutableArray(Of Symbol), kind As SymbolKind, Optional offset As Integer = -1) As IEnumerable(Of TSymbol)
If offset < 0 Then
offset = GetIndexOfFirstMember(members, kind)
End If
Dim n = members.Length
For i = offset To n - 1
Dim member = members(i)
If member.Kind <> kind Then
Return
End If
Yield DirectCast(member, TSymbol)
Next
End Function
Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol)
Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)()
End Function
End Class
End Namespace
|
robinsedlaczek/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb
|
Visual Basic
|
apache-2.0
| 65,403
|
Imports System.IO
Imports System.Windows.Forms
Public Class frmNewEmail
Public DocumentTemplate As String = ""
Dim lPass As Long
Public attachFile As OpenFileDialog
Private Sub frmNewEmail_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
txtFrom.Text = KeyValue("popfromemail")
txtFrom.ReadOnly = True
btnRichText.Checked = True
btnHTML.Checked = False
ShowBodyContainer(DocumentTemplate)
End Sub
Private Sub InitialBrowserLoader(ByVal sInitialValue As String)
Dim doc As HtmlDocument
ToFile(sInitialValue)
If lPass = 0 Then WebBrowser1.Navigate(GetGridPath("Email") + "\temp.html")
End Sub
Private Sub ShowBodyContainer(ByVal sInitialValue As String)
If btnRichText.Checked = True Then
RichTextBox1.Width = WebBrowser1.Width
RichTextBox1.Height = WebBrowser1.Height
RichTextBox1.Visible = True
RichTextBox1.Top = Panel1.Top
WebBrowser1.Visible = False
RichTextBox1.Text = sInitialValue
Else
RichTextBox1.Visible = False
WebBrowser1.Visible = True
lPass = 0
InitialBrowserLoader(sInitialValue)
End If
End Sub
Private Sub ToFile(ByVal sData As String)
Dim oWriter As New System.IO.StreamWriter(GetGridPath("email") + "\temp.html")
oWriter.Write(sData)
oWriter.Close()
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
lPass = lPass + 1
If lPass = 1 Then
WebBrowser1.Document.DomDocument.GetType.GetProperty("designMode").SetValue(WebBrowser1.Document.DomDocument, "On", Nothing)
End If
End Sub
Private Function GetBody() As String
If btnRichText.Checked Then
GetBody = RichTextBox1.Text
Else
GetBody = WebBrowser1.DocumentText
End If
End Function
Private Sub SetBody(ByVal sBody As String)
If btnRichText.Checked Then
RichTextBox1.Text = sBody
Else
WebBrowser1.DocumentText = sBody
End If
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim client As Net.Mail.SmtpClient = New Net.Mail.SmtpClient(KeyValue("smtphost"))
Dim n As New System.Net.NetworkCredential(KeyValue("popuser"), KeyValue("poppassword"))
client.UseDefaultCredentials = False
client.Credentials = n
client.Port = 587
client.EnableSsl = True
Dim msg As Net.Mail.MailMessage = New Net.Mail.MailMessage
Dim em As New System.Net.Mail.MailAddress(txtFrom.Text, txtFrom.Text)
msg.From = em
Dim emto As New System.Net.Mail.MailAddress(txtTo.Text, txtTo.Text)
msg.To.Add(emto)
msg.Body = GetBody()
For x = 0 To listAttachments.Nodes.Count - 1
Dim sFile As String
sFile = listAttachments.Nodes(x).Tag
If System.IO.File.Exists(sFile) Then
Dim mat As New Net.Mail.Attachment(sFile)
msg.Attachments.Add(mat)
End If
Next
msg.Subject = txtSubject.Text
If InStr(1, LCase(msg.Body), "html") > 0 Then msg.IsBodyHtml = True
Dim sBody As String
sBody = frmMail.Encrypt(msg.Body)
msg.Body = sBody
msg.Subject = msg.Subject + " - encrypted"
Try
client.Send(msg)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error occurred while Sending")
End Try
Me.Close()
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
listAttachments.Nodes.Clear()
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
attachFile = New OpenFileDialog
Dim result As DialogResult = attachFile.ShowDialog()
If result <> DialogResult.OK Then
Return
End If
Dim file As New FileInfo(attachFile.FileName)
Dim na As TreeNode
na = listAttachments.Nodes.Add(file.Name)
na.Tag = file.FullName
End Sub
Private Sub btnHTML_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHTML.CheckedChanged
If btnHTML.Checked Then
Dim sBody As String
sBody = RichTextBox1.Text
'SetBody(sBody)
ShowBodyContainer(sBody)
End If
End Sub
Private Sub btnRichText_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRichText.CheckedChanged
If btnRichText.Checked Then
Dim sBody As String
sBody = WebBrowser1.DocumentText
RichTextBox1.Text = sBody
ShowBodyContainer(sBody)
End If
End Sub
End Class
|
icede/Gridcoin-master
|
src/boinc/boinc/frmNewEmail.vb
|
Visual Basic
|
mit
| 5,147
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.CompilerServices
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods
Public Class WithStatementSymbolsTests
Inherits BasicTestBase
<Fact()>
Public Sub LocalInEmptyWithStatementExpression()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression">
<file name="a.vb">
Module WithTestScoping
Sub Main()
Dim o1 As New Object()
With [#0 o1 0#]
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As System.Object", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub NestedWithWithLambdasAndObjectInitializers()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression">
<file name="a.vb">
Imports System
Structure SS1
Public A As String
Public B As String
End Structure
Structure SS2
Public X As SS1
Public Y As SS1
End Structure
Structure Clazz
Shared Sub Main(args() As String)
Dim t As New Clazz(1)
End Sub
Sub New(i As Integer)
Dim outer As New SS2
With outer
Dim a As New [#0 SS2 0#]() With {.X = Function() As SS1
With .Y
a.Y.B = a.Y.A
a.Y.A = "1"
End With
Return .Y
End Function.Invoke()}
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("SS2", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub LocalInEmptyWithStatementExpression_Struct()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression_Struct">
<file name="a.vb">
Structure STR
Public F As String
End Structure
Module WithTestScoping
Sub Main()
Dim o1 As New STR()
With [#0 o1 0#]
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As STR", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub LocalInWithStatementExpression()
Dim compilationDef =
<compilation name="LocalInWithStatementExpression">
<file name="a.vb">
Module WithTestScoping
Sub Main()
Dim o1 As New Object()
With [#0 o1 0#]
Dim o1 = Nothing
With [#1 o1 1#]
Dim o2 = Nothing
End With
With [#2 New Object() 2#]
Dim o1 As New Object()
Dim o2 = Nothing
End With
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes,
<errors>
BC30616: Variable 'o1' hides a variable in an enclosing block.
Dim o1 = Nothing
~~
BC30616: Variable 'o1' hides a variable in an enclosing block.
Dim o1 As New Object()
~~
</errors>)
Assert.Equal(3, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As System.Object", info0.Symbol.ToTestDisplayString())
Dim info1 = model.GetSemanticInfoSummary(DirectCast(nodes(1), ExpressionSyntax))
Assert.NotNull(info1.Symbol)
Assert.Equal("o1 As System.Object", info1.Symbol.ToTestDisplayString())
Assert.NotSame(info0.Symbol, info1.Symbol)
Dim info2 = model.GetSemanticInfoSummary(DirectCast(nodes(2), ExpressionSyntax))
Assert.NotNull(info2.Symbol)
Assert.Equal("Sub System.Object..ctor()", info2.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub NestedWithStatements()
Dim compilationDef =
<compilation name="NestedWithStatements">
<file name="a.vb">
Structure Clazz
Structure SS
Public FLD As String
End Structure
Public FLD As SS
Sub TEST()
With Me
With [#0 .FLD 0#]
Dim v As String = .GetType() .ToString()
End With
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("Clazz.FLD As Clazz.SS", info0.Symbol.ToTestDisplayString())
Dim systemObject = compilation.GetTypeByMetadataName("System.Object")
Dim conv = model.ClassifyConversion(DirectCast(nodes(0), ExpressionSyntax), systemObject)
Assert.True(conv.IsWidening)
End Sub
<Fact()>
Public Sub LocalInWithStatementExpression3()
Dim compilationDef =
<compilation name="LocalInWithStatementExpression3">
<file name="a.vb">
Structure Clazz
Structure SSS
Public FLD As String
End Structure
Structure SS
Public FS As SSS
End Structure
Public FLD As SS
Sub TEST()
With Me
With .FLD
With .FS
Dim v = [#0 .FLD 0#]
End With
End With
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("Clazz.SSS.FLD As System.String", info0.Symbol.ToTestDisplayString())
Dim systemObject = compilation.GetTypeByMetadataName("System.Object")
Dim conv = model.ClassifyConversion(DirectCast(nodes(0), ExpressionSyntax), systemObject)
Assert.True(conv.IsWidening)
End Sub
#Region "Utils"
Private Function Compile(text As XElement, ByRef tree As SyntaxTree, nodes As List(Of SyntaxNode), Optional errors As XElement = Nothing) As VisualBasicCompilation
Dim spans As New List(Of TextSpan)
ExtractTextIntervals(text, spans)
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndReferences(text, {SystemRef, SystemCoreRef, MsvbRef})
If errors Is Nothing Then
CompilationUtils.AssertNoErrors(compilation)
Else
CompilationUtils.AssertTheseDiagnostics(compilation, errors)
End If
tree = compilation.SyntaxTrees(0)
For Each span In spans
Dim stack As New Stack(Of SyntaxNode)
stack.Push(tree.GetRoot())
While stack.Count > 0
Dim node = stack.Pop()
If span.Contains(node.Span) Then
nodes.Add(node)
Exit While
End If
For Each child In node.ChildNodes
stack.Push(child)
Next
End While
Next
Return compilation
End Function
Private Shared Sub ExtractTextIntervals(text As XElement, nodes As List(Of TextSpan))
text.<file>.Value = text.<file>.Value.Trim().Replace(vbLf, vbCrLf)
Dim index As Integer = 0
Do
Dim startMarker = "[#" & index
Dim endMarker = index & "#]"
' opening '[#{0-9}'
Dim start = text.<file>.Value.IndexOf(startMarker)
If start < 0 Then
Exit Do
End If
' closing '{0-9}#]'
Dim [end] = text.<file>.Value.IndexOf(endMarker)
Assert.InRange([end], 0, Int32.MaxValue)
nodes.Add(New TextSpan(start, [end] - start + 3))
text.<file>.Value = text.<file>.Value.Replace(startMarker, " ").Replace(endMarker, " ")
index += 1
Assert.InRange(index, 0, 9)
Loop
End Sub
Private Shared Function GetNamedTypeSymbol(c As VisualBasicCompilation, namedTypeName As String, Optional fromCorLib As Boolean = False) As NamedTypeSymbol
Dim nameParts = namedTypeName.Split("."c)
Dim srcAssembly = DirectCast(c.Assembly, SourceAssemblySymbol)
Dim nsSymbol As NamespaceSymbol = (If(fromCorLib, srcAssembly.CorLibrary, srcAssembly)).GlobalNamespace
For Each ns In nameParts.Take(nameParts.Length - 1)
nsSymbol = DirectCast(nsSymbol.GetMember(ns), NamespaceSymbol)
Next
Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol)
End Function
#End Region
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/WithStatementSymbolsTests.vb
|
Visual Basic
|
apache-2.0
| 11,418
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnnecessaryImports
Partial Public Class RemoveUnnecessaryImportsTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicRemoveUnnecessaryImportsDiagnosticAnalyzer(),
New VisualBasicRemoveUnnecessaryImportsCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestProjectLevelMemberImport1() As Task
Await TestAsync(
"[|Imports System
Module Program
Sub Main(args As DateTime())
End Sub
End Module|]",
"Module Program
Sub Main(args As DateTime())
End Sub
End Module",
parseOptions:=TestOptions.Regular,
compilationOptions:=TestOptions.ReleaseExe.WithGlobalImports({GlobalImport.Parse("System")}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestProjectLevelMemberImport2() As Task
Await TestMissingInRegularAndScriptAsync(
"[|Imports System
Module Program
Sub Main(args As DateTime())
End Sub
End Module|]")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestNoImports() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
End Sub
End Module|]",
"Module Program
Sub Main(args As String())
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestSimpleTypeName() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim s As DateTime
End Sub
End Module|]",
"Imports System
Module Program
Sub Main(args As String())
Dim s As DateTime
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestGenericTypeName() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim s As List(Of Integer)
End Sub
End Module|]",
"Imports System.Collections.Generic
Module Program
Sub Main(args As String())
Dim s As List(Of Integer)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestNamespaceName() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim s As Collections.Generic.List(Of Integer)
End Sub
End Module|]",
"Imports System
Module Program
Sub Main(args As String())
Dim s As Collections.Generic.List(Of Integer)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestAliasName() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports G = System.Collections.Generic
Module Program
Sub Main(args As String())
Dim s As G.List(Of Integer)
End Sub
End Module|]",
"Imports G = System.Collections.Generic
Module Program
Sub Main(args As String())
Dim s As G.List(Of Integer)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestExtensionMethod() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
args.Where(Function(a) a.Length > 21)
End Sub
End Module|]",
"Imports System.Linq
Module Program
Sub Main(args As String())
args.Where(Function(a) a.Length > 21)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestModuleMember() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports Foo
Namespace Foo
Public Module M
Public Sub Bar(i As Integer)
End Sub
End Module
End Namespace
Module Program
Sub Main(args As String())
Bar(0)
End Sub
End Module|]",
"Imports Foo
Namespace Foo
Public Module M
Public Sub Bar(i As Integer)
End Sub
End Module
End Namespace
Module Program
Sub Main(args As String())
Bar(0)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestInvalidCodeRemovesImports() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
gibberish Dim lst As List(Of String)
Console.WriteLine(""TEST"")
End Sub
End Module|]",
"Imports System
Module Program
Sub Main()
gibberish Dim lst As List(Of String)
Console.WriteLine(""TEST"")
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestExcludedCodeIsIgnored() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System
Module Program
Sub Main()
#If False Then
Console.WriteLine(""TEST"")
#End If
End Sub
End Module|]",
"Module Program
Sub Main()
#If False Then
Console.WriteLine(""TEST"")
#End If
End Sub
End Module")
End Function
<WorkItem(541744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541744")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestCommentsAroundImportsStatement() As Task
Await TestInRegularAndScriptAsync(
<Text>'c1
[|Imports System.Configuration 'c2
Imports System, System.Collections.Generic 'c3
'c4
Module Module1
Sub Main()
Dim x As List(Of Integer)
End Sub
End Module|]</Text>.NormalizedValue,
<Text>'c1
Imports System.Collections.Generic 'c3
'c4
Module Module1
Sub Main()
Dim x As List(Of Integer)
End Sub
End Module</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(541747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541747")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestAttribute() As Task
Await TestMissingInRegularAndScriptAsync(
"[|Imports SomeNamespace
<SomeAttr>
Class Foo
End Class
Namespace SomeNamespace
Public Class SomeAttrAttribute
Inherits Attribute
End Class
End Namespace|]")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestAttributeArgument() As Task
Await TestMissingInRegularAndScriptAsync(
"[|Imports System
Imports SomeNamespace
<SomeAttribute(Foo.C)>
Module Program
Sub Main(args As String())
End Sub
End Module
Namespace SomeNamespace
Public Enum Foo
A
B
C
End Enum
End Namespace
Public Class SomeAttribute
Inherits Attribute
Public Sub New(x As SomeNamespace.Foo)
End Sub
End Class|]")
End Function
<WorkItem(541757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541757")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestImportsSurroundedByDirectives() As Task
Await TestInRegularAndScriptAsync(
"#If True Then
[|Imports System.Collections.Generic
#End If
Module Program
End Module|]",
"#If True Then
#End If
Module Program
End Module")
End Function
<WorkItem(541758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541758")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemovingUnbindableImports() As Task
Await TestInRegularAndScriptAsync(
"[|Imports gibberish
Module Program
End Module|]",
"Module Program
End Module")
End Function
<WorkItem(541744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541744")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestPreservePrecedingComments() As Task
Await TestInRegularAndScriptAsync(
<Text>' c1
[|Imports System 'c2
' C3
Module Module1
End Module|]</Text>.NormalizedValue,
<Text>' c1
' C3
Module Module1
End Module</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(541757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541757")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestDirective1() As Task
Await TestInRegularAndScriptAsync(
<Text>#If True Then
[|Imports System.Collections.Generic
#End If
Module Program
End Module|]</Text>.NormalizedValue,
<Text>#If True Then
#End If
Module Program
End Module</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(541757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541757")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestDirective2() As Task
Await TestInRegularAndScriptAsync(
<Text>#If True Then
[|Imports System
Imports System.Collections.Generic
#End If
Module Program
Dim a As List(Of Integer)
End Module|]</Text>.NormalizedValue,
<Text>#If True Then
Imports System.Collections.Generic
#End If
Module Program
Dim a As List(Of Integer)
End Module</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(541932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541932")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestImportsClauseRemoval1() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System, foo, System.Collections.Generic
Module Program
Sub Main(args As String())
Console.WriteLine(""TEST"")
Dim q As List(Of Integer)
End Sub
End Module
Namespace foo
Class bar
End Class
End Namespace|]",
"Imports System, System.Collections.Generic
Module Program
Sub Main(args As String())
Console.WriteLine(""TEST"")
Dim q As List(Of Integer)
End Sub
End Module
Namespace foo
Class bar
End Class
End Namespace")
End Function
<WorkItem(541932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541932")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestImportsClauseRemoval2() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System, System.Collections.Generic, foo
Module Program
Sub Main(args As String())
Console.WriteLine(""TEST"")
Dim q As List(Of Integer)
End Sub
End Module
Namespace foo
Class bar
End Class
End Namespace|]",
"Imports System, System.Collections.Generic
Module Program
Sub Main(args As String())
Console.WriteLine(""TEST"")
Dim q As List(Of Integer)
End Sub
End Module
Namespace foo
Class bar
End Class
End Namespace")
End Function
<WorkItem(541932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541932")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestImportsClauseRemoval3() As Task
Await TestInRegularAndScriptAsync(
"[|Imports foo, System, System.Collections.Generic
Module Program
Sub Main(args As String())
Console.WriteLine(""TEST"")
Dim q As List(Of Integer)
End Sub
End Module
Namespace foo
Class bar
End Class
End Namespace|]",
"Imports System, System.Collections.Generic
Module Program
Sub Main(args As String())
Console.WriteLine(""TEST"")
Dim q As List(Of Integer)
End Sub
End Module
Namespace foo
Class bar
End Class
End Namespace")
End Function
<WorkItem(541758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541758")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestUnbindableNamespace() As Task
Await TestInRegularAndScriptAsync(
"[|Imports gibberish
Module Program
End Module|]",
"Module Program
End Module")
End Function
<WorkItem(541780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541780")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemoveClause() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System, foo, System.Collections.Generic
Module Program
Sub Main(args As String())
Console.WriteLine(""TEST"")
Dim q As List(Of Integer)
End Sub
End Module
Namespace foo
Class bar
End Class
End Namespace|]",
"Imports System, System.Collections.Generic
Module Program
Sub Main(args As String())
Console.WriteLine(""TEST"")
Dim q As List(Of Integer)
End Sub
End Module
Namespace foo
Class bar
End Class
End Namespace")
End Function
<WorkItem(528603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemoveClauseWithExplicitLC1() As Task
Await TestInRegularAndScriptAsync(
"[|Imports A _
, B
Module Program
Sub Main(args As String())
Dim q As CA
End Sub
End Module
Namespace A
Public Class CA
End Class
End Namespace
Namespace B
Public Class CB
End Class
End Namespace|]",
"Imports A
Module Program
Sub Main(args As String())
Dim q As CA
End Sub
End Module
Namespace A
Public Class CA
End Class
End Namespace
Namespace B
Public Class CB
End Class
End Namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemoveClauseWithExplicitLC2() As Task
Await TestInRegularAndScriptAsync(
"[|Imports B _
, A
Module Program
Sub Main(args As String())
Dim q As CA
End Sub
End Module
Namespace A
Public Class CA
End Class
End Namespace
Namespace B
Public Class CB
End Class
End Namespace|]",
"Imports A
Module Program
Sub Main(args As String())
Dim q As CA
End Sub
End Module
Namespace A
Public Class CA
End Class
End Namespace
Namespace B
Public Class CB
End Class
End Namespace")
End Function
<WorkItem(528603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemoveClauseWithExplicitLC3() As Task
Await TestInRegularAndScriptAsync(
<Text>[|Imports A _
, B _
, C
Module Program
Sub Main()
Dim q As CB
End Sub
End Module
Namespace A
Public Class CA
End Class
End Namespace
Namespace B
Public Class CB
End Class
End Namespace
Namespace C
Public Class CC
End Class
End Namespace|]</Text>.NormalizedValue,
<Text>Imports B _
Module Program
Sub Main()
Dim q As CB
End Sub
End Module
Namespace A
Public Class CA
End Class
End Namespace
Namespace B
Public Class CB
End Class
End Namespace
Namespace C
Public Class CC
End Class
End Namespace</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestTypeImports() As Task
Await TestInRegularAndScriptAsync(
<Text>[|Imports Foo
Module Program
Sub Main()
End Sub
End Module
Public Class Foo
Shared Sub Bar()
End Sub
End Class|]</Text>.NormalizedValue,
<Text>Module Program
Sub Main()
End Sub
End Module
Public Class Foo
Shared Sub Bar()
End Sub
End Class</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(528603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestTypeImports_DoesNotRemove() As Task
Await TestMissingAsync(
<Text>[|Imports Foo
Module Program
Sub Main()
Bar()
End Sub
End Module
Public Class Foo
Shared Sub Bar()
End Sub
End Class|]</Text>.NormalizedValue)
' TODO: Enable testing in script when it comes online
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestAlias() As Task
Await TestInRegularAndScriptAsync(
<Text>[|Imports F = SomeNS
Module Program
Sub Main()
End Sub
End Module
Namespace SomeNS
Public Class Foo
End Class
End Namespace|]</Text>.NormalizedValue,
<Text>Module Program
Sub Main()
End Sub
End Module
Namespace SomeNS
Public Class Foo
End Class
End Namespace</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestAlias_DoesNotRemove() As Task
Await TestMissingInRegularAndScriptAsync(
<Text>[|Imports F = SomeNS
Module Program
Sub Main()
Dim q As F.Foo
End Sub
End Module
Namespace SomeNS
Public Class Foo
End Class
End Namespace|]</Text>.NormalizedValue)
End Function
<WorkItem(541809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541809")>
<WorkItem(16488, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestImportsOnSameLine1() As Task
Await TestInRegularAndScriptAsync(
<Text>[|Imports A : Imports B
Module Program
Sub Main()
Dim q As ClassA
End Sub
End Module
Namespace A
Public Class ClassA
End Class
End Namespace
Namespace B
Public Class ClassB
End Class
End Namespace|]</Text>.NormalizedValue,
<Text>Imports A
Module Program
Sub Main()
Dim q As ClassA
End Sub
End Module
Namespace A
Public Class ClassA
End Class
End Namespace
Namespace B
Public Class ClassB
End Class
End Namespace</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestImportsOnSameLine2() As Task
Await TestInRegularAndScriptAsync(
<Text>[|Imports A : Imports B
Imports C
Module Program
Sub Main()
Dim q1 As ClassA
Dim q2 As ClassC
End Sub
End Module
Namespace A
Public Class ClassA
End Class
End Namespace
Namespace B
Public Class ClassB
End Class
End Namespace
Namespace C
Public Class ClassC
End Class
End Namespace|]</Text>.NormalizedValue,
<Text>Imports A
Imports C
Module Program
Sub Main()
Dim q1 As ClassA
Dim q2 As ClassC
End Sub
End Module
Namespace A
Public Class ClassA
End Class
End Namespace
Namespace B
Public Class ClassB
End Class
End Namespace
Namespace C
Public Class ClassC
End Class
End Namespace</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(541808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541808")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestTypeImport1() As Task
Await TestMissingAsync(
"[|Imports Foo
Module Program
Sub Main()
Bar()
End Sub
End Module
Public Class Foo
Shared Sub Bar()
End Sub
End Class|]") 'TODO (tomat): modules not yet supported in script
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestTypeImport2() As Task
Await TestMissingAsync(
"[|Imports Foo
Module Program
Sub Main()
Dim q As Integer = Bar
End Sub
End Module
Public Class Foo
Public Shared Bar As Integer
End Sub
End Class|]") 'TODO (tomat): modules not yet supported in script
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestUnusedTypeImportIsRemoved() As Task
Await TestInRegularAndScriptAsync(
<Text>[|Imports SomeNS.Foo
Module Program
Sub Main(args As String())
End Sub
End Module
Namespace SomeNS
Module Foo
End Module
End Namespace|]</Text>.NormalizedValue,
<Text>Module Program
Sub Main(args As String())
End Sub
End Module
Namespace SomeNS
Module Foo
End Module
End Namespace</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(528643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528643")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestExtensionMethodLinq() As Task
' TODO: Enable script context testing.
Await TestMissingAsync(<Text>[|Imports System.Collections
Imports System
Imports SomeNS
Public Module Program
Sub Main()
Dim qq As Foo = New Foo()
Dim x As IEnumerable = From q In qq Select q
End Sub
End Module
Public Class Foo
Public Sub Foo()
End Sub
End Class
Namespace SomeNS
Public Module SomeClass
<System.Runtime.CompilerServices.ExtensionAttribute()>
Public Function [Select](ByRef o As Foo, f As Func(Of Object, Object)) As IEnumerable
Return Nothing
End Function
End Module
End Namespace|]</Text>.NormalizedValue, New TestParameters(parseOptions:=TestOptions.Regular))
End Function
<WorkItem(543217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543217")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestExtensionMethodLinq2() As Task
Await TestMissingInRegularAndScriptAsync(
<Text>[|Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim product = New With {Key .Name = "", Key .Price = 0}
Dim products = ToList(product)
Dim namePriceQuery = From prod In products
Select prod.Name, prod.Price
End Sub
Function ToList(Of T)(a As T) As IEnumerable(Of T)
Return Nothing
End Function
End Module
|]</Text>.NormalizedValue)
End Function
<WorkItem(542135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542135")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestImportedTypeUsedAsGenericTypeArgument() As Task
Await TestMissingInRegularAndScriptAsync(
<Text>[|Imports GenericThingie
Public Class GenericType(Of T)
End Class
Namespace GenericThingie
Public Class Something
End Class
End Namespace
Public Class Program
Sub foo()
Dim type As GenericType(Of Something)
End Sub
End Class|]</Text>.NormalizedValue)
End Function
<WorkItem(542132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542132")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemoveSuperfluousNewLines1() As Task
Await TestInRegularAndScriptAsync(
<Text>[|Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
End Sub
End Module|]</Text>.NormalizedValue,
<Text>Module Program
Sub Main(args As String())
End Sub
End Module</Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(542132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542132")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemoveSuperfluousNewLines2() As Task
Await TestInRegularAndScriptAsync(
<Text><![CDATA[[|Imports System
Imports System.Collections.Generic
Imports System.Linq
<Assembly: System.Obsolete()>
Module Program
Sub Main(args As String())
End Sub
End Module|]]]></Text>.NormalizedValue,
<Text><![CDATA[<Assembly: System.Obsolete()>
Module Program
Sub Main(args As String())
End Sub
End Module]]></Text>.NormalizedValue,
ignoreTrivia:=False)
End Function
<WorkItem(542895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542895")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRegressionFor10326() As Task
Await TestInRegularAndScriptAsync(
"[|Imports System.ComponentModel
<Foo(GetType(Category))>
Class Category
End Class|]",
"<Foo(GetType(Category))>
Class Category
End Class")
End Function
<WorkItem(712656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/712656")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemovalSpan1() As Task
Await TestSpansAsync(
<text> [|Imports System|]
Namespace N
End Namespace</text>.NormalizedValue)
End Function
<WorkItem(545434, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545434")>
<WorkItem(712656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/712656")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemovalSpan2() As Task
Await TestSpansAsync(
<text>
#Const A = 1
[|Imports System|]
#Const B = 1
Imports System.Runtime.InteropServices</text>.NormalizedValue,
diagnosticId:=IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId)
End Function
<WorkItem(545434, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545434")>
<WorkItem(712656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/712656")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemovalSpan3() As Task
Await TestSpansAsync(
<text>
#Const A = 1
Imports System
#Const B = 1
[|Imports System.Runtime.InteropServices|]</text>.NormalizedValue,
diagnosticId:=IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId)
End Function
<WorkItem(712656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/712656")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestRemovalSpan4() As Task
Await TestInRegularAndScriptAsync(
<text>
#Const A = 1
Imports System
[|#Const B = 1|]
Imports System.Runtime.InteropServices
Class C : Dim x As Action : End Class</text>.NormalizedValue,
<text>
#Const A = 1
Imports System
#Const B = 1
Class C : Dim x As Action : End Class</text>.NormalizedValue)
End Function
<WorkItem(545831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545831")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestImplicitElementAtOrDefault() As Task
Await TestInRegularAndScriptAsync(
<Text><) As C
End Function
End Module
End Namespace|]]]></Text>.NormalizedValue,
<Text><) As C
End Function
End Module
End Namespace]]></Text>.NormalizedValue)
End Function
<WorkItem(545964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545964")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)>
Public Async Function TestMissingOnSynthesizedEventType() As Task
Await TestMissingInRegularAndScriptAsync(
"[|Class C
Event E()
End Class|]")
End Function
End Class
End Namespace
|
amcasey/roslyn
|
src/EditorFeatures/VisualBasicTest/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests.vb
|
Visual Basic
|
apache-2.0
| 30,926
|
' 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.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class NamespaceBlockHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function GetHighlighterType() As Type
Return GetType(NamespaceBlockHighlighter)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestNamespace1() As Task
Await TestAsync(<Text>
{|Cursor:[|Namespace|]|} N1
[|End Namespace|]</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestNamespace2() As Task
Await TestAsync(<Text>
[|Namespace|] N1
{|Cursor:[|End Namespace|]|}</Text>)
End Function
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/NamespaceBlockHighlighterTests.vb
|
Visual Basic
|
apache-2.0
| 1,114
|
Imports SistFoncreagro.BussinessEntities
Public Interface ITipoConvenioBL
Function GetAllFromTipoConvenio() As List(Of TipoConvenio)
Function GetFromTipoConvenioById(ByVal id As Int32) As TipoConvenio
Sub SaveTipoConvenio(ByVal _TipoConvenio As TipoConvenio)
Sub DeleteTipoConvenio(ByVal id As Int32)
End Interface
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinesLogic/ITipoConvenioBL.vb
|
Visual Basic
|
mit
| 335
|
'------------------------------------------------------------------------------
' <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 My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global._02.StudentSystem.My.MySettings
Get
Return Global._02.StudentSystem.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
VanyaD/HTML5
|
SemanticHTMLHomework/02. StudentSystem/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,901
|
Imports System.Data.OleDb
Public Class markRoll
'MAKE MORE EFFICIENT connects this form to previous form.
Public y7 As Integer
Public y8 As Integer
Public y9 As Integer
Public y10 As Integer
Public y11 As Integer
Public y12 As Integer
Dim adpNamesUser As New OleDbDataAdapter
Dim conNames As OleDbConnection
Dim dataNames As New DataSet()
Dim adpAbsenceUser As New OleDbDataAdapter
Dim conAbsence As OleDbConnection
Dim dataAbsence As New DataSet()
Dim adpUser As New OleDbDataAdapter
Dim conAttendance As OleDbConnection
Dim dataAttendance As New DataSet()
'Preventing listViews headers from being resized
Private Sub ListView1_ColumnWidthChanging(ByVal Sender As Object, ByVal E As System.Windows.Forms.ColumnWidthChangingEventArgs) Handles ListView1.ColumnWidthChanging
For DCol = 0 To 4
If E.ColumnIndex = DCol Then
E.Cancel = True
E.NewWidth = Sender.Columns(DCol).Width
End If
Next DCol
End Sub
Private Sub markRoll_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'takes year values from previous form
y7 = lblY7.Text
y8 = lblY8.Text
y9 = lblY9.Text
y10 = lblY10.Text
y11 = lblY11.Text
y12 = lblY12.Text
'tooltip initialise
ToolTipListView.SetToolTip(ListView1, "Double click to mark absent")
'init database
Dim connectString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\rowingDatabase (1).accdb"
conNames = New OleDbConnection(connectString)
conNames.Open()
adpNamesUser = New OleDbDataAdapter()
adpNamesUser.SelectCommand = New OleDbCommand()
With adpNamesUser.SelectCommand
.Connection = conNames
.CommandText = "select * FROM tbProfiles"
.CommandType = CommandType.Text
.ExecuteNonQuery()
End With
adpNamesUser.Fill(dataNames, "tbProfiles")
'add item to listview table
Dim table As DataTable = dataNames.Tables("tbProfiles")
ListView1.View = View.Details
For Each row In table.Rows
If y7 > 0 And y7 = row.item(4) Then
addListRow(row)
totalPresent.Text += 1
End If
Next
For Each row In table.Rows
If y8 > 0 And y8 = row.item(4) Then
addListRow(row)
totalPresent.Text += 1
End If
Next
For Each row In table.Rows
If y9 > 0 And y9 = row.item(4) Then
addListRow(row)
totalPresent.Text += 1
End If
Next
For Each row In table.Rows
If y10 > 0 And y10 = row.item(4) Then
addListRow(row)
totalPresent.Text += 1
End If
Next
For Each row In table.Rows
If y11 > 0 And y11 = row.item(4) Then
addListRow(row)
totalPresent.Text += 1
End If
Next
For Each row In table.Rows
If y12 > 0 And y12 = row.item(4) Then
addListRow(row)
totalPresent.Text += 1
End If
Next
'construct table
Dim header1, header2, header3 As ColumnHeader
header1 = New ColumnHeader
header2 = New ColumnHeader
header3 = New ColumnHeader
header1.Text = "Last Name"
header1.TextAlign = HorizontalAlignment.Left
header1.Width = 116
header2.Text = "First Name"
header2.TextAlign = HorizontalAlignment.Left
header2.Width = 116
header3.Text = "Year"
header3.TextAlign = HorizontalAlignment.Left
header3.Width = 41
ListView1.Columns.Add(header1)
ListView1.Columns.Add(header2)
ListView1.Columns.Add(header3)
buttonStyle(btnCancel)
buttonStyle(btnSave)
End Sub
Sub addListRow(row As Object)
Dim tempstring As String = row.item("gName")
Dim item1 As New ListViewItem(tempstring)
item1.SubItems.Add(row.item("sName"))
item1.SubItems.Add(row.item("Group"))
item1.SubItems.Add(row.item("House"))
item1.SubItems.Add(row.item("ID"))
ListView1.Items.AddRange(New ListViewItem() {item1})
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
openForm(Me, New newRoll)
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim saveConfirm As Integer = MessageBox.Show("Are you sure? Changes cannot be undone", "Confirm", MessageBoxButtons.YesNo)
If saveConfirm = DialogResult.Yes Then
'establishes connections with databases
Dim connectAbsenceString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\rowingDatabase (1).accdb"
conAbsence = New OleDbConnection(connectAbsenceString)
conAbsence.Open()
adpAbsenceUser = New OleDbDataAdapter()
adpAbsenceUser.SelectCommand = New OleDbCommand()
With adpAbsenceUser.SelectCommand
.Connection = conAbsence
.CommandText = "select * FROM tblAbsence"
.CommandType = CommandType.Text
.ExecuteNonQuery()
End With
adpAbsenceUser.Fill(dataAbsence, "tblAbsence")
Dim connectAttendanceString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\rowingDatabase (1).accdb"
conAttendance = New OleDbConnection(connectAttendanceString)
conAttendance.Open()
adpUser = New OleDbDataAdapter()
adpUser.SelectCommand = New OleDbCommand()
With adpUser.SelectCommand
.Connection = conAttendance
.CommandText = "select * FROM tblAttendance"
.CommandType = CommandType.Text
.ExecuteNonQuery()
End With
adpUser.Fill(dataAttendance, "tblAttendance")
'inserts details into attendance database
Try
Dim command As String
command = "INSERT INTO tblAttendance(Sessions, Dates, coachOfSession, totalAbsences, totalPresent, YearsPresent, Notes) VALUES (@sessions, @dates, @coachOfSession, @totalabsences, @totalPresent, @YearsPresent, @Notes)"
Dim cmd As OleDbCommand
cmd = New OleDbCommand(command, conAttendance)
cmd.Parameters.AddWithValue("Sessions", sessionType.Text)
cmd.Parameters.AddWithValue("Dates", sessionDate.Text)
cmd.Parameters.AddWithValue("coachOfSession", coachOfSession.Text)
cmd.Parameters.AddWithValue("totalAbsences", totalAbsent.Text)
cmd.Parameters.AddWithValue("totalPresent", totalPresent.Text)
cmd.Parameters.AddWithValue("YearsPresent", lblYearGroups.Text)
cmd.Parameters.AddWithValue("Notes", coachNotes.Text)
cmd.ExecuteNonQuery()
Catch exceptionobject As Exception
MessageBox.Show(exceptionobject.Message)
End Try
'records all absentees who have been ticked
For i = 0 To (ListView1.Items.Count - 1)
If ListView1.Items(i).Checked = True Then
Try
Dim commandAbsence As String
commandAbsence = "INSERT INTO tblAbsence(Given, Family, Sessions, Dates, SchoolYr,SchoolHouse, SchoolIDNum) VALUES (@first, @last, @sessions, @dates, @group, @house, @IDnum)"
Dim cmdAbsence As OleDbCommand
cmdAbsence = New OleDbCommand(commandAbsence, conAbsence)
cmdAbsence.Parameters.AddWithValue("Given", ListView1.Items(i).SubItems(0).Text)
cmdAbsence.Parameters.AddWithValue("Family", ListView1.Items(i).SubItems(1).Text)
cmdAbsence.Parameters.AddWithValue("Sessions", sessionType.Text)
cmdAbsence.Parameters.AddWithValue("Dates", sessionDate.Text)
cmdAbsence.Parameters.AddWithValue("School", ListView1.Items(i).SubItems(2).Text)
cmdAbsence.Parameters.AddWithValue("SchoolHouse", ListView1.Items(i).SubItems(3).Text)
cmdAbsence.Parameters.AddWithValue("SchoolIDNum", ListView1.Items(i).SubItems(4).Text)
cmdAbsence.ExecuteNonQuery()
Catch exceptionobject As Exception
MessageBox.Show(exceptionobject.Message)
End Try
End If
Next
conAttendance.Close()
conAbsence.Close()
openForm(Me, New MainAttendance)
End If
End Sub
Private Sub ListView1_ItemChecked(sender As Object, e As ItemCheckedEventArgs) Handles ListView1.ItemChecked
'when someone is checked, absent += 1
totalAbsent.Text = 0
totalPresent.Text = 0
For i = 0 To (ListView1.Items.Count - 1)
If ListView1.Items(i).Checked = False Then
totalPresent.Text += 1
End If
Next
For i = 0 To (ListView1.Items.Count - 1)
If ListView1.Items(i).Checked = True Then
totalAbsent.Text += 1
End If
Next
End Sub
Private Sub ToolTipListView_Popup(sender As Object, e As PopupEventArgs) Handles ToolTipListView.Popup
End Sub
End Class
|
SDDHSC/MajorWork
|
MajorWork/MajorWork/markRoll.vb
|
Visual Basic
|
mit
| 9,709
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34209
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.assgn4.Form1
End Sub
End Class
End Namespace
|
rhildred/controlArrays
|
assgn4/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,472
|
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 featureControlFrames As SolidEdgeFrameworkSupport.FeatureControlFrames = Nothing
Dim featureControlFrame As SolidEdgeFrameworkSupport.FeatureControlFrame = 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
featureControlFrames = CType(sheet.FeatureControlFrames, SolidEdgeFrameworkSupport.FeatureControlFrames)
featureControlFrame = featureControlFrames.Add(0.1, 0.1, 0)
featureControlFrame.PrimaryFrame = "%FL%VB0.001%MC%VBA"
featureControlFrame.AddVertex(0.2, 0.2, 0)
featureControlFrame.BreakLine = True
featureControlFrame.Move(0.1, 0.1, 0.3, 0.2)
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.FeatureControlFrame.Move.vb
|
Visual Basic
|
mit
| 1,906
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicRemoveUnnecessaryImportsDiagnosticAnalyzer
Inherits AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer
Private Shared ReadOnly s_TitleAndMessageFormat As LocalizableString =
New LocalizableResourceString(NameOf(VBFeaturesResources.Imports_statement_is_unnecessary), VBFeaturesResources.ResourceManager, GetType(VBFeaturesResources))
Protected Overrides Function GetTitleAndMessageFormatForClassificationIdDescriptor() As LocalizableString
Return s_TitleAndMessageFormat
End Function
Protected Overrides ReadOnly Property UnnecessaryImportsProvider As IUnnecessaryImportsProvider
Get
Return VisualBasicUnnecessaryImportsProvider.Instance
End Get
End Property
Protected Overrides Function IsRegularCommentOrDocComment(trivia As SyntaxTrivia) As Boolean
Return trivia.IsRegularOrDocComment()
End Function
''' Takes the import clauses we want to remove and returns them *or* their
''' containing ImportsStatements *if* we wanted to remove all the clauses of
''' that ImportStatement.
Protected Overrides Function MergeImports(unnecessaryImports As ImmutableArray(Of SyntaxNode)) As ImmutableArray(Of SyntaxNode)
Dim result = ArrayBuilder(Of SyntaxNode).GetInstance()
Dim importsClauses = unnecessaryImports.ToImmutableHashSet()
For Each clause In importsClauses
If Not result.Contains(clause.Parent) Then
Dim statement = DirectCast(clause.Parent, ImportsStatementSyntax)
If statement.ImportsClauses.All(AddressOf importsClauses.Contains) Then
result.Add(statement)
Else
result.Add(clause)
End If
End If
Next
Return result.ToImmutableAndFree()
End Function
Protected Overrides Function GetFixableDiagnosticSpans(
nodes As IEnumerable(Of SyntaxNode), tree As SyntaxTree, cancellationToken As CancellationToken) As IEnumerable(Of TextSpan)
' Create one fixable diagnostic that contains the entire Imports list.
Return SpecializedCollections.SingletonEnumerable(tree.GetCompilationUnitRoot().Imports.GetContainedSpan())
End Function
Protected Overrides Function GetLastTokenDelegateForContiguousSpans() As Func(Of SyntaxNode, SyntaxToken)
Return Function(n)
Dim lastToken = n.GetLastToken()
Return If(lastToken.GetNextToken().Kind = SyntaxKind.CommaToken,
lastToken.GetNextToken(),
lastToken)
End Function
End Function
End Class
End Namespace
|
agocke/roslyn
|
src/Features/VisualBasic/Portable/RemoveUnnecessaryImports/VisualBasicRemoveUnnecessaryImportsDiagnosticAnalyzer.vb
|
Visual Basic
|
mit
| 3,551
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rTVentas_Marcas_Ipos"
'-------------------------------------------------------------------------------------------'
Partial Class rTVentas_Marcas_Ipos
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcParametro7Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7))
Dim lcParametro7Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(7))
Dim lcParametro8Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8))
Dim lcParametro8Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(8))
Dim lcParametro9Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(9))
Dim lcParametro9Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(9))
Dim lcParametro10Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(10))
Dim lcParametro10Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(10))
Dim lcParametro11Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(11))
Dim lcParametro11Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(11))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" WITH curTemporal AS ( ")
loComandoSeleccionar.AppendLine("SELECT Articulos.Cod_Mar AS Cod_Mar, ")
loComandoSeleccionar.AppendLine(" Marcas.Nom_Mar AS Nom_Mar, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Can_Art1 AS Can_Art, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Mon_Net AS Mon_Net ")
loComandoSeleccionar.AppendLine("FROM Facturas ")
loComandoSeleccionar.AppendLine("JOIN Renglones_Facturas ON Facturas.Documento = Renglones_Facturas.Documento")
loComandoSeleccionar.AppendLine("JOIN Articulos ON Renglones_Facturas.Cod_Art = Articulos.Cod_Art")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro10Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro10Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro11Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro11Hasta)
loComandoSeleccionar.AppendLine("JOIN Marcas ON Marcas.Cod_Mar = Articulos.Cod_Mar")
loComandoSeleccionar.AppendLine("JOIN Clientes ON Facturas.Cod_Cli = Clientes.Cod_Cli")
loComandoSeleccionar.AppendLine("WHERE Facturas.Status IN ('Confirmado', 'Afectado', 'Procesado')")
loComandoSeleccionar.AppendLine(" AND Facturas.Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Cli BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Ven BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Rev BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Suc BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Usu_Cre BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(") ")
loComandoSeleccionar.AppendLine(" SELECT Cod_Mar, ")
loComandoSeleccionar.AppendLine(" Nom_Mar, ")
loComandoSeleccionar.AppendLine(" SUM(Can_Art) AS Can_Art, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Net) AS Mon_Net ")
loComandoSeleccionar.AppendLine(" FROM curTemporal ")
loComandoSeleccionar.AppendLine(" GROUP BY Cod_Mar, Nom_Mar ")
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
' Me.mEscribirConsulta(loComandoSeleccionar.ToString)
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rTVentas_Marcas_Ipos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrTVentas_Marcas_Ipos.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' MAT: 20/06/11: Codigo inicial
'-------------------------------------------------------------------------------------------'
' MAT: 21/06/11: Adición del Filtro Marca
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rTVentas_Marcas_Ipos.aspx.vb
|
Visual Basic
|
mit
| 9,750
|
Public Class TLSE_settings
Private IsFormBeingDragged As Boolean = False
Private MousedwnX As Integer
Private MousedwnY As Integer
'form settings
Private Sub Closebutton_Click(sender As Object, e As EventArgs) Handles Closebutton.Click
My.Settings.Para_AdvH = Settings_Advhelp.Checked
My.Settings.Para_chkupdate = Settings_ckupdate.Checked
My.Settings.Para_hidden = Settings_hidden.Checked
My.Settings.Para_music = Settings_music.Checked
My.Settings.Para_path = Settings_filepath.Checked
My.Settings.Para_spesymb = Settings_spesymb.Checked
My.Settings.Para_language = Selects_language.SelectedItem
My.Settings.Para_selmusic = Selects_music.SelectedItem
Me.Close()
End Sub
Private Sub Closebutton_MouseMove(sender As Object, e As EventArgs) Handles Closebutton.MouseMove
Closebutton.Image = My.Resources.close_red_tl
End Sub
Private Sub Closebutton_MouseLeave(sender As Object, e As EventArgs) Handles Closebutton.MouseLeave
Closebutton.Image = My.Resources.close_tl
End Sub
Private Sub TLSE_header_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TLSE_header.MouseDown, TLSE_title.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
IsFormBeingDragged = True
MousedwnX = e.X
MousedwnY = e.Y
End If
End Sub
Private Sub TLSE_header_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TLSE_header.MouseUp, TLSE_title.MouseUp
If e.Button = Windows.Forms.MouseButtons.Left Then
IsFormBeingDragged = False
End If
End Sub
Private Sub TLSE_header_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TLSE_header.MouseMove, TLSE_title.MouseMove
If IsFormBeingDragged = True Then
Dim tmp As Point = New Point()
tmp.X = Me.Location.X + (e.X - MousedwnX)
tmp.Y = Me.Location.Y + (e.Y - MousedwnY)
Me.Location = tmp
tmp = Nothing
End If
End Sub
Private Sub Minimizebutton_Click(sender As Object, e As EventArgs) Handles Minimizebutton.Click
Me.WindowState = FormWindowState.Minimized
End Sub
Private Sub Minimizebutton_MouseMove(sender As Object, e As MouseEventArgs) Handles Minimizebutton.MouseMove
Minimizebutton.Image = My.Resources.minimize_gray
End Sub
Private Sub Minimizebutton_MouseLeave(sender As Object, e As EventArgs) Handles Minimizebutton.MouseLeave
Minimizebutton.Image = My.Resources.minimize
End Sub
'end form settings
'form menu
Private Sub Icon_menu_MouseMove(sender As Object, e As MouseEventArgs) Handles Icon_menu.MouseMove
Icon_menu.Image = My.Resources.icon_menu_on
End Sub
Private Sub Icon_menu_MouseLeave(sender As Object, e As EventArgs) Handles Icon_menu.MouseLeave
Icon_menu.Image = My.Resources.icon_menu_off
End Sub
Private Sub Icon_menu_Click(sender As Object, e As EventArgs) Handles Icon_menu.Click
My.Settings.Para_AdvH = Settings_Advhelp.Checked
My.Settings.Para_chkupdate = Settings_ckupdate.Checked
My.Settings.Para_hidden = Settings_hidden.Checked
My.Settings.Para_music = Settings_music.Checked
My.Settings.Para_path = Settings_filepath.Checked
My.Settings.Para_spesymb = Settings_spesymb.Checked
My.Settings.Para_language = Selects_language.SelectedItem
My.Settings.Para_selmusic = Selects_music.SelectedItem
If TLSE_logo_update.Visible = True Then
TLSE_hub.TLSE_logo_update.Visible = True
End If
TLSE_hub.Show()
TLSE_hub.Filever_text.Text = Filever_text.Text
TLSE_hub.TLSE_filepath.Text = TLSE_filepath.Text
Me.Close()
End Sub
'end form menu
Private Sub Menu_settings_MouseMove(sender As Object, e As MouseEventArgs) Handles Menu_settings.MouseMove, Menu_text_settings.MouseMove
Menu_settings.BackgroundImage = My.Resources.menu_settings_on
Menu_text_settings.ForeColor = Color.White
End Sub
Private Sub Menu_settings_MouseLeave(sender As Object, e As EventArgs) Handles Menu_settings.MouseLeave, Menu_text_settings.MouseLeave
Menu_settings.BackgroundImage = My.Resources.menu_settings_off
Menu_text_settings.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
End Sub
Private Sub Menu_text_settings_Click(sender As Object, e As EventArgs) Handles Menu_text_settings.Click, Menu_settings.Click
Hidesettings()
Settings_settings.Visible = True
End Sub
Private Sub Menu_changelog_MouseMove(sender As Object, e As MouseEventArgs) Handles Menu_changelog.MouseMove, Menu_text_changelog.MouseMove
Menu_changelog.BackgroundImage = My.Resources.menu_settings_on
Menu_text_changelog.ForeColor = Color.White
End Sub
Private Sub Menu_changelog_MouseLeave(sender As Object, e As EventArgs) Handles Menu_changelog.MouseLeave, Menu_text_changelog.MouseLeave
Menu_changelog.BackgroundImage = My.Resources.menu_settings_off
Menu_text_changelog.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
End Sub
Private Sub Menu_text_changelog_Click(sender As Object, e As EventArgs) Handles Menu_text_changelog.Click, Menu_changelog.Click
Hidesettings()
Settings_changelog.Visible = True
End Sub
Private Sub Menu_credits_MouseMove(sender As Object, e As MouseEventArgs) Handles Menu_credits.MouseMove, Menu_text_credits.MouseMove
Menu_credits.BackgroundImage = My.Resources.menu_settings_on
Menu_text_credits.ForeColor = Color.White
End Sub
Private Sub Menu_credits_MouseLeave(sender As Object, e As EventArgs) Handles Menu_credits.MouseLeave, Menu_text_credits.MouseLeave
Menu_credits.BackgroundImage = My.Resources.menu_settings_off
Menu_text_credits.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
End Sub
Private Sub Menu_text_credits_Click(sender As Object, e As EventArgs) Handles Menu_text_credits.Click, Menu_credits.Click
Hidesettings()
Settings_credits.Visible = True
End Sub
Private Sub Menu_links_MouseMove(sender As Object, e As MouseEventArgs) Handles Menu_links.MouseMove, Menu_text_links.MouseMove
Menu_links.BackgroundImage = My.Resources.menu_settings_on
Menu_text_links.ForeColor = Color.White
End Sub
Private Sub Menu_links_MouseLeave(sender As Object, e As EventArgs) Handles Menu_links.MouseLeave, Menu_text_links.MouseLeave
Menu_links.BackgroundImage = My.Resources.menu_settings_off
Menu_text_links.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
End Sub
Private Sub Settings_music_CheckedChanged(sender As Object, e As EventArgs) Handles Settings_music.CheckedChanged
If Settings_music.Checked = True Then
Settings_music.FlatAppearance.BorderColor = Color.White
Settings_music.ForeColor = Color.White
Panel_bgmusic.Visible = True
End If
If Settings_music.Checked = False Then
Settings_music.FlatAppearance.BorderColor = Color.FromArgb(255, 96, 0)
Settings_music.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
Panel_bgmusic.Visible = False
End If
End Sub
Private Sub Settings_hidden_CheckedChanged(sender As Object, e As EventArgs) Handles Settings_hidden.CheckedChanged
If Settings_hidden.Checked = True Then
Settings_hidden.FlatAppearance.BorderColor = Color.White
Settings_hidden.ForeColor = Color.White
Panel_hiddenthings.Visible = True
End If
If Settings_hidden.Checked = False Then
Settings_hidden.FlatAppearance.BorderColor = Color.FromArgb(255, 96, 0)
Settings_hidden.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
Panel_hiddenthings.Visible = False
End If
End Sub
Private Sub Settings_filepath_CheckedChanged(sender As Object, e As EventArgs) Handles Settings_filepath.CheckedChanged
If Settings_filepath.Checked = True Then
Settings_filepath.FlatAppearance.BorderColor = Color.White
Settings_filepath.ForeColor = Color.White
Panel_filepath.Visible = True
TLSE_filepath.Visible = True
End If
If Settings_filepath.Checked = False Then
Settings_filepath.FlatAppearance.BorderColor = Color.FromArgb(255, 96, 0)
Settings_filepath.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
Panel_filepath.Visible = False
TLSE_filepath.Visible = False
End If
End Sub
Private Sub Settings_ckupdate_CheckedChanged(sender As Object, e As EventArgs) Handles Settings_ckupdate.CheckedChanged
If Settings_ckupdate.Checked = True Then
Settings_ckupdate.FlatAppearance.BorderColor = Color.White
Settings_ckupdate.ForeColor = Color.White
Panel_chkupdate.Visible = True
End If
If Settings_ckupdate.Checked = False Then
Settings_ckupdate.FlatAppearance.BorderColor = Color.FromArgb(255, 96, 0)
Settings_ckupdate.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
Panel_chkupdate.Visible = False
End If
End Sub
Private Sub Settings_Advhelp_CheckedChanged(sender As Object, e As EventArgs) Handles Settings_Advhelp.CheckedChanged
If Settings_Advhelp.Checked = True Then
Settings_Advhelp.FlatAppearance.BorderColor = Color.White
Settings_Advhelp.ForeColor = Color.White
Panel_Advhelp.Visible = True
End If
If Settings_Advhelp.Checked = False Then
Settings_Advhelp.FlatAppearance.BorderColor = Color.FromArgb(255, 96, 0)
Settings_Advhelp.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
Panel_Advhelp.Visible = False
End If
End Sub
Private Sub Settings_spesymb_CheckedChanged(sender As Object, e As EventArgs) Handles Settings_spesymb.CheckedChanged
If Settings_spesymb.Checked = True Then
Settings_spesymb.FlatAppearance.BorderColor = Color.White
Settings_spesymb.ForeColor = Color.White
Panel_bspesymb.Visible = True
End If
If Settings_spesymb.Checked = False Then
Settings_spesymb.FlatAppearance.BorderColor = Color.FromArgb(255, 96, 0)
Settings_spesymb.ForeColor = Color.FromKnownColor(KnownColor.ControlText)
Panel_bspesymb.Visible = False
End If
End Sub
Public Sub Hidesettings()
Settings_settings.Visible = False
Settings_changelog.Visible = False
Settings_credits.Visible = False
Settings_links.Visible = False
End Sub
Private Sub Menu_text_links_Click(sender As Object, e As EventArgs) Handles Menu_text_links.Click, Menu_links.Click
Hidesettings()
Settings_links.Visible = True
End Sub
Private Sub TLSE_settings_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Selects_language.SelectedItem = Selects_language.Items.Item(0)
Selects_music.SelectedItem = Select_music.Items.Item(0)
Try
Settings_Advhelp.Checked = My.Settings.Para_AdvH
Settings_ckupdate.Checked = My.Settings.Para_chkupdate
Settings_hidden.Checked = My.Settings.Para_hidden
Settings_music.Checked = My.Settings.Para_music
Settings_filepath.Checked = My.Settings.Para_path
Settings_spesymb.Checked = My.Settings.Para_spesymb
Selects_language.SelectedItem = My.Settings.Para_language
Selects_music.SelectedItem = My.Settings.Para_selmusic
Catch ex As Exception
End Try
TLSE_language()
End Sub
Public Sub TLSE_language()
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Menu_text_settings.Text = "Settings"
Menu_text_changelog.Text = "Changelog"
Menu_text_credits.Text = "Credits"
Menu_text_links.Text = "Links"
Text_language.Text = "Language"
Settings_music.Text = "Active background music"
Settings_hidden.Text = "Show hidden things"
Settings_filepath.Text = "Show file path"
Settings_ckupdate.Text = "Unactive check updates"
Settings_Advhelp.Text = "Show advance help"
Settings_spesymb.Text = "Active special symbol"
Text_othersaveedit.Text = "Other save editors"
End If
If Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Menu_text_settings.Text = "Paramètres"
Menu_text_changelog.Text = "Changelog"
Menu_text_credits.Text = "Crédits"
Menu_text_links.Text = "Liens"
Text_language.Text = "Langage"
Settings_music.Text = "Activer la musique de fond"
Settings_hidden.Text = "Afficher les choses cachés"
Settings_filepath.Text = "Afficher le chemin du fichier"
Settings_ckupdate.Text = "Désactiver la vérifications des mises à jour"
Settings_Advhelp.Text = "Afficher l'aide avancée"
Settings_spesymb.Text = "Activer les symboles spéciaux"
Text_othersaveedit.Text = "Autre éditeurs de sauvegarde"
End If
End Sub
Private Sub Selects_language_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Selects_language.SelectedIndexChanged
TLSE_language()
End Sub
Private Sub Icon_TLSE_git_Click(sender As Object, e As EventArgs) Handles Icon_TLSE_git.Click
Process.Start("https://github.com/Brionjv/Tomodachi-Life-Save-Editor")
End Sub
Private Sub Icon_TLSE_git_MouseLeave(sender As Object, e As EventArgs) Handles Icon_TLSE_git.MouseLeave
Icon_TLSE_git.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_TLSE_git_MouseMove(sender As Object, e As MouseEventArgs) Handles Icon_TLSE_git.MouseMove
Icon_TLSE_git.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to access to Tomodachi Life Save Editor page (Github)"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour accéder à la page de Tomodachi Life Save Editor (Github)"
End If
Panel_description.Visible = True
End Sub
Private Sub Icon_TLSE_gbt_Click(sender As Object, e As EventArgs) Handles Icon_TLSE_gbt.Click
Process.Start("https://gbatemp.net/threads/wip-tomodachi-life-save-editor.399006/")
End Sub
Private Sub Icon_TLSE_gbt_MouseLeave(sender As Object, e As EventArgs) Handles Icon_TLSE_gbt.MouseLeave
Icon_TLSE_gbt.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_TLSE_gbt_MouseMove(sender As Object, e As MouseEventArgs) Handles Icon_TLSE_gbt.MouseMove
Icon_TLSE_gbt.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to access to Tomodachi Life Save Editor page (gbatemp.net)"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour accéder à la page de Tomodachi Life Save Editor (gbatemp.net)"
End If
Panel_description.Visible = True
End Sub
Private Sub Icon_MiitopiaSE_Click(sender As Object, e As EventArgs) Handles Icon_MiitopiaSE.Click
Process.Start("https://github.com/Brionjv/Miitopia-Save-Editor/releases")
End Sub
Private Sub Icon_MiitopiaSE_MouseLeave(sender As Object, e As EventArgs) Handles Icon_MiitopiaSE.MouseLeave
Icon_MiitopiaSE.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_MiitopiaSE_MouseMove(sender As Object, e As EventArgs) Handles Icon_MiitopiaSE.MouseMove
Icon_MiitopiaSE.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to download and try Miitopia Save Editor"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour télécharger et essayer Miitopia Save Editor"
End If
Panel_description.Visible = True
End Sub
Private Sub Icon_ChibiRoboZLSE_Click(sender As Object, e As EventArgs) Handles Icon_ChibiRoboZLSE.Click
Process.Start("https://github.com/Brionjv/Chibi-Robo-ZL-Save-Editor/releases")
End Sub
Private Sub Icon_ChibiRoboZLSE_MouseLeave(sender As Object, e As EventArgs) Handles Icon_ChibiRoboZLSE.MouseLeave
Icon_ChibiRoboZLSE.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_ChibiRoboZLSE_MouseMove(sender As Object, e As EventArgs) Handles Icon_ChibiRoboZLSE.MouseMove
Icon_ChibiRoboZLSE.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to download and try Chibi Robo zip Lash Save Editor"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour télécharger et essayer Chibi Robo zip Lash Save Editor"
End If
Panel_description.Visible = True
End Sub
Private Sub Icon_PaparMarioSSSE_Click(sender As Object, e As EventArgs) Handles Icon_PaparMarioSSSE.Click
Process.Start("https://github.com/Brionjv/Paper-Mario-SS-Save-Editor/releases")
End Sub
Private Sub Icon_PaparMarioSSSE_MouseLeave(sender As Object, e As EventArgs) Handles Icon_PaparMarioSSSE.MouseLeave
Icon_PaparMarioSSSE.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_PaparMarioSSSE_MouseMove(sender As Object, e As EventArgs) Handles Icon_PaparMarioSSSE.MouseMove
Icon_PaparMarioSSSE.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to download and try Paper Mario Sticker Star Save Editor"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour télécharger et essayer Paper Mario Sticker Star Save Editor"
End If
Panel_description.Visible = True
End Sub
Private Sub Icon_IronfallISE_Click(sender As Object, e As EventArgs) Handles Icon_IronfallISE.Click
Process.Start("https://github.com/Brionjv/Ironfall-Invasion-Save-Editor/releases")
End Sub
Private Sub Icon_IronfallISE_MouseLeave(sender As Object, e As EventArgs) Handles Icon_IronfallISE.MouseLeave
Icon_IronfallISE.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_IronfallISE_MouseMove(sender As Object, e As EventArgs) Handles Icon_IronfallISE.MouseMove
Icon_IronfallISE.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to download and try Ironfall Invasion Save Editor"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour télécharger et essayer Ironfall Invasion Save Editor"
End If
Panel_description.Visible = True
End Sub
Private Sub Icon_NintendogscatSE_Click(sender As Object, e As EventArgs) Handles Icon_nintendogscatSE.Click
Process.Start("https://github.com/Brionjv/3ds-Nintendogs-cats-Save-Editor/releases")
End Sub
Private Sub Icon_NintendogscatSE_MouseLeave(sender As Object, e As EventArgs) Handles Icon_nintendogscatSE.MouseLeave
Icon_nintendogscatSE.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_NintendogscatSE_MouseMove(sender As Object, e As EventArgs) Handles Icon_nintendogscatSE.MouseMove
Icon_nintendogscatSE.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to download and try 3ds Nintendogs + cats Save Editor"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour télécharger et essayer 3ds Nintendogs + cats Save Editor"
End If
Panel_description.Visible = True
End Sub
Private Sub Icon_MarioPartyITSE_Click(sender As Object, e As EventArgs) Handles Icon_MarioPartyITSE.Click
Process.Start("https://github.com/Brionjv/Mario-Party-IT-Save-Editor/releases")
End Sub
Private Sub Icon_MarioPartyITSE_MouseLeave(sender As Object, e As EventArgs) Handles Icon_MarioPartyITSE.MouseLeave
Icon_MarioPartyITSE.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_MarioPartyITSE_MouseMove(sender As Object, e As EventArgs) Handles Icon_MarioPartyITSE.MouseMove
Icon_MarioPartyITSE.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to download and try Mario Party Island Tour Save Editor"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour télécharger et essayer Mario Party Island Tour Save Editor"
End If
Panel_description.Visible = True
End Sub
Private Sub Icon_3dsSEL_Click(sender As Object, e As EventArgs) Handles Icon_3dsSEL.Click
Process.Start("https://github.com/Brionjv/3DS-Save-Editors-Library/releases")
End Sub
Private Sub Icon_3dsSEL_MouseLeave(sender As Object, e As EventArgs) Handles Icon_3dsSEL.MouseLeave
Icon_3dsSEL.BorderStyle = BorderStyle.None
Panel_description.Visible = False
End Sub
Private Sub Icon_3dsSEL_MouseMove(sender As Object, e As EventArgs) Handles Icon_3dsSEL.MouseMove
Icon_3dsSEL.BorderStyle = BorderStyle.FixedSingle
If Selects_language.SelectedItem = Selects_language.Items.Item(0) Then
Text_description.Text = "Click to download and try 3DS Save Editors Library (Collection of little save editors)"
ElseIf Selects_language.SelectedItem = Selects_language.Items.Item(1) Then
Text_description.Text = "Cliquez pour télécharger et essayer 3DS Save Editors Library (Collection de petit éditeurs de sauvegarde)"
End If
Panel_description.Visible = True
End Sub
Private Sub Text_othersaveedit_Click(sender As Object, e As EventArgs) Handles Text_othersaveedit.Click
Process.Start("https://github.com/Brionjv?tab=repositories")
End Sub
End Class
|
Brionjv/Tomodachi-Life-Save-Editor
|
Project EX/Tomodachi Life Save Editor/TLSE_settings.vb
|
Visual Basic
|
mit
| 23,396
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim models As SolidEdgePart.Models = Nothing
Dim model As SolidEdgePart.Model = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument)
If partDocument IsNot Nothing Then
models = partDocument.Models
model = models.Item(1)
Dim tabs = model.Tabs
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.Model.Tabs.vb
|
Visual Basic
|
mit
| 1,350
|
' 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 System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Completion.CompletionProviders
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Namespace Tests
Public Class OverrideCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture)
MyBase.New(workspaceFixture)
End Sub
Friend Overrides Function CreateCompletionProvider() As CompletionListProvider
Return New OverrideCompletionProvider(TestWaitIndicator.Default)
End Function
#Region "CompletionItem tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotOfferedBaseClassMember() As Task
Dim text = <a>MustInherit Class Base
Public MustOverride Sub Foo()
End Class
Class Derived
Inherits Base
Public Overrides Sub Foo()
End Sub
End Class
Class SomeClass
Inherits Derived
Overrides $$
End Class</a>
Await VerifyItemIsAbsentAsync(text.Value, "Foo()", "Sub Base.Foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestIntermediateClassOverriddenMember() As Task
Dim text = <a>MustInherit Class Base
Public MustOverride Sub Foo()
End Class
Class Derived
Inherits Base
Public Overrides Sub Foo()
End Sub
End Class
Class SomeClass
Inherits Derived
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "Foo()", "Sub Derived.Foo()")
End Function
<WorkItem(543807)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestHideFinalize() As Task
Dim text = <a>Class foo
Overrides $$
End Class</a>
Await VerifyItemIsAbsentAsync(text.Value, "Finalize()")
End Function
<WorkItem(543807)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestShowShadowingFinalize() As Task
Dim text = <a>Class foo
Overridable Shadows Sub Finalize()
End Sub
End Class
Class bar
Inherits foo
overrides $$
End class</a>
Await VerifyItemIsAbsentAsync(text.Value, "foo.Finalize()")
End Function
<WorkItem(543806)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestShowObjectOverrides() As Task
Dim text = <a>Class foo
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "Equals(obj As Object)")
Await VerifyItemExistsAsync(text.Value, "ToString()")
Await VerifyItemExistsAsync(text.Value, "GetHashCode()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInheritedOverridableSub() As Task
Dim text = <a>Public Class a
Public Overridable Sub foo()
End Sub
End Class
Public Class b
Inherits a
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInheritedOverridableFunction() As Task
Dim text = <a>Public Class a
Public Overridable Function foo() As Integer
Return 0
End Function
End Class
Public Class b
Inherits a
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInheritedMustOverrideFunction() As Task
Dim text = <a>Public Class a
Public MustOverride Sub foo()
End Sub
End Class
Public Class b
Inherits a
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchSub() As Task
Dim text = <a>Public Class a
Public Overridable Sub foo()
End Sub
Public Overridable Function bar() As Integer
Return 0
End Function
End Class
Public Class b
Inherits a
Overrides Sub $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "foo()")
Await VerifyItemIsAbsentAsync(text.Value, "bar()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchFunction() As Task
Dim text = <a>Public Class a
Public Overridable Sub foo()
End Sub
Public Overridable Function bar() As Integer
Return 0
End Function
End Class
Public Class b
Inherits a
Overrides Function $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "bar()")
Await VerifyItemIsAbsentAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDontFilterIfNothingMatchesReturnTypeVoidness() As Task
Dim text = <a>MustInherit Class Base
MustOverride Function Foo() As String
Protected NotOverridable Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
Class Derived
Inherits Base
Overrides Sub $$
End Class</a>
' Show Foo() even though it's a Function
Await VerifyItemExistsAsync(text.Value, "Foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotAlreadyImplemented() As Task
Dim text = <a>Public Class a
Public Overridable Sub foo()
End Sub
End Class
Public Class b
Inherits a
Public Overrides Sub foo()
MyBase.foo()
End Sub
Overrides $$
End Class</a>
Await VerifyItemIsAbsentAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotShowNotInheritable() As Task
Dim text = <a>Public Class a
Public NotInheritable Sub foo()
End Sub
End Class
Public Class b
Inherits a
Overrides $$
End Class</a>
Await VerifyItemIsAbsentAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotShowNotOverridable() As Task
Dim text = <a>Public Class a
Public Sub foo()
End Sub
End Class
Public Class b
Inherits a
Overrides $$
End Class</a>
Await VerifyItemIsAbsentAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotIfTextAfterPosition() As Task
Dim text = <a>Public Class a
Public Overridable Function foo() As Integer
Return 0
End Function
End Class
Public Class b
Inherits a
Overrides $$ Function
End Class</a>
Await VerifyItemIsAbsentAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotIfDeclaringShared() As Task
Dim text = <a>Public Class a
Public Overridable Function foo() As Integer
Return 0
End Function
End Class
Public Class b
Inherits a
Shared Overrides $$
End Class</a>
Await VerifyItemIsAbsentAsync(text.Value, "foo()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSuggestProperty() As Task
Dim text = <a>Public Class a
Public Overridable Property foo As String
End Class
Public Class b
Inherits a
Public Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "foo")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestShowAllAccessibilitiesIfNoneTyped() As Task
Dim text = <a>Public Class a
Public Overridable Sub r1()
End Sub
Private Overridable Sub s1()
End Sub
Protected Overridable Sub t1()
End Sub
Friend Overridable Sub u1()
End Sub
End Class
Public Class b
Inherits a
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "r1()")
Await VerifyItemExistsAsync(text.Value, "t1()")
Await VerifyItemExistsAsync(text.Value, "u1()")
Await VerifyItemIsAbsentAsync(text.Value, "s1()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFilterPublic() As Task
Dim text = <a>Public Class a
Public Overridable Sub r1()
End Sub
Private Overridable Sub s1()
End Sub
Protected Overridable Sub t1()
End Sub
Friend Overridable Sub u1()
End Sub
End Class
Public Class b
Inherits a
Public Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "r1()")
Await VerifyItemIsAbsentAsync(text.Value, "s1()")
Await VerifyItemIsAbsentAsync(text.Value, "t1()")
Await VerifyItemIsAbsentAsync(text.Value, "u1()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFilterProtected() As Task
Dim text = <a>Public Class a
Public Overridable Sub r1()
End Sub
Private Overridable Sub s1()
End Sub
Protected Overridable Sub t1()
End Sub
Friend Overridable Sub u1()
End Sub
End Class
Public Class b
Inherits a
Protected Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "t1()")
Await VerifyItemIsAbsentAsync(text.Value, "r1()")
Await VerifyItemIsAbsentAsync(text.Value, "s1()")
Await VerifyItemIsAbsentAsync(text.Value, "u1()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFilterFriend() As Task
Dim text = <a>Public Class a
Public Overridable Sub r1()
End Sub
Private Overridable Sub s1()
End Sub
Protected Overridable Sub t1()
End Sub
Friend Overridable Sub u1()
End Sub
End Class
Public Class b
Inherits a
Friend Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "u1()")
Await VerifyItemIsAbsentAsync(text.Value, "r1()")
Await VerifyItemIsAbsentAsync(text.Value, "s1()")
Await VerifyItemIsAbsentAsync(text.Value, "t1()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFilterProtectedFriend() As Task
Dim text = <a>Public Class a
Public Overridable Sub r1()
End Sub
Private Overridable Sub s1()
End Sub
Protected Overridable Sub t1()
End Sub
Friend Overridable Sub u1()
End Sub
Protected Friend Overridable Sub v1()
End Sub
End Class
Public Class b
Inherits a
Protected Friend Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "v1()")
Await VerifyItemIsAbsentAsync(text.Value, "u1()")
Await VerifyItemIsAbsentAsync(text.Value, "r1()")
Await VerifyItemIsAbsentAsync(text.Value, "s1()")
Await VerifyItemIsAbsentAsync(text.Value, "t1()")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestGenericTypeNameSubstitutedForGenericInDerivedClass1() As Task
Dim markup = <a>Public MustInherit Class Base(Of T)
Public MustOverride Sub Foo(t As T)
End Class
Public Class SomeClass(Of X)
Inherits Base(Of X)
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(markup.Value, "Foo(t As X)")
Await VerifyItemIsAbsentAsync(markup.Value, "Foo(t As T)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestGenericTypeNameSubstitutedForGenericInDerivedClass2() As Task
Dim markup = <a>Public MustInherit Class Base(Of T)
Public MustOverride Sub Foo(t As T)
End Class
Public Class SomeClass(Of X, Y, Z)
Inherits Base(Of Y)
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(markup.Value, "Foo(t As Y)")
Await VerifyItemIsAbsentAsync(markup.Value, "Foo(t As T)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestGenericTypeNameSubstitutedForGenericInDerivedClass3() As Task
Dim markup = <a>Public MustInherit Class Base(Of T, S)
Public MustOverride Sub Foo(t As T, s As S)
End Class
Public Class SomeClass(Of X, Y, Z)
Inherits Base(Of Y, Z)
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(markup.Value, "Foo(t As Y, s As Z)")
Await VerifyItemIsAbsentAsync(markup.Value, "Foo(t As T, s As S)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestGenericTypeNameSubstitutedForNonGenericInDerivedClass1() As Task
Dim markup = <a>Public MustInherit Class Base(Of T)
Public MustOverride Sub Foo(t As T)
End Class
Public Class SomeClass
Inherits Base(Of Integer)
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(markup.Value, "Foo(t As Integer)")
Await VerifyItemIsAbsentAsync(markup.Value, "Foo(t As T)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestGenericTypeNameSubstitutedForNonGenericInDerivedClass2() As Task
Dim markup = <a>Public MustInherit Class Base(Of T)
Public MustOverride Sub Foo(t As T)
End Class
Public Class SomeClass(Of X, Y, Z)
Inherits Base(Of Integer)
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(markup.Value, "Foo(t As Integer)")
Await VerifyItemIsAbsentAsync(markup.Value, "Foo(t As T)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestGenericTypeNameSubstitutedForNonGenericInDerivedClass3() As Task
Dim markup = <a>Imports System
Public MustInherit Class Base(Of T, S)
Public MustOverride Sub Foo(t As T, s As S)
End Class
Public Class SomeClass
Inherits Base(Of Integer, Exception)
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(markup.Value, "Foo(t As Integer, s As Exception)")
Await VerifyItemIsAbsentAsync(markup.Value, "Foo(t As T, s As S)")
End Function
<WorkItem(529714)>
<WpfFact(Skip:="529714"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestGenericMethodTypeParametersRenamed() As Task
Dim text = <a>Class CFoo
Overridable Function Something(Of X)(arg As X) As X
End Function
End Class
Class Derived(Of X)
Inherits CFoo
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "Something(Of X1)(arg As X1)")
Await VerifyItemIsAbsentAsync(text.Value, "Something(Of X)(arg As X)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterTypeSimplified() As Task
Dim text = <a>Imports System
Class CBase
Public Overridable Sub foo(e As System.Exception)
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "foo(e As Exception)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEscapedMethodNameInIntelliSenseList() As Task
Dim markup = <a>Class CBase
Public Overridable Sub [Class]()
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>.Value
Dim code As String = Nothing
Dim position As Integer
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), code, position)
Await BaseVerifyWorkerAsync(code, position, "[Class]()", "Sub CBase.Class()", SourceCodeKind.Regular, False, False, Nothing, experimental:=False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEscapedPropertyNameInIntelliSenseList() As Task
Dim markup = <a>Class CBase
Public Overridable Property [Class] As Integer
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>.Value
Dim code As String = Nothing
Dim position As Integer
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), code, position)
Await BaseVerifyWorkerAsync(code, position, "[Class]", "Property CBase.Class As Integer", SourceCodeKind.Regular, False, False, Nothing, experimental:=False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEscapedParameterNameInIntelliSenseList() As Task
Dim markup = <a>Class CBase
Public Overridable Sub Foo([Integer] As Integer)
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(markup.Value, "Foo([Integer] As Integer)", "Sub CBase.Foo([Integer] As Integer)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestHideKeywords() As Task
Dim text = <a>
Class Program
Overrides $$
End Class</a>
Await VerifyItemExistsAsync(text.Value, "ToString()")
Await VerifyItemIsAbsentAsync(text.Value, "Function")
End Function
#End Region
#Region "Commit tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitInEmptyClass() As Task
Dim markupBeforeCommit = <a>Class c
Overrides $$
End Class</a>
Dim expectedCode = <a>Class c
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode()$$
End Function
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "GetHashCode()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitSubBeforeSub() As Task
Dim markupBeforeCommit = <a>Class c
Overrides $$
Sub bar()
End Sub
End Class</a>
Dim expectedCode = <a>Class c
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode()$$
End Function
Sub bar()
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "GetHashCode()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitSubAfterSub() As Task
Dim markupBeforeCommit = <a>Class c
Sub bar()
End Sub
Overrides $$
End Class</a>
Dim expectedCode = <a>Class c
Sub bar()
End Sub
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode()$$
End Function
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "GetHashCode()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitFunction() As Task
Dim markupBeforeCommit = <a>Public Class c
Public Overridable Function foo() As Integer
Return 0
End Function
End Class
Public Class d
Inherits c
Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class c
Public Overridable Function foo() As Integer
Return 0
End Function
End Class
Public Class d
Inherits c
Public Overrides Function foo() As Integer
Return MyBase.foo()$$
End Function
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitFunctionWithParams() As Task
Dim markupBeforeCommit = <a>Public Class c
Public Overridable Function foo(x As Integer) As Integer
Return x
End Function
End Class
Public Class d
Inherits c
Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class c
Public Overridable Function foo(x As Integer) As Integer
Return x
End Function
End Class
Public Class d
Inherits c
Public Overrides Function foo(x As Integer) As Integer
Return MyBase.foo(x)$$
End Function
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo(x As Integer)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitSubWithParams() As Task
Dim markupBeforeCommit = <a>Public Class c
Public Overridable Sub foo(x As Integer)
End Sub
End Class
Public Class d
Inherits c
Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class c
Public Overridable Sub foo(x As Integer)
End Sub
End Class
Public Class d
Inherits c
Public Overrides Sub foo(x As Integer)
MyBase.foo(x)$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo(x As Integer)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitProtected() As Task
Dim markupBeforeCommit = <a>Public Class c
Protected Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class c
Protected Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
Protected Overrides Sub foo()
MyBase.foo()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitFriend() As Task
Dim markupBeforeCommit = <a>Public Class c
Friend Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class c
Friend Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
Friend Overrides Sub foo()
MyBase.foo()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitProtectedFriend() As Task
Dim markupBeforeCommit = <a>Public Class c
Protected Friend Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class c
Protected Friend Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
Protected Friend Overrides Sub foo()
MyBase.foo()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitAbstractThrows() As Task
Dim markupBeforeCommit = <a>Public MustInherit Class c
Public MustOverride Sub foo()
End Class
Public Class d
Inherits c
Overrides $$
End Class</a>
Dim expectedCode = <a>Imports System
Public MustInherit Class c
Public MustOverride Sub foo()
End Class
Public Class d
Inherits c
Public Overrides Sub foo()
Throw New NotImplementedException()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitRetainMustOverride() As Task
Dim markupBeforeCommit = <a>Public Class c
Public Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
MustOverride Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class c
Public Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
Public MustOverride Overrides Sub foo()$$
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitRetainNotOverridable() As Task
Dim markupBeforeCommit = <a>Public Class c
Public Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
NotOverridable Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class c
Public Overridable Sub foo()
End Sub
End Class
Public Class d
Inherits c
Public NotOverridable Overrides Sub foo()
MyBase.foo()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitProperty() As Task
Dim markupBeforeCommit = <a>Public Class base
Public Overridable Property foo As String
End Class
Public Class derived
Inherits base
Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class base
Public Overridable Property foo As String
End Class
Public Class derived
Inherits base
Public Overrides Property foo As String
Get
Return MyBase.foo$$
End Get
Set(value As String)
MyBase.foo = value
End Set
End Property
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitWriteOnlyProperty() As Task
Dim markupBeforeCommit = <a>Public Class base
Public Overridable WriteOnly Property foo As String
Set(value As String)
End Set
End Property
End Class
Class derived
Inherits base
Public Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class base
Public Overridable WriteOnly Property foo As String
Set(value As String)
End Set
End Property
End Class
Class derived
Inherits base
Public Overrides WriteOnly Property foo As String
Set(value As String)
MyBase.foo = value$$
End Set
End Property
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitReadOnlyProperty() As Task
Dim markupBeforeCommit = <a>Public Class base
Public Overridable ReadOnly Property foo As String
Get
End Get
End Property
End Class
Class derived
Inherits base
Public Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class base
Public Overridable ReadOnly Property foo As String
Get
End Get
End Property
End Class
Class derived
Inherits base
Public Overrides ReadOnly Property foo As String
Get
Return MyBase.foo$$
End Get
End Property
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(543937)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitOptionalKeywordAndParameterValuesAreGenerated() As Task
Dim markupBeforeCommit = <a><![CDATA[Class CBase
Public Overridable Sub foo(Optional x As Integer = 42)
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class]]></a>
Dim expectedCode = <a><![CDATA[Class CBase
Public Overridable Sub foo(Optional x As Integer = 42)
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub foo(Optional x As Integer = 42)
MyBase.foo(x)$$
End Sub
End Class]]></a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo(x As Integer = 42)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitAttributesAreNotGenerated() As Task
Dim markupBeforeCommit = <a><![CDATA[Imports System
Class CBase
<Obsolete()>
Public Overridable Sub foo()
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class]]></a>
Dim expectedCode = <a><![CDATA[Imports System
Class CBase
<Obsolete()>
Public Overridable Sub foo()
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub foo()
MyBase.foo()$$
End Sub
End Class]]></a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitGenericMethod() As Task
Dim markupBeforeCommit = <a>Class CBase
Public Overridable Sub foo(Of T)(x As T)
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Class CBase
Public Overridable Sub foo(Of T)(x As T)
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub foo(Of T)(x As T)
MyBase.foo(x)$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo(Of T)(x As T)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(545627)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitGenericMethodOnArraySubstitutedGenericType() As Task
Dim markupBeforeCommit = <a>Class A(Of T)
Public Overridable Sub M(Of U As T)()
End Sub
End Class
Class B
Inherits A(Of Object())
Overrides $$
End Class</a>
Dim expectedCode = <a>Class A(Of T)
Public Overridable Sub M(Of U As T)()
End Sub
End Class
Class B
Inherits A(Of Object())
Public Overrides Sub M(Of U As Object())()
MyBase.M(Of U)()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "M(Of U)()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitFormats() As Task
Dim markupBeforeCommit = <a>Class CBase
Public Overridable Sub foo()
End Sub
End Class
Class CDerived
Inherits CBase
overrides $$
End Class</a>
Dim expectedCode = <a>Class CBase
Public Overridable Sub foo()
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub foo()
MyBase.foo()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitSimplifiesParameterTypes() As Task
Dim markupBeforeCommit = <a>Imports System
Class CBase
Public Overridable Sub foo(e As System.Exception)
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Imports System
Class CBase
Public Overridable Sub foo(e As System.Exception)
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub foo(e As Exception)
MyBase.foo(e)$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo(e As Exception)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitSimplifiesReturnType() As Task
Dim markupBeforeCommit = <a>Imports System
Class CBase
Public Overridable Function foo() As System.Exception
Return 0
End Function
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Imports System
Class CBase
Public Overridable Function foo() As System.Exception
Return 0
End Function
End Class
Class CDerived
Inherits CBase
Public Overrides Function foo() As Exception
Return MyBase.foo()$$
End Function
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitEscapedMethodName() As Task
Dim markupBeforeCommit = <a>Class CBase
Public Overridable Sub [Class]()
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Class CBase
Public Overridable Sub [Class]()
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub [Class]()
MyBase.Class()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "[Class]()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitEscapedPropertyName() As Task
Dim markupBeforeCommit = <a>Class CBase
Public Overridable Property [Class] As Integer
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Class CBase
Public Overridable Property [Class] As Integer
End Class
Class CDerived
Inherits CBase
Public Overrides Property [Class] As Integer
Get
Return MyBase.Class$$
End Get
Set(value As Integer)
MyBase.Class = value
End Set
End Property
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "[Class]", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitEscapedParameterName() As Task
Dim markupBeforeCommit = <a>Class CBase
Public Overridable Sub Foo([Integer] As Integer)
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Class CBase
Public Overridable Sub Foo([Integer] As Integer)
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub Foo([Integer] As Integer)
MyBase.Foo([Integer])$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Foo([Integer] As Integer)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitByRef() As Task
Dim markupBeforeCommit = <a>Class CBase
Public Overridable Sub foo(ByRef x As Integer, y As String)
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Class CBase
Public Overridable Sub foo(ByRef x As Integer, y As String)
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub foo(ByRef x As Integer, y As String)
MyBase.foo(x, y)$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo(ByRef x As Integer, y As String)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(529714)>
<WpfFact(Skip:="529714"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitGenericMethodTypeParametersRenamed() As Task
Dim markupBeforeCommit = <a>Class CFoo
Overridable Function Something(Of X)(arg As X) As X
End Function
End Class
Class Derived(Of X)
Inherits CFoo
Overrides $$
End Class</a>
Dim expectedCode = <a>Class CFoo
Overridable Function Something(Of X)(arg As X) As X
End Function
End Class
Class Derived(Of X)
Inherits CFoo
Public Overrides Function Something(Of X1)(arg As X1) As X1
Return MyBase.Something(Of X1)(arg)$$
End Function
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Something(Of X1)(arg As X1)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAddsImports() As Task
Dim markupBeforeCommit = <a>MustInherit Class CBase
MustOverride Sub Foo()
End Class
Class Derived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Imports System
MustInherit Class CBase
MustOverride Sub Foo()
End Class
Class Derived
Inherits CBase
Public Overrides Sub Foo()
Throw New NotImplementedException()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(543937)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOptionalArguments() As Task
Dim markupBeforeCommit = <a>Class CBase
Public Overridable Sub foo(Optional x As Integer = 42)
End Sub
End Class
Class CDerived
Inherits CBase
Overrides $$
End Class</a>
Dim expectedCode = <a>Class CBase
Public Overridable Sub foo(Optional x As Integer = 42)
End Sub
End Class
Class CDerived
Inherits CBase
Public Overrides Sub foo(Optional x As Integer = 42)
MyBase.foo(x)$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "foo(x As Integer = 42)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(636706)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterizedProperty() As Task
Dim markupBeforeCommit = <a>Public Class Foo
Public Overridable Property Bar(bay As Integer) As Integer
Get
Return 23
End Get
Set(value As Integer)
End Set
End Property
End Class
Public Class Foo3
Inherits Foo
Overrides $$
End Class</a>
Dim expectedCode = <a>Public Class Foo
Public Overridable Property Bar(bay As Integer) As Integer
Get
Return 23
End Get
Set(value As Integer)
End Set
End Property
End Class
Public Class Foo3
Inherits Foo
Public Overrides Property Bar(bay As Integer) As Integer
Get
Return MyBase.Bar(bay)$$
End Get
Set(value As Integer)
MyBase.Bar(bay) = value
End Set
End Property
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Bar(bay As Integer)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(529737)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOverrideDefaultPropertiesByName() As Task
Dim markupBeforeCommit = <a>Class A
Default Overridable ReadOnly Property Foo(x As Integer) As Object
Get
End Get
End Property
End Class
Class B
Inherits A
Overrides $$
End Class
</a>
Dim expectedCode = <a>Class A
Default Overridable ReadOnly Property Foo(x As Integer) As Object
Get
End Get
End Property
End Class
Class B
Inherits A
Default Public Overrides ReadOnly Property Foo(x As Integer) As Object
Get
Return MyBase.Foo(x)$$
End Get
End Property
End Class
</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Foo(x As Integer)", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
#End Region
#Region "Commit: With Trivia"
<WorkItem(529216)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitSurroundingTriviaDirective() As Task
Dim markupBeforeCommit = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
#If True Then
Overrides $$
#End If
End Class</a>
Dim expectedCode = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
#If True Then
Public Overrides Sub Foo()
MyBase.Foo()$$
End Sub
#End If
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitBeforeTriviaDirective() As Task
Dim markupBeforeCommit = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
Overrides $$
#If True Then
#End If
End Class</a>
Dim expectedCode = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
Public Overrides Sub Foo()
MyBase.Foo()$$
End Sub
#If True Then
#End If
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(529216)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitAfterTriviaDirective() As Task
Dim markupBeforeCommit = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
#If True Then
#End If
Overrides $$
End Class</a>
Dim expectedCode = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
#If True Then
#End If
Public Overrides Sub Foo()
MyBase.Foo()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitBeforeComment() As Task
Dim markupBeforeCommit = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
Overrides $$
'SomeComment
End Class</a>
Dim expectedCode = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
Public Overrides Sub Foo()
MyBase.Foo()$$
End Sub
'SomeComment
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(529216)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitAfterComment() As Task
Dim markupBeforeCommit = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
'SomeComment
Overrides $$
End Class</a>
Dim expectedCode = <a>Class Base
Public Overridable Sub Foo()
End Sub
End Class
Class Derived
Inherits Base
'SomeComment
Public Overrides Sub Foo()
MyBase.Foo()$$
End Sub
End Class</a>
Await VerifyCustomCommitProviderAsync(markupBeforeCommit.Value.Replace(vbLf, vbCrLf), "Foo()", expectedCode.Value.Replace(vbLf, vbCrLf))
End Function
#End Region
<WorkItem(529572)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestWitheventsFieldNotOffered() As Task
Dim text = <a>Public Class C1
Public WithEvents w As C1 = Me
End Class
Class C2 : Inherits C1
overrides $$
End Class
</a>
Await VerifyItemIsAbsentAsync(text.Value, "w")
End Function
<WorkItem(715, "https://github.com/dotnet/roslyn/issues/715")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEventsNotOffered() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSProject</ProjectReference>
<Document FilePath="VBDocument">
Class D
Inherits C
overrides $$
End Class</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProject">
<Document FilePath="CSDocument">
using System;
public class C
{
public virtual event EventHandler e;
}
</Document>
</Project>
</Workspace>
Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(text)
Dim hostDocument = workspace.Documents.First()
Dim caretPosition = hostDocument.CursorPosition.Value
Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id)
Dim triggerInfo = CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo()
Dim completionList = Await GetCompletionListAsync(document, caretPosition, triggerInfo)
Assert.False(completionList.Items.Any(Function(c) c.DisplayText = "e"))
End Using
End Function
End Class
End Namespace
|
HellBrick/roslyn
|
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/OverrideCompletionProviderTests.vb
|
Visual Basic
|
apache-2.0
| 48,809
|
' 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 System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit
Friend Class CommitTestData
Implements IDisposable
Public ReadOnly Buffer As ITextBuffer
Public ReadOnly CommandHandler As CommitCommandHandler
Public ReadOnly EditorOperations As IEditorOperations
Public ReadOnly Workspace As TestWorkspace
Public ReadOnly View As ITextView
Public ReadOnly UndoHistory As ITextUndoHistory
Private ReadOnly _formatter As FormatterMock
Private ReadOnly _inlineRenameService As InlineRenameServiceMock
Public Shared Async Function CreateAsync(test As XElement) As Task(Of CommitTestData)
Dim workspace = Await TestWorkspace.CreateAsync(test)
Return New CommitTestData(workspace)
End Function
Public Sub New(workspace As TestWorkspace)
Me.Workspace = workspace
View = workspace.Documents.Single().GetTextView()
EditorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(View)
Dim position = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
View.Caret.MoveTo(New SnapshotPoint(View.TextSnapshot, position))
Buffer = workspace.Documents.Single().TextBuffer
' HACK: We may have already created a CommitBufferManager for the buffer, so remove it
If (Buffer.Properties.ContainsProperty(GetType(CommitBufferManager))) Then
Dim oldManager = Buffer.Properties.GetProperty(Of CommitBufferManager)(GetType(CommitBufferManager))
oldManager.RemoveReferencingView()
Buffer.Properties.RemoveProperty(GetType(CommitBufferManager))
End If
Dim textUndoHistoryRegistry = workspace.GetService(Of ITextUndoHistoryRegistry)()
UndoHistory = textUndoHistoryRegistry.GetHistory(View.TextBuffer)
_formatter = New FormatterMock(workspace)
_inlineRenameService = New InlineRenameServiceMock()
Dim commitManagerFactory As New CommitBufferManagerFactory(_formatter, _inlineRenameService)
' Make sure the manager exists for the buffer
Dim commitManager = commitManagerFactory.CreateForBuffer(Buffer)
commitManager.AddReferencingView()
CommandHandler = New CommitCommandHandler(
commitManagerFactory,
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of ISmartIndentationService),
textUndoHistoryRegistry,
workspace.GetService(Of Microsoft.CodeAnalysis.Editor.Host.IWaitIndicator))
End Sub
Friend Sub AssertHadCommit(expectCommit As Boolean)
Assert.Equal(expectCommit, _formatter.GotCommit)
End Sub
Friend Sub AssertUsedSemantics(expected As Boolean)
Assert.Equal(expected, _formatter.UsedSemantics)
End Sub
Friend Sub StartInlineRenameSession()
_inlineRenameService.HasSession = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Workspace.Dispose()
End Sub
Private Class InlineRenameServiceMock
Implements IInlineRenameService
Public Property HasSession As Boolean
Public ReadOnly Property ActiveSession As IInlineRenameSession Implements IInlineRenameService.ActiveSession
Get
Return If(HasSession, New MockInlineRenameSession(), Nothing)
End Get
End Property
Public Function StartInlineSession(snapshot As Document, triggerSpan As TextSpan, Optional cancellationToken As CancellationToken = Nothing) As InlineRenameSessionInfo Implements IInlineRenameService.StartInlineSession
Throw New NotImplementedException()
End Function
Private Class MockInlineRenameSession
Implements IInlineRenameSession
Public Sub Cancel() Implements IInlineRenameSession.Cancel
Throw New NotImplementedException()
End Sub
Public Sub Commit(Optional previewChanges As Boolean = False) Implements IInlineRenameSession.Commit
Throw New NotImplementedException()
End Sub
End Class
End Class
Private Class FormatterMock
Implements ICommitFormatter
Private ReadOnly _testWorkspace As TestWorkspace
Public Property GotCommit As Boolean
Public Property UsedSemantics As Boolean
Public Sub New(testWorkspace As TestWorkspace)
_testWorkspace = testWorkspace
End Sub
Public Sub CommitRegion(spanToFormat As SnapshotSpan,
isExplicitFormat As Boolean,
useSemantics As Boolean,
dirtyRegion As SnapshotSpan,
baseSnapshot As ITextSnapshot,
baseTree As SyntaxTree,
cancellationToken As CancellationToken) Implements ICommitFormatter.CommitRegion
GotCommit = True
UsedSemantics = useSemantics
' Assert the span if we have an assertion
If _testWorkspace.Documents.Any(Function(d) d.SelectedSpans.Any()) Then
Dim expectedSpan = _testWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Single()
Dim trackingSpan = _testWorkspace.Documents.Single().InitialTextSnapshot.CreateTrackingSpan(expectedSpan.ToSpan(), SpanTrackingMode.EdgeInclusive)
Assert.Equal(trackingSpan.GetSpan(spanToFormat.Snapshot), spanToFormat.Span)
End If
Dim realCommitFormatter As New CommitFormatter()
realCommitFormatter.CommitRegion(spanToFormat, isExplicitFormat, useSemantics, dirtyRegion, baseSnapshot, baseTree, cancellationToken)
End Sub
End Class
End Class
End Namespace
|
bbarry/roslyn
|
src/EditorFeatures/VisualBasicTest/LineCommit/CommitTestData.vb
|
Visual Basic
|
apache-2.0
| 6,842
|
Imports System
Imports System.Collections.Generic
Imports Xunit
Imports Xunit.Extensions
Public Class MyTest
<Theory>
<PropertyData("DataEnumerator", PropertyType := GetType(ProvidesPropertyData))>
Public Sub Test1(ByVal value As Int32)
Assert.Equal(42, value)
End Sub
End Class
Public Class ProvidesPropertyData
Public Shared ReadOnly Iterator Property DataEnumerator() As IEnumerable(Of Object())
Get
Yield New Object() { 42 }
End Get
End Property
End Class
|
derigel23/resharper-xunit
|
resharper/test/data/References/PropertyDataInOtherClass.vb
|
Visual Basic
|
apache-2.0
| 522
|
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security
Imports System
Imports System.Threading.Tasks
Imports System.Security.Claims
' You can add profile data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
Public Class ApplicationUser
Inherits IdentityUser
Public Function GenerateUserIdentityAsync(manager As ApplicationUserManager) As Task(Of ClaimsIdentity)
Return Task.FromResult(GenerateUserIdentity(manager))
End Function
Public Function GenerateUserIdentity(manager As ApplicationUserManager) As ClaimsIdentity
' Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
Dim userIdentity = manager.CreateIdentity(Me, DefaultAuthenticationTypes.ApplicationCookie)
' Add custom user claims here
Return userIdentity
End Function
End Class
Public Class ApplicationDbContext
Inherits IdentityDbContext(Of ApplicationUser)
Public Sub New()
MyBase.New("DefaultConnection", throwIfV1Schema:=False)
Entity.Database.SetInitializer(New DatabaseInitializer())
End Sub
Public Shared Function Create As ApplicationDbContext
Return New ApplicationDbContext()
End Function
Public Property Books As System.Data.Entity.DbSet(Of Book)
Public Property Categories As System.Data.Entity.DbSet(Of Category)
Public Property Products As System.Data.Entity.DbSet(Of Product)
Public Property Employees As System.Data.Entity.DbSet(Of Employee)
Public Property Movies As System.Data.Entity.DbSet(Of Movie)
End Class
#Region "Helpers"
Public Class IdentityHelper
'Used for XSRF when linking external logins
Public Const XsrfKey As String = "xsrfKey"
Public Shared Sub SignIn(manager As ApplicationUserManager, user As ApplicationUser, isPersistent As Boolean)
Dim authenticationManager As IAuthenticationManager = HttpContext.Current.GetOwinContext().Authentication
authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie)
Dim identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie)
authenticationManager.SignIn(New AuthenticationProperties() With {.IsPersistent = isPersistent}, identity)
End Sub
Public Const ProviderNameKey As String = "providerName"
Public Shared Function GetProviderNameFromRequest(request As HttpRequest) As String
Return request.QueryString(ProviderNameKey)
End Function
Public Const CodeKey As String = "code"
Public Shared Function GetCodeFromRequest(request As HttpRequest) As String
Return request.QueryString(CodeKey)
End Function
Public Const UserIdKey As String = "userId"
Public Shared Function GetUserIdFromRequest(request As HttpRequest) As String
Return HttpUtility.UrlDecode(request.QueryString(UserIdKey))
End Function
Public Shared Function GetResetPasswordRedirectUrl(code As String) As String
Return "/Account/ResetPassword?" + CodeKey + "=" + HttpUtility.UrlEncode(code)
End Function
Public Shared Function GetUserConfirmationRedirectUrl(code As String, userId As String) As String
Return "/Account/Confirm?" + CodeKey + "=" + HttpUtility.UrlEncode(code) + "&" + UserIdKey + "=" + HttpUtility.UrlEncode(userId)
End Function
Private Shared Function IsLocalUrl(url As String) As Boolean
Return Not String.IsNullOrEmpty(url) AndAlso ((url(0) = "/"c AndAlso (url.Length = 1 OrElse (url(1) <> "/"c AndAlso url(1) <> "\"c))) OrElse (url.Length > 1 AndAlso url(0) = "~"c AndAlso url(1) = "/"c))
End Function
Public Shared Sub RedirectToReturnUrl(returnUrl As String, response As HttpResponse)
If Not [String].IsNullOrEmpty(returnUrl) AndAlso IsLocalUrl(returnUrl) Then
response.Redirect(returnUrl)
Else
response.Redirect("~/")
End If
End Sub
End Class
#End Region
|
neozhu/WebFormsScaffolding
|
Samples.VB/Models/IdentityModels.vb
|
Visual Basic
|
apache-2.0
| 4,114
|
Imports System.IO
Imports System.Runtime.InteropServices
Module Example
<STAThread()> _
Sub Main()
Dim objApplication As SolidEdgeFramework.Application = Nothing
Dim objPartDocument As SolidEdgePart.PartDocument = Nothing
Dim objHoleDataCollection As SolidEdgePart.HoleDataCollection = Nothing
Dim objHoleData As SolidEdgePart.HoleData = Nothing
Try
OleMessageFilter.Register()
objApplication = Marshal.GetActiveObject("SolidEdge.Application")
objPartDocument = objApplication.ActiveDocument
objHoleDataCollection = objPartDocument.HoleDataCollection
For Each objHoleData In objHoleDataCollection
Console.WriteLine(objHoleData.Name)
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
OleMessageFilter.Revoke()
End Try
End Sub
End Module
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.PartDocument.HoleDataCollection.vb
|
Visual Basic
|
mit
| 947
|
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
|
jirikadlec2/hydrodata
|
hydrodatainfo/meteo_admin/Default.aspx.vb
|
Visual Basic
|
bsd-3-clause
| 178
|
' 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.Globalization
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Metadata
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
''' <summary>
''' The class to represent all methods imported from a PE/module.
''' </summary>
Friend NotInheritable Class PEMethodSymbol
Inherits MethodSymbol
Private ReadOnly _handle As MethodDefinitionHandle
Private ReadOnly _name As String
Private ReadOnly _implFlags As UShort
Private ReadOnly _flags As UShort
Private ReadOnly _containingType As PENamedTypeSymbol
Private _associatedPropertyOrEventOpt As Symbol
Private _packedFlags As PackedFlags
Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Private _lazyExplicitMethodImplementations As ImmutableArray(Of MethodSymbol)
''' <summary>
''' A single field to hold optional auxiliary data.
''' In many scenarios it is possible to avoid allocating this, thus saving total space in <see cref="PEModuleSymbol"/>.
''' Even for lazily-computed values, it may be possible to avoid allocating <see cref="_uncommonFields"/> if
''' the computed value is a well-known "empty" value. In this case, bits in <see cref="_packedFlags"/> are used
''' to indicate that the lazy values have been computed and, if <see cref="_uncommonFields"/> is null, then
''' the "empty" value should be inferred.
''' </summary>
Private _uncommonFields As UncommonFields
Private Structure PackedFlags
' Flags are packed into a 32-bit int with the following layout:
' | h|g|f|e|d|c|b|aaaaa|
'
' a = method kind. 5 bits
' b = method kind populated. 1 bit
' c = isExtensionMethod. 1 bit.
' d = isExtensionMethod populated. 1 bit.
' e = obsolete attribute populated. 1 bit
' f = custom attributes populated. 1 bit
' g = use site diagnostic populated. 1 bit
' h = conditional attributes populated. 1 bit
Private _bits As Integer
Private Const s_methodKindOffset As Integer = 0
Private Const s_methodKindMask As Integer = &H1F
Private Const s_methodKindIsPopulatedBit As Integer = 1 << 5
Private Const s_isExtensionMethodBit As Integer = 1 << 6
Private Const s_isExtensionMethodIsPopulatedBit As Integer = 1 << 7
Private Const s_isObsoleteAttributePopulatedBit As Integer = 1 << 8
Private Const s_isCustomAttributesPopulatedBit As Integer = 1 << 9
Private Const s_isUseSiteDiagnosticPopulatedBit As Integer = 1 << 10
Private Const s_isConditionalAttributePopulatedBit As Integer = 1 << 11
Public Property MethodKind As MethodKind
Get
Return CType((_bits >> s_methodKindOffset) And s_methodKindMask, MethodKind)
End Get
Set(value As MethodKind)
Debug.Assert(value = (value And s_methodKindMask))
_bits = (_bits And Not (s_methodKindMask << s_methodKindOffset)) Or (value << s_methodKindOffset) Or s_methodKindIsPopulatedBit
End Set
End Property
Public ReadOnly Property MethodKindIsPopulated As Boolean
Get
Return (_bits And s_methodKindIsPopulatedBit) <> 0
End Get
End Property
Public ReadOnly Property IsExtensionMethod As Boolean
Get
Return (_bits And s_isExtensionMethodBit) <> 0
End Get
End Property
Public ReadOnly Property IsExtensionMethodPopulated As Boolean
Get
Return (_bits And s_isExtensionMethodIsPopulatedBit) <> 0
End Get
End Property
Public ReadOnly Property IsObsoleteAttributePopulated As Boolean
Get
Return (_bits And s_isObsoleteAttributePopulatedBit) <> 0
End Get
End Property
Public ReadOnly Property IsCustomAttributesPopulated As Boolean
Get
Return (_bits And s_isCustomAttributesPopulatedBit) <> 0
End Get
End Property
Public ReadOnly Property IsUseSiteDiagnosticPopulated As Boolean
Get
Return (_bits And s_isUseSiteDiagnosticPopulatedBit) <> 0
End Get
End Property
Public ReadOnly Property IsConditionalPopulated As Boolean
Get
Return (_bits And s_isConditionalAttributePopulatedBit) <> 0
End Get
End Property
Private Shared Function BitsAreUnsetOrSame(bits As Integer, mask As Integer) As Boolean
Return (bits And mask) = 0 OrElse (bits And mask) = mask
End Function
Public Sub InitializeMethodKind(methodKind As MethodKind)
Debug.Assert(methodKind = (methodKind And s_methodKindMask))
Dim bitsToSet = ((methodKind And s_methodKindMask) << s_methodKindOffset) Or s_methodKindIsPopulatedBit
Debug.Assert(BitsAreUnsetOrSame(_bits, bitsToSet))
ThreadSafeFlagOperations.Set(_bits, bitsToSet)
End Sub
Public Sub InitializeIsExtensionMethod(isExtensionMethod As Boolean)
Dim bitsToSet = If(isExtensionMethod, s_isExtensionMethodBit, 0) Or s_isExtensionMethodIsPopulatedBit
Debug.Assert(BitsAreUnsetOrSame(_bits, bitsToSet))
ThreadSafeFlagOperations.Set(_bits, bitsToSet)
End Sub
Public Sub SetIsObsoleteAttributePopulated()
ThreadSafeFlagOperations.Set(_bits, s_isObsoleteAttributePopulatedBit)
End Sub
Public Sub SetIsCustomAttributesPopulated()
ThreadSafeFlagOperations.Set(_bits, s_isCustomAttributesPopulatedBit)
End Sub
Public Sub SetIsUseSiteDiagnosticPopulated()
ThreadSafeFlagOperations.Set(_bits, s_isUseSiteDiagnosticPopulatedBit)
End Sub
Public Sub SetIsConditionalAttributePopulated()
ThreadSafeFlagOperations.Set(_bits, s_isConditionalAttributePopulatedBit)
End Sub
End Structure
''' <summary>
''' Holds infrequently accessed fields. See <seealso cref="_uncommonFields"/> for an explanation.
''' </summary>
Private NotInheritable Class UncommonFields
Public _lazyMeParameter As ParameterSymbol
Public _lazyDocComment As Tuple(Of CultureInfo, String)
Public _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData)
Public _lazyConditionalAttributeSymbols As ImmutableArray(Of String)
Public _lazyObsoleteAttributeData As ObsoleteAttributeData
Public _lazyUseSiteErrorInfo As DiagnosticInfo
End Class
Private Function CreateUncommonFields() As UncommonFields
Dim retVal = New UncommonFields
If Not _packedFlags.IsObsoleteAttributePopulated Then
retVal._lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized
End If
If Not _packedFlags.IsUseSiteDiagnosticPopulated Then
retVal._lazyUseSiteErrorInfo = ErrorFactory.EmptyErrorInfo ' Indicates unknown state.
End If
If _packedFlags.IsCustomAttributesPopulated Then
retVal._lazyCustomAttributes = ImmutableArray(Of VisualBasicAttributeData).Empty
End If
If _packedFlags.IsConditionalPopulated Then
retVal._lazyConditionalAttributeSymbols = ImmutableArray(Of String).Empty
End If
Return retVal
End Function
Private Function AccessUncommonFields() As UncommonFields
Dim retVal = _uncommonFields
Return If(retVal, InterlockedOperations.Initialize(_uncommonFields, CreateUncommonFields()))
End Function
#Region "Signature data"
Private _lazySignature As SignatureData
Private Class SignatureData
Public ReadOnly Header As SignatureHeader
Public ReadOnly Parameters As ImmutableArray(Of ParameterSymbol)
Public ReadOnly ReturnParam As PEParameterSymbol
Public Sub New(signatureHeader As SignatureHeader, parameters As ImmutableArray(Of ParameterSymbol), returnParam As PEParameterSymbol)
Me.Header = signatureHeader
Me.Parameters = parameters
Me.ReturnParam = returnParam
End Sub
End Class
#End Region
Friend Sub New(
moduleSymbol As PEModuleSymbol,
containingType As PENamedTypeSymbol,
handle As MethodDefinitionHandle
)
Debug.Assert(moduleSymbol IsNot Nothing)
Debug.Assert(containingType IsNot Nothing)
Debug.Assert(Not handle.IsNil)
_handle = handle
_containingType = containingType
Try
Dim implFlags As MethodImplAttributes
Dim flags As MethodAttributes
Dim rva As Integer
moduleSymbol.Module.GetMethodDefPropsOrThrow(handle, _name, implFlags, flags, rva)
_implFlags = CType(implFlags, UShort)
_flags = CType(flags, UShort)
Catch mrEx As BadImageFormatException
If _name Is Nothing Then
_name = String.Empty
End If
InitializeUseSiteErrorInfo(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, CustomSymbolDisplayFormatter.ShortErrorName(Me)))
End Try
End Sub
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _containingType
End Get
End Property
Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol
Get
Return _containingType
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return (_flags And MethodAttributes.SpecialName) <> 0
End Get
End Property
Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean
Get
Return (_flags And MethodAttributes.RTSpecialName) <> 0
End Get
End Property
Friend Overrides ReadOnly Property IsMetadataFinal As Boolean
Get
Return (_flags And MethodAttributes.Final) <> 0
End Get
End Property
Friend ReadOnly Property MethodImplFlags As MethodImplAttributes
Get
Return CType(_implFlags, MethodImplAttributes)
End Get
End Property
Friend ReadOnly Property MethodFlags As MethodAttributes
Get
Return CType(_flags, MethodAttributes)
End Get
End Property
Public Overrides ReadOnly Property MethodKind As MethodKind
Get
If Not _packedFlags.MethodKindIsPopulated Then
_packedFlags.InitializeMethodKind(ComputeMethodKind())
End If
Return _packedFlags.MethodKind
End Get
End Property
Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Get
Return False
End Get
End Property
Private Function ComputeMethodKind() As MethodKind
Dim name As String = Me.Name
If HasSpecialName Then
If name.StartsWith("."c, StringComparison.Ordinal) Then
' 10.5.1 Instance constructor
' An instance constructor shall be an instance (not static or virtual) method,
' it shall be named .ctor, and marked instance, rtspecialname, and specialname (§15.4.2.6).
' An instance constructor can have parameters, but shall not return a value.
' An instance constructor cannot take generic type parameters.
' 10.5.3 Type initializer
' This method shall be static, take no parameters, return no value,
' be marked with rtspecialname and specialname (§15.4.2.6), and be named .cctor.
If (_flags And (MethodAttributes.RTSpecialName Or MethodAttributes.Virtual)) = MethodAttributes.RTSpecialName AndAlso
String.Equals(name, If(IsShared, WellKnownMemberNames.StaticConstructorName, WellKnownMemberNames.InstanceConstructorName), StringComparison.Ordinal) AndAlso
IsSub AndAlso Arity = 0 Then
If IsShared Then
If Parameters.Length = 0 Then
Return MethodKind.SharedConstructor
End If
Else
Return MethodKind.Constructor
End If
End If
Return MethodKind.Ordinary
ElseIf IsShared AndAlso DeclaredAccessibility = Accessibility.Public AndAlso Not IsSub AndAlso Arity = 0 Then
Dim opInfo As OverloadResolution.OperatorInfo = OverloadResolution.GetOperatorInfo(name)
If opInfo.ParamCount <> 0 Then
' Combination of all conditions that should be met to get here must match implementation of
' IsPotentialOperatorOrConversion (with exception of ParameterCount matching).
If OverloadResolution.ValidateOverloadedOperator(Me, opInfo) Then
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo)
End If
End If
Return MethodKind.Ordinary
End If
End If
If Not IsShared AndAlso String.Equals(name, WellKnownMemberNames.DelegateInvokeName, StringComparison.Ordinal) AndAlso _containingType.TypeKind = TypeKind.Delegate Then
Return MethodKind.DelegateInvoke
End If
Return MethodKind.Ordinary
End Function
Friend Overrides Function IsParameterlessConstructor() As Boolean
If _packedFlags.MethodKindIsPopulated Then
Return _packedFlags.MethodKind = MethodKind.Constructor AndAlso ParameterCount = 0
End If
' 10.5.1 Instance constructor
' An instance constructor shall be an instance (not static or virtual) method,
' it shall be named .ctor, and marked instance, rtspecialname, and specialname (§15.4.2.6).
' An instance constructor can have parameters, but shall not return a value.
' An instance constructor cannot take generic type parameters.
If (_flags And (MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName Or MethodAttributes.Static Or MethodAttributes.Virtual)) =
(MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName) AndAlso
String.Equals(Me.Name, WellKnownMemberNames.InstanceConstructorName, StringComparison.Ordinal) AndAlso
ParameterCount = 0 AndAlso
IsSub AndAlso Arity = 0 Then
_packedFlags.MethodKind = MethodKind.Constructor
Return True
End If
Return False
End Function
Private Function ComputeMethodKindForPotentialOperatorOrConversion(opInfo As OverloadResolution.OperatorInfo) As MethodKind
' Don't mark methods involved in unsupported overloading as operators.
If opInfo.IsUnary Then
Select Case opInfo.UnaryOperatorKind
Case UnaryOperatorKind.Implicit
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.Conversion, WellKnownMemberNames.ExplicitConversionName, True)
Case UnaryOperatorKind.Explicit
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.Conversion, WellKnownMemberNames.ImplicitConversionName, True)
Case UnaryOperatorKind.IsFalse, UnaryOperatorKind.IsTrue, UnaryOperatorKind.Minus, UnaryOperatorKind.Plus
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, Nothing, False)
Case UnaryOperatorKind.Not
If IdentifierComparison.Equals(Me.Name, WellKnownMemberNames.OnesComplementOperatorName) Then
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, Nothing, False)
Else
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, WellKnownMemberNames.OnesComplementOperatorName, False)
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(opInfo.UnaryOperatorKind)
End Select
Else
Debug.Assert(opInfo.IsBinary)
Select Case opInfo.BinaryOperatorKind
Case BinaryOperatorKind.Add,
BinaryOperatorKind.Subtract,
BinaryOperatorKind.Multiply,
BinaryOperatorKind.Divide,
BinaryOperatorKind.IntegerDivide,
BinaryOperatorKind.Modulo,
BinaryOperatorKind.Power,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.Like,
BinaryOperatorKind.Concatenate,
BinaryOperatorKind.Xor
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, Nothing, False)
Case BinaryOperatorKind.And
If IdentifierComparison.Equals(Me.Name, WellKnownMemberNames.BitwiseAndOperatorName) Then
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, Nothing, False)
Else
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, WellKnownMemberNames.BitwiseAndOperatorName, False)
End If
Case BinaryOperatorKind.Or
If IdentifierComparison.Equals(Me.Name, WellKnownMemberNames.BitwiseOrOperatorName) Then
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, Nothing, False)
Else
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, WellKnownMemberNames.BitwiseOrOperatorName, False)
End If
Case BinaryOperatorKind.LeftShift
If IdentifierComparison.Equals(Me.Name, WellKnownMemberNames.LeftShiftOperatorName) Then
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, Nothing, False)
Else
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, WellKnownMemberNames.LeftShiftOperatorName, False)
End If
Case BinaryOperatorKind.RightShift
If IdentifierComparison.Equals(Me.Name, WellKnownMemberNames.RightShiftOperatorName) Then
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, Nothing, False)
Else
Return ComputeMethodKindForPotentialOperatorOrConversion(opInfo, MethodKind.UserDefinedOperator, WellKnownMemberNames.RightShiftOperatorName, False)
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(opInfo.BinaryOperatorKind)
End Select
End If
End Function
Private Function IsPotentialOperatorOrConversion(opInfo As OverloadResolution.OperatorInfo) As Boolean
Return HasSpecialName AndAlso
IsShared AndAlso DeclaredAccessibility = Accessibility.Public AndAlso
Not IsSub AndAlso Arity = 0 AndAlso
ParameterCount = opInfo.ParamCount
End Function
Private Function ComputeMethodKindForPotentialOperatorOrConversion(
opInfo As OverloadResolution.OperatorInfo,
potentialMethodKind As MethodKind,
additionalNameOpt As String,
adjustContendersOfAdditionalName As Boolean
) As MethodKind
Debug.Assert(potentialMethodKind = MethodKind.Conversion OrElse potentialMethodKind = MethodKind.UserDefinedOperator)
Dim result As MethodKind = potentialMethodKind
Dim inputParams As ImmutableArray(Of ParameterSymbol) = Parameters
Dim outputType As TypeSymbol = ReturnType
For i As Integer = 0 To If(additionalNameOpt Is Nothing, 0, 1)
For Each m In _containingType.GetMembers(If(i = 0, Me.Name, additionalNameOpt))
If m Is Me Then
Continue For
End If
If m.Kind <> SymbolKind.Method Then
Continue For
End If
Dim contender = TryCast(m, PEMethodSymbol)
If contender Is Nothing OrElse Not contender.IsPotentialOperatorOrConversion(opInfo) Then
Continue For
End If
If contender._packedFlags.MethodKindIsPopulated Then
Select Case contender._packedFlags.MethodKind
Case MethodKind.Ordinary
' Need to check against our method
Case potentialMethodKind
If i = 0 OrElse adjustContendersOfAdditionalName Then
' Contender was already cleared, so it cannot conflict with this operator.
Continue For
End If
Case Else
' Cannot be an operator of the target kind.
Continue For
End Select
End If
If potentialMethodKind = MethodKind.Conversion AndAlso Not outputType.IsSameTypeIgnoringCustomModifiers(contender.ReturnType) Then
Continue For
End If
Dim j As Integer
For j = 0 To inputParams.Length - 1
If Not inputParams(j).Type.IsSameTypeIgnoringCustomModifiers(contender.Parameters(j).Type) Then
Exit For
End If
Next
If j < inputParams.Length Then
Continue For
End If
' Unsupported overloading
result = MethodKind.Ordinary
' Mark the contender too.
If i = 0 OrElse adjustContendersOfAdditionalName Then
contender._packedFlags.InitializeMethodKind(MethodKind.Ordinary)
End If
Next
Next
Return result
End Function
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return _associatedPropertyOrEventOpt
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Dim access As Accessibility = Accessibility.Private
Select Case _flags And MethodAttributes.MemberAccessMask
Case MethodAttributes.Assembly
access = Accessibility.Friend
Case MethodAttributes.FamORAssem
access = Accessibility.ProtectedOrFriend
Case MethodAttributes.FamANDAssem
access = Accessibility.ProtectedAndFriend
Case MethodAttributes.Private,
MethodAttributes.PrivateScope
access = Accessibility.Private
Case MethodAttributes.Public
access = Accessibility.Public
Case MethodAttributes.Family
access = Accessibility.Protected
Case Else
access = Accessibility.Private
End Select
Return access
End Get
End Property
Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
If Not _packedFlags.IsCustomAttributesPopulated Then
Dim attributeData As ImmutableArray(Of VisualBasicAttributeData) = Nothing
Dim containingPEModuleSymbol = DirectCast(ContainingModule(), PEModuleSymbol)
containingPEModuleSymbol.LoadCustomAttributes(Me.Handle, attributeData)
Debug.Assert(Not attributeData.IsDefault)
If Not attributeData.IsEmpty Then
attributeData = InterlockedOperations.Initialize(AccessUncommonFields()._lazyCustomAttributes, attributeData)
End If
_packedFlags.SetIsCustomAttributesPopulated()
Return attributeData
End If
Dim uncommonFields = _uncommonFields
If uncommonFields Is Nothing Then
Return ImmutableArray(Of VisualBasicAttributeData).Empty
Else
Dim attributeData = uncommonFields._lazyCustomAttributes
Return If(attributeData.IsDefault,
InterlockedOperations.Initialize(uncommonFields._lazyCustomAttributes, ImmutableArray(Of VisualBasicAttributeData).Empty),
attributeData)
End If
End Function
Friend Overrides Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData)
Return GetAttributes()
End Function
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
If Not _packedFlags.IsExtensionMethodPopulated Then
Dim result As Boolean = False
If Me.IsShared AndAlso
Me.ParameterCount > 0 AndAlso
Me.MethodKind = MethodKind.Ordinary AndAlso
_containingType.MightContainExtensionMethods AndAlso
_containingType.ContainingPEModule.Module.HasExtensionAttribute(Me.Handle, ignoreCase:=True) AndAlso
ValidateGenericConstraintsOnExtensionMethodDefinition() Then
Dim firstParam As ParameterSymbol = Me.Parameters(0)
result = Not (firstParam.IsOptional OrElse firstParam.IsParamArray)
End If
_packedFlags.InitializeIsExtensionMethod(result)
End If
Return _packedFlags.IsExtensionMethod
End Get
End Property
Public Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return (_flags And MethodAttributes.PinvokeImpl) <> 0 OrElse
(_implFlags And (MethodImplAttributes.InternalCall Or MethodImplAttributes.Runtime)) <> 0
End Get
End Property
Public Overrides Function GetDllImportData() As DllImportData
If (_flags And MethodAttributes.PinvokeImpl) = 0 Then
Return Nothing
End If
' do not cache the result, the compiler doesn't use this (it's only exposed through public API):
Return _containingType.ContainingPEModule.Module.GetDllImportData(Me._handle)
End Function
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return (_flags And MethodAttributes.NewSlot) <> 0
End Function
Friend Overrides ReadOnly Property IsExternal As Boolean
Get
Return IsExternalMethod OrElse
(_implFlags And MethodImplAttributes.Runtime) <> 0
End Get
End Property
Friend Overrides ReadOnly Property IsAccessCheckedOnOverride As Boolean
Get
Return (_flags And MethodAttributes.CheckAccessOnOverride) <> 0
End Get
End Property
Friend Overrides ReadOnly Property ReturnValueIsMarshalledExplicitly As Boolean
Get
Return _lazySignature.ReturnParam.IsMarshalledExplicitly
End Get
End Property
Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return _lazySignature.ReturnParam.MarshallingInformation
End Get
End Property
Friend Overrides ReadOnly Property ReturnValueMarshallingDescriptor As ImmutableArray(Of Byte)
Get
Return _lazySignature.ReturnParam.MarshallingDescriptor
End Get
End Property
Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return CType(_implFlags, Reflection.MethodImplAttributes)
End Get
End Property
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Private ReadOnly Property Signature As SignatureData
Get
Return If(_lazySignature, LoadSignature())
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return Signature.Header.CallingConvention = SignatureCallingConvention.VarArgs
End Get
End Property
Public Overrides ReadOnly Property IsGenericMethod As Boolean
Get
Return Me.Arity > 0
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
If Me._lazyTypeParameters.IsDefault Then
Try
Dim paramCount As Integer = 0
Dim typeParamCount As Integer = 0
MetadataDecoder.GetSignatureCountsOrThrow(Me._containingType.ContainingPEModule.Module, Me._handle, paramCount, typeParamCount)
Return typeParamCount
Catch mrEx As BadImageFormatException
Return TypeParameters.Length
End Try
Else
Return Me._lazyTypeParameters.Length
End If
End Get
End Property
Friend ReadOnly Property Handle As MethodDefinitionHandle
Get
Return _handle
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return (_flags And MethodAttributes.Virtual) <> 0 AndAlso
(_flags And MethodAttributes.Abstract) <> 0
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return (_flags And
(MethodAttributes.Virtual Or
MethodAttributes.Final Or
MethodAttributes.Abstract Or
MethodAttributes.NewSlot)) =
(MethodAttributes.Virtual Or MethodAttributes.Final)
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return (_flags And MethodAttributes.HideBySig) <> 0 OrElse
IsOverrides ' If overrides is present, then Overloads is implicit
' The check for IsOverrides is needed because of bug Dev10 #850631,
' VB compiler doesn't emit HideBySig flag for overriding methods that
' aren't marked explicitly with Overrides modifier.
End Get
End Property
Friend Overrides ReadOnly Property IsHiddenBySignature As Boolean
Get
Return (_flags And MethodAttributes.HideBySig) <> 0
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Dim flagsToCheck = (_flags And
(MethodAttributes.Virtual Or
MethodAttributes.Final Or
MethodAttributes.Abstract Or
MethodAttributes.NewSlot))
Return flagsToCheck = (MethodAttributes.Virtual Or MethodAttributes.NewSlot) OrElse
(flagsToCheck = MethodAttributes.Virtual AndAlso _containingType.BaseTypeNoUseSiteDiagnostics Is Nothing)
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
' ECMA-335
' 10.3.1 Introducing a virtual method
' If the definition is not marked newslot, the definition creates a new virtual method only
' if there is not virtual method of the same name and signature inherited from a base class.
'
' This means that a virtual method without NewSlot flag in a type that doesn't have a base
' is a new virtual method and doesn't override anything.
Return (_flags And MethodAttributes.Virtual) <> 0 AndAlso
(_flags And MethodAttributes.NewSlot) = 0 AndAlso
_containingType.BaseTypeNoUseSiteDiagnostics IsNot Nothing
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return (_flags And MethodAttributes.Static) <> 0
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return Me.ReturnType.SpecialType = SpecialType.System_Void
End Get
End Property
Public Overrides ReadOnly Property IsAsync As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsIterator As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return StaticCast(Of Location).From(_containingType.ContainingPEModule.MetadataLocation)
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 ReadOnly Property ParameterCount As Integer
Get
If Me._lazySignature Is Nothing Then
Try
Dim paramCount As Integer = 0
Dim typeParamCount As Integer = 0
MetadataDecoder.GetSignatureCountsOrThrow(Me._containingType.ContainingPEModule.Module, Me._handle, paramCount, typeParamCount)
Return paramCount
Catch mrEx As BadImageFormatException
Return Parameters.Length
End Try
Else
Return Me._lazySignature.Parameters.Length
End If
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return Signature.Parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return Signature.ReturnParam.IsByRef
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return Signature.ReturnParam.Type
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return Signature.ReturnParam.CustomModifiers
End Get
End Property
Public Overrides Function GetReturnTypeAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Return Signature.ReturnParam.GetAttributes()
End Function
Friend ReadOnly Property ReturnParam As PEParameterSymbol
Get
Return Signature.ReturnParam
End Get
End Property
''' <summary>
''' Associate the method with a particular property. Returns
''' false if the method is already associated with a property or event.
''' </summary>
Friend Function SetAssociatedProperty(propertySymbol As PEPropertySymbol, methodKind As MethodKind) As Boolean
Debug.Assert((methodKind = MethodKind.PropertyGet) OrElse (methodKind = MethodKind.PropertySet))
Return Me.SetAssociatedPropertyOrEvent(propertySymbol, methodKind)
End Function
''' <summary>
''' Associate the method with a particular event. Returns
''' false if the method is already associated with a property or event.
''' </summary>
Friend Function SetAssociatedEvent(eventSymbol As PEEventSymbol, methodKind As MethodKind) As Boolean
Debug.Assert((methodKind = MethodKind.EventAdd) OrElse (methodKind = MethodKind.EventRemove) OrElse (methodKind = MethodKind.EventRaise))
Return Me.SetAssociatedPropertyOrEvent(eventSymbol, methodKind)
End Function
Private Function SetAssociatedPropertyOrEvent(propertyOrEventSymbol As Symbol, methodKind As MethodKind) As Boolean
If Me._associatedPropertyOrEventOpt Is Nothing Then
Debug.Assert(propertyOrEventSymbol.ContainingType = Me.ContainingType)
Me._associatedPropertyOrEventOpt = propertyOrEventSymbol
_packedFlags.MethodKind = methodKind
Return True
End If
Return False
End Function
Private Function LoadSignature() As SignatureData
Dim moduleSymbol = _containingType.ContainingPEModule
Dim signatureHeader As SignatureHeader
Dim mrEx As BadImageFormatException = Nothing
Dim paramInfo() As ParamInfo(Of TypeSymbol) =
(New MetadataDecoder(moduleSymbol, Me)).GetSignatureForMethod(_handle, signatureHeader, mrEx, allowByRefReturn:=True)
' If method is not generic, let's assign empty list for type parameters
If Not signatureHeader.IsGeneric() AndAlso
_lazyTypeParameters.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(_lazyTypeParameters,
ImmutableArray(Of TypeParameterSymbol).Empty)
End If
Dim count As Integer = paramInfo.Length - 1
Dim params As ImmutableArray(Of ParameterSymbol)
Dim isBad As Boolean
Dim hasBadParameter As Boolean = False
If count > 0 Then
Dim builder = ImmutableArray.CreateBuilder(Of ParameterSymbol)(count)
For i As Integer = 0 To count - 1 Step 1
builder.Add(PEParameterSymbol.Create(moduleSymbol, Me, i, paramInfo(i + 1), isBad))
If isBad Then
hasBadParameter = True
End If
Next
params = builder.ToImmutable()
Else
params = ImmutableArray(Of ParameterSymbol).Empty
End If
' paramInfo(0) contains information about return "parameter"
Dim returnParam = PEParameterSymbol.Create(moduleSymbol, Me, 0, paramInfo(0), isBad)
If mrEx IsNot Nothing OrElse hasBadParameter OrElse isBad Then
InitializeUseSiteErrorInfo(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, CustomSymbolDisplayFormatter.ShortErrorName(Me)))
End If
Dim signature As New SignatureData(signatureHeader, params, returnParam)
Return InterlockedOperations.Initialize(_lazySignature, signature)
End Function
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Dim errorInfo As DiagnosticInfo = Nothing
EnsureTypeParametersAreLoaded(errorInfo)
Dim typeParams = EnsureTypeParametersAreLoaded(errorInfo)
If errorInfo IsNot Nothing Then
InitializeUseSiteErrorInfo(errorInfo)
End If
Return typeParams
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
If IsGenericMethod Then
Return StaticCast(Of TypeSymbol).From(Me.TypeParameters)
Else
Return ImmutableArray(Of TypeSymbol).Empty
End If
End Get
End Property
Private Function EnsureTypeParametersAreLoaded(ByRef errorInfo As DiagnosticInfo) As ImmutableArray(Of TypeParameterSymbol)
Dim typeParams = _lazyTypeParameters
If Not typeParams.IsDefault Then
Return typeParams
End If
Return InterlockedOperations.Initialize(_lazyTypeParameters, LoadTypeParameters(errorInfo))
End Function
Private Function LoadTypeParameters(ByRef errorInfo As DiagnosticInfo) As ImmutableArray(Of TypeParameterSymbol)
Try
Dim moduleSymbol = _containingType.ContainingPEModule
Dim gpHandles = moduleSymbol.Module.GetGenericParametersForMethodOrThrow(_handle)
If gpHandles.Count = 0 Then
Return ImmutableArray(Of TypeParameterSymbol).Empty
Else
Dim ownedParams = ImmutableArray.CreateBuilder(Of TypeParameterSymbol)(gpHandles.Count)
For i = 0 To gpHandles.Count - 1
ownedParams.Add(New PETypeParameterSymbol(moduleSymbol, Me, CUShort(i), gpHandles(i)))
Next
Return ownedParams.ToImmutable()
End If
Catch mrEx As BadImageFormatException
errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, CustomSymbolDisplayFormatter.ShortErrorName(Me))
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Try
End Function
Friend Overrides ReadOnly Property CallingConvention As Cci.CallingConvention
Get
Return CType(Signature.Header.RawValue, Cci.CallingConvention)
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
If Not _lazyExplicitMethodImplementations.IsDefault Then
Return _lazyExplicitMethodImplementations
End If
Dim moduleSymbol = _containingType.ContainingPEModule
' Context: we need the containing type of this method as context so that we can substitute appropriately into
' any generic interfaces that we might be explicitly implementing. There is no reason to pass in the method
' context, however, because any method type parameters will belong to the implemented (i.e. interface) method,
' which we do not yet know.
Dim explicitlyOverriddenMethods = New MetadataDecoder(
moduleSymbol,
_containingType).GetExplicitlyOverriddenMethods(_containingType.Handle, Me._handle, Me.ContainingType)
'avoid allocating a builder in the common case
Dim anyToRemove = False
For Each method In explicitlyOverriddenMethods
If Not method.ContainingType.IsInterface Then
anyToRemove = True
Exit For
End If
Next
Dim explicitImplementations = explicitlyOverriddenMethods
If anyToRemove Then
Dim explicitInterfaceImplementationsBuilder = ArrayBuilder(Of MethodSymbol).GetInstance()
For Each method In explicitlyOverriddenMethods
If method.ContainingType.IsInterface Then
explicitInterfaceImplementationsBuilder.Add(method)
End If
Next
explicitImplementations = explicitInterfaceImplementationsBuilder.ToImmutableAndFree()
End If
Return InterlockedOperations.Initialize(_lazyExplicitMethodImplementations, explicitImplementations)
End Get
End Property
Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String
' Note: m_lazyDocComment is passed ByRef
Return PEDocumentationCommentUtils.GetDocumentationComment(
Me, _containingType.ContainingPEModule, preferredCulture, cancellationToken, AccessUncommonFields()._lazyDocComment)
End Function
Friend Overrides ReadOnly Property Syntax As VisualBasicSyntaxNode
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetUseSiteErrorInfo() As DiagnosticInfo
If Not _packedFlags.IsUseSiteDiagnosticPopulated Then
Dim errorInfo As DiagnosticInfo = CalculateUseSiteErrorInfo()
EnsureTypeParametersAreLoaded(errorInfo)
Return InitializeUseSiteErrorInfo(errorInfo)
End If
Dim uncommonFields = _uncommonFields
If uncommonFields Is Nothing Then
Return Nothing
Else
Dim result = uncommonFields._lazyUseSiteErrorInfo
Return If(result Is ErrorFactory.EmptyErrorInfo,
InterlockedOperations.Initialize(uncommonFields._lazyUseSiteErrorInfo, Nothing, ErrorFactory.EmptyErrorInfo),
result)
End If
End Function
Private Function InitializeUseSiteErrorInfo(errorInfo As DiagnosticInfo) As DiagnosticInfo
Debug.Assert(errorInfo IsNot ErrorFactory.EmptyErrorInfo)
If errorInfo IsNot Nothing Then
errorInfo = InterlockedOperations.Initialize(AccessUncommonFields()._lazyUseSiteErrorInfo, errorInfo, ErrorFactory.EmptyErrorInfo)
End If
_packedFlags.SetIsUseSiteDiagnosticPopulated()
Return errorInfo
End Function
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
If Not _packedFlags.IsObsoleteAttributePopulated Then
Dim result = ObsoleteAttributeHelpers.GetObsoleteDataFromMetadata(_handle, DirectCast(ContainingModule, PEModuleSymbol))
If result IsNot Nothing Then
result = InterlockedOperations.Initialize(AccessUncommonFields()._lazyObsoleteAttributeData, result, ObsoleteAttributeData.Uninitialized)
End If
_packedFlags.SetIsObsoleteAttributePopulated()
Return result
End If
Dim uncommonFields = _uncommonFields
If uncommonFields Is Nothing Then
Return Nothing
Else
Dim result = uncommonFields._lazyObsoleteAttributeData
Return If(result Is ObsoleteAttributeData.Uninitialized,
InterlockedOperations.Initialize(uncommonFields._lazyObsoleteAttributeData, Nothing, ObsoleteAttributeData.Uninitialized),
result)
End If
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
If Not _packedFlags.IsConditionalPopulated Then
Dim moduleSymbol As PEModuleSymbol = _containingType.ContainingPEModule
Dim conditionalSymbols As ImmutableArray(Of String) = moduleSymbol.Module.GetConditionalAttributeValues(_handle)
Debug.Assert(Not conditionalSymbols.IsDefault)
If Not conditionalSymbols.IsEmpty Then
conditionalSymbols = InterlockedOperations.Initialize(AccessUncommonFields()._lazyConditionalAttributeSymbols, conditionalSymbols)
End If
_packedFlags.SetIsConditionalAttributePopulated()
Return conditionalSymbols
End If
Dim uncommonFields = _uncommonFields
If uncommonFields Is Nothing Then
Return ImmutableArray(Of String).Empty
Else
Dim result = uncommonFields._lazyConditionalAttributeSymbols
Return If(result.IsDefault,
InterlockedOperations.Initialize(uncommonFields._lazyConditionalAttributeSymbols, ImmutableArray(Of String).Empty),
result)
End If
End Function
''' <remarks>
''' This is for perf, not for correctness.
''' </remarks>
Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation
Get
Return Nothing
End Get
End Property
Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean
If IsShared Then
meParameter = Nothing
Else
meParameter = If(_uncommonFields?._lazyMeParameter, InterlockedOperations.Initialize(AccessUncommonFields()._lazyMeParameter, New MeParameterSymbol(Me)))
End If
Return True
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEMethodSymbol.vb
|
Visual Basic
|
apache-2.0
| 53,419
|
' 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.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' This class represents a synthesized delegate type derived from an Event declaration
''' </summary>
''' <remarks>
''' <example>
''' Class C
''' Event Name(a As Integer, b As Integer)
''' End Class
'''
''' defines an event and a delegate type:
'''
''' Event Name As NamedEventHandler
''' Delegate Sub NameEventHandler(a As Integer, b As Integer)
'''
''' </example>
''' </remarks>
Friend NotInheritable Class SynthesizedEventDelegateSymbol
Inherits InstanceTypeSymbol
Private ReadOnly _eventName As String
Private ReadOnly _name As String
Private ReadOnly _containingType As NamedTypeSymbol
Private ReadOnly _syntaxRef As SyntaxReference
Private _lazyMembers As ImmutableArray(Of Symbol)
Private _lazyEventSymbol As EventSymbol
Private _reportedAllDeclarationErrors As Integer = 0 ' An integer to be able to do Interlocked operations.
Friend Sub New(syntaxRef As SyntaxReference, containingSymbol As NamedTypeSymbol)
Me._containingType = containingSymbol
Me._syntaxRef = syntaxRef
Dim eventName = Me.EventSyntax.Identifier.ValueText
Me._eventName = eventName
Me._name = _eventName & EVENT_DELEGATE_SUFFIX
End Sub
Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol)
If Not _lazyMembers.IsDefault Then
Return _lazyMembers
End If
Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol)
Dim binder As binder = BinderBuilder.CreateBinderForType(sourceModule, _syntaxRef.SyntaxTree, Me.ContainingType)
Dim diagBag = DiagnosticBag.GetInstance()
Dim syntax = Me.EventSyntax
Dim paramListOpt = syntax.ParameterList
Dim ctor As MethodSymbol = Nothing
Dim beginInvoke As MethodSymbol = Nothing
Dim endInvoke As MethodSymbol = Nothing
Dim invoke As MethodSymbol = Nothing
SourceDelegateMethodSymbol.MakeDelegateMembers(Me, Me.EventSyntax, syntax.ParameterList, binder, ctor, beginInvoke, endInvoke, invoke, diagBag)
' We shouldn't need to check if this is a winmd compilation because
' winmd output requires that all events be declared Event ... As ...,
' but we can't add Nothing to the array, even if a diagnostic will be produced later
' Invoke must always be the last member
Dim members As ImmutableArray(Of Symbol)
If beginInvoke Is Nothing OrElse endInvoke Is Nothing Then
members = ImmutableArray.Create(Of Symbol)(ctor, invoke)
Else
members = ImmutableArray.Create(Of Symbol)(ctor, beginInvoke, endInvoke, invoke)
End If
sourceModule.AtomicStoreArrayAndDiagnostics(_lazyMembers, members, diagBag, CompilationStage.Declare)
diagBag.Free()
Return _lazyMembers
End Function
Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return (From m In GetMembers() Where IdentifierComparison.Equals(m.Name, name)).AsImmutable
End Function
Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
Return SpecializedCollections.EmptyEnumerable(Of FieldSymbol)()
End Function
Private ReadOnly Property EventSyntax As EventStatementSyntax
Get
Return DirectCast(Me._syntaxRef.GetSyntax, EventStatementSyntax)
End Get
End Property
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
If _lazyEventSymbol Is Nothing Then
Dim events = _containingType.GetMembers(_eventName)
For Each e In events
Dim asEvent = TryCast(e, SourceEventSymbol)
If asEvent IsNot Nothing Then
Dim evSyntax = asEvent.SyntaxReference.GetSyntax
If evSyntax IsNot Nothing AndAlso evSyntax Is EventSyntax Then
_lazyEventSymbol = asEvent
End If
End If
Next
End If
Debug.Assert(_lazyEventSymbol IsNot Nothing, "We should have found our event here")
Return _lazyEventSymbol
End Get
End Property
''' <summary>
''' This property may be called while containing type is still being constructed.
''' Therefore it can take membersInProgress context to ensure that returned symbol
''' is relevant to the current type construction.
''' (there could be several optimistically concurrent sessions)
''' </summary>
Friend Overrides ReadOnly Property ImplicitlyDefinedBy(Optional membersInProgress As Dictionary(Of String, ArrayBuilder(Of Symbol)) = Nothing) As Symbol
Get
If membersInProgress Is Nothing Then
Return AssociatedSymbol
End If
Dim candidates = membersInProgress(_eventName)
Dim eventInCurrentContext As SourceEventSymbol = Nothing
Debug.Assert(candidates IsNot Nothing, "where is my event?")
If candidates IsNot Nothing Then
For Each e In candidates
Dim asEvent = TryCast(e, SourceEventSymbol)
If asEvent IsNot Nothing Then
Dim evSyntax = asEvent.SyntaxReference.GetSyntax
If evSyntax IsNot Nothing AndAlso evSyntax Is EventSyntax Then
eventInCurrentContext = asEvent
End If
End If
Next
End If
Return eventInCurrentContext
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _containingType
End Get
End Property
Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol
Get
Return _containingType
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return AssociatedSymbol.DeclaredAccessibility
End Get
End Property
Friend Overrides ReadOnly Property DefaultPropertyName As String
Get
Return Nothing
End Get
End Property
Public Overloads Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overloads Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overloads Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides ReadOnly Property IsMustInherit As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotInheritable As Boolean
Get
Return True
End Get
End Property
Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean
Get
Return AssociatedSymbol.ShadowsExplicitly
End Get
End Property
Friend Overrides Function GetLexicalSortKey() As LexicalSortKey
' WARNING: this should not allocate memory!
Return New LexicalSortKey(_syntaxRef, Me.DeclaringCompilation)
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray.Create(_syntaxRef.GetLocation())
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 MakeAcyclicBaseType(diagnostics As DiagnosticBag) As NamedTypeSymbol
Return MakeDeclaredBase(Nothing, diagnostics)
End Function
Friend Overrides Function MakeAcyclicInterfaces(diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Friend Overrides Function MakeDeclaredBase(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As NamedTypeSymbol
Return _containingType.ContainingAssembly.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_MulticastDelegate)
End Function
Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Friend Overrides ReadOnly Property MangleName As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property MemberNames As System.Collections.Generic.IEnumerable(Of String)
Get
Return New HashSet(Of String)(From member In GetMembers() Select member.Name)
End Get
End Property
Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property HasEmbeddedAttribute As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsComImport As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property CoClassType As TypeSymbol
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsSerializable As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property Layout As TypeLayout
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property MarshallingCharSet As CharSet
Get
Return DefaultMarshallingCharSet
End Get
End Property
Public Overrides ReadOnly Property TypeKind As TYPEKIND
Get
Return TypeKind.Delegate
End Get
End Property
Friend Overrides ReadOnly Property IsInterface As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
''' <summary>
''' Force all declaration errors to be generated.
''' </summary>
Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken)
If _reportedAllDeclarationErrors <> 0 Then
Return
End If
GetMembers()
cancellationToken.ThrowIfCancellationRequested()
Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance()
' Force parameters and return value of Invoke method to be bound and errors reported.
' Parameters on other delegate methods are derived from Invoke so we don't need to call those.
Me.DelegateInvokeMethod.GenerateDeclarationErrors(cancellationToken)
Dim container = _containingType
Dim outermostVariantInterface As NamedTypeSymbol = Nothing
Do
If Not container.IsInterfaceType() Then
Debug.Assert(Not container.IsDelegateType())
' Non-interface, non-delegate containers are illegal within variant interfaces.
' An error on the container will be sufficient if we haven't run into an interface already.
Exit Do
End If
If container.TypeParameters.HaveVariance() Then
' We are inside of a variant interface
outermostVariantInterface = container
End If
container = container.ContainingType
Loop While container IsNot Nothing
If outermostVariantInterface IsNot Nothing Then
' "Event definitions with parameters are not allowed in an interface such as '|1' that has
' 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which
' is not defined within '|1'. For example, 'Event |2 As Action(Of ...)'."
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_VariancePreventsSynthesizedEvents2,
CustomSymbolDisplayFormatter.QualifiedName(outermostVariantInterface),
AssociatedSymbol.Name),
Locations(0)))
End If
DirectCast(ContainingModule, SourceModuleSymbol).AtomicStoreIntegerAndDiagnostics(_reportedAllDeclarationErrors, 1, 0, diagnostics, CompilationStage.Declare)
diagnostics.Free()
End Sub
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
' these are always implicitly declared.
Return True
End Get
End Property
Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind
Get
Return Me.ContainingType.EmbeddedSymbolKind
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol)
Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)()
End Function
End Class
End Namespace
|
weltkante/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb
|
Visual Basic
|
apache-2.0
| 17,062
|
Imports Orleans
Namespace $rootnamespace$
''' <summary>
''' Orleans grain communication interface $safeitemname$
''' </summary>
Public Interface $safeitemname$
Inherits Orleans.IGrainWithGuidKey
' TODO: add your interface methods.
'
' All methods must return a Task or Task<T>.
'
End Interface
End Namespace
|
Carlm-MS/orleans
|
src/OrleansVSTools/VSItemTemplateGrainInterfaceVB/GrainInterfaceTemplate.vb
|
Visual Basic
|
mit
| 376
|
' 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
Imports Microsoft.CodeAnalysis.Editor.Commands
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
''' <summary>
''' Watches for the enter key being pressed, and triggers a commit in response.
''' </summary>
''' <remarks>This particular command filter acts as a "wrapper" around any other command, as it
''' wishes to invoke the commit after whatever processed the enter is done doing what it's
''' doing.</remarks>
<ExportCommandHandler(PredefinedCommandHandlerNames.Commit, ContentTypeNames.VisualBasicContentType)>
<Order(Before:=PredefinedCommandHandlerNames.EndConstruct)>
<Order(Before:=PredefinedCommandHandlerNames.Completion)>
Friend Class CommitCommandHandler
Implements ICommandHandler(Of ReturnKeyCommandArgs)
Implements ICommandHandler(Of PasteCommandArgs)
Implements ICommandHandler(Of SaveCommandArgs)
Implements ICommandHandler(Of FormatDocumentCommandArgs)
Implements ICommandHandler(Of FormatSelectionCommandArgs)
Private ReadOnly _bufferManagerFactory As CommitBufferManagerFactory
Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService
Private ReadOnly _smartIndentationService As ISmartIndentationService
Private ReadOnly _textUndoHistoryRegistry As ITextUndoHistoryRegistry
Private ReadOnly _waitIndicator As IWaitIndicator
<ImportingConstructor()>
Friend Sub New(
bufferManagerFactory As CommitBufferManagerFactory,
editorOperationsFactoryService As IEditorOperationsFactoryService,
smartIndentationService As ISmartIndentationService,
textUndoHistoryRegistry As ITextUndoHistoryRegistry,
waitIndicator As IWaitIndicator)
_bufferManagerFactory = bufferManagerFactory
_editorOperationsFactoryService = editorOperationsFactoryService
_smartIndentationService = smartIndentationService
_textUndoHistoryRegistry = textUndoHistoryRegistry
_waitIndicator = waitIndicator
End Sub
Public Sub ExecuteCommand(args As FormatDocumentCommandArgs, nextHandler As Action) Implements ICommandHandler(Of FormatDocumentCommandArgs).ExecuteCommand
If Not args.SubjectBuffer.CanApplyChangeDocumentToWorkspace() Then
nextHandler()
Return
End If
_waitIndicator.Wait(
VBEditorResources.Format_Document,
VBEditorResources.Formatting_Document,
allowCancel:=True,
action:=
Sub(waitContext)
Dim buffer = args.SubjectBuffer
Dim snapshot = buffer.CurrentSnapshot
Dim wholeFile = snapshot.GetFullSpan()
Dim commitBufferManager = _bufferManagerFactory.CreateForBuffer(buffer)
commitBufferManager.ExpandDirtyRegion(wholeFile)
commitBufferManager.CommitDirty(isExplicitFormat:=True, cancellationToken:=waitContext.CancellationToken)
End Sub)
End Sub
Public Function GetCommandState(args As FormatDocumentCommandArgs, nextHandler As Func(Of CommandState)) As CommandState Implements ICommandHandler(Of FormatDocumentCommandArgs).GetCommandState
Return nextHandler()
End Function
Public Sub ExecuteCommand(args As FormatSelectionCommandArgs, nextHandler As Action) Implements ICommandHandler(Of FormatSelectionCommandArgs).ExecuteCommand
If Not args.SubjectBuffer.CanApplyChangeDocumentToWorkspace() Then
nextHandler()
Return
End If
_waitIndicator.Wait(
VBEditorResources.Format_Document,
VBEditorResources.Formatting_Document,
allowCancel:=True,
action:=
Sub(waitContext)
Dim buffer = args.SubjectBuffer
Dim selections = args.TextView.Selection.GetSnapshotSpansOnBuffer(buffer)
If selections.Count < 1 Then
nextHandler()
Return
End If
Dim snapshot = buffer.CurrentSnapshot
For index As Integer = 0 To selections.Count - 1
Dim textspan = CommonFormattingHelpers.GetFormattingSpan(snapshot, selections(0))
Dim selectedSpan = New SnapshotSpan(snapshot, textspan.Start, textspan.Length)
Dim commitBufferManager = _bufferManagerFactory.CreateForBuffer(buffer)
commitBufferManager.ExpandDirtyRegion(selectedSpan)
commitBufferManager.CommitDirty(isExplicitFormat:=True, cancellationToken:=waitContext.CancellationToken)
Next
End Sub)
'We don't call nextHandler, since we have handled this command.
End Sub
Public Function GetCommandState(args As FormatSelectionCommandArgs, nextHandler As Func(Of CommandState)) As CommandState Implements ICommandHandler(Of FormatSelectionCommandArgs).GetCommandState
Return nextHandler()
End Function
Public Sub ExecuteCommand(args As ReturnKeyCommandArgs, nextHandler As Action) Implements ICommandHandler(Of ReturnKeyCommandArgs).ExecuteCommand
If Not args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.PrettyListing) Then
nextHandler()
Return
End If
' Commit is not cancellable.
Dim _cancellationToken = CancellationToken.None
Dim bufferManager = _bufferManagerFactory.CreateForBuffer(args.SubjectBuffer)
Dim oldCaretPoint = args.TextView.GetCaretPoint(args.SubjectBuffer)
' When we call nextHandler(), it's possible that some other feature might try to move the caret
' or something similar. We want this "outer" commit to be the real one, so start suppressing any
' re-entrant commits.
Dim suppressionHandle = bufferManager.BeginSuppressingCommits()
Try
' Evil: we really want a enter in VB to be always grouped as a single undo transaction, and so make sure all
' things from here on out are grouped as one.
Using transaction = _textUndoHistoryRegistry.GetHistory(args.TextView.TextBuffer).CreateTransaction(VBEditorResources.Insert_new_line)
transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance
nextHandler()
If ShouldCommitFromEnter(oldCaretPoint, args.TextView, args.SubjectBuffer, _cancellationToken) Then
' We are done suppressing at this point
suppressionHandle.Dispose()
suppressionHandle = Nothing
bufferManager.CommitDirty(isExplicitFormat:=False, cancellationToken:=_cancellationToken)
' We may have re-indented the surrounding block, so let's recompute
' where we should end up
Dim newCaretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer)
If newCaretPosition.HasValue Then
Dim currentLine = newCaretPosition.Value.GetContainingLine()
Dim desiredIndentation = args.TextView.GetDesiredIndentation(_smartIndentationService, currentLine)
If currentLine.Length = 0 AndAlso desiredIndentation.HasValue Then
args.TextView.TryMoveCaretToAndEnsureVisible(New VirtualSnapshotPoint(currentLine.Start, desiredIndentation.Value))
_editorOperationsFactoryService.GetEditorOperations(args.TextView).AddAfterTextBufferChangePrimitive()
End If
End If
End If
transaction.Complete()
End Using
Finally
' Resume committing
If suppressionHandle IsNot Nothing Then
suppressionHandle.Dispose()
End If
End Try
End Sub
Private Function ShouldCommitFromEnter(
oldCaretPositionInOldSnapshot As SnapshotPoint?,
textView As ITextView,
subjectBuffer As ITextBuffer,
cancellationToken As CancellationToken) As Boolean
Dim newCaretPosition = textView.GetCaretPoint(subjectBuffer)
If Not oldCaretPositionInOldSnapshot.HasValue OrElse Not newCaretPosition.HasValue Then
' We somehow moved in or out of our subject buffer during this commit. Not sure how,
' but that counts as losing focus and thus is a commit
Return True
End If
' Map oldCaretPosition forward to the current snapshot
Dim oldCaretPositionInCurrentSnapshot = oldCaretPositionInOldSnapshot.Value.CreateTrackingPoint(PointTrackingMode.Negative).GetPoint(subjectBuffer.CurrentSnapshot)
Dim bufferManager = _bufferManagerFactory.CreateForBuffer(subjectBuffer)
If bufferManager.IsMovementBetweenStatements(oldCaretPositionInCurrentSnapshot, newCaretPosition.Value, cancellationToken) Then
Dim document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return False
End If
Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken)
Dim token = tree.FindTokenOnLeftOfPosition(oldCaretPositionInOldSnapshot.Value, cancellationToken)
If token.IsKind(SyntaxKind.StringLiteralToken) AndAlso token.FullSpan.Contains(oldCaretPositionInOldSnapshot.Value) Then
Return False
End If
' Get the statement which we pressed enter for
Dim oldStatement = ContainingStatementInfo.GetInfo(oldCaretPositionInCurrentSnapshot, tree, cancellationToken)
Return oldStatement Is Nothing OrElse Not oldStatement.IsIncomplete
End If
Return False
End Function
Public Function GetCommandState(args As ReturnKeyCommandArgs, nextHandler As Func(Of CommandState)) As CommandState Implements ICommandHandler(Of ReturnKeyCommandArgs).GetCommandState
' We don't make any decision if the enter key is allowed; we just forward onto the next handler
Return nextHandler()
End Function
Public Sub ExecuteCommand(args As PasteCommandArgs, nextHandler As Action) Implements ICommandHandler(Of PasteCommandArgs).ExecuteCommand
_waitIndicator.Wait(
title:=VBEditorResources.Format_Paste,
message:=VBEditorResources.Formatting_pasted_text,
allowCancel:=True,
action:=Sub(waitContext) CommitOnPaste(args, nextHandler, waitContext))
End Sub
Private Sub CommitOnPaste(args As PasteCommandArgs, nextHandler As Action, waitContext As IWaitContext)
Using transaction = _textUndoHistoryRegistry.GetHistory(args.TextView.TextBuffer).CreateTransaction(VBEditorResources.Paste)
Dim oldVersion = args.SubjectBuffer.CurrentSnapshot.Version
' Do the paste in the same transaction as the commit/format
nextHandler()
If Not args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.FormatOnPaste) Then
transaction.Complete()
Return
End If
Dim document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document IsNot Nothing Then
Dim formattingRuleService = document.Project.Solution.Workspace.Services.GetService(Of IHostDependentFormattingRuleFactoryService)()
If formattingRuleService.ShouldNotFormatOrCommitOnPaste(document) Then
transaction.Complete()
Return
End If
End If
' Did we paste content that changed the number of lines?
If oldVersion.Changes IsNot Nothing AndAlso oldVersion.Changes.IncludesLineChanges Then
Try
_bufferManagerFactory.CreateForBuffer(args.SubjectBuffer).CommitDirty(isExplicitFormat:=False, cancellationToken:=waitContext.CancellationToken)
Catch ex As OperationCanceledException
' If the commit was cancelled, we still want the paste to go through
End Try
End If
transaction.Complete()
End Using
End Sub
Public Function GetCommandState(args As PasteCommandArgs, nextHandler As Func(Of CommandState)) As CommandState Implements ICommandHandler(Of PasteCommandArgs).GetCommandState
Return nextHandler()
End Function
Public Sub ExecuteCommand(args As SaveCommandArgs, nextHandler As Action) Implements ICommandHandler(Of SaveCommandArgs).ExecuteCommand
If args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.FormatOnSave) Then
_waitIndicator.Wait(
title:=VBEditorResources.Format_on_Save,
message:=VBEditorResources.Formatting_Document,
allowCancel:=True,
action:=Sub(waitContext)
Using transaction = _textUndoHistoryRegistry.GetHistory(args.TextView.TextBuffer).CreateTransaction(VBEditorResources.Format_on_Save)
_bufferManagerFactory.CreateForBuffer(args.SubjectBuffer).CommitDirty(isExplicitFormat:=False, cancellationToken:=waitContext.CancellationToken)
' We should only create the transaction if anything actually happened
If transaction.UndoPrimitives.Any() Then
transaction.Complete()
End If
End Using
End Sub)
End If
nextHandler()
End Sub
Public Function GetCommandState(args As SaveCommandArgs, nextHandler As Func(Of CommandState)) As CommandState Implements ICommandHandler(Of SaveCommandArgs).GetCommandState
Return nextHandler()
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/EditorFeatures/VisualBasic/LineCommit/CommitCommandHandler.vb
|
Visual Basic
|
apache-2.0
| 15,478
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundAttribute
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return Me.Constructor
End Get
End Property
End Class
End Namespace
|
AmadeusW/roslyn
|
src/Compilers/VisualBasic/Portable/BoundTree/BoundAttribute.vb
|
Visual Basic
|
apache-2.0
| 623
|
Imports SistFoncreagro.BussinessEntities
Public Interface IRequisitoAdicionalBL
Function GetAllFromREQUISITOADICIONAL() As List(Of RequisitoAdicional)
Function SaveREQUISITOADICIONAL(ByVal RequisitoAdicional As RequisitoAdicional) As Int32
Function GetREQUISITOADICIONALByIdRequisitoAndIdPosicion(ByVal IdRequisito As Int32, ByVal IdPosicion As Int32) As RequisitoAdicional
Function GetREQUISITOADICIONALByIdPosicion(ByVal IdPosicion As Int32) As List(Of RequisitoAdicional)
Sub DeleteREQUISITOADICIONAL(ByVal idRequisito As Int32)
End Interface
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinesLogic/IRequisitoAdicionalBL.vb
|
Visual Basic
|
mit
| 569
|
Public Class Param_OwlTensorSet
Inherits Owl.GH.Common.Param_OwlTensorSet
End Class
|
mateuszzwierzycki/Owl
|
Owl.GH/Params/Param_OwlTensorSet.vb
|
Visual Basic
|
mit
| 91
|
' Copyright (c) 2015 NWSC.com
' All rights reserved.
'
' 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.Collections.Generic
Imports DotNetNuke.Data
Namespace Components
Public Class TechnicianRepository
Public Sub CreateTechnician(ByVal t As Technician)
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of Technician) = ctx.GetRepository(Of Technician)()
rep.Insert(t)
End Using
End Sub
Public Sub DeleteTechnician(ByVal t As Integer, ByVal moduleId As Integer)
Dim _Technician As Technician = GetTechnician(t, moduleId)
DeleteTechnician(_Technician)
End Sub
Public Sub DeleteTechnician(ByVal t As Technician)
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of Technician) = ctx.GetRepository(Of Technician)()
rep.Delete(t)
End Using
End Sub
Public Function GetTechnicians(ByVal moduleId As Integer) As IEnumerable(Of Technician)
Dim t As IEnumerable(Of Technician)
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of Technician) = ctx.GetRepository(Of Technician)()
t = rep.Get(moduleId)
End Using
Return t
End Function
Public Function GetTechnician(ByVal Techid As Integer, ByVal moduleId As Integer) As Technician
Dim t As Technician
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of Technician) = ctx.GetRepository(Of Technician)()
t = rep.GetById(Of Int32, Int32)(Techid, moduleId)
End Using
Return t
End Function
Public Sub UpdateTechnician(ByVal t As Technician)
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of Technician) = ctx.GetRepository(Of Technician)()
rep.Update(t)
End Using
End Sub
End Class
End Namespace
|
dmcdonald11/CallTrackerLite
|
Components/TechnicianRepository.vb
|
Visual Basic
|
mit
| 2,572
|
'------------------------------------------------------------------------------
' <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", "12.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.SignWriterStudio.Document.My.MySettings
Get
Return Global.SignWriterStudio.Document.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
JonathanDDuncan/SignWriterStudio
|
SignWriterStudio.Document/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,940
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports CompilationCreationTestHelpers
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE
Public Class LoadingFields : Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences(
{
TestResources.SymbolsTests.Fields.CSFields,
TestResources.SymbolsTests.Fields.VBFields,
TestMetadata.ResourcesNet40.mscorlib
}, importInternals:=True)
Dim module1 = assemblies(0).Modules(0)
Dim module2 = assemblies(1).Modules(0)
Dim module3 = assemblies(2).Modules(0)
Dim vbFields = module2.GlobalNamespace.GetTypeMembers("VBFields").Single()
Dim csFields = module1.GlobalNamespace.GetTypeMembers("CSFields").Single()
Dim f1 = DirectCast(vbFields.GetMembers("F1").Single(), FieldSymbol)
Dim f2 = DirectCast(vbFields.GetMembers("F2").Single(), FieldSymbol)
Dim f3 = DirectCast(vbFields.GetMembers("F3").Single(), FieldSymbol)
Dim f4 = DirectCast(vbFields.GetMembers("F4").Single(), FieldSymbol)
Dim f5 = DirectCast(vbFields.GetMembers("F5").Single(), FieldSymbol)
Dim f6 = DirectCast(csFields.GetMembers("F6").Single(), FieldSymbol)
Assert.Equal("F1", f1.Name)
Assert.Same(vbFields.TypeParameters(0), f1.Type)
Assert.False(f1.IsMustOverride)
Assert.False(f1.IsConst)
Assert.True(f1.IsDefinition)
Assert.False(f1.IsOverrides)
Assert.False(f1.IsReadOnly)
Assert.False(f1.IsNotOverridable)
Assert.True(f1.IsShared)
Assert.False(f1.IsOverridable)
Assert.Equal(SymbolKind.Field, f1.Kind)
Assert.Equal(module2.Locations, f1.Locations)
Assert.Same(f1, f1.OriginalDefinition)
Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility)
Assert.Same(vbFields, f1.ContainingSymbol)
Assert.Equal(0, f1.CustomModifiers.Length)
Assert.Equal("F2", f2.Name)
Assert.Same(DirectCast(module2, PEModuleSymbol).GetCorLibType(SpecialType.System_Int32), f2.Type)
Assert.False(f2.IsConst)
Assert.True(f2.IsReadOnly)
Assert.False(f2.IsShared)
Assert.Equal(Accessibility.Protected, f2.DeclaredAccessibility)
Assert.Equal(0, f2.CustomModifiers.Length)
Assert.Equal("F3", f3.Name)
Assert.False(f3.IsConst)
Assert.False(f3.IsReadOnly)
Assert.False(f3.IsShared)
Assert.Equal(Accessibility.Friend, f3.DeclaredAccessibility)
Assert.Equal(0, f3.CustomModifiers.Length)
Assert.Equal("F4", f4.Name)
Assert.False(f4.IsConst)
Assert.False(f4.IsReadOnly)
Assert.False(f4.IsShared)
Assert.Equal(Accessibility.ProtectedOrFriend, f4.DeclaredAccessibility)
Assert.Equal(0, f4.CustomModifiers.Length)
Assert.Equal("F5", f5.Name)
Assert.True(f5.IsConst)
Assert.False(f5.IsReadOnly)
Assert.True(f5.IsShared)
Assert.Equal(Accessibility.Protected, f5.DeclaredAccessibility)
Assert.Equal(0, f5.CustomModifiers.Length)
Assert.Equal("F6", f6.Name)
Assert.False(f6.IsConst)
Assert.False(f6.IsReadOnly)
Assert.False(f6.IsShared)
Assert.False(f6.CustomModifiers.Single().IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsVolatile", f6.CustomModifiers.Single().Modifier.ToTestDisplayString())
Assert.True(f6.HasUnsupportedMetadata)
Assert.Equal(3, csFields.GetMembers("FFF").Length())
Assert.Equal(3, csFields.GetMembers("Fff").Length())
Assert.Equal(3, csFields.GetMembers("FfF").Length())
End Sub
<Fact>
Public Sub ConstantFields()
Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences(
{
TestResources.SymbolsTests.Fields.ConstantFields,
TestMetadata.ResourcesNet40.mscorlib
})
Dim module1 = assemblies(0).Modules(0)
Dim ConstFields = module1.GlobalNamespace.GetTypeMembers("ConstFields").Single()
Dim ByteEnum = module1.GlobalNamespace.GetTypeMembers("ByteEnum").Single()
Dim SByteEnum = module1.GlobalNamespace.GetTypeMembers("SByteEnum").Single()
Dim UInt16Enum = module1.GlobalNamespace.GetTypeMembers("UInt16Enum").Single()
Dim Int16Enum = module1.GlobalNamespace.GetTypeMembers("Int16Enum").Single()
Dim UInt32Enum = module1.GlobalNamespace.GetTypeMembers("UInt32Enum").Single()
Dim Int32Enum = module1.GlobalNamespace.GetTypeMembers("Int32Enum").Single()
Dim UInt64Enum = module1.GlobalNamespace.GetTypeMembers("UInt64Enum").Single()
Dim Int64Enum = module1.GlobalNamespace.GetTypeMembers("Int64Enum").Single()
'Public Const Int64Field As Long = 634315546432909307
'Public DateTimeField As DateTime
'Public Const SingleField As Single = 9
'Public Const DoubleField As Double = -10
'Public Const StringField As String = "11"
'Public Const StringNullField As String = Nothing
'Public Const ObjectNullField As Object = Nothing
Dim Int64Field = DirectCast(ConstFields.GetMembers("Int64Field").Single(), FieldSymbol)
Dim DateTimeField = DirectCast(ConstFields.GetMembers("DateTimeField").Single(), FieldSymbol)
Dim SingleField = DirectCast(ConstFields.GetMembers("SingleField").Single(), FieldSymbol)
Dim DoubleField = DirectCast(ConstFields.GetMembers("DoubleField").Single(), FieldSymbol)
Dim StringField = DirectCast(ConstFields.GetMembers("StringField").Single(), FieldSymbol)
Dim StringNullField = DirectCast(ConstFields.GetMembers("StringNullField").Single(), FieldSymbol)
Dim ObjectNullField = DirectCast(ConstFields.GetMembers("ObjectNullField").Single(), FieldSymbol)
Assert.True(Int64Field.IsConst)
Assert.True(Int64Field.HasConstantValue)
Assert.Equal(Int64Field.ConstantValue, 634315546432909307)
Assert.Equal(ConstantValueTypeDiscriminator.Int64, Int64Field.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(634315546432909307, Int64Field.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Int64Value)
Assert.True(DateTimeField.IsConst)
Assert.True(DateTimeField.HasConstantValue)
Assert.Equal(DateTimeField.ConstantValue, New DateTime(634315546432909307))
Assert.Equal(ConstantValueTypeDiscriminator.DateTime, DateTimeField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(New DateTime(634315546432909307), DateTimeField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).DateTimeValue)
Assert.True(SingleField.IsConst)
Assert.True(SingleField.HasConstantValue)
Assert.Equal(SingleField.ConstantValue, 9.0F)
Assert.Equal(ConstantValueTypeDiscriminator.Single, SingleField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(9.0F, SingleField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).SingleValue)
Assert.True(DoubleField.IsConst)
Assert.True(DoubleField.HasConstantValue)
Assert.Equal(DoubleField.ConstantValue, -10.0)
Assert.Equal(ConstantValueTypeDiscriminator.Double, DoubleField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(-10.0, DoubleField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).DoubleValue)
Assert.True(StringField.IsConst)
Assert.True(StringField.HasConstantValue)
Assert.Equal(StringField.ConstantValue, "11")
Assert.Equal(ConstantValueTypeDiscriminator.String, StringField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal("11", StringField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).StringValue)
Assert.True(StringNullField.IsConst)
Assert.True(StringNullField.HasConstantValue)
Assert.Null(StringNullField.ConstantValue)
Assert.Equal(ConstantValueTypeDiscriminator.Nothing, StringNullField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.True(ObjectNullField.IsConst)
Assert.True(ObjectNullField.HasConstantValue)
Assert.Null(ObjectNullField.ConstantValue)
Assert.Equal(ConstantValueTypeDiscriminator.Nothing, ObjectNullField.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
'ByteValue = 1
'SByteValue = -2
'UInt16Value = 3
'Int16Value = -4
'UInt32Value = 5
'Int32Value = -6
'UInt64Value = 7
'Int64Value = -8
Dim ByteValue = DirectCast(ByteEnum.GetMembers("ByteValue").Single(), FieldSymbol)
Dim SByteValue = DirectCast(SByteEnum.GetMembers("SByteValue").Single(), FieldSymbol)
Dim UInt16Value = DirectCast(UInt16Enum.GetMembers("UInt16Value").Single(), FieldSymbol)
Dim Int16Value = DirectCast(Int16Enum.GetMembers("Int16Value").Single(), FieldSymbol)
Dim UInt32Value = DirectCast(UInt32Enum.GetMembers("UInt32Value").Single(), FieldSymbol)
Dim Int32Value = DirectCast(Int32Enum.GetMembers("Int32Value").Single(), FieldSymbol)
Dim UInt64Value = DirectCast(UInt64Enum.GetMembers("UInt64Value").Single(), FieldSymbol)
Dim Int64Value = DirectCast(Int64Enum.GetMembers("Int64Value").Single(), FieldSymbol)
Assert.True(ByteValue.IsConst)
Assert.True(ByteValue.HasConstantValue)
Assert.Equal(ByteValue.ConstantValue, CByte(1))
Assert.Equal(ConstantValueTypeDiscriminator.Byte, ByteValue.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(CByte(1), ByteValue.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).ByteValue)
Assert.True(SByteValue.IsConst)
Assert.True(SByteValue.HasConstantValue)
Assert.Equal(SByteValue.ConstantValue, CSByte(-2))
Assert.Equal(ConstantValueTypeDiscriminator.SByte, SByteValue.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(CSByte(-2), SByteValue.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).SByteValue)
Assert.True(UInt16Value.IsConst)
Assert.True(UInt16Value.HasConstantValue)
Assert.Equal(UInt16Value.ConstantValue, 3US)
Assert.Equal(ConstantValueTypeDiscriminator.UInt16, UInt16Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(3US, UInt16Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).UInt16Value)
Assert.True(Int16Value.IsConst)
Assert.True(Int16Value.HasConstantValue)
Assert.Equal(Int16Value.ConstantValue, -4S)
Assert.Equal(ConstantValueTypeDiscriminator.Int16, Int16Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(-4S, Int16Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Int16Value)
Assert.True(UInt32Value.IsConst)
Assert.True(UInt32Value.HasConstantValue)
Assert.Equal(UInt32Value.ConstantValue, 5UI)
Assert.Equal(ConstantValueTypeDiscriminator.UInt32, UInt32Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(5UI, UInt32Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).UInt32Value)
Assert.True(Int32Value.IsConst)
Assert.True(Int32Value.HasConstantValue)
Assert.Equal(Int32Value.ConstantValue, -6)
Assert.Equal(ConstantValueTypeDiscriminator.Int32, Int32Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(-6, Int32Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Int32Value)
Assert.True(UInt64Value.IsConst)
Assert.True(UInt64Value.HasConstantValue)
Assert.Equal(UInt64Value.ConstantValue, 7UL)
Assert.Equal(ConstantValueTypeDiscriminator.UInt64, UInt64Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(7UL, UInt64Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).UInt64Value)
Assert.True(Int64Value.IsConst)
Assert.True(Int64Value.HasConstantValue)
Assert.Equal(Int64Value.ConstantValue, -8L)
Assert.Equal(ConstantValueTypeDiscriminator.Int64, Int64Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Discriminator)
Assert.Equal(-8L, Int64Value.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty).Int64Value)
End Sub
<Fact>
<WorkItem(193333, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=193333")>
Public Sub EnumWithPrivateValueField()
Dim ilSource = "
.class public auto ansi sealed TestEnum
extends [mscorlib]System.Enum
{
.field private specialname rtspecialname int32 value__
.field public static literal valuetype TestEnum Value1 = int32(0x00000000)
.field public static literal valuetype TestEnum Value2 = int32(0x00000001)
} // end of class TestEnum
"
Dim vbSource =
<compilation>
<file>
Module Module1
Sub Main()
Dim val as TestEnum = TestEnum.Value1
System.Console.WriteLine(val.ToString())
val = TestEnum.Value2
System.Console.WriteLine(val.ToString())
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, includeVbRuntime:=True, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:="Value1
Value2")
End Sub
End Class
End Namespace
|
panopticoncentral/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingFields.vb
|
Visual Basic
|
mit
| 15,262
|
'------------------------------------------------------------------------------
' <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 ReporteSaldoCuenta20
'''<summary>
'''Control Head1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead
'''<summary>
'''Control form1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm
'''<summary>
'''Control ReportViewer1.
'''</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 ReportViewer1 As Global.Telerik.ReportViewer.WebForms.ReportViewer
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Contabilidad/Formularios/ReporteSaldoCuenta20.aspx.designer.vb
|
Visual Basic
|
mit
| 1,513
|
'------------------------------------------------------------------------------
' <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
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.VBAccessToAnotherMailbox.My.MySettings
Get
Return Global.VBAccessToAnotherMailbox.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBAccessToAnotherMailbox/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,938
|
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 centerMarks As SolidEdgeFrameworkSupport.CenterMarks = Nothing
Dim centerMark1 As SolidEdgeFrameworkSupport.CenterMark = Nothing
Dim centerMark2 As SolidEdgeFrameworkSupport.CenterMark = 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
centerMarks = CType(sheet.CenterMarks, SolidEdgeFrameworkSupport.CenterMarks)
centerMark1 = centerMarks.Add(0.25, 0.25, 0)
centerMark2 = centerMarks.Add(0.3, 0.3, 0)
Dim zOrder = centerMark2.ZOrder
centerMark2.SendBackward()
zOrder = centerMark2.ZOrder
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFrameworkSupport.CenterMark.SendBackward.vb
|
Visual Basic
|
mit
| 1,858
|
Namespace Reporting
Public Class SPReportUIFactory
Public Shared Function GetDefaultFilterList() As DSFilters.SPFilterTableDataTable
Dim newFilterTable As New DSFilters.SPFilterTableDataTable
Return newFilterTable
End Function
End Class
End Namespace
|
okyereadugyamfi/softlogik
|
SPCode/Reporting/Support/UI/SPReportUIFactory.vb
|
Visual Basic
|
mit
| 302
|
Imports Leviathan.Commands
Imports Leviathan.Configuration.TypeConvertor
Imports Leviathan.Inspection.AnalyserQuery
Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.Serialization
Namespace Configuration
Public Class XmlSerialiser
#Region " Public Constants "
Public Const ATTRIBUTE_ITERATE_FORMAT As String = "iterate-format"
Public Const ATTRIBUTE_LOAD_FROM As String = "load-from"
#End Region
#Region " Public Methods "
''' <summary>
''' Public Method that Parses the Object and Creates the Xml.
''' </summary>
''' <remarks></remarks>
Public Sub Write( _
ByRef value As Object, _
Optional ByVal previouslyParsed As ArrayList = Nothing _
)
Dim isRootObject As Boolean = False
If previouslyParsed Is Nothing Then
isRootObject = True
previouslyParsed = New ArrayList()
End If
If Not value Is Nothing AndAlso Not previouslyParsed.Contains(value) Then
previouslyParsed.Add(value)
Dim valueType As TypeAnalyser = TypeAnalyser.GetInstance(value.GetType)
If valueType.IsValue Then
OutputWriter.WriteValue(value.ToString)
ElseIf valueType.Type Is GetType(String) Then
OutputWriter.WriteValue(value)
ElseIf valueType.IsType Then
OutputWriter.WriteValue(CType(value, Type).FullName)
ElseIf Not isRootObject AndAlso valueType.IsComplexArray Then
OutputWriter.WriteStartElement(valueType.ElementType.FullName & HYPHEN)
For i As Integer = 0 To CType(value, Array).Length - 1
Write(CType(value, Array)(i), previouslyParsed.Clone)
Next
OutputWriter.WriteEndElement()
ElseIf Not isRootObject AndAlso valueType.IsSimpleArray Then
OutputWriter.WriteValue(StringCommands.ObjectToSingleString(value, SEMI_COLON))
ElseIf Not isRootObject AndAlso valueType.IsIList Then
OutputWriter.WriteStartElement(valueType.FullName)
For i As Integer = 0 To CType(value, IList).Count - 1
Write(CType(value, IList)(i), previouslyParsed.Clone)
Next
OutputWriter.WriteEndElement()
Else
Dim l_fields As MemberAnalyser() = _
valueType.ExecuteQuery(QUERY_MEMBERS_READABLE _
.SetPresentAttribute(GetType(XmlElementAttribute)))
If Not l_fields Is Nothing Then
OutputWriter.WriteStartElement(valueType.FullName)
For Each l_field As MemberAnalyser In l_fields
Dim field_Value As Object = l_field.Read(value)
If Not field_Value Is Nothing Then
Dim element As XmlElementAttribute = _
l_field.Member.GetCustomAttributes( _
GetType(XmlElementAttribute), False)(0)
OutputWriter.WriteStartElement(element.ElementName)
Write(field_Value, previouslyParsed.Clone)
OutputWriter.WriteEndElement()
End If
Next
OutputWriter.WriteEndElement()
Else
OutputWriter.WriteValue(value.ToString())
End If
End If
End If
OutputWriter.Flush()
End Sub
Public Function Read( _
Optional ByRef current_Value As Object = Nothing, _
Optional ByVal ignore_Members As MemberAnalyser() = Nothing _
) As Object
' -- Get to the Root Element our current position.
If InputReader.MoveToContent() = XmlNodeType.Element Then
' -- Parse the Type Name from the Element Name.
Dim parsed_Type As Boolean = False
Dim current_Type As Type = Parser.Parse(InputReader.Name.Replace( _
HYPHEN, SQUARE_BRACKET_START & SQUARE_BRACKET_END), parsed_Type, GetType(System.Type))
If Not parsed_Type Then Throw New Exception(String.Format(EXCEPTION_SERIALISER_WRONGTYPENAME, _
InputReader.NodeType.ToString, InputReader.Name, InputReader.Depth, InputReader.LineNumber))
Dim current_Analyser As TypeAnalyser
If current_Value Is Nothing Then
' -- Create the current_Value object from the Parsed Type
current_Analyser = TypeAnalyser.GetInstance(current_Type)
current_Value = current_Analyser.Create()
If current_Value Is Nothing Then Throw New Exception(String.Format(EXCEPTION_SERIALISER_TYPECREATION, _
InputReader.NodeType.ToString, InputReader.Name, InputReader.Depth, InputReader.LineNumber))
ElseIf Not TypeAnalyser.IsSubClassOf(current_Value.GetType, current_Type) Then
' -- Check whether the supplied object is compatible with the Parsed Type
Throw New Exception(String.Format(EXCEPTION_SERIALISER_INCOMPATIBLETYPE, _
InputReader.NodeType.ToString, InputReader.Name, InputReader.Depth))
Else
' -- Get the Analyser for the Type (the bottom of the inheritance model)
current_Analyser = TypeAnalyser.GetInstance(current_Value.GetType)
End If
If Not InputReader.IsEmptyElement Then
Dim start_Name As String = InputReader.Name
Dim start_Depth As Integer = InputReader.Depth
' -- If we get here, then we're fine, we have a type and an object.
Dim current_Fields As MemberAnalyser() = current_Analyser.ExecuteQuery( _
AnalyserQuery.QUERY_MEMBERS_WRITEABLE.SetPresentAttribute(GetType(XmlElementAttribute)))
While InputReader.Read
If InputReader.NodeType = XmlNodeType.Element Then
If current_Fields Is Nothing AndAlso current_Analyser.IsArray
' -- If we're an Array, resize ourselves and append the new value to the end.
Dim parsed_ArrayValue As Object = Read()
If Not parsed_ArrayValue Is Nothing Then
Array.Resize(current_Value, CType(current_Value, Array).Length + 1)
CType(current_Value, Array)(CType(current_Value, Array).Length - 1) = parsed_ArrayValue
End If
ElseIf current_Fields Is Nothing AndAlso current_Analyser.IsIList
' -- If we're an IList then add the new value.
Dim parsed_ListValue As Object = Read()
If Not parsed_ListValue Is Nothing Then CType(current_Value, IList).Add(parsed_ListValue)
ElseIf Not current_Fields Is Nothing Then
' -- Have to assume this is a Field, so we need to find it!
Dim current_Field As MemberAnalyser = Nothing
For i As Integer = 0 To current_Fields.Length - 1
If String.Compare(current_Fields(i).Member.GetCustomAttributes( _
GetType(XmlElementAttribute), False)(0).ElementName, InputReader.Name, True) = 0 Then
current_Field = current_Fields(i)
Exit For
End If
Next
If current_Field Is Nothing Then Throw New Exception(String.Format(EXCEPTION_SERIALISER_NOFIELD, _
InputReader.NodeType.ToString, InputReader.Name, InputReader.Depth, InputReader.LineNumber))
If Not ignore_Members Is Nothing Then
For i As Integer = 0 To ignore_Members.Length - 1
If String.Compare(current_Field.FullName, ignore_Members(i).FullName, True) = 0 Then
' -- We're not going to parse this field as we should ignore it!
current_Field = Nothing
InputReader.ReadSubtree()
Exit For
End If
Next
End If
If Not current_Field Is Nothing Then
If InputReader.HasAttributes ' -- This requires attribute-specific parsing.
Dim value_List As New ArrayList()
If Not String.IsNullOrEmpty(InputReader.GetAttribute(ATTRIBUTE_ITERATE_FORMAT)) Then
Dim parsed_Iteration As Boolean
Dim iteration As Array = CreateArray(Parser.Parse(InputReader.GetAttribute(ATTRIBUTE_ITERATE_FORMAT), _
parsed_Iteration, GetType(Object)))
If Not parsed_Iteration Then Throw New Exception(String.Format(EXCEPTION_SERIALISER_ITERATEFORMAT, _
InputReader.NodeType.ToString, InputReader.Name, InputReader.Depth, InputReader.LineNumber))
Dim iteration_Node As String = InputReader.ReadOuterXml
For i As Integer = 0 To iteration.Length - 1
Dim iteration_Reader As New XmlTextReader(iteration_Node, XmlNodeType.Element, _
New XmlParserContext(Nothing, New XmlNamespaceManager(InputReader.NameTable), Nothing, XmlSpace.None))
value_List.AddRange(CreateArray(New XmlSerialiser(iteration_Reader, Nothing, _
Parser, iteration(i)).Read()))
iteration_Reader.Close()
Next
ElseIf Not String.IsNullOrEmpty(InputReader.GetAttribute(ATTRIBUTE_LOAD_FROM)) Then
Dim parsed_Streams As Boolean
Dim streams As Stream() = Parser.Parse(InputReader.GetAttribute(ATTRIBUTE_LOAD_FROM), _
parsed_Streams, GetType(IO.Stream).MakeArrayType)
If Not streams Is Nothing Then
For i As Integer = 0 To streams.Length - 1
Try
Dim stream_Reader As New XmlTextReader(streams(i))
value_List.AddRange(CreateArray(New XmlSerialiser(stream_Reader, Nothing, Parser).Read()))
stream_Reader.Close()
Catch ex As Exception
Throw New Exception(String.Format(EXCEPTION_SERIALISER_LOADFROM, _
InputReader.NodeType.ToString, InputReader.Name, InputReader.Depth, InputReader.LineNumber), ex)
End Try
Next
End If
End If
If current_Field.ReturnTypeAnalyser.IsArray Then
current_Field.Write(current_Value, TypeAnalyser.ConvertToArray( _
value_list, current_Field.ReturnTypeAnalyser.ElementType))
ElseIf current_Field.ReturnTypeAnalyser.IsIList Then
current_Field.Write(current_Value, value_List)
ElseIf current_Field.ReturnTypeAnalyser.IsScalar AndAlso value_List.Count = 1
current_Field.Write(current_Value, value_List(0))
End If
Else
InputReader.Read() ' Read because we're currently on the Field Name Element, not the next Type Name!
If InputReader.NodeType = XmlNodeType.Text Then ' We can use the String Parser to Populate it.
If Not String.IsNullOrEmpty(InputReader.Value) Then
Dim parsed_Value As Boolean = False
Dim field_Value As Object = Parser.Parse(InputReader.Value, parsed_Value, current_Field.ReturnType)
If parsed_Value Then current_Field.Write(current_Value, field_Value)
End If
Else ' -- This is a Complex Type.
Dim field_Value As Object = Read(current_Field.Read(current_Value))
If Not field_Value Is Nothing Then current_Field.Write(current_Value, field_Value)
End If
End If
End If
Else
Throw New Exception(String.Format(EXCEPTION_SERIALISER_NONCONFIGURABLETYPE, _
InputReader.NodeType.ToString, InputReader.Name, InputReader.Depth, InputReader.LineNumber))
End If
End If
' -- Exits Look if we're back to the same level/element as we started on.
If InputReader.NodeType = XmlNodeType.EndElement AndAlso _
InputReader.Depth = start_Depth AndAlso InputReader.Name = start_Name Then Exit While
End While
' -- Progressing to the next Node for recursive calling.
InputReader.Read()
End If
End If
Return current_Value
End Function
#End Region
#Region " Public Shared Methods "
Public Shared Function CreateReader( _
ByVal inputFile As String _
) As XmlSerialiser
If File.Exists(inputFile) Then
Return CreateReader( _
New FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
Else
Throw New ArgumentException()
End If
End Function
Public Shared Function CreateReader( _
ByVal inputStream As Stream _
) As XmlSerialiser
If inputStream.CanRead Then
Return CreateReader(New XmlTextReader(inputStream))
Else
Throw New ArgumentException()
End If
End Function
Public Shared Function CreateReader( _
ByVal inputReader As XmlReader _
) As XmlSerialiser
Return New XmlSerialiser(inputReader, Nothing, New FromString())
End Function
Public Shared Function CreateWriter( _
ByVal outputFile As String _
) As XmlSerialiser
If Not File.Exists(outputFile) Then
Return CreateWriter( _
New FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
Else
Throw New ArgumentException()
End If
End Function
Public Shared Function CreateWriter( _
ByVal outputStream As Stream _
) As XmlSerialiser
If outputStream.CanWrite Then
Dim writer As New XmlTextWriter(outputStream, Encoding.UTF8)
writer.Formatting = Formatting.Indented
writer.Indentation = 2
Return CreateWriter(writer)
Else
Throw New ArgumentException()
End If
End Function
Public Shared Function CreateWriter( _
ByVal outputWriter As XmlWriter _
) As XmlSerialiser
Return New XmlSerialiser(Nothing, outputWriter, New FromString())
End Function
Public Shared Function GenerateSchema( _
ByVal objType As Type _
) As XmlSchema
' TODO: Write Schema Generation Function
Return Nothing
End Function
Public Shared Sub ReadXml( _
ByRef obj As Object, _
ByVal reader As XmlReader, _
Optional ByVal belowObject As Type = Nothing _
)
Dim parsed_object As Object = CreateReader(reader).Read()
If Not parsed_object Is Nothing Then
TypeAnalyser.Integrate(obj, AnalyserQuery.QUERY_VARIABLES _
.SetDeclaredBelowType(belowObject), parsed_object)
End If
End Sub
Public Shared Sub WriteXml( _
ByRef obj As Object, _
ByVal writer As XmlWriter _
)
CreateWriter(writer).Write(obj)
End Sub
#End Region
End Class
End Namespace
|
thiscouldbejd/Leviathan
|
_Configuration/Partials/XmlSerialiser.vb
|
Visual Basic
|
mit
| 13,785
|
Module Module1
Function ToBase(n As Integer, b As Integer) As String
Dim result = ""
If b < 2 Or b > 16 Then
Throw New ArgumentException("The base is out of range")
End If
Do
Dim remainder = n Mod b
result = "0123456789ABCDEF"(remainder) + result
n = n \ b
Loop While n > 0
Return result
End Function
Sub Main()
For b = 2 To 5
Console.WriteLine("Base = {0}", b)
For i = 0 To 12
Dim s = "." + ToBase(i, b)
Console.Write("{0,6} ", s)
Next
Console.WriteLine()
Console.WriteLine()
Next
End Sub
End Module
|
ncoe/rosetta
|
Van_der_Corput_sequence/Visual Basic .NET/VanDerCorputSequence/VanDerCorputSequence/Module1.vb
|
Visual Basic
|
mit
| 729
|
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.VisualBasic
Imports System
Imports System.Diagnostics
Imports System.ComponentModel.Design
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Runtime.InteropServices
Namespace Microsoft.VisualStudio.Editors
Friend NotInheritable Class Constants
'
' Window Styles
'
Public Const WS_OVERLAPPED As Integer = &H0L
Public Const WS_POPUP As Integer = &H80000000
Public Const WS_CHILD As Integer = &H40000000L
Public Const WS_MINIMIZE As Integer = &H20000000L
Public Const WS_VISIBLE As Integer = &H10000000L
Public Const WS_DISABLED As Integer = &H8000000L
Public Const WS_CLIPSIBLINGS As Integer = &H4000000L
Public Const WS_CLIPCHILDREN As Integer = &H2000000L
Public Const WS_MAXIMIZE As Integer = &H1000000L
Public Const WS_CAPTION As Integer = &HC00000L '/* WS_BORDER | WS_DLGFRAME */
Public Const WS_BORDER As Integer = &H800000L
Public Const WS_DLGFRAME As Integer = &H400000L
Public Const WS_VSCROLL As Integer = &H200000L
Public Const WS_HSCROLL As Integer = &H100000L
Public Const WS_SYSMENU As Integer = &H80000L
Public Const WS_THICKFRAME As Integer = &H40000L
Public Const WS_GROUP As Integer = &H20000L
Public Const WS_TABSTOP As Integer = &H10000L
Public Const WS_MINIMIZEBOX As Integer = &H20000L
Public Const WS_MAXIMIZEBOX As Integer = &H10000L
Public Const WS_TILED As Integer = WS_OVERLAPPED
Public Const WS_ICONIC As Integer = WS_MINIMIZE
Public Const WS_SIZEBOX As Integer = WS_THICKFRAME
Public Const WS_TILEDWINDOW As Integer = WS_OVERLAPPEDWINDOW
'/*
' * Common Window Styles
' */
Public Const WS_OVERLAPPEDWINDOW As Integer = (WS_OVERLAPPED Or WS_CAPTION Or WS_SYSMENU Or WS_THICKFRAME Or WS_MINIMIZEBOX Or WS_MAXIMIZEBOX)
Public Const WS_POPUPWINDOW As Integer = (WS_POPUP Or WS_BORDER Or WS_SYSMENU)
Public Const WS_CHILDWINDOW As Integer = (WS_CHILD)
Public Const WS_EX_RIGHT As Integer = &H1000
Public Const WS_EX_LEFT As Integer = &H0
Public Const WS_EX_RTLREADING As Integer = &H2000
Public Const WS_EX_LTRREADING As Integer = &H0
Public Const WS_EX_LEFTSCROLLBAR As Integer = &H4000
Public Const WS_EX_RIGHTSCROLLBAR As Integer = &H0
Public Const WS_EX_CONTROLPARENT As Integer = &H10000
Public Const WS_EX_STATICEDGE As Integer = &H20000
Public Const WS_EX_APPWINDOW As Integer = &H40000
Public Const WS_EX_OVERLAPPEDWINDOW As Integer = (WS_EX_WINDOWEDGE Or WS_EX_CLIENTEDGE)
Public Const WS_EX_PALETTEWINDOW As Integer = (WS_EX_WINDOWEDGE Or WS_EX_TOOLWINDOW Or WS_EX_TOPMOST)
'/*
' * Extended Window Styles
' */
Public Const WS_EX_DLGMODALFRAME As Integer = &H1L
Public Const WS_EX_NOPARENTNOTIFY As Integer = &H4L
Public Const WS_EX_TOPMOST As Integer = &H8L
Public Const WS_EX_ACCEPTFILES As Integer = &H10L
Public Const WS_EX_TRANSPARENT As Integer = &H20L
Public Const WS_EX_MDICHILD As Integer = &H40L
Public Const WS_EX_TOOLWINDOW As Integer = &H80L
Public Const WS_EX_WINDOWEDGE As Integer = &H100L
Public Const WS_EX_CLIENTEDGE As Integer = &H200L
Public Const WS_EX_CONTEXTHELP As Integer = &H400L
Public Const DS_3DLOOK As Integer = &H4
Public Const DS_FIXEDSYS As Integer = &H8
Public Const DS_NOFAILCREATE As Integer = &H10
Public Const DS_CONTROL As Integer = &H400
Public Const DS_CENTER As Integer = &H800
Public Const DS_CENTERMOUSE As Integer = &H1000
Public Const DS_CONTEXTHELP As Integer = &H2000
End Class
<ComVisible(False)> _
Friend Enum VSITEMID As UInteger
NIL = &HFFFFFFFFUI '-1
ROOT = &HFFFFFFFEUI '-2
SELECTION = &HFFFFFFFDUI '-3
End Enum
End Namespace
|
chkn/fsharp
|
vsintegration/src/vs/FsPkgs/FSharp.Project/VB/FSharpPropPage/Package/Constants.vb
|
Visual Basic
|
apache-2.0
| 4,218
|
Imports System.Dynamic
Imports Runtime.Shared
Public Module [Class]
Public Function P(ParamArray args())
Return Prop(args)
End Function
Public Function Prop(ParamArray args())
If args.Length < 2 Then Throw New ArgumentException("Prop must have at least two arguments.")
Try
Dim Target As IDictionary(Of String, Object) = args(0)
args = args.Skip(1).ToArray()
If args.Length = 1 Then
If Target.ContainsKey(args(0)) Then
Target(args(0)) = Nothing
Else
Target.Add(New KeyValuePair(Of String, Object)(args(0), Nothing))
End If
ElseIf args.Length = 2 Then
If Target.ContainsKey(args(0)) Then
Target(args(0)) = args(1)
Else
Target.Add(New KeyValuePair(Of String, Object)(args(0), args(1)))
End If
End If
Return Target
Catch ex As Exception
Throw New ArgumentException("First argument to Prop must be created by a call to Dynamic().")
End Try
End Function
Public Function Dynamic()
Return New ExpandoObject()
End Function
End Module
|
wessupermare/WCompiler
|
Runtime/Class/Class.vb
|
Visual Basic
|
apache-2.0
| 1,266
|
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("02-SimpleTracingBeforeAndAfter")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("02-SimpleTracingBeforeAndAfter")>
<Assembly: AssemblyCopyright("Copyright © 2007")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("c13870bd-a071-4caa-88ec-072cdb813954")>
' 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")>
|
wschult23/LOOM.NET
|
Deploy/RapierLoom.Examples/02-SimpleTracingBeforeAndAfter/VB/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,178
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.ApiDesignGuidelines.Analyzers
''' <summary>
''' CA1726: Use preferred terms
''' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public NotInheritable Class BasicUsePreferredTermsFixer
Inherits UsePreferredTermsFixer
End Class
End Namespace
|
srivatsn/roslyn-analyzers
|
src/Microsoft.ApiDesignGuidelines.Analyzers/VisualBasic/BasicUsePreferredTerms.Fixer.vb
|
Visual Basic
|
apache-2.0
| 691
|
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports System.Reflection.Metadata.Ecma335
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend Module CompilationExtensions
Private Function [GetType]([module] As PEModuleSymbol, typeHandle As TypeDefinitionHandle) As PENamedTypeSymbol
Dim metadataDecoder = New MetadataDecoder([module])
Return DirectCast(metadataDecoder.GetTypeOfToken(typeHandle), PENamedTypeSymbol)
End Function
<Extension>
Friend Function [GetType](compilation As VisualBasicCompilation, moduleVersionId As Guid, typeToken As Integer, <Out> ByRef metadataDecoder As MetadataDecoder) As PENamedTypeSymbol
Dim [module] = compilation.GetModule(moduleVersionId)
Dim reader = [module].Module.MetadataReader
Dim typeHandle = CType(MetadataTokens.Handle(typeToken), TypeDefinitionHandle)
Dim type = [GetType]([module], typeHandle)
metadataDecoder = New MetadataDecoder([module], type)
Return type
End Function
<Extension>
Friend Function GetSourceMethod(compilation As VisualBasicCompilation, moduleVersionId As Guid, methodToken As Integer) As PEMethodSymbol
Dim methodHandle = CType(MetadataTokens.Handle(methodToken), MethodDefinitionHandle)
Dim method = GetMethod(compilation, moduleVersionId, methodHandle)
Dim metadataDecoder = New MetadataDecoder(DirectCast(method.ContainingModule, PEModuleSymbol))
Dim containingType = method.ContainingType
Dim sourceMethodName As String = Nothing
If GeneratedNames.TryParseStateMachineTypeName(containingType.Name, sourceMethodName) Then
For Each member In containingType.ContainingType.GetMembers(sourceMethodName)
Dim candidateMethod = TryCast(member, PEMethodSymbol)
If candidateMethod IsNot Nothing Then
Dim [module] = metadataDecoder.Module
methodHandle = candidateMethod.Handle
Dim stateMachineTypeName As String = Nothing
If [module].HasStringValuedAttribute(methodHandle, AttributeDescription.AsyncStateMachineAttribute, stateMachineTypeName) OrElse
[module].HasStringValuedAttribute(methodHandle, AttributeDescription.IteratorStateMachineAttribute, stateMachineTypeName) _
Then
If metadataDecoder.GetTypeSymbolForSerializedType(stateMachineTypeName).OriginalDefinition.Equals(containingType) Then
Return candidateMethod
End If
End If
End If
Next
End If
Return method
End Function
<Extension>
Friend Function GetMethod(compilation As VisualBasicCompilation, moduleVersionId As Guid, methodHandle As MethodDefinitionHandle) As PEMethodSymbol
Dim [module] = compilation.GetModule(moduleVersionId)
Dim reader = [module].Module.MetadataReader
Dim typeHandle = reader.GetMethodDefinition(methodHandle).GetDeclaringType()
Dim type = [GetType]([module], typeHandle)
Dim method = DirectCast(New MetadataDecoder([module], type).GetMethodSymbolForMethodDefOrMemberRef(methodHandle, type), PEMethodSymbol)
Return method
End Function
<Extension>
Friend Function GetModule(compilation As VisualBasicCompilation, moduleVersionId As Guid) As PEModuleSymbol
For Each pair In compilation.GetBoundReferenceManager().GetReferencedAssemblies()
Dim assembly = DirectCast(pair.Value, AssemblySymbol)
For Each [module] In assembly.Modules
Dim m = DirectCast([module], PEModuleSymbol)
Dim id = m.Module.GetModuleVersionIdOrThrow()
If id = moduleVersionId Then
Return m
End If
Next
Next
Return Nothing
End Function
<Extension>
Friend Function ToCompilation(metadataBlocks As ImmutableArray(Of MetadataBlock)) As VisualBasicCompilation
Return VisualBasicCompilation.Create(
assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName(),
references:=metadataBlocks.MakeAssemblyReferences(),
options:=CompilationOptions)
End Function
' XML file references, #r directives not supported:
Private ReadOnly CompilationOptions As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(
outputKind:=OutputKind.DynamicallyLinkedLibrary,
platform:=Platform.AnyCpu, ' Platform should match PEModule.Machine, in this case I386.
optimizationLevel:=OptimizationLevel.Release,
assemblyIdentityComparer:=DesktopAssemblyIdentityComparer.Default).
WithMetadataImportOptions(MetadataImportOptions.All)
End Module
End Namespace
|
DavidKarlas/roslyn
|
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationExtensions.vb
|
Visual Basic
|
apache-2.0
| 5,443
|
' 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.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports Xunit.Abstractions
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Partial Public MustInherit Class AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Inherits AbstractDiagnosticProviderBasedUserDiagnosticTest
Private ReadOnly _compilationOptions As VisualBasicCompilationOptions =
New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithParseOptions(New VisualBasicParseOptions(LanguageVersion.Latest))
Protected Sub New(Optional logger As ITestOutputHelper = Nothing)
MyBase.New(logger)
End Sub
Protected Overrides Function GetScriptOptions() As ParseOptions
Return TestOptions.Script
End Function
Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters
Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)))
End Function
Friend Overloads Async Function TestAsync(
initialMarkup As XElement, expected As XElement, Optional index As Integer = 0) As Threading.Tasks.Task
Dim initialMarkupStr = initialMarkup.ConvertTestSourceTag()
Dim expectedStr = expected.ConvertTestSourceTag()
Await MyBase.TestAsync(initialMarkupStr, expectedStr,
parseOptions:=_compilationOptions.ParseOptions, compilationOptions:=_compilationOptions,
index:=index)
End Function
Protected Overloads Async Function TestMissingAsync(initialMarkup As XElement) As Threading.Tasks.Task
Dim initialMarkupStr = initialMarkup.ConvertTestSourceTag()
Await MyBase.TestMissingAsync(initialMarkupStr, New TestParameters(parseOptions:=Nothing, compilationOptions:=_compilationOptions))
End Function
Protected Overrides Function GetLanguage() As String
Return LanguageNames.VisualBasic
End Function
Friend ReadOnly Property RequireArithmeticBinaryParenthesesForClarity As OptionsCollection
Get
Return ParenthesesOptionsProvider.RequireArithmeticBinaryParenthesesForClarity
End Get
End Property
Friend ReadOnly Property RequireRelationalBinaryParenthesesForClarity As OptionsCollection
Get
Return ParenthesesOptionsProvider.RequireRelationalBinaryParenthesesForClarity
End Get
End Property
Friend ReadOnly Property RequireOtherBinaryParenthesesForClarity As OptionsCollection
Get
Return ParenthesesOptionsProvider.RequireOtherBinaryParenthesesForClarity
End Get
End Property
Friend ReadOnly Property IgnoreAllParentheses As OptionsCollection
Get
Return ParenthesesOptionsProvider.IgnoreAllParentheses
End Get
End Property
Friend ReadOnly Property RemoveAllUnnecessaryParentheses As OptionsCollection
Get
Return ParenthesesOptionsProvider.RemoveAllUnnecessaryParentheses
End Get
End Property
Friend ReadOnly Property RequireAllParenthesesForClarity As OptionsCollection
Get
Return ParenthesesOptionsProvider.RequireAllParenthesesForClarity
End Get
End Property
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb
|
Visual Basic
|
apache-2.0
| 3,918
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18449
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("RealTermBusPirateSniff.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
pyblendnet-js/RealTermBusPirateSniff
|
RealTermBusPirateSniff/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,731
|
Imports System.Linq
Imports GemBox.Document
Module Program
Sub Main()
' If using Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
Example1()
Example2()
End Sub
Sub Example1()
Dim document As New DocumentModel()
Dim section As New Section(document)
document.Sections.Add(section)
Dim blocks = section.Blocks
' Create bullet list style.
Dim bulletList As New ListStyle(ListTemplateType.Bullet)
bulletList.ListLevelFormats(0).ParagraphFormat.NoSpaceBetweenParagraphsOfSameStyle = True
bulletList.ListLevelFormats(0).CharacterFormat.FontColor = Color.Red
' Create bullet list items.
blocks.Add(New Paragraph(document, "First item.") With
{
.ListFormat = New ListFormat() With {.Style = bulletList}
})
blocks.Add(New Paragraph(document, "Second item.") With
{
.ListFormat = New ListFormat() With {.Style = bulletList}
})
blocks.Add(New Paragraph(document, "Third item.") With
{
.ListFormat = New ListFormat() With {.Style = bulletList}
})
blocks.Add(New Paragraph(document))
' Create number list style.
Dim numberList As New ListStyle(ListTemplateType.NumberWithDot)
' Create number list items.
blocks.Add(New Paragraph(document, "First item.") With
{
.ListFormat = New ListFormat() With {.Style = numberList}
})
blocks.Add(New Paragraph(document, "Sub item 1. a.") With
{
.ListFormat = New ListFormat() With {.Style = numberList, .ListLevelNumber = 1}
})
blocks.Add(New Paragraph(document, "Item below sub item 1. a.") With
{
.ListFormat = New ListFormat() With {.Style = numberList, .ListLevelNumber = 2}
})
blocks.Add(New Paragraph(document, "Sub item 1. b.") With
{
.ListFormat = New ListFormat() With {.Style = numberList, .ListLevelNumber = 1}
})
blocks.Add(New Paragraph(document, "Second item.") With
{
.ListFormat = New ListFormat() With {.Style = numberList}
})
document.Save("Lists.docx")
End Sub
Sub Example2()
Dim listItemsCount As Integer = 12
Dim document As New DocumentModel()
Dim section As New Section(document)
document.Sections.Add(section)
' Create number list style.
Dim numberList As New ListStyle(ListTemplateType.NumberWithDot)
' Customize list level formats.
For level = 0 To numberList.ListLevelFormats.Count - 1
Dim levelFormat As ListLevelFormat = numberList.ListLevelFormats(level)
levelFormat.ParagraphFormat.NoSpaceBetweenParagraphsOfSameStyle = True
levelFormat.Alignment = HorizontalAlignment.Left
levelFormat.NumberStyle = NumberStyle.Decimal
levelFormat.NumberPosition = 18 * level
levelFormat.NumberFormat = String.Concat(Enumerable.Range(1, level + 1).Select(Function(i) $"%{i}."))
Next
' Create number list items.
For i = 0 To listItemsCount - 1
Dim paragraph As New Paragraph(document, "Lorem ipsum")
paragraph.ListFormat.Style = numberList
paragraph.ListFormat.ListLevelNumber = i Mod 9
section.Blocks.Add(paragraph)
Next
document.Save("CustomizedList.docx")
End Sub
End Module
|
gemboxsoftware-dev-team/GemBox.Document.Examples
|
VB.NET/Formatting/Lists/Program.vb
|
Visual Basic
|
mit
| 3,577
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.