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
Option Infer On Imports System Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim partDocument As SolidEdgePart.PartDocument = Nothing Dim models As SolidEdgePart.Models = Nothing Dim model As SolidEdgePart.Model = Nothing Dim revolvedProtrusions As SolidEdgePart.RevolvedProtrusions = Nothing Dim revolvedProtrusion As SolidEdgePart.RevolvedProtrusion = 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) revolvedProtrusions = model.RevolvedProtrusions For i As Integer = 1 To revolvedProtrusions.Count revolvedProtrusion = revolvedProtrusions.Item(i) Dim Description As Object = Nothing Dim status = revolvedProtrusion.Status(Description) Next i End If Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgePart.RevolvedProtrusion.Status.vb
Visual Basic
mit
1,812
 Imports System.Collections.Generic Imports System.Linq Namespace Collections ''' <summary> Extension methods for collections. </summary> Public Module CollectionExtensions ''' <summary> Finds the first occurence of a given value in a <see cref="System.Collections.Generic.IDictionary(Of TKey, TValue)"/> and gets it's key. </summary> ''' <typeparam name="TKey"> Type of keys. </typeparam> ''' <typeparam name="TValue"> Type of values. </typeparam> ''' <param name="dictionary"> The dictionary. </param> ''' <param name="Value"> The value to search for. </param> ''' <param name="FoundKey"> [Out] Will contain the key of the found value, otherwise it isn't changed. </param> ''' <returns> <see langword="true"/>, if the value has been found, otherwise <see langword="false"/>. </returns> ''' <remarks> For value types of TKey, the result is ambigious if the default value of TKey is returned (May be a real occurence or not)! </remarks> ''' <exception cref="System.ArgumentNullException"> <paramref name="dictionary"/> is <see langword="null"/>. </exception> <System.Runtime.CompilerServices.Extension()> Public Function findKeyByValue(Of TKey, TValue)(ByVal dictionary As IDictionary(Of TKey, TValue), Value As TValue, ByRef FoundKey As TKey) As Boolean FoundKey = getKeyByValue(dictionary, Value) Dim DefaultKey As TKey = Nothing Return (Not Object.Equals(FoundKey, DefaultKey)) End Function ''' <summary> Finds the first occurence of a given value in a <see cref="System.Collections.Generic.IDictionary(Of TKey, TValue)"/> and returns it's key. </summary> ''' <typeparam name="TKey"> Type of keys. </typeparam> ''' <typeparam name="TValue"> Type of values. </typeparam> ''' <param name="dictionary"> The dictionary. </param> ''' <param name="Value"> The value to search for. </param> ''' <returns> The key of the found value, or default value of type parameter <c>TKey</c>. </returns> ''' <remarks> For value types of TKey, the result is ambigious if the default value of TKey is returned (May be a real occurence or not)! </remarks> ''' <exception cref="System.ArgumentNullException"> <paramref name="dictionary"/> is <see langword="null"/>. </exception> <System.Runtime.CompilerServices.Extension()> Public Function getKeyByValue(Of TKey, TValue)(ByVal dictionary As IDictionary(Of TKey, TValue), Value As TValue) As TKey If (dictionary Is Nothing) Then Throw New System.ArgumentNullException("dictionary") Dim RetKey As TKey = Nothing Dim DefaultKvp As KeyValuePair(Of TKey, TValue) = Nothing Dim FirstKvp As KeyValuePair(Of TKey, TValue) = dictionary.FirstOrDefault( Function(kvp) ( kvp.Value.Equals(Value))) If (Not FirstKvp.Equals(DefaultKvp)) Then RetKey = FirstKvp.Key End If Return RetKey End Function ''' <summary> Finds and returns the first Item in a <see cref="ICollection(Of TItem)"/> which string representation equals a given string. </summary> ''' <typeparam name="TItem"> Type of Items. </typeparam> ''' <param name="collection"> The collection. </param> ''' <param name="ItemToString"> The string representation to search for. </param> ''' <param name="FoundItem"> [Out] Will contain the found Item, otherwise it isn't changed. </param> ''' <returns> <see langword="true"/>, if the Item has been found, otherwise <see langword="false"/>. </returns> ''' <remarks> For value types the result is ambigious if the default value is returned (May be a real occurence or not)! </remarks> ''' <exception cref="System.ArgumentNullException"> <paramref name="collection"/> is <see langword="null"/>. </exception> ''' <exception cref="System.ArgumentNullException"> <paramref name="ItemToString"/> is <see langword="null"/>. </exception> <System.Runtime.CompilerServices.Extension()> Public Function findItemByString(Of TItem)(ByVal collection As ICollection(Of TItem), ItemToString As String, ByRef FoundItem As TItem) As Boolean FoundItem = getItemByString(collection, ItemToString) Dim DefaultItem As TItem = Nothing Return (Not Object.Equals(FoundItem, DefaultItem)) End Function ''' <summary> Finds and returns the first Item in a <see cref="ICollection(Of TItem)"/> which string representation equals a given string. </summary> ''' <typeparam name="TItem"> Type of Items. </typeparam> ''' <param name="collection"> The collection. </param> ''' <param name="ItemToString"> The string representation to search for. </param> ''' <returns> The found Item, or default value of type parameter <c>TKey</c>. </returns> ''' <remarks> For value types the result is ambigious if the default value is returned (May be a real occurence or not)! </remarks> ''' <exception cref="System.ArgumentNullException"> <paramref name="collection"/> is <see langword="null"/>. </exception> ''' <exception cref="System.ArgumentNullException"> <paramref name="ItemToString"/> is <see langword="null"/>. </exception> <System.Runtime.CompilerServices.Extension()> Public Function getItemByString(Of TItem)(ByVal collection As ICollection(Of TItem), ItemToString As String) As TItem If (collection Is Nothing) Then Throw New System.ArgumentNullException("collection") If (ItemToString Is Nothing) Then Throw New System.ArgumentNullException("ItemToString") Dim RetItem As TItem = Nothing Dim DefaultItem As TItem = Nothing Dim FirstItem As TItem = collection.FirstOrDefault( Function(oItem) ( oItem.ToString().ToLower() = ItemToString.ToLower())) If ((FirstItem ISNot Nothing) AndAlso (Not FirstItem.Equals(DefaultItem))) Then RetItem = FirstItem End If Return RetItem End Function End Module End Namespace ' for jEdi :collapseFolds=2::tabSize=4::indentSize=4:
rschwenn/Rstyx.Utilities
Utilities/source/Collections/CollectionExtensions.vb
Visual Basic
mit
6,696
' --- Copyright (c) notice NevoWeb --- ' Copyright (c) 2008 SARL NevoWeb. www.nevoweb.com. BSD License. ' Author: D.C.Lee, Romain Doidy ' ------------------------------------------------------------------------ ' 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. ' ------------------------------------------------------------------------ ' This copyright notice may NOT be removed, obscured or modified without written consent from the author. ' --- End copyright notice --- ' ' Imports DotNetNuke Imports DotNetNuke.Common Imports DotNetNuke.Services.Exceptions Imports DotNetNuke.Services.Localization Imports System.IO Namespace NEvoWeb.Modules.NB_Store ''' ----------------------------------------------------------------------------- ''' <summary> ''' The AdminReportEdit class is used to manage content ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' </history> ''' ----------------------------------------------------------------------------- Partial Class AdminReportEdit Inherits Framework.UserControlBase #Region "Private Members" Protected _RepID As Integer = -1 #End Region Public Event DeleteButton(ByVal sender As Object, ByVal e As System.EventArgs) Public Event UpdateButton(ByVal sender As Object, ByVal e As System.EventArgs) Public Event CancelButton(ByVal sender As Object, ByVal e As System.EventArgs) Public Event AddParamButton(ByVal sender As Object, ByVal e As System.EventArgs) Public Property RepID() As Integer Get Return _RepID End Get Set(ByVal value As Integer) _RepID = value End Set End Property #Region "Event Handlers" Private Sub cmdCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdCancel.Click Try RaiseEvent CancelButton(sender, e) Catch exc As Exception 'Module failed to load ProcessModuleLoadException(Me, exc) End Try End Sub Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdUpdate.Click Try SaveReport(_RepID) ' Redirect back to the portal home page RaiseEvent UpdateButton(sender, e) Catch exc As Exception 'Module failed to load ProcessModuleLoadException(Me, exc) End Try End Sub Private Sub cmdDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdDelete.Click Try ' Only attempt to delete the item if it exists already7 If _RepID >= 0 Then Dim objSQLReports As New SQLReportController objSQLReports.DeleteSQLReport(_RepID) End If ' Redirect back to the portal home page RaiseEvent DeleteButton(sender, e) Catch exc As Exception 'Module failed to load ProcessModuleLoadException(Me, exc) End Try End Sub Private Sub cmdAddParam_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdAddParam.Click Try Dim objCtrl As New SQLReportController Dim objInfo As NB_Store_SQLReportParamInfo Dim lp As Integer _RepID = SaveReport(_RepID) If IsNumeric(txtAddParams.Text) Then For lp = 1 To CInt(txtAddParams.Text) objInfo = New NB_Store_SQLReportParamInfo objInfo.ParamName = "" objInfo.ParamType = "nvarchar(50)" objInfo.ParamValue = "" objInfo.ReportID = _RepID objInfo.ReportParamID = -1 objInfo.ParamSource = 1 objCtrl.UpdateObjSQLReportParam(objInfo) Next RaiseEvent AddParamButton(sender, e) End If Catch exc As Exception 'Module failed to load ProcessModuleLoadException(Me, exc) End Try End Sub Private Sub dgParam_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgParam.DeleteCommand Try Dim ItemId As Integer = Int32.Parse(e.CommandArgument.ToString) Dim objCtrl As New SQLReportController objCtrl.DeleteSQLReportParam(ItemId) PopulateParams(RepID) Catch exc As Exception 'Module failed to load ProcessModuleLoadException(Me, exc) End Try End Sub Public Sub populateEdit(ByVal ReportID As Integer) Dim objCtrl As New SQLReportController Dim objRinfo As NB_Store_SQLReportInfo objRinfo = objCtrl.GetSQLReport(ReportID) If Not objRinfo Is Nothing Then chkAllowDisplay.Checked = objRinfo.AllowDisplay chkAllowExport.Checked = objRinfo.AllowExport chkDisplayInLine.Checked = objRinfo.DisplayInLine txtEmailFrom.Text = objRinfo.EmailFrom chkEmailResults.Checked = objRinfo.EmailResults txtEmailTo.Text = objRinfo.EmailTo txtReportName.Text = objRinfo.ReportName chkSchedulerFlag.Checked = objRinfo.SchedulerFlag ddlSchReRunMins.SelectedValue = objRinfo.SchReRunMins ddlSchStartHour.SelectedValue = objRinfo.SchStartHour ddlSchStartMins.SelectedValue = objRinfo.SchStartMins txtSQLText.Text = objRinfo.SQL chkShowSQL.Checked = objRinfo.ShowSQL If objRinfo.ReportRef = "" Then txtReportRef.Text = "R" & objRinfo.ReportID.ToString Else txtReportRef.Text = objRinfo.ReportRef End If txtReportTitle.Text = objRinfo.ReportTitle txtFieldDelimeter.Text = objRinfo.FieldDelimeter If txtFieldDelimeter.Text = "" Then txtFieldDelimeter.Text = "," txtFieldQualifier.Text = objRinfo.FieldQualifier PopulateParams(ReportID) Else cmdDelete.Visible = False End If End Sub Private Function SaveReport(ByVal ReportID As Integer) As Integer Dim objCtrl As New SQLReportController Dim objRinfo As NB_Store_SQLReportInfo Dim rtnRepID As Integer objRinfo = objCtrl.GetSQLReport(ReportID) If objRinfo Is Nothing Then objRinfo = New NB_Store_SQLReportInfo End If objRinfo.AllowDisplay = chkAllowDisplay.Checked objRinfo.AllowExport = chkAllowExport.Checked objRinfo.DisplayInLine = chkDisplayInLine.Checked objRinfo.EmailFrom = txtEmailFrom.Text objRinfo.EmailResults = chkEmailResults.Checked objRinfo.EmailTo = txtEmailTo.Text objRinfo.LastRunTime = Today objRinfo.PortalID = PortalSettings.PortalId objRinfo.ReportID = ReportID objRinfo.ReportName = txtReportName.Text objRinfo.SchedulerFlag = chkSchedulerFlag.Checked objRinfo.SchReRunMins = ddlSchReRunMins.SelectedValue objRinfo.SchStartHour = ddlSchStartHour.SelectedValue objRinfo.SchStartMins = ddlSchStartMins.SelectedValue objRinfo.SQL = txtSQLText.Text objRinfo.ShowSQL = chkShowSQL.Checked objRinfo.AllowPaging = False objRinfo.ReportRef = txtReportRef.Text objRinfo.ReportTitle = txtReportTitle.Text objRinfo.FieldDelimeter = txtFieldDelimeter.Text If objRinfo.FieldDelimeter = "" Then objRinfo.FieldDelimeter = "," objRinfo.FieldQualifier = txtFieldQualifier.Text rtnRepID = objCtrl.UpdateObjSQLReport(objRinfo) 'save params updateParams() Return rtnRepID End Function Private Sub updateParams() Dim objCtrl As New SQLReportController Dim objInfo As NB_Store_SQLReportParamInfo Dim i As DataGridItem Dim ParamID As Integer For Each i In dgParam.Items ParamID = CInt(i.Cells(0).Text) objInfo = objCtrl.GetSQLReportParam(ParamID) If Not objInfo Is Nothing Then objInfo.ParamName = CType(i.FindControl("txtParamName"), TextBox).Text objInfo.ParamSource = CType(i.FindControl("ddlSource"), DropDownList).SelectedValue objInfo.ParamType = CType(i.FindControl("ddlType"), DropDownList).SelectedValue objInfo.ParamValue = CType(i.FindControl("txtParamValue"), TextBox).Text objCtrl.UpdateObjSQLReportParam(objInfo) End If Next End Sub Private Sub PopulateParams(ByVal ReportID As Integer) Dim objCtrl As New SQLReportController Dim aryList As ArrayList aryList = objCtrl.GetSQLReportParamList(ReportID) dgParam.DataSource = aryList dgParam.DataBind() End Sub #End Region End Class End Namespace
skamphuis/NB_Store
AdminReportEdit.ascx.vb
Visual Basic
mit
10,233
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("VBRemoveTableRow")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("VBRemoveTableRow")> <Assembly: AssemblyCopyright("Copyright © 2016")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("37e44d1c-c37c-4ee1-9399-df0b3944e379")> ' 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")>
AndreKuzubov/Easy_Report
packages/Independentsoft.Office.Word.2.0.400/Tutorial/VBRemoveTableRow/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
1,150
' 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.Text Imports System.Text.RegularExpressions Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic <ExportLanguageService(GetType(ILinkedFileMergeConflictCommentAdditionService), LanguageNames.VisualBasic), [Shared]> Friend Class BasicLinkedFileMergeConflictCommentAdditionService Inherits AbstractLinkedFileMergeConflictCommentAdditionService <ImportingConstructor> Public Sub New() End Sub Friend Overrides Function GetConflictCommentText(header As String, beforeString As String, afterString As String) As String If beforeString Is Nothing AndAlso afterString Is Nothing Then Return Nothing ElseIf beforeString Is Nothing Then ' Added code Return String.Format(" ' {0} ' {1} {2} ", header, WorkspacesResources.Added_colon, GetCommentedText(afterString)) ElseIf afterString Is Nothing Then ' Removed code Return String.Format(" ' {0} ' {1} {2} ", header, WorkspacesResources.Removed_colon, GetCommentedText(beforeString)) Else Return String.Format(" ' {0} ' {1} {2} ' {3} {4} ", header, WorkspacesResources.Before_colon, GetCommentedText(beforeString), WorkspacesResources.After_colon, GetCommentedText(afterString)) End If End Function Private Function GetCommentedText(text As String) As String Dim lines = Regex.Split(text, "\r\n|\r|\n") If Not lines.Any() Then Return text End If Dim newlines = Regex.Matches(text, "\r\n|\r|\n") Debug.Assert(newlines.Count = lines.Length - 1) Dim builder = New StringBuilder() For i = 0 To lines.Length - 2 builder.Append(String.Format("' {0}{1}", lines(i), newlines(i))) Next builder.Append(String.Format("' {0}", lines.Last())) Return builder.ToString() End Function End Class End Namespace
aelij/roslyn
src/Workspaces/VisualBasic/Portable/LinkedFiles/BasicLinkedFileMergeConflictCommentAdditionService.vb
Visual Basic
apache-2.0
2,486
'*******************************************************************************************' ' ' ' 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.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. <Assembly: AssemblyTitle("ExtractTextFromPageArea")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyConfiguration("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("ExtractTextFromPageArea")> <Assembly: AssemblyCopyright("Copyright © 2010")> <Assembly: AssemblyTrademark("")> <Assembly: AssemblyCulture("")> ' Setting ComVisible to false makes the types in this assembly not visible ' to COM components. If you need to access a type in this assembly from ' COM, set the ComVisible attribute to true on that type. <Assembly: ComVisible(False)> ' The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("90c92623-11ae-4ddb-9982-80552a4cc3f5")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
bytescout/ByteScout-SDK-SourceCode
Premium Suite/VB.NET/Extract text from page area in pdf with pdf extractor sdk/Properties/AssemblyInfo.vb
Visual Basic
apache-2.0
2,223
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification <ExportLanguageService(GetType(ISimplificationService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicSimplificationService Inherits AbstractSimplificationService(Of ExpressionSyntax, ExecutableStatementSyntax, CrefReferenceSyntax) Private Shared ReadOnly s_reducers As ImmutableArray(Of AbstractReducer) = ImmutableArray.Create(Of AbstractReducer)( New VisualBasicExtensionMethodReducer(), New VisualBasicCastReducer(), New VisualBasicNameReducer(), New VisualBasicParenthesesReducer(), New VisualBasicCallReducer(), New VisualBasicEscapingReducer(), ' order before VisualBasicMiscellaneousReducer, see RenameNewOverload test New VisualBasicMiscellaneousReducer(), New VisualBasicCastReducer(), New VisualBasicVariableDeclaratorReducer(), New VisualBasicInferredMemberNameReducer()) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(s_reducers) End Sub Public Overrides Function Expand(node As SyntaxNode, semanticModel As SemanticModel, aliasReplacementAnnotation As SyntaxAnnotation, expandInsideNode As Func(Of SyntaxNode, Boolean), expandParameter As Boolean, cancellationToken As CancellationToken) As SyntaxNode Using Logger.LogBlock(FunctionId.Simplifier_ExpandNode, cancellationToken) If TypeOf node Is ExpressionSyntax OrElse TypeOf node Is StatementSyntax OrElse TypeOf node Is AttributeSyntax OrElse TypeOf node Is SimpleArgumentSyntax OrElse TypeOf node Is CrefReferenceSyntax OrElse TypeOf node Is TypeConstraintSyntax Then Dim rewriter = New Expander(semanticModel, expandInsideNode, cancellationToken, expandParameter, aliasReplacementAnnotation) Return rewriter.Visit(node) Else Throw New ArgumentException( VBWorkspaceResources.Only_attributes_expressions_or_statements_can_be_made_explicit, paramName:=NameOf(node)) End If End Using End Function Public Overrides Function Expand(token As SyntaxToken, semanticModel As SemanticModel, expandInsideNode As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) As SyntaxToken Using Logger.LogBlock(FunctionId.Simplifier_ExpandToken, cancellationToken) Dim rewriter = New Expander(semanticModel, expandInsideNode, cancellationToken) Return TryEscapeIdentifierToken(rewriter.VisitToken(token)) End Using End Function Protected Overrides Function GetSpeculativeSemanticModel(ByRef nodeToSpeculate As SyntaxNode, originalSemanticModel As SemanticModel, originalNode As SyntaxNode) As SemanticModel Contract.ThrowIfNull(nodeToSpeculate) Contract.ThrowIfNull(originalNode) Dim speculativeModel As SemanticModel Dim methodBlockBase = TryCast(nodeToSpeculate, MethodBlockBaseSyntax) ' Speculation over Field Declarations is not supported If originalNode.Kind() = SyntaxKind.VariableDeclarator AndAlso originalNode.Parent.Kind() = SyntaxKind.FieldDeclaration Then Return originalSemanticModel End If If methodBlockBase IsNot Nothing Then ' Certain reducers for VB (escaping, parentheses) require to operate on the entire method body, rather than individual statements. ' Hence, we need to reduce the entire method body as a single unit. ' However, there is no SyntaxNode for the method body or statement list, hence NodesAndTokensToReduceComputer added the MethodBlockBaseSyntax to the list of nodes to be reduced. ' Here we make sure that we create a speculative semantic model for the method body for the given MethodBlockBaseSyntax. Dim originalMethod = DirectCast(originalNode, MethodBlockBaseSyntax) Contract.ThrowIfFalse(originalMethod.Statements.Any(), "How did empty method body get reduced?") Dim position As Integer If originalSemanticModel.IsSpeculativeSemanticModel Then ' Chaining speculative model Not supported, speculate off the original model. Debug.Assert(originalSemanticModel.ParentModel IsNot Nothing) Debug.Assert(Not originalSemanticModel.ParentModel.IsSpeculativeSemanticModel) position = originalSemanticModel.OriginalPositionForSpeculation originalSemanticModel = originalSemanticModel.ParentModel Else position = originalMethod.Statements.First.SpanStart End If speculativeModel = Nothing originalSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(position, methodBlockBase, speculativeModel) Return speculativeModel End If Contract.ThrowIfFalse(SpeculationAnalyzer.CanSpeculateOnNode(nodeToSpeculate)) Dim isAsNewClause = nodeToSpeculate.Kind = SyntaxKind.AsNewClause If isAsNewClause Then ' Currently, there is no support for speculating on an AsNewClauseSyntax node. ' So we synthesize an EqualsValueSyntax with the inner NewExpression and speculate on this EqualsValueSyntax node. Dim asNewClauseNode = DirectCast(nodeToSpeculate, AsNewClauseSyntax) nodeToSpeculate = SyntaxFactory.EqualsValue(asNewClauseNode.NewExpression) nodeToSpeculate = asNewClauseNode.CopyAnnotationsTo(nodeToSpeculate) End If speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(originalNode, nodeToSpeculate, originalSemanticModel) If isAsNewClause Then nodeToSpeculate = speculativeModel.SyntaxTree.GetRoot() End If Return speculativeModel End Function Protected Overrides Function TransformReducedNode(reducedNode As SyntaxNode, originalNode As SyntaxNode) As SyntaxNode ' Please see comments within the above GetSpeculativeSemanticModel method for details. If originalNode.Kind = SyntaxKind.AsNewClause AndAlso reducedNode.Kind = SyntaxKind.EqualsValue Then Return originalNode.ReplaceNode(DirectCast(originalNode, AsNewClauseSyntax).NewExpression, DirectCast(reducedNode, EqualsValueSyntax).Value) End If Dim originalMethod = TryCast(originalNode, MethodBlockBaseSyntax) If originalMethod IsNot Nothing Then Dim reducedMethod = DirectCast(reducedNode, MethodBlockBaseSyntax) reducedMethod = reducedMethod.ReplaceNode(reducedMethod.BlockStatement, originalMethod.BlockStatement) Return reducedMethod.ReplaceNode(reducedMethod.EndBlockStatement, originalMethod.EndBlockStatement) End If Return reducedNode End Function Protected Overrides Function GetNodesAndTokensToReduce(root As SyntaxNode, isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) As ImmutableArray(Of NodeOrTokenToReduce) Return NodesAndTokensToReduceComputer.Compute(root, isNodeOrTokenOutsideSimplifySpans) End Function Protected Overrides Function CanNodeBeSimplifiedWithoutSpeculation(node As SyntaxNode) As Boolean Return node IsNot Nothing AndAlso node.Parent IsNot Nothing AndAlso TypeOf node Is VariableDeclaratorSyntax AndAlso TypeOf node.Parent Is FieldDeclarationSyntax End Function Private Const s_BC50000_UnusedImportsClause As String = "BC50000" Private Const s_BC50001_UnusedImportsStatement As String = "BC50001" Protected Overrides Sub GetUnusedNamespaceImports(model As SemanticModel, namespaceImports As HashSet(Of SyntaxNode), cancellationToken As CancellationToken) Dim root = model.SyntaxTree.GetRoot(cancellationToken) Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken) For Each diagnostic In diagnostics If diagnostic.Id = s_BC50000_UnusedImportsClause OrElse diagnostic.Id = s_BC50001_UnusedImportsStatement Then Dim node = root.FindNode(diagnostic.Location.SourceSpan) Dim statement = TryCast(node, ImportsStatementSyntax) Dim clause = TryCast(node, ImportsStatementSyntax) If statement IsNot Nothing Or clause IsNot Nothing Then namespaceImports.Add(node) End If End If Next End Sub End Class End Namespace
shyamnamboodiripad/roslyn
src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.vb
Visual Basic
apache-2.0
9,766
' 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.Globalization Imports System.Security Imports Microsoft.VisualBasic.CompilerServices Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Imports Microsoft.VisualBasic.CompilerServices.Utils Namespace Microsoft.VisualBasic Public Module Information 'QBColorTable below consists of : '&H0I, ' 0 - black '&H800000I, ' 1 - blue '&H8000I, ' 2 - green '&H808000I, ' 3 - cyan '&H80I, ' 4 - red '&H800080I, ' 5 - magenta '&H8080I, ' 6 - yellow '&HC0C0C0I, ' 7 - white '&H808080I, ' 8 - gray '&HFF0000I, ' 9 - light blue '&HFF00I, ' 10 - light green '&HFFFF00I, ' 11 - light cyan '&HFFI, ' 12 - light red '&HFF00FFI, ' 13 - light magenta '&HFFFFI, ' 14 - light yellow '&HFFFFFFI, ' 15 - bright white Private ReadOnly QBColorTable() As Integer = {&H0I, &H800000I, &H8000I, &H808000I, &H80I, &H800080I, &H8080I, &HC0C0C0I, &H808080I, &HFF0000I, &HFF00I, &HFFFF00I, &HFFI, &HFF00FFI, &HFFFFI, &HFFFFFFI} Friend Const COMObjectName As String = "__ComObject" Public Function IsArray(ByVal VarName As Object) As Boolean If VarName Is Nothing Then Return False End If Return (TypeOf VarName Is System.Array) End Function Public Function IsDate(ByVal Expression As Object) As Boolean If Expression Is Nothing Then Return False End If If TypeOf Expression Is Date Then Return True Else Dim stringExpression As String = TryCast(Expression, String) If stringExpression IsNot Nothing Then Dim convertedDate As DateTime Return Conversions.TryParseDate(stringExpression, convertedDate) End If End If Return False End Function Public Function IsDBNull(ByVal Expression As Object) As Boolean If Expression Is Nothing Then Return False ElseIf TypeOf Expression Is System.DBNull Then Return True Else Return False End If End Function Public Function IsNothing(ByVal Expression As Object) As Boolean Return (Expression Is Nothing) End Function Public Function IsError(ByVal Expression As Object) As Boolean If Expression Is Nothing Then Return False End If Return (TypeOf Expression Is Exception) End Function Public Function IsReference(ByVal Expression As Object) As Boolean Return Not (TypeOf Expression Is System.ValueType) End Function Public Function LBound(ByVal Array As System.Array, Optional ByVal Rank As Integer = 1) As Integer If (Array Is Nothing) Then Throw VbMakeException(New ArgumentNullException(NameOf(Array)), vbErrors.OutOfBounds) ElseIf (Rank < 1) OrElse (Rank > Array.Rank) Then Throw New RankException(SR.Format(SR.Argument_InvalidRank1, NameOf(Rank))) End If Return Array.GetLowerBound(Rank - 1) End Function Public Function UBound(ByVal Array As System.Array, Optional ByVal Rank As Integer = 1) As Integer If (Array Is Nothing) Then Throw VbMakeException(New ArgumentNullException(NameOf(Array)), vbErrors.OutOfBounds) ElseIf (Rank < 1) OrElse (Rank > Array.Rank) Then Throw New RankException(SR.Format(SR.Argument_InvalidRank1, NameOf(Rank))) End If Return Array.GetUpperBound(Rank - 1) End Function Public Function QBColor(ByVal Color As Integer) As Integer If (Color And &HFFF0I) <> 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(Color)), NameOf(Color)) End If Return QBColorTable(Color) End Function Public Function RGB(ByVal Red As Integer, ByVal Green As Integer, ByVal Blue As Integer) As Integer If (Red And &H80000000I) <> 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(Red)), NameOf(Red)) ElseIf (Green And &H80000000I) <> 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(Green)), NameOf(Green)) ElseIf (Blue And &H80000000I) <> 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(Blue)), NameOf(Blue)) End If ' VB2 treats any value > 255 as 255 If (Red > 255) Then Red = &HFFI End If If (Green > 255) Then Green = &HFFI End If If (Blue > 255) Then Blue = &HFFI End If Return ((Blue * &H10000I) + (Green * &H100I) + Red) End Function Public Function VarType(ByVal VarName As Object) As VariantType If VarName Is Nothing Then Return VariantType.Object End If Return VarTypeFromComType(VarName.GetType()) End Function Friend Function VarTypeFromComType(ByVal typ As System.Type) As VariantType If typ Is Nothing Then Return VariantType.Object End If If typ.IsArray() Then typ = typ.GetElementType() If typ.IsArray Then Return CType(VariantType.Array Or VariantType.Object, VariantType) End If Dim result As VariantType = VarTypeFromComType(typ) If (result And VariantType.Array) <> 0 Then 'Element type is also an array, so just return "array of objects" Return CType(VariantType.Array Or VariantType.Object, VariantType) End If Return CType(result Or VariantType.Array, VariantType) ElseIf typ.IsEnum() Then typ = System.Enum.GetUnderlyingType(typ) End If If typ Is Nothing Then Return VariantType.Empty End If Select Case Type.GetTypeCode(typ) Case TypeCode.String Return VariantType.String Case TypeCode.Int32 Return VariantType.Integer Case TypeCode.Int16 Return VariantType.Short Case TypeCode.Int64 Return VariantType.Long Case TypeCode.Single Return VariantType.Single Case TypeCode.Double Return VariantType.Double Case TypeCode.DateTime Return VariantType.Date Case TypeCode.Boolean Return VariantType.Boolean Case TypeCode.Decimal Return VariantType.Decimal Case TypeCode.Byte Return VariantType.Byte Case TypeCode.Char Return VariantType.Char Case TypeCode.DBNull Return VariantType.Null End Select If (typ Is GetType(System.Reflection.Missing)) OrElse (typ Is GetType(System.Exception)) OrElse (typ.IsSubclassOf(GetType(System.Exception))) Then Return VariantType.Error ElseIf typ.IsValueType() Then Return VariantType.UserDefinedType Else Return VariantType.Object End If End Function Friend Function IsOldNumericTypeCode(ByVal TypCode As System.TypeCode) As Boolean Select Case TypCode Case TypeCode.Int16, TypeCode.Int32, TypeCode.Int64, TypeCode.Single, TypeCode.Double, TypeCode.Boolean, TypeCode.Decimal, TypeCode.Byte Return True Case Else Return False End Select End Function Public Function IsNumeric(ByVal Expression As Object) As Boolean Dim valueInterface As IConvertible Dim valueTypeCode As TypeCode valueInterface = TryCast(Expression, IConvertible) If valueInterface Is Nothing Then Dim charArray As Char() = TryCast(Expression, Char()) If charArray IsNot Nothing Then Expression = CStr(charArray) Else Return False End If End If valueTypeCode = valueInterface.GetTypeCode() If (valueTypeCode = TypeCode.String) OrElse (valueTypeCode = TypeCode.Char) Then 'Convert to double, exception thrown if not a number Dim dbl As Double Dim i64Value As Int64 Dim value As String value = valueInterface.ToString(Nothing) Try If IsHexOrOctValue(value, i64Value) Then Return True End If Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch ex As System.Threading.ThreadAbortException Throw ex Catch Return False End Try Return DoubleType.TryParse(value, dbl) End If Return IsOldNumericTypeCode(valueTypeCode) End Function Public Function SystemTypeName(ByVal VbName As String) As String Select Case Trim(VbName).ToUpperInvariant() Case "OBJECT" : Return "System.Object" Case "SHORT" : Return "System.Int16" Case "INTEGER" : Return "System.Int32" Case "SINGLE" : Return "System.Single" Case "DOUBLE" : Return "System.Double" Case "DATE" : Return "System.DateTime" Case "STRING" : Return "System.String" Case "BOOLEAN" : Return "System.Boolean" Case "DECIMAL" : Return "System.Decimal" Case "BYTE" : Return "System.Byte" Case "CHAR" : Return "System.Char" Case "LONG" : Return "System.Int64" Case Else : Return Nothing End Select End Function Public Function VbTypeName(ByVal UrtName As String) As String Return OldVbTypeName(UrtName) End Function Friend Function OldVbTypeName(ByVal UrtName As String) As String UrtName = Trim(UrtName).ToUpperInvariant() If Left(UrtName, 7) = "SYSTEM." Then UrtName = Mid(UrtName, 8) End If Select Case UrtName Case "OBJECT" : Return "Object" Case "INT16" : Return "Short" Case "INT32" : Return "Integer" Case "SINGLE" : Return "Single" Case "DOUBLE" : Return "Double" Case "DATETIME" : Return "Date" Case "STRING" : Return "String" Case "BOOLEAN" : Return "Boolean" Case "DECIMAL" : Return "Decimal" Case "BYTE" : Return "Byte" Case "CHAR" : Return "Char" Case "INT64" : Return "Long" Case Else Return Nothing End Select End Function End Module End Namespace
ptoonen/corefx
src/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Information.vb
Visual Basic
mit
12,477
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class ConditionalPreprocessorHighlighter Inherits AbstractKeywordHighlighter(Of DirectiveTriviaSyntax) Protected Overloads Overrides Function GetHighlights(directive As DirectiveTriviaSyntax, cancellationToken As CancellationToken) As IEnumerable(Of TextSpan) Dim conditionals = directive.GetMatchingConditionalDirectives(cancellationToken) If conditionals Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of TextSpan)() End If Dim highlights As New List(Of TextSpan) For Each conditional In conditionals If TypeOf conditional Is IfDirectiveTriviaSyntax Then With DirectCast(conditional, IfDirectiveTriviaSyntax) highlights.Add(TextSpan.FromBounds(.HashToken.SpanStart, .IfOrElseIfKeyword.Span.End)) If .ThenKeyword.Kind <> SyntaxKind.None Then highlights.Add(.ThenKeyword.Span) End If End With ElseIf TypeOf conditional Is ElseDirectiveTriviaSyntax Then With DirectCast(conditional, ElseDirectiveTriviaSyntax) highlights.Add(TextSpan.FromBounds(.HashToken.SpanStart, .ElseKeyword.Span.End)) End With ElseIf TypeOf conditional Is EndIfDirectiveTriviaSyntax Then With DirectCast(conditional, EndIfDirectiveTriviaSyntax) highlights.Add(TextSpan.FromBounds(.HashToken.SpanStart, .IfKeyword.Span.End)) End With End If Next Return highlights End Function End Class End Namespace
pdelvo/roslyn
src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/ConditionalPreprocessorHighlighter.vb
Visual Basic
apache-2.0
2,227
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator ''' <summary> ''' A synthesized instance method used for binding expressions outside ''' of a method - specifically, binding DebuggerDisplayAttribute expressions. ''' </summary> Friend NotInheritable Class SynthesizedContextMethodSymbol Inherits SynthesizedMethodBase Public Sub New(container As NamedTypeSymbol) MyBase.New(container) End Sub Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property 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
mmitche/roslyn
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.vb
Visual Basic
apache-2.0
3,114
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Public Class ForOrForEachBlockSyntax ''' <summary> ''' The For or For Each statement that begins the block. ''' </summary> Public MustOverride ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax End Class Partial Public Class ForBlockSyntax <ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)> Public Overrides ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax Get Return ForStatement End Get End Property End Class Partial Public Class ForEachBlockSyntax <ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)> Public Overrides ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax Get Return ForEachStatement End Get End Property End Class End Namespace
mmitche/roslyn
src/Compilers/VisualBasic/Portable/Syntax/ForOrForEachBlockSyntax.vb
Visual Basic
apache-2.0
1,312
Imports Microsoft.Win32 Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports NetOffice Imports Excel = NetOffice.ExcelApi Imports NetOffice.ExcelApi.Enums Imports Office = NetOffice.OfficeApi Imports NetOffice.OfficeApi.Enums <Guid("20B04286-C912-432E-9546-AEBC81986EDE"), ProgId("ExcelAddinVB4.TaskPaneAddin"), ComVisible(True)> Public Class Addin Implements IDTExtensibility2, Office.Native.ICustomTaskPaneConsumer Private Shared ReadOnly _addinOfficeRegistryKey As String = "Software\\Microsoft\\Office\\Excel\\AddIns\\" Private Shared ReadOnly _progId As String = "ExcelAddinVB4.TaskPaneAddin" Private Shared ReadOnly _addinFriendlyName As String = "NetOffice Sample Addin in VB" Private Shared ReadOnly _addinDescription As String = "NetOffice Sample Addin with custom Task Pane" Private Shared _sampleControl As SampleControl Private Shared _excelApplication As Excel.Application Public Shared ReadOnly Property Application() As Excel.Application Get Return _excelApplication End Get End Property #Region "ICustomTaskPaneConsumer Member" Public Sub CTPFactoryAvailable(ByVal CTPFactoryInst As Object) Implements NetOffice.OfficeApi.Native.ICustomTaskPaneConsumer.CTPFactoryAvailable Try Dim ctpFactory As Office.ICTPFactory = New Office.ICTPFactory(_excelApplication, CTPFactoryInst) Dim taskPane As Office._CustomTaskPane = ctpFactory.CreateCTP(GetType(Addin).Assembly.GetName().Name + ".SampleControl", "NetOffice Sample Pane(VB4)", Type.Missing) taskPane.DockPosition = MsoCTPDockPosition.msoCTPDockPositionLeft taskPane.Width = 300 taskPane.Visible = True _sampleControl = taskPane.ContentControl ctpFactory.Dispose() Catch ex As Exception Dim message As String = String.Format("An error occured.{0}{0}{1}", Environment.NewLine, ex.Message) MessageBox.Show(message, _progId, MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub #End Region #Region "IDTExtensibility2 Member" Public Sub OnConnection(ByVal Application As Object, ByVal ConnectMode As Extensibility.ext_ConnectMode, ByVal AddInInst As Object, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnConnection Try _excelApplication = New Excel.Application(Nothing, Application) Catch ex As Exception Dim message As String = String.Format("An error occured.{0}{0}{1}", Environment.NewLine, ex.Message) MessageBox.Show(message, _progId, MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Public Sub OnDisconnection(ByVal RemoveMode As Extensibility.ext_DisconnectMode, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnDisconnection Try If (Not IsNothing(_excelApplication)) Then _excelApplication.Dispose() End If Catch ex As Exception Dim message As String = String.Format("An error occured.{0}{0}{1}", Environment.NewLine, ex.Message) MessageBox.Show(message, _progId, MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Public Sub OnStartupComplete(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnStartupComplete End Sub Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnAddInsUpdate End Sub Public Sub OnBeginShutdown(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnBeginShutdown End Sub #End Region #Region "COM Register Functions" <ComRegisterFunctionAttribute()> _ Public Shared Sub RegisterFunction(ByVal type As Type) Try ' add codebase value Dim thisAssembly As Assembly = Assembly.GetAssembly(GetType(Addin)) Dim key As RegistryKey = Registry.ClassesRoot.CreateSubKey("CLSID\\{" + type.GUID.ToString().ToUpper() + "}\\InprocServer32\\1.0.0.0") key.SetValue("CodeBase", thisAssembly.CodeBase) key.Close() Registry.ClassesRoot.CreateSubKey("CLSID\{" + type.GUID.ToString().ToUpper() + "}\Programmable") ' add bypass key ' http://support.microsoft.com/kb/948461 key = Registry.ClassesRoot.CreateSubKey("Interface\\{000C0601-0000-0000-C000-000000000046}") Dim defaultValue As String = key.GetValue("") If (IsNothing(defaultValue)) Then key.SetValue("", "Office .NET Framework Lockback Bypass Key") End If key.Close() ' add excel addin key Dim rk As RegistryKey = Registry.CurrentUser.CreateSubKey(_addinOfficeRegistryKey + _progId) rk.SetValue("LoadBehavior", CInt(3)) rk.SetValue("FriendlyName", _addinFriendlyName) rk.SetValue("Description", _addinDescription) rk.Close() Catch ex As Exception Dim details As String = String.Format("{1}{1}Details:{1}{1}{0}", ex.Message, Environment.NewLine) MessageBox.Show("An error occured." + details, "Register " + _progId, MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub <ComUnregisterFunctionAttribute()> _ Public Shared Sub UnregisterFunction(ByVal type As Type) Try Registry.ClassesRoot.DeleteSubKey("CLSID\\{" + type.GUID.ToString().ToUpper() + "}\\Programmable", False) Registry.CurrentUser.DeleteSubKey(_addinOfficeRegistryKey + _progId, False) Catch throwedException As Exception Dim details As String = String.Format("{1}{1}Details:{1}{1}{0}", throwedException.Message, Environment.NewLine) MessageBox.Show("An error occured." + details, "Unregister " + _progId, MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub #End Region End Class
NetOfficeFw/NetOffice
Examples/Excel/VB/IExtensibility COMAddin Examples/TaskPane/Addin.vb
Visual Basic
mit
6,026
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 circles2d As SolidEdgeFrameworkSupport.Circles2d = Nothing Dim circle2d As SolidEdgeFrameworkSupport.Circle2d = 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 profileSets = partDocument.ProfileSets profileSet = profileSets.Add() profiles = profileSet.Profiles profile = profiles.Add(refPlanes.Item(1)) circles2d = profile.Circles2d circle2d = circles2d.AddByCenterRadius(0, 0, 0.01) circle2d.SetMajorAxis(0.05, 0) 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.Circle2d.SetMajorAxis.vb
Visual Basic
mit
2,024
Option Explicit On Option Infer On Option Strict On #Region " --------------->> Imports/ usings " Imports SSP.Base.DateTimeHandling.PublicHolidays.Interfaces Imports SSP.Base.StringHandling #End Region Namespace DateTimeHandling.PublicHolidays Public NotInheritable Class PublicHolidaysLogicLuxembourg Inherits PublicHolidaysLogicBase #Region " --------------->> Enumerationen der Klasse " #End Region #Region " --------------->> Eigenschaften der Klasse " #End Region #Region " --------------->> Konstruktor und Destruktor der Klasse " Public Sub New() End Sub #End Region #Region " --------------->> Zugriffsmethoden der Klasse " Public Shared ReadOnly Property Instance() As New PublicHolidaysLogicLuxembourg Public Overrides ReadOnly Property CultureCode As CultureCodes = CultureCodes.de_LU #End Region #Region " --------------->> Ereignismethoden Methoden der Klasse " #End Region #Region " --------------->> Private Methoden der Klasse " Protected Overrides Sub InitializePublicHolidays() Me.Holidays.Clear() With Me.Holidays AddFixedNotRegionalPublicDay(GetDateTime(1, 1), "Neujahr") AddFixedNotRegionalPublicDay(GetDateTime(5, 1), "Tag der Arbeit") AddFixedNotRegionalPublicDay(GetDateTime(6, 23), "Nationalfeiertag") AddFixedNotRegionalPublicDay(GetDateTime(8, 15), "Mariä Himmelfahrt") AddFixedNotRegionalPublicDay(GetDateTime(11, 1), "Allerheiligen") AddFixedNotRegionalPublicDay(GetDateTime(12, 25), "1. Weihnachtsfeiertag") AddFixedNotRegionalPublicDay(GetDateTime(12, 26), "2. Weihnachtsfeiertag (Stephanstag)") Dim easterSunday = GetEasterSunday() AddNotFixedNotRegionalPublicDay(easterSunday.AddDays(1), "Ostermontag") AddNotFixedNotRegionalPublicDay(easterSunday.AddDays(39), "Christi Himmelfahrt") AddNotFixedNotRegionalPublicDay(easterSunday.AddDays(50), "Pfingstmontag") End With End Sub #End Region #Region " --------------->> Öffentliche Methoden der Klasse " #End Region End Class End Namespace
vanitas-mundi/Base
Base/DateTimeHandling/PublicHolidays/PublicHolidaysLogicLuxembourg.vb
Visual Basic
mit
2,079
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18444 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My 'NOTE: This file is auto-generated; do not modify it directly. To make changes, ' or if you encounter build errors in this file, go to the Project Designer ' (go to Project Properties or double-click the My Project node in ' Solution Explorer), and make changes on the Application tab. ' Partial Friend Class MyApplication <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Public Sub New() MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) Me.IsSingleInstance = false Me.EnableVisualStyles = true Me.SaveMySettingsOnExit = true Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses End Sub <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Protected Overrides Sub OnCreateMainForm() Me.MainForm = Global.JokerResults.Form1 End Sub End Class End Namespace
trod80/JokerGreece
JokerResults/JokerResults/My Project/Application.Designer.vb
Visual Basic
mit
1,516
Option Infer On Imports System Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As RevisionManager.Application = Nothing Dim document As RevisionManager.Document = Nothing Try application = New RevisionManager.Application() document = CType(application.Open("C:\Program Files\Solid Edge ST9\Training\Coffee Pot.asm"), RevisionManager.Document) Dim fullName = document.FullName Catch ex As System.Exception Console.WriteLine(ex) End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/RevisionManager.IDocAuto.FullName.vb
Visual Basic
mit
728
Imports System Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Security ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("12list-of-IDEs")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("12list-of-IDEs")> <Assembly: AssemblyCopyright("Copyright © 2014")> <Assembly: AssemblyTrademark("")> ' Setting ComVisible to false makes the types in this assembly not visible ' to COM components. If you need to access a type in this assembly from ' COM, set the ComVisible attribute to true on that type. <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("247c2681-b079-4554-b482-c17cd037f5b6")> ' 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")> Friend Module DesignTimeConstants Public Const RibbonTypeSerializer As String = "Microsoft.VisualStudio.Tools.Office.Ribbon.Serialization.RibbonTypeCodeDomSerializer, Microsoft.VisualStudio.Tools.Office.Designer, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Public Const RibbonBaseTypeSerializer As String = "System.ComponentModel.Design.Serialization.TypeCodeDomSerializer, System.Design" Public Const RibbonDesigner As String = "Microsoft.VisualStudio.Tools.Office.Ribbon.Design.RibbonDesigner, Microsoft.VisualStudio.Tools.Office.Designer, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" End Module
ilinaTomova/Csharp
Intro-Programming-Homework/12list-of-IDEs/My Project/AssemblyInfo.vb
Visual Basic
mit
2,036
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmPostage Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.lblWeight = New System.Windows.Forms.Label() Me.txtWeight = New System.Windows.Forms.TextBox() Me.btnCAC = New System.Windows.Forms.Button() Me.lblCost = New System.Windows.Forms.Label() Me.txtCost = New System.Windows.Forms.TextBox() Me.SuspendLayout() ' 'lblWeight ' Me.lblWeight.AutoSize = True Me.lblWeight.Location = New System.Drawing.Point(10, 15) Me.lblWeight.Name = "lblWeight" Me.lblWeight.Size = New System.Drawing.Size(126, 13) Me.lblWeight.TabIndex = 0 Me.lblWeight.Text = "Weight of letter (ounces):" ' 'txtWeight ' Me.txtWeight.Location = New System.Drawing.Point(142, 12) Me.txtWeight.Name = "txtWeight" Me.txtWeight.Size = New System.Drawing.Size(100, 20) Me.txtWeight.TabIndex = 1 ' 'btnCAC ' Me.btnCAC.Location = New System.Drawing.Point(13, 38) Me.btnCAC.Name = "btnCAC" Me.btnCAC.Size = New System.Drawing.Size(229, 35) Me.btnCAC.TabIndex = 2 Me.btnCAC.Text = "Compute Airmail Cost" Me.btnCAC.UseVisualStyleBackColor = True ' 'lblCost ' Me.lblCost.AutoSize = True Me.lblCost.Location = New System.Drawing.Point(52, 82) Me.lblCost.Name = "lblCost" Me.lblCost.Size = New System.Drawing.Size(31, 13) Me.lblCost.TabIndex = 3 Me.lblCost.Text = "Cost:" ' 'txtCost ' Me.txtCost.Location = New System.Drawing.Point(89, 79) Me.txtCost.Name = "txtCost" Me.txtCost.ReadOnly = True Me.txtCost.Size = New System.Drawing.Size(100, 20) Me.txtCost.TabIndex = 4 ' 'frmPostage ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(264, 122) Me.Controls.Add(Me.txtCost) Me.Controls.Add(Me.lblCost) Me.Controls.Add(Me.btnCAC) Me.Controls.Add(Me.txtWeight) Me.Controls.Add(Me.lblWeight) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.MaximizeBox = False Me.Name = "frmPostage" Me.Text = "Postage" Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents lblWeight As System.Windows.Forms.Label Friend WithEvents txtWeight As System.Windows.Forms.TextBox Friend WithEvents btnCAC As System.Windows.Forms.Button Friend WithEvents lblCost As System.Windows.Forms.Label Friend WithEvents txtCost As System.Windows.Forms.TextBox End Class
patkub/visual-basic-intro
Postage/Postage/frmPostage.Designer.vb
Visual Basic
mit
3,625
Imports System Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim document As SolidEdgeFramework.SolidEdgeDocument = Nothing Dim variables As SolidEdgeFramework.Variables = Nothing Dim variable As SolidEdgeFramework.variable = Nothing Dim variableList As SolidEdgeFramework.VariableList = 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) document = CType(application.ActiveDocument, SolidEdgeFramework.SolidEdgeDocument) variables = CType(document.Variables, SolidEdgeFramework.Variables) Dim pFindCriterium As String = "*" Dim NamedBy As Object = SolidEdgeConstants.VariableNameBy.seVariableNameByBoth Dim VarType As Object = SolidEdgeConstants.VariableVarType.SeVariableVarTypeBoth Dim CaseInsensitive As Object = False ' Execute query. variableList = CType(variables.Query(pFindCriterium, NamedBy, VarType, CaseInsensitive), SolidEdgeFramework.VariableList) ' Add a new variable after the initial query. variable = CType(variables.Add("Test", "100.0", SolidEdgeConstants.UnitTypeConstants.igUnitDistance), SolidEdgeFramework.variable) ' Add the new variable to the VariableList. variableList.Add(variable) For i As Integer = 1 To variableList.Count Dim item = variableList.Item(i) ' Determine the runtime type of the object. Dim itemType = item.GetType() Dim objectType = CType(itemType.InvokeMember("Type", System.Reflection.BindingFlags.GetProperty, Nothing, item, Nothing), SolidEdgeFramework.ObjectType) Select Case objectType Case SolidEdgeFramework.ObjectType.igDimension Dim dimension = CType(item, SolidEdgeFrameworkSupport.Dimension) Case SolidEdgeFramework.ObjectType.igVariable variable = CType(item, SolidEdgeFramework.variable) End Select Next i Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeFramework.VariableList.Add.vb
Visual Basic
mit
2,876
 Option Explicit On Option Strict On Public Enum Token '' General UNKNOWN NUMBER IDENTIFIER '' Operators ADD_OPERATOR SUBTRACT_OPERATOR MULTIPLY_OPERATOR DIVIDE_OPERATOR MOD_OPERATOR NOT_OPERATOR EQUALS_OPERATOR '' Common Symbols OPEN_PARANTHESIS CLOSE_PARANTHESIS '' Type System VARIABLE_KEYWORD CONSTANT_KEYWORD AS_KEYWORD '' Terminators NEW_LINE EOF CLASS_KEYWORD End Enum
ananse/ananse
src/Token.vb
Visual Basic
mit
477
'*******************************************************************************************' ' ' ' 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 BytescoutImageToVideo Class Program Friend Shared Sub Main(args As String()) Try Console.WriteLine("Converting JPG slides to video, please wait...") For i As Integer = 0 To 4 ' Create BytescoutImageToVideoLib.ImageToVideo object instance Dim converter As New ImageToVideo() ' Activate the component converter.RegistrationName = "demo" converter.RegistrationKey = "demo" ' Set output video size converter.OutputWidth = 640 converter.OutputHeight = 480 ' Add images and set duration and effects for every slide Dim slide As Slide slide = converter.AddImageFromFileName("..\..\..\..\slide1.jpg") slide.Duration = 3000 ' 3000ms = 3s slide.InEffect = TransitionEffectType.teFade slide.OutEffect = TransitionEffectType.teFade Release(slide) ' useful to decrease memory consumption during the batch conversion but not critical slide = converter.AddImageFromFileName("..\..\..\..\slide2.jpg") slide.Duration = 3000 slide.InEffect = TransitionEffectType.teWipeLeft slide.OutEffect = TransitionEffectType.teWipeRight Release(slide) slide = converter.AddImageFromFileName("..\..\..\..\slide3.jpg") slide.Duration = 3000 slide.InEffect = TransitionEffectType.teWipeLeft slide.OutEffect = TransitionEffectType.teWipeRight Release(slide) ' Set output video file name converter.OutputVideoFileName = "result" & i & ".wmv" ' Run the conversion converter.RunAndWait() Console.WriteLine("Created " + converter.OutputVideoFileName) ' CRITICAL! ' Releases all resources consumed during the conversion Release(converter) Next Console.WriteLine("Done. Press any key to continue..") Console.ReadKey() Catch e As Exception Console.WriteLine("Error: " & e.ToString()) Console.WriteLine(vbLf & "Press any key to exit") Console.ReadKey() End Try End Sub Private Shared Sub Release(o As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(o) Catch Finally o = Nothing End Try End Sub End Class
bytescout/ByteScout-SDK-SourceCode
Image To Video SDK/VB.NET/Batch Video Generation/Program.vb
Visual Basic
apache-2.0
3,187
Imports bv.common.Core Imports bv.model.Model.Core Imports System.Data.Common Imports bv.common.db.Core Imports eidss.model.Core Imports EIDSS.model.Enums Public Class SampleDestruction_DB Inherits bv.common.db.BaseDbService Public Property DestroyMode As Boolean = False Public Sub New() End Sub Public Overrides Function GetDetail(ByVal ID As Object) As System.Data.DataSet Me.m_IsNewObject = True 'MyBase.GetDetail(ID) Dim ds As DataSet = New DataSet Dim rows As IEnumerable = CType(ID, IEnumerable) Dim cmd As IDbCommand If Not rows Is Nothing Then Dim table As DataTable = New DataTable("Samples") table.Columns.Add("idfMaterial", GetType(Long)) table.Columns.Add("strBarcode", GetType(String)) table.Columns.Add("strSampleName", GetType(String)) table.Columns.Add("idfsSampleStatus", GetType(Long)) table.Columns.Add("idfsDestructionMethod", GetType(Long)) table.PrimaryKey = New DataColumn() {table.Columns("idfMaterial")} For Each sample As IObject In rows Dim row As DataRow = table.NewRow For Each col As DataColumn In table.Columns Dim val As Object = sample.GetValue(col.ColumnName) If Not val Is Nothing Then If col.ColumnName = "idfsSampleStatus" Then If DestroyMode Then If Utils.Str(val) = CType(SampleStatus.Delete, Long).ToString() Then val = SampleStatus.IsDeleted Else val = SampleStatus.Destroyed End If Else val = SampleStatus.RoutineDestruction End If End If row(col.ColumnName) = val ElseIf col.ColumnName = "idfsDestructionMethod" AndAlso CLng(SampleStatus.Destroyed).Equals(row("idfsSampleStatus")) Then SetDefaultDestructionMethod(row) End If Next table.Rows.Add(row) Next table.TableName = "Samples" ds.Tables.Add(table) End If Dim user As DataTable = New DataTable("User") user.Columns.Add("idfDestroyedByPerson", GetType(Long)) user.PrimaryKey = New DataColumn() {user.Columns(0)} user.Rows.Add(New Object() {EIDSS.model.Core.EidssUserContext.User.EmployeeID}) ds.Tables.Add(user) cmd = CreateSPCommand("spLabSampleDestruction_SelectDetail") AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage) AddParam(cmd, "@destroy", DestroyMode) CreateAdapter(cmd).Fill(ds, "Status") Return ds End Function Public Shared Sub SetDefaultDestructionMethod(row As DataRow) Dim view As DataView = LookupCache.Get(db.BaseReferenceType.rftDestructionMethod) If view.Count > 1 Then row("idfsDestructionMethod") = view(1)("idfsReference") row.EndEdit() End If End Sub Public Overrides Function PostDetail(ByVal ds As System.Data.DataSet, ByVal postType As Integer, Optional ByVal transaction As System.Data.IDbTransaction = Nothing) As Boolean Dim person As Object = ds.Tables("User").Rows(0)("idfDestroyedByPerson") Dim table As DataTable = ds.Tables("Samples") For Each row As DataRow In table.Rows If row.RowState = DataRowState.Deleted Then Continue For Dim cmd As IDbCommand = CreateSPCommand("spLabSampleDestruction_Post", transaction) AddParam(cmd, "idfMaterial", row("idfMaterial"), ParameterDirection.Input) AddParam(cmd, "@idfsSampleStatus", row("idfsSampleStatus"), ParameterDirection.Input) AddParam(cmd, "@idfsDestructionMethod", row("idfsDestructionMethod"), ParameterDirection.Input) AddParam(cmd, "@idfDestroyedByPerson", person, ParameterDirection.Input) AddParam(cmd, "@destroy", Me.DestroyMode, ParameterDirection.Input) AddParam(cmd, "@idfMarkedForDispositionByPerson", EidssUserContext.User.EmployeeID, ParameterDirection.Input) cmd.ExecuteNonQuery() Next Return True End Function ' Public Overrides Function CanDelete(ByVal ID As Object, Optional ByVal aObjectName As String = Nothing, Optional ByVal transaction As System.Data.IDbTransaction = Nothing) As Boolean ' Return True ' End Function Public Overrides Function Delete(ByVal ID As Object, ByVal transaction As System.Data.IDbTransaction, ByVal name As String) As Boolean 'Dim rows As DataRow() = CType(ID, DataRow()) 'For Each row As DataRow In rows Dim cmd As IDbCommand = CreateSPCommand("spLabSampleDestruction_Delete", Connection, transaction) If AddParam(cmd, "@ID", ID, m_Error) Is Nothing Then Return (False) m_Error = ExecCommand(cmd, Connection, transaction) If Not m_Error Is Nothing Then Return False 'Next Return True End Function End Class
EIDSS/EIDSS-Legacy
EIDSS v6/vb/EIDSS/EIDSS_Limps_db/Destruction/SampleDestruction_DB.vb
Visual Basic
bsd-2-clause
5,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 System.Composition Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic <ExportLanguageService(GetType(ISyntaxFactsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxFactsService Implements ISyntaxFactsService Public Function IsAwaitKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsAwaitKeyword Return token.Kind = SyntaxKind.AwaitKeyword End Function Public Function IsIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsIdentifier Return token.Kind = SyntaxKind.IdentifierToken End Function Public Function IsGlobalNamespaceKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsGlobalNamespaceKeyword Return token.Kind = SyntaxKind.GlobalKeyword End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsKeyword Return token.IsKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsHashToken(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsHashToken Return token.Kind = SyntaxKind.HashToken End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFactsService.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.Item1 Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsInInactiveRegion(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.IsInInactiveRegion Dim vbTree = TryCast(syntaxTree, SyntaxTree) If vbTree Is Nothing Then Return False End If Return vbTree.IsInInactiveRegion(position, cancellationToken) End Function Public Function IsInNonUserCode(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.IsInNonUserCode Dim vbTree = TryCast(syntaxTree, SyntaxTree) If vbTree Is Nothing Then Return False End If Return vbTree.IsInNonUserCode(position, cancellationToken) End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.IsEntirelyWithinStringOrCharOrNumericLiteral Dim vbTree = TryCast(syntaxTree, SyntaxTree) If vbTree Is Nothing Then Return False End If Return vbTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFactsService.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsMemberAccessExpressionName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsMemberAccessExpressionName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsMemberAccessExpressionName() End Function Public Function IsConditionalMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsConditionalMemberAccessExpression Return TypeOf node Is ConditionalAccessExpressionSyntax End Function Public Function IsInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInvocationExpression Return TypeOf node Is InvocationExpressionSyntax End Function Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsGenericName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsGenericName Return TypeOf node Is GenericNameSyntax End Function Public Function IsNamedParameter(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsNamedParameter Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function IsSkippedTokensTrivia(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsSkippedTokensTrivia Return TypeOf node Is SkippedTokensTriviaSyntax End Function Public Function HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.HasIncompleteParentMember Return node.IsParentKind(SyntaxKind.IncompleteMember) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFactsService.GetIdentifierOfGenericName Dim vbGenericName = TryCast(genericName, GenericNameSyntax) Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing) End Function Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFactsService.IsCaseSensitive Get Return False End Get End Property Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsForEachStatement Return TypeOf node Is ForEachStatementSyntax End Function Public Function IsLockStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLockStatement Return TypeOf node Is SyncLockStatementSyntax End Function Public Function IsUsingStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsUsingStatement Return TypeOf node Is UsingStatementSyntax End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsQueryExpression Return TypeOf node Is QueryExpressionSyntax End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFactsService.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFactsService.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFactsService.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFactsService.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFactsService.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFactsService.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFactsService.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFactsService.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFactsService.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFactsService.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFactsService.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFactsService.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFactsService.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsMemberAccessExpression Return TypeOf node Is MemberAccessExpressionSyntax AndAlso DirectCast(node, MemberAccessExpressionSyntax).Kind = SyntaxKind.SimpleMemberAccessExpression End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFactsService.GetNameAndArityOfSimpleName Dim simpleName = TryCast(node, SimpleNameSyntax) If simpleName IsNot Nothing Then name = simpleName.Identifier.ValueText arity = simpleName.Arity End If End Sub Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFactsService.GetExpressionOfMemberAccessExpression Return DirectCast(node, MemberAccessExpressionSyntax).GetExpressionOfMemberAccessExpression() End Function Public Function GetExpressionOfConditionalMemberAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfConditionalMemberAccessExpression Return TryCast(node, ConditionalAccessExpressionSyntax)?.Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFactsService.GetExpressionOfArgument Return TryCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFactsService.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to to determine this. Return RefKind.None End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFactsService.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function IsAttribute(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAttribute Return TypeOf node Is AttributeSyntax End Function Public Function IsAttributeNamedArgumentIdentifier(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) If identifierName IsNot Nothing Then Dim simpleArgument = TryCast(identifierName.Parent, SimpleArgumentSyntax) If simpleArgument IsNot Nothing AndAlso simpleArgument.IsNamed AndAlso identifierName Is simpleArgument.NameColonEquals.Name Then Return simpleArgument.Parent.IsParentKind(SyntaxKind.Attribute) End If End If Return False End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFactsService.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFactsService.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFactsService.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsObjectCreationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsObjectCreationExpression Return TypeOf node Is ObjectCreationExpressionSyntax End Function Public Function IsObjectInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsObjectInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) Return If(identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name), False) End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Function ConvertToSingleLine(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.ConvertToSingleLine Return node.ConvertToSingleLine() End Function Public Function ToIdentifierToken(name As String) As SyntaxToken Implements ISyntaxFactsService.ToIdentifierToken Return name.ToIdentifierToken() End Function Public Function Parenthesize(expression As SyntaxNode, Optional includeElasticTrivia As Boolean = True) As SyntaxNode Implements ISyntaxFactsService.Parenthesize Return DirectCast(expression, ExpressionSyntax).Parenthesize() End Function Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFactsService.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsMethodLevelMember If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If Return TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFactsService.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If Return TextSpan.FromBounds(method.BlockStatement.Span.End, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFactsService.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Contract.Requires(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Contract.Requires(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFactsService.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMethodLevelMembers(root, list) Return list End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Public Function TryGetDeclaredSymbolInfo(node As SyntaxNode, ByRef declaredSymbolInfo As DeclaredSymbolInfo) As Boolean Implements ISyntaxFactsService.TryGetDeclaredSymbolInfo Select Case node.Kind() Case SyntaxKind.ClassBlock Dim classDecl = CType(node, ClassBlockSyntax) declaredSymbolInfo = New DeclaredSymbolInfo(classDecl.ClassStatement.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Class, classDecl.ClassStatement.Identifier.Span) Return True Case SyntaxKind.ConstructorBlock Dim constructor = CType(node, ConstructorBlockSyntax) Dim typeBlock = TryCast(constructor.Parent, TypeBlockSyntax) If typeBlock IsNot Nothing Then declaredSymbolInfo = New DeclaredSymbolInfo( typeBlock.BlockStatement.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Constructor, constructor.SubNewStatement.NewKeyword.Span, parameterCount:=CType(If(constructor.SubNewStatement.ParameterList?.Parameters.Count, 0), UShort)) Return True End If Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Dim delegateDecl = CType(node, DelegateStatementSyntax) declaredSymbolInfo = New DeclaredSymbolInfo(delegateDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span) Return True Case SyntaxKind.EnumBlock Dim enumDecl = CType(node, EnumBlockSyntax) declaredSymbolInfo = New DeclaredSymbolInfo(enumDecl.EnumStatement.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Enum, enumDecl.EnumStatement.Identifier.Span) Return True Case SyntaxKind.EnumMemberDeclaration Dim enumMember = CType(node, EnumMemberDeclarationSyntax) declaredSymbolInfo = New DeclaredSymbolInfo(enumMember.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span) Return True Case SyntaxKind.EventStatement Dim eventDecl = CType(node, EventStatementSyntax) Dim eventParent = If(TypeOf node.Parent Is EventBlockSyntax, node.Parent.Parent, node.Parent) declaredSymbolInfo = New DeclaredSymbolInfo(eventDecl.Identifier.ValueText, GetContainerDisplayName(eventParent), GetFullyQualifiedContainerName(eventParent), DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span) Return True Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Dim funcDecl = CType(node, MethodBlockSyntax) declaredSymbolInfo = New DeclaredSymbolInfo( funcDecl.SubOrFunctionStatement.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Method, funcDecl.SubOrFunctionStatement.Identifier.Span, parameterCount:=CType(If(funcDecl.SubOrFunctionStatement.ParameterList?.Parameters.Count, 0), UShort), typeParameterCount:=CType(If(funcDecl.SubOrFunctionStatement.TypeParameterList?.Parameters.Count, 0), UShort)) Return True Case SyntaxKind.InterfaceBlock Dim interfaceDecl = CType(node, InterfaceBlockSyntax) declaredSymbolInfo = New DeclaredSymbolInfo(interfaceDecl.InterfaceStatement.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Interface, interfaceDecl.InterfaceStatement.Identifier.Span) Return True Case SyntaxKind.ModifiedIdentifier Dim modifiedIdentifier = CType(node, ModifiedIdentifierSyntax) Dim variableDeclarator = TryCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax) Dim fieldDecl = TryCast(variableDeclarator?.Parent, FieldDeclarationSyntax) If fieldDecl IsNot Nothing Then Dim kind = If(fieldDecl.Modifiers.Any(Function(m) m.Kind() = SyntaxKind.ConstKeyword), DeclaredSymbolInfoKind.Constant, DeclaredSymbolInfoKind.Field) declaredSymbolInfo = New DeclaredSymbolInfo(modifiedIdentifier.Identifier.ValueText, GetContainerDisplayName(fieldDecl.Parent), GetFullyQualifiedContainerName(fieldDecl.Parent), kind, modifiedIdentifier.Identifier.Span) Return True End If Case SyntaxKind.ModuleBlock Dim moduleDecl = CType(node, ModuleBlockSyntax) declaredSymbolInfo = New DeclaredSymbolInfo(moduleDecl.ModuleStatement.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Module, moduleDecl.ModuleStatement.Identifier.Span) Return True Case SyntaxKind.PropertyStatement Dim propertyDecl = CType(node, PropertyStatementSyntax) Dim propertyParent = If(TypeOf node.Parent Is PropertyBlockSyntax, node.Parent.Parent, node.Parent) declaredSymbolInfo = New DeclaredSymbolInfo(propertyDecl.Identifier.ValueText, GetContainerDisplayName(propertyParent), GetFullyQualifiedContainerName(propertyParent), DeclaredSymbolInfoKind.Property, propertyDecl.Identifier.Span) Return True Case SyntaxKind.StructureBlock Dim structDecl = CType(node, StructureBlockSyntax) declaredSymbolInfo = New DeclaredSymbolInfo(structDecl.StructureStatement.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Struct, structDecl.StructureStatement.Identifier.Span) Return True End Select declaredSymbolInfo = Nothing Return False End Function Private Shared Function GetContainerDisplayName(node As SyntaxNode) As String Return GetContainer(node, immediate:=True) End Function Private Shared Function GetFullyQualifiedContainerName(node As SyntaxNode) As String Return GetContainer(node, immediate:=False) End Function Private Shared Function GetContainer(node As SyntaxNode, immediate As Boolean) As String If node Is Nothing Then Return String.Empty End If Dim name = GetNodeName(node, includeTypeParameters:=immediate) Dim names = New List(Of String) From {name} Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax Dim currentParent = CType(parent, TypeBlockSyntax) Dim typeName = currentParent.BlockStatement.Identifier.ValueText names.Add(If(immediate, typeName + ExpandTypeParameterList(currentParent.BlockStatement.TypeParameterList), typeName)) parent = currentParent.Parent End While ' If they're just asking for the immediate parent, then we're done. Otherwise keep ' walking all the way to the root, adding the names. If Not immediate Then While parent IsNot Nothing AndAlso parent.Kind() <> SyntaxKind.CompilationUnit names.Add(GetNodeName(parent, includeTypeParameters:=False)) parent = parent.Parent End While End If names.Reverse() Return String.Join(".", names) End Function Private Shared Function GetNodeName(node As SyntaxNode, includeTypeParameters As Boolean) As String Dim name As String Dim typeParameterList As TypeParameterListSyntax Select Case node.Kind() Case SyntaxKind.ClassBlock Dim classDecl = CType(node, ClassBlockSyntax) name = classDecl.ClassStatement.Identifier.ValueText typeParameterList = classDecl.ClassStatement.TypeParameterList Case SyntaxKind.CompilationUnit Return String.Empty Case SyntaxKind.EnumBlock Return CType(node, EnumBlockSyntax).EnumStatement.Identifier.ValueText Case SyntaxKind.IdentifierName Return CType(node, IdentifierNameSyntax).Identifier.ValueText Case SyntaxKind.InterfaceBlock Dim interfaceDecl = CType(node, InterfaceBlockSyntax) name = interfaceDecl.InterfaceStatement.Identifier.ValueText typeParameterList = interfaceDecl.InterfaceStatement.TypeParameterList Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Dim methodDecl = CType(node, MethodBlockSyntax) name = methodDecl.SubOrFunctionStatement.Identifier.ValueText typeParameterList = methodDecl.SubOrFunctionStatement.TypeParameterList Case SyntaxKind.ModuleBlock Dim moduleDecl = CType(node, ModuleBlockSyntax) name = moduleDecl.ModuleStatement.Identifier.ValueText typeParameterList = moduleDecl.ModuleStatement.TypeParameterList Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then Return Nothing Else Return GetNodeName(nameSyntax, includeTypeParameters:=False) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then Return GetNodeName(qualified.Right, includeTypeParameters:=False) ' don't use the Global prefix if specified Else Return GetNodeName(qualified.Left, includeTypeParameters:=False) + "." + GetNodeName(qualified.Right, includeTypeParameters:=False) End If Case SyntaxKind.StructureBlock Dim structDecl = CType(node, StructureBlockSyntax) name = structDecl.StructureStatement.Identifier.ValueText typeParameterList = structDecl.StructureStatement.TypeParameterList Case Else Debug.Assert(False, "Unexpected node type " + node.Kind().ToString()) Return Nothing End Select Return If(includeTypeParameters, name + ExpandTypeParameterList(typeParameterList), name) End Function Private Shared Function ExpandTypeParameterList(typeParameterList As TypeParameterListSyntax) As String If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then Dim builder = New StringBuilder() builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.ValueText) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(","c) builder.Append(typeParameterList.Parameters(i).Identifier.ValueText) Next builder.Append(")"c) Return builder.ToString() Else Return Nothing End If End Function Private Sub AppendMethodLevelMembers(node As SyntaxNode, list As List(Of SyntaxNode)) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then AppendMethodLevelMembers(member, list) Continue For End If If IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function GetMethodLevelMemberId(root As SyntaxNode, node As SyntaxNode) As Integer Implements ISyntaxFactsService.GetMethodLevelMemberId Contract.Requires(root.SyntaxTree Is node.SyntaxTree) Dim currentId As Integer = Nothing Dim currentNode As SyntaxNode = Nothing Contract.ThrowIfFalse(TryGetMethodLevelMember(root, Function(n, i) n Is node, currentId, currentNode)) Contract.ThrowIfFalse(currentId >= 0) CheckMemberId(root, node, currentId) Return currentId End Function Public Function GetMethodLevelMember(root As SyntaxNode, memberId As Integer) As SyntaxNode Implements ISyntaxFactsService.GetMethodLevelMember Dim currentId As Integer = Nothing Dim currentNode As SyntaxNode = Nothing If Not TryGetMethodLevelMember(root, Function(n, i) i = memberId, currentId, currentNode) Then Return Nothing End If Contract.ThrowIfNull(currentNode) CheckMemberId(root, currentNode, memberId) Return currentNode End Function Private Function TryGetMethodLevelMember(node As SyntaxNode, predicate As Func(Of SyntaxNode, Integer, Boolean), ByRef currentId As Integer, ByRef currentNode As SyntaxNode) As Boolean For Each member In node.GetMembers() If TypeOf member Is NamespaceBlockSyntax OrElse TypeOf member Is TypeBlockSyntax OrElse TypeOf member Is EnumBlockSyntax Then If TryGetMethodLevelMember(member, predicate, currentId, currentNode) Then Return True End If Continue For End If If IsMethodLevelMember(member) Then If predicate(member, currentId) Then currentNode = member Return True End If currentId = currentId + 1 End If Next currentNode = Nothing Return False End Function <Conditional("DEBUG")> Private Sub CheckMemberId(root As SyntaxNode, node As SyntaxNode, memberId As Integer) Dim list = GetMethodLevelMembers(root) Dim index = list.IndexOf(node) Contract.ThrowIfFalse(index = memberId) End Sub Public Function GetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFactsService.GetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFactsService.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub End Class End Namespace
furesoft/roslyn
src/Workspaces/VisualBasic/Portable/LanguageServices/VisualBasicSyntaxFactsService.vb
Visual Basic
apache-2.0
58,878
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Globalization Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Editting Public Class SyntaxGeneratorTests Private ReadOnly _g As SyntaxGenerator = SyntaxGenerator.GetGenerator(New AdhocWorkspace(), LanguageNames.VisualBasic) Private ReadOnly _emptyCompilation As VisualBasicCompilation = VisualBasicCompilation.Create("empty", references:={TestReferences.NetFx.v4_0_30319.mscorlib}) Private _ienumerableInt As INamedTypeSymbol Public Sub New() Me._ienumerableInt = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).Construct(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)) End Sub Public Function Compile(code As String) As Compilation code = code.Replace(vbLf, vbCrLf) Return VisualBasicCompilation.Create("test").AddReferences(TestReferences.NetFx.v4_0_30319.mscorlib).AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)) End Function Private Sub VerifySyntax(Of TSyntax As SyntaxNode)(type As SyntaxNode, expectedText As String) Assert.IsAssignableFrom(GetType(TSyntax), type) Dim normalized = type.NormalizeWhitespace().ToFullString() Dim fixedExpectations = expectedText.Replace(vbLf, vbCrLf) Assert.Equal(fixedExpectations, normalized) End Sub Private Function ParseCompilationUnit(text As String) As CompilationUnitSyntax Dim fixedText = text.Replace(vbLf, vbCrLf) Return SyntaxFactory.ParseCompilationUnit(fixedText) End Function <Fact> Public Sub TestLiteralExpressions() VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(0), "0") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(1), "1") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(-1), "-1") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Integer.MinValue), "Global.System.Int32.MinValue") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Integer.MaxValue), "Global.System.Int32.MaxValue") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(0L), "0L") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(1L), "1L") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(-1L), "-1L") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Long.MinValue), "Global.System.Int64.MinValue") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Long.MaxValue), "Global.System.Int64.MaxValue") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(0UL), "0UL") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(1UL), "1UL") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(ULong.MinValue), "0UL") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(ULong.MaxValue), "Global.System.UInt64.MaxValue") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(0.0F), "0F") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(1.0F), "1F") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(-1.0F), "-1F") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Single.MinValue), "Global.System.Single.MinValue") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Single.MaxValue), "Global.System.Single.MaxValue") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Single.Epsilon), "Global.System.Single.Epsilon") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Single.NaN), "Global.System.Single.NaN") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Single.NegativeInfinity), "Global.System.Single.NegativeInfinity") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Single.PositiveInfinity), "Global.System.Single.PositiveInfinity") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(0.0), "0R") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(1.0), "1R") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(-1.0), "-1R") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Double.MinValue), "Global.System.Double.MinValue") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Double.MaxValue), "Global.System.Double.MaxValue") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Double.Epsilon), "Global.System.Double.Epsilon") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Double.NaN), "Global.System.Double.NaN") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Double.NegativeInfinity), "Global.System.Double.NegativeInfinity") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Double.PositiveInfinity), "Global.System.Double.PositiveInfinity") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(0D), "0D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(0.00D), "0.00D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("1.00", CultureInfo.InvariantCulture)), "1.00D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("-1.00", CultureInfo.InvariantCulture)), "-1.00D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("1.0000000000", CultureInfo.InvariantCulture)), "1.0000000000D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("0.000000", CultureInfo.InvariantCulture)), "0.000000D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("0.0000000", CultureInfo.InvariantCulture)), "0.0000000D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(1000000000D), "1000000000D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(123456789.123456789D), "123456789.123456789D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("1E-28", NumberStyles.Any, CultureInfo.InvariantCulture)), "0.0000000000000000000000000001D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("0E-28", NumberStyles.Any, CultureInfo.InvariantCulture)), "0.0000000000000000000000000000D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("1E-29", NumberStyles.Any, CultureInfo.InvariantCulture)), "0.0000000000000000000000000000D") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(Decimal.Parse("-1E-29", NumberStyles.Any, CultureInfo.InvariantCulture)), "0.0000000000000000000000000000D") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Decimal.MinValue), "Global.System.Decimal.MinValue") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.LiteralExpression(Decimal.MaxValue), "Global.System.Decimal.MaxValue") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression("c"c), """c""c") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression("str"), """str""") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(True), "True") VerifySyntax(Of LiteralExpressionSyntax)(_g.LiteralExpression(False), "False") End Sub <Fact> Public Sub TestNameExpressions() VerifySyntax(Of IdentifierNameSyntax)(_g.IdentifierName("x"), "x") VerifySyntax(Of QualifiedNameSyntax)(_g.QualifiedName(_g.IdentifierName("x"), _g.IdentifierName("y")), "x.y") VerifySyntax(Of QualifiedNameSyntax)(_g.DottedName("x.y"), "x.y") VerifySyntax(Of GenericNameSyntax)(_g.GenericName("x", _g.IdentifierName("y")), "x(Of y)") VerifySyntax(Of GenericNameSyntax)(_g.GenericName("x", _g.IdentifierName("y"), _g.IdentifierName("z")), "x(Of y, z)") ' convert identifer name into generic name VerifySyntax(Of GenericNameSyntax)(_g.WithTypeArguments(_g.IdentifierName("x"), _g.IdentifierName("y")), "x(Of y)") ' convert qualified name into qualified generic name VerifySyntax(Of QualifiedNameSyntax)(_g.WithTypeArguments(_g.DottedName("x.y"), _g.IdentifierName("z")), "x.y(Of z)") ' convert member access expression into generic member access expression VerifySyntax(Of MemberAccessExpressionSyntax)(_g.WithTypeArguments(_g.MemberAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "x.y(Of z)") ' convert existing generic name into a different generic name Dim gname = _g.WithTypeArguments(_g.IdentifierName("x"), _g.IdentifierName("y")) VerifySyntax(Of GenericNameSyntax)(gname, "x(Of y)") VerifySyntax(Of GenericNameSyntax)(_g.WithTypeArguments(gname, _g.IdentifierName("z")), "x(Of z)") End Sub <Fact> Public Sub TestTypeExpressions() ' these are all type syntax too VerifySyntax(Of TypeSyntax)(_g.IdentifierName("x"), "x") VerifySyntax(Of TypeSyntax)(_g.QualifiedName(_g.IdentifierName("x"), _g.IdentifierName("y")), "x.y") VerifySyntax(Of TypeSyntax)(_g.DottedName("x.y"), "x.y") VerifySyntax(Of TypeSyntax)(_g.GenericName("x", _g.IdentifierName("y")), "x(Of y)") VerifySyntax(Of TypeSyntax)(_g.GenericName("x", _g.IdentifierName("y"), _g.IdentifierName("z")), "x(Of y, z)") VerifySyntax(Of TypeSyntax)(_g.ArrayTypeExpression(_g.IdentifierName("x")), "x()") VerifySyntax(Of TypeSyntax)(_g.ArrayTypeExpression(_g.ArrayTypeExpression(_g.IdentifierName("x"))), "x()()") VerifySyntax(Of TypeSyntax)(_g.NullableTypeExpression(_g.IdentifierName("x")), "x?") VerifySyntax(Of TypeSyntax)(_g.NullableTypeExpression(_g.NullableTypeExpression(_g.IdentifierName("x"))), "x?") End Sub <Fact> Public Sub TestSpecialTypeExpression() VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Byte), "Byte") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_SByte), "SByte") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Int16), "Short") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_UInt16), "UShort") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Int32), "Integer") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_UInt32), "UInteger") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Int64), "Long") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_UInt64), "ULong") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Single), "Single") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Double), "Double") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Char), "Char") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_String), "String") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Object), "Object") VerifySyntax(Of TypeSyntax)(_g.TypeExpression(SpecialType.System_Decimal), "Decimal") End Sub <Fact> Public Sub TestSymbolTypeExpressions() Dim genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T) VerifySyntax(Of QualifiedNameSyntax)(_g.TypeExpression(genericType), "Global.System.Collections.Generic.IEnumerable(Of T)") Dim arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)) VerifySyntax(Of ArrayTypeSyntax)(_g.TypeExpression(arrayType), "System.Int32()") End Sub <Fact> Public Sub TestMathAndLogicExpressions() VerifySyntax(Of UnaryExpressionSyntax)(_g.NegateExpression(_g.IdentifierName("x")), "-(x)") VerifySyntax(Of BinaryExpressionSyntax)(_g.AddExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) + (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.SubtractExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) - (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.MultiplyExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) * (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.DivideExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) / (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.ModuloExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) Mod (y)") VerifySyntax(Of UnaryExpressionSyntax)(_g.BitwiseNotExpression(_g.IdentifierName("x")), "Not(x)") VerifySyntax(Of BinaryExpressionSyntax)(_g.BitwiseAndExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) And (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.BitwiseOrExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) Or (y)") VerifySyntax(Of UnaryExpressionSyntax)(_g.LogicalNotExpression(_g.IdentifierName("x")), "Not(x)") VerifySyntax(Of BinaryExpressionSyntax)(_g.LogicalAndExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) AndAlso (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.LogicalOrExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) OrElse (y)") End Sub <Fact> Public Sub TestEqualityAndInequalityExpressions() VerifySyntax(Of BinaryExpressionSyntax)(_g.ReferenceEqualsExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) Is (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.ValueEqualsExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) = (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.ReferenceNotEqualsExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) IsNot (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.ValueNotEqualsExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) <> (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.LessThanExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) < (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.LessThanOrEqualExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) <= (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.GreaterThanExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) > (y)") VerifySyntax(Of BinaryExpressionSyntax)(_g.GreaterThanOrEqualExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "(x) >= (y)") End Sub <Fact> Public Sub TestConditionalExpressions() VerifySyntax(Of BinaryConditionalExpressionSyntax)(_g.CoalesceExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "If(x, y)") VerifySyntax(Of TernaryConditionalExpressionSyntax)(_g.ConditionalExpression(_g.IdentifierName("x"), _g.IdentifierName("y"), _g.IdentifierName("z")), "If(x, y, z)") End Sub <Fact> Public Sub TestMemberAccessExpressions() VerifySyntax(Of MemberAccessExpressionSyntax)(_g.MemberAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "x.y") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.MemberAccessExpression(_g.IdentifierName("x"), "y"), "x.y") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.MemberAccessExpression(_g.MemberAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "x.y.z") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.MemberAccessExpression(_g.InvocationExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "x(y).z") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.MemberAccessExpression(_g.ElementAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "x(y).z") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.MemberAccessExpression(_g.AddExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "((x) + (y)).z") VerifySyntax(Of MemberAccessExpressionSyntax)(_g.MemberAccessExpression(_g.NegateExpression(_g.IdentifierName("x")), _g.IdentifierName("y")), "(-(x)).y") End Sub <Fact> Public Sub TestObjectCreationExpressions() VerifySyntax(Of ObjectCreationExpressionSyntax)( _g.ObjectCreationExpression(_g.IdentifierName("x")), "New x()") VerifySyntax(Of ObjectCreationExpressionSyntax)( _g.ObjectCreationExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "New x(y)") Dim intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32) Dim listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1") Dim listOfIntType = listType.Construct(intType) VerifySyntax(Of ObjectCreationExpressionSyntax)( _g.ObjectCreationExpression(listOfIntType, _g.IdentifierName("y")), "New Global.System.Collections.Generic.List(Of System.Int32)(y)") End Sub <Fact> Public Sub TestElementAccessExpressions() VerifySyntax(Of InvocationExpressionSyntax)( _g.ElementAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "x(y)") VerifySyntax(Of InvocationExpressionSyntax)( _g.ElementAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y"), _g.IdentifierName("z")), "x(y, z)") VerifySyntax(Of InvocationExpressionSyntax)( _g.ElementAccessExpression(_g.MemberAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "x.y(z)") VerifySyntax(Of InvocationExpressionSyntax)( _g.ElementAccessExpression(_g.ElementAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "x(y)(z)") VerifySyntax(Of InvocationExpressionSyntax)( _g.ElementAccessExpression(_g.InvocationExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "x(y)(z)") VerifySyntax(Of InvocationExpressionSyntax)( _g.ElementAccessExpression(_g.AddExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), _g.IdentifierName("z")), "((x) + (y))(z)") End Sub <Fact> Public Sub TestCastAndConvertExpressions() VerifySyntax(Of DirectCastExpressionSyntax)(_g.CastExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "DirectCast(y, x)") VerifySyntax(Of CTypeExpressionSyntax)(_g.ConvertExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "CType(y, x)") End Sub <Fact> Public Sub TestIsAndAsExpressions() VerifySyntax(Of TypeOfExpressionSyntax)(_g.IsTypeExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "TypeOf(x) Is y") VerifySyntax(Of TryCastExpressionSyntax)(_g.TryCastExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "TryCast(x, y)") End Sub <Fact> Public Sub TestInvocationExpressions() ' without explicit arguments VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.IdentifierName("x")), "x()") VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.IdentifierName("x"), _g.IdentifierName("y")), "x(y)") VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.IdentifierName("x"), _g.IdentifierName("y"), _g.IdentifierName("z")), "x(y, z)") ' using explicit arguments VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.IdentifierName("x"), _g.Argument(_g.IdentifierName("y"))), "x(y)") VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.IdentifierName("x"), _g.Argument(RefKind.Ref, _g.IdentifierName("y"))), "x(y)") VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.IdentifierName("x"), _g.Argument(RefKind.Out, _g.IdentifierName("y"))), "x(y)") VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.MemberAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y"))), "x.y()") VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.ElementAccessExpression(_g.IdentifierName("x"), _g.IdentifierName("y"))), "x(y)()") VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.InvocationExpression(_g.IdentifierName("x"), _g.IdentifierName("y"))), "x(y)()") VerifySyntax(Of InvocationExpressionSyntax)(_g.InvocationExpression(_g.AddExpression(_g.IdentifierName("x"), _g.IdentifierName("y"))), "((x) + (y))()") End Sub <Fact> Public Sub TestAssignmentStatement() VerifySyntax(Of AssignmentStatementSyntax)(_g.AssignmentStatement(_g.IdentifierName("x"), _g.IdentifierName("y")), "x = y") End Sub <Fact> Public Sub TestExpressionStatement() VerifySyntax(Of ExpressionStatementSyntax)(_g.ExpressionStatement(_g.IdentifierName("x")), "x") VerifySyntax(Of ExpressionStatementSyntax)(_g.ExpressionStatement(_g.InvocationExpression(_g.IdentifierName("x"))), "x()") End Sub <Fact> Public Sub TestLocalDeclarationStatements() VerifySyntax(Of LocalDeclarationStatementSyntax)(_g.LocalDeclarationStatement(_g.IdentifierName("x"), "y"), "Dim y As x") VerifySyntax(Of LocalDeclarationStatementSyntax)(_g.LocalDeclarationStatement(_g.IdentifierName("x"), "y", _g.IdentifierName("z")), "Dim y As x = z") VerifySyntax(Of LocalDeclarationStatementSyntax)(_g.LocalDeclarationStatement("y", _g.IdentifierName("z")), "Dim y = z") VerifySyntax(Of LocalDeclarationStatementSyntax)(_g.LocalDeclarationStatement(_g.IdentifierName("x"), "y", isConst:=True), "Const y As x") VerifySyntax(Of LocalDeclarationStatementSyntax)(_g.LocalDeclarationStatement(_g.IdentifierName("x"), "y", _g.IdentifierName("z"), isConst:=True), "Const y As x = z") VerifySyntax(Of LocalDeclarationStatementSyntax)(_g.LocalDeclarationStatement(DirectCast(Nothing, SyntaxNode), "y", _g.IdentifierName("z"), isConst:=True), "Const y = z") End Sub <Fact> Public Sub TestReturnStatements() VerifySyntax(Of ReturnStatementSyntax)(_g.ReturnStatement(), "Return") VerifySyntax(Of ReturnStatementSyntax)(_g.ReturnStatement(_g.IdentifierName("x")), "Return x") End Sub <Fact> Public Sub TestThrowStatements() VerifySyntax(Of ThrowStatementSyntax)(_g.ThrowStatement(), "Throw") VerifySyntax(Of ThrowStatementSyntax)(_g.ThrowStatement(_g.IdentifierName("x")), "Throw x") End Sub <Fact> Public Sub TestIfStatements() VerifySyntax(Of MultiLineIfBlockSyntax)( _g.IfStatement(_g.IdentifierName("x"), New SyntaxNode() {}), <x>If x Then End If</x>.Value) VerifySyntax(Of MultiLineIfBlockSyntax)( _g.IfStatement(_g.IdentifierName("x"), Nothing), <x>If x Then End If</x>.Value) VerifySyntax(Of MultiLineIfBlockSyntax)( _g.IfStatement(_g.IdentifierName("x"), New SyntaxNode() {}, New SyntaxNode() {}), <x>If x Then Else End If</x>.Value) VerifySyntax(Of MultiLineIfBlockSyntax)( _g.IfStatement(_g.IdentifierName("x"), {_g.IdentifierName("y")}), <x>If x Then y End If</x>.Value) VerifySyntax(Of MultiLineIfBlockSyntax)( _g.IfStatement(_g.IdentifierName("x"), {_g.IdentifierName("y")}, {_g.IdentifierName("z")}), <x>If x Then y Else z End If</x>.Value) VerifySyntax(Of MultiLineIfBlockSyntax)( _g.IfStatement(_g.IdentifierName("x"), {_g.IdentifierName("y")}, {_g.IfStatement(_g.IdentifierName("p"), {_g.IdentifierName("q")})}), <x>If x Then y ElseIf p Then q End If</x>.Value) VerifySyntax(Of MultiLineIfBlockSyntax)( _g.IfStatement(_g.IdentifierName("x"), {_g.IdentifierName("y")}, _g.IfStatement(_g.IdentifierName("p"), {_g.IdentifierName("q")}, {_g.IdentifierName("z")})), <x>If x Then y ElseIf p Then q Else z End If</x>.Value) End Sub <Fact> Public Sub TestSwitchStatements() Dim x = 10 VerifySyntax(Of SelectBlockSyntax)( _g.SwitchStatement(_g.IdentifierName("x"), _g.SwitchSection(_g.IdentifierName("y"), {_g.IdentifierName("z")})), <x>Select x Case y z End Select</x>.Value) VerifySyntax(Of SelectBlockSyntax)( _g.SwitchStatement(_g.IdentifierName("x"), _g.SwitchSection( {_g.IdentifierName("y"), _g.IdentifierName("p"), _g.IdentifierName("q")}, {_g.IdentifierName("z")})), <x>Select x Case y, p, q z End Select</x>.Value) VerifySyntax(Of SelectBlockSyntax)( _g.SwitchStatement(_g.IdentifierName("x"), _g.SwitchSection(_g.IdentifierName("y"), {_g.IdentifierName("z")}), _g.SwitchSection(_g.IdentifierName("a"), {_g.IdentifierName("b")})), <x>Select x Case y z Case a b End Select</x>.Value) VerifySyntax(Of SelectBlockSyntax)( _g.SwitchStatement(_g.IdentifierName("x"), _g.SwitchSection(_g.IdentifierName("y"), {_g.IdentifierName("z")}), _g.DefaultSwitchSection( {_g.IdentifierName("b")})), <x>Select x Case y z Case Else b End Select</x>.Value) VerifySyntax(Of SelectBlockSyntax)( _g.SwitchStatement(_g.IdentifierName("x"), _g.SwitchSection(_g.IdentifierName("y"), {_g.ExitSwitchStatement()})), <x>Select x Case y Exit Select End Select</x>.Value) End Sub <Fact> Public Sub TestUsingStatements() VerifySyntax(Of UsingBlockSyntax)( _g.UsingStatement(_g.IdentifierName("x"), {_g.IdentifierName("y")}), <x>Using x y End Using</x>.Value) VerifySyntax(Of UsingBlockSyntax)( _g.UsingStatement("x", _g.IdentifierName("y"), {_g.IdentifierName("z")}), <x>Using x = y z End Using</x>.Value) VerifySyntax(Of UsingBlockSyntax)( _g.UsingStatement(_g.IdentifierName("x"), "y", _g.IdentifierName("z"), {_g.IdentifierName("q")}), <x>Using y As x = z q End Using</x>.Value) End Sub <Fact> Public Sub TestTryCatchStatements() VerifySyntax(Of TryBlockSyntax)( _g.TryCatchStatement( {_g.IdentifierName("x")}, _g.CatchClause(_g.IdentifierName("y"), "z", {_g.IdentifierName("a")})), <x>Try x Catch z As y a End Try</x>.Value) VerifySyntax(Of TryBlockSyntax)( _g.TryCatchStatement( {_g.IdentifierName("s")}, _g.CatchClause(_g.IdentifierName("x"), "y", {_g.IdentifierName("z")}), _g.CatchClause(_g.IdentifierName("a"), "b", {_g.IdentifierName("c")})), <x>Try s Catch y As x z Catch b As a c End Try</x>.Value) VerifySyntax(Of TryBlockSyntax)( _g.TryCatchStatement( {_g.IdentifierName("s")}, {_g.CatchClause(_g.IdentifierName("x"), "y", {_g.IdentifierName("z")})}, {_g.IdentifierName("a")}), <x>Try s Catch y As x z Finally a End Try</x>.Value) VerifySyntax(Of TryBlockSyntax)( _g.TryFinallyStatement( {_g.IdentifierName("x")}, {_g.IdentifierName("a")}), <x>Try x Finally a End Try</x>.Value) End Sub <Fact> Public Sub TestWhileStatements() VerifySyntax(Of WhileBlockSyntax)( _g.WhileStatement(_g.IdentifierName("x"), {_g.IdentifierName("y")}), <x>While x y End While</x>.Value) VerifySyntax(Of WhileBlockSyntax)( _g.WhileStatement(_g.IdentifierName("x"), Nothing), <x>While x End While</x>.Value) End Sub <Fact> Public Sub TestLambdaExpressions() VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.ValueReturningLambdaExpression("x", _g.IdentifierName("y")), <x>Function(x) y</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.ValueReturningLambdaExpression({_g.LambdaParameter("x"), _g.LambdaParameter("y")}, _g.IdentifierName("z")), <x>Function(x, y) z</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.ValueReturningLambdaExpression(New SyntaxNode() {}, _g.IdentifierName("y")), <x>Function() y</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.VoidReturningLambdaExpression("x", _g.IdentifierName("y")), <x>Sub(x) y</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.VoidReturningLambdaExpression({_g.LambdaParameter("x"), _g.LambdaParameter("y")}, _g.IdentifierName("z")), <x>Sub(x, y) z</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.VoidReturningLambdaExpression(New SyntaxNode() {}, _g.IdentifierName("y")), <x>Sub() y</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.ValueReturningLambdaExpression("x", {_g.ReturnStatement(_g.IdentifierName("y"))}), <x>Function(x) Return y End Function</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.ValueReturningLambdaExpression({_g.LambdaParameter("x"), _g.LambdaParameter("y")}, {_g.ReturnStatement(_g.IdentifierName("z"))}), <x>Function(x, y) Return z End Function</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.ValueReturningLambdaExpression(New SyntaxNode() {}, {_g.ReturnStatement(_g.IdentifierName("y"))}), <x>Function() Return y End Function</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.VoidReturningLambdaExpression("x", {_g.IdentifierName("y")}), <x>Sub(x) y End Sub</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.VoidReturningLambdaExpression({_g.LambdaParameter("x"), _g.LambdaParameter("y")}, {_g.IdentifierName("z")}), <x>Sub(x, y) z End Sub</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.VoidReturningLambdaExpression(New SyntaxNode() {}, {_g.IdentifierName("y")}), <x>Sub() y End Sub</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.ValueReturningLambdaExpression({_g.LambdaParameter("x", _g.IdentifierName("y"))}, _g.IdentifierName("z")), <x>Function(x As y) z</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.ValueReturningLambdaExpression({_g.LambdaParameter("x", _g.IdentifierName("y")), _g.LambdaParameter("a", _g.IdentifierName("b"))}, _g.IdentifierName("z")), <x>Function(x As y, a As b) z</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.VoidReturningLambdaExpression({_g.LambdaParameter("x", _g.IdentifierName("y"))}, _g.IdentifierName("z")), <x>Sub(x As y) z</x>.Value) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.VoidReturningLambdaExpression({_g.LambdaParameter("x", _g.IdentifierName("y")), _g.LambdaParameter("a", _g.IdentifierName("b"))}, _g.IdentifierName("z")), <x>Sub(x As y, a As b) z</x>.Value) End Sub <Fact> Public Sub TestFieldDeclarations() VerifySyntax(Of FieldDeclarationSyntax)( _g.FieldDeclaration("fld", _g.TypeExpression(SpecialType.System_Int32)), <x>Dim fld As Integer</x>.Value) VerifySyntax(Of FieldDeclarationSyntax)( _g.FieldDeclaration("fld", _g.TypeExpression(SpecialType.System_Int32), initializer:=_g.LiteralExpression(0)), <x>Dim fld As Integer = 0</x>.Value) VerifySyntax(Of FieldDeclarationSyntax)( _g.FieldDeclaration("fld", _g.TypeExpression(SpecialType.System_Int32), accessibility:=Accessibility.Public), <x>Public fld As Integer</x>.Value) VerifySyntax(Of FieldDeclarationSyntax)( _g.FieldDeclaration("fld", _g.TypeExpression(SpecialType.System_Int32), modifiers:=DeclarationModifiers.Static Or DeclarationModifiers.ReadOnly), <x>Shared ReadOnly fld As Integer</x>.Value) End Sub <Fact> Public Sub TestMethodDeclarations() VerifySyntax(Of MethodBlockSyntax)( _g.MethodDeclaration("m"), <x>Sub m() End Sub</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.MethodDeclaration("m", typeParameters:={"x", "y"}), <x>Sub m(Of x, y)() End Sub</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("x")), <x>Function m() As x End Function</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("x"), statements:={_g.ReturnStatement(_g.IdentifierName("y"))}), <x>Function m() As x Return y End Function</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.MethodDeclaration("m", parameters:={_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, returnType:=_g.IdentifierName("x")), <x>Function m(z As y) As x End Function</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.MethodDeclaration("m", parameters:={_g.ParameterDeclaration("z", _g.IdentifierName("y"), _g.IdentifierName("a"))}, returnType:=_g.IdentifierName("x")), <x>Function m(Optional z As y = a) As x End Function</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("x"), accessibility:=Accessibility.Public, modifiers:=DeclarationModifiers.None), <x>Public Function m() As x End Function</x>.Value) VerifySyntax(Of MethodStatementSyntax)( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("x"), accessibility:=Accessibility.Public, modifiers:=DeclarationModifiers.Abstract), <x>Public MustInherit Function m() As x</x>.Value) End Sub <Fact> Public Sub TestPropertyDeclarations() VerifySyntax(Of PropertyStatementSyntax)( _g.PropertyDeclaration("p", _g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract + DeclarationModifiers.ReadOnly), <x>MustInherit ReadOnly Property p As x</x>.Value) VerifySyntax(Of PropertyStatementSyntax)( _g.PropertyDeclaration("p", _g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract + DeclarationModifiers.WriteOnly), <x>MustInherit WriteOnly Property p As x</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.PropertyDeclaration("p", _g.IdentifierName("x"), modifiers:=DeclarationModifiers.ReadOnly), <x>ReadOnly Property p As x Get End Get End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.PropertyDeclaration("p", _g.IdentifierName("x"), modifiers:=DeclarationModifiers.WriteOnly), <x>WriteOnly Property p As x Set(value As x) End Set End Property</x>.Value) VerifySyntax(Of PropertyStatementSyntax)( _g.PropertyDeclaration("p", _g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract), <x>MustInherit Property p As x</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.PropertyDeclaration("p", _g.IdentifierName("x"), modifiers:=DeclarationModifiers.ReadOnly, getAccessorStatements:={_g.IdentifierName("y")}), <x>ReadOnly Property p As x Get y End Get End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.PropertyDeclaration("p", _g.IdentifierName("x"), modifiers:=DeclarationModifiers.WriteOnly, setAccessorStatements:={_g.IdentifierName("y")}), <x>WriteOnly Property p As x Set(value As x) y End Set End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.PropertyDeclaration("p", _g.IdentifierName("x"), setAccessorStatements:={_g.IdentifierName("y")}), <x>Property p As x Get End Get Set(value As x) y End Set End Property</x>.Value) End Sub <Fact> Public Sub TestIndexerDeclarations() VerifySyntax(Of PropertyStatementSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract + DeclarationModifiers.ReadOnly), <x>Default MustInherit ReadOnly Property Item(z As y) As x</x>.Value) VerifySyntax(Of PropertyStatementSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract + DeclarationModifiers.WriteOnly), <x>Default MustInherit WriteOnly Property Item(z As y) As x</x>.Value) VerifySyntax(Of PropertyStatementSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract), <x>Default MustInherit Property Item(z As y) As x</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.ReadOnly), <x>Default ReadOnly Property Item(z As y) As x Get End Get End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.WriteOnly), <x>Default WriteOnly Property Item(z As y) As x Set(value As x) End Set End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.ReadOnly, getAccessorStatements:={_g.IdentifierName("a")}), <x>Default ReadOnly Property Item(z As y) As x Get a End Get End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.WriteOnly, setAccessorStatements:={_g.IdentifierName("a")}), <x>Default WriteOnly Property Item(z As y) As x Set(value As x) a End Set End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.None), <x>Default Property Item(z As y) As x Get End Get Set(value As x) End Set End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), setAccessorStatements:={_g.IdentifierName("a")}), <x>Default Property Item(z As y) As x Get End Get Set(value As x) a End Set End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), getAccessorStatements:={_g.IdentifierName("a")}, setAccessorStatements:={_g.IdentifierName("b")}), <x>Default Property Item(z As y) As x Get a End Get Set(value As x) b End Set End Property</x>.Value) End Sub <Fact> Public Sub TestEventDeclarations() VerifySyntax(Of EventStatementSyntax)( _g.EventDeclaration("ev", _g.IdentifierName("t")), <x>Event ev As t</x>.Value) VerifySyntax(Of EventStatementSyntax)( _g.EventDeclaration("ev", _g.IdentifierName("t"), accessibility:=Accessibility.Public, modifiers:=DeclarationModifiers.Static), <x>Public Shared Event ev As t</x>.Value) VerifySyntax(Of EventBlockSyntax)( _g.CustomEventDeclaration("ev", _g.IdentifierName("t")), <x>Custom Event ev As t AddHandler(value As t) End AddHandler RemoveHandler(value As t) End RemoveHandler RaiseEvent() End RaiseEvent End Event</x>.Value) Dim params = {_g.ParameterDeclaration("sender", _g.TypeExpression(SpecialType.System_Object)), _g.ParameterDeclaration("args", _g.IdentifierName("EventArgs"))} VerifySyntax(Of EventBlockSyntax)( _g.CustomEventDeclaration("ev", _g.IdentifierName("t"), parameters:=params), <x>Custom Event ev As t AddHandler(value As t) End AddHandler RemoveHandler(value As t) End RemoveHandler RaiseEvent(sender As Object, args As EventArgs) End RaiseEvent End Event</x>.Value) End Sub <Fact> Public Sub TestConstructorDeclaration() VerifySyntax(Of ConstructorBlockSyntax)( _g.ConstructorDeclaration("c"), <x>Sub New() End Sub</x>.Value) VerifySyntax(Of ConstructorBlockSyntax)( _g.ConstructorDeclaration("c", accessibility:=Accessibility.Public, modifiers:=DeclarationModifiers.Static), <x>Public Shared Sub New() End Sub</x>.Value) VerifySyntax(Of ConstructorBlockSyntax)( _g.ConstructorDeclaration("c", parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t"))}), <x>Sub New(p As t) End Sub</x>.Value) VerifySyntax(Of ConstructorBlockSyntax)( _g.ConstructorDeclaration("c", parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t"))}, baseConstructorArguments:={_g.IdentifierName("p")}), <x>Sub New(p As t) MyBase.New(p) End Sub</x>.Value) End Sub <Fact> Public Sub TestClassDeclarations() VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("c"), <x>Class c End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("c", typeParameters:={"x", "y"}), <x>Class c(Of x, y) End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("c", accessibility:=Accessibility.Public), <x>Public Class c End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("c", baseType:=_g.IdentifierName("x")), <x>Class c Inherits x End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("c", interfaceTypes:={_g.IdentifierName("x")}), <x>Class c Implements x End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("c", baseType:=_g.IdentifierName("x"), interfaceTypes:={_g.IdentifierName("y"), _g.IdentifierName("z")}), <x>Class c Inherits x Implements y, z End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("c", interfaceTypes:={}), <x>Class c End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("c", members:={_g.FieldDeclaration("y", type:=_g.IdentifierName("x"))}), <x>Class c Dim y As x End Class</x>.Value) End Sub <Fact> Public Sub TestStructDeclarations() VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s"), <x>Structure s End Structure</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s", typeParameters:={"x", "y"}), <x>Structure s(Of x, y) End Structure</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s", accessibility:=Accessibility.Public, modifiers:=DeclarationModifiers.Partial), <x>Public Partial Structure s End Structure</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s", interfaceTypes:={_g.IdentifierName("x")}), <x>Structure s Implements x End Structure</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s", interfaceTypes:={_g.IdentifierName("x"), _g.IdentifierName("y")}), <x>Structure s Implements x, y End Structure</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s", interfaceTypes:={}), <x>Structure s End Structure</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s", members:={_g.FieldDeclaration("y", _g.IdentifierName("x"))}), <x>Structure s Dim y As x End Structure</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s", members:={_g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"))}), <x>Structure s Function m() As t End Function End Structure</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.StructDeclaration("s", members:={_g.ConstructorDeclaration(accessibility:=Accessibility.NotApplicable, modifiers:=DeclarationModifiers.None)}), <x>Structure s Sub New() End Sub End Structure</x>.Value) End Sub <Fact> Public Sub TestInterfaceDeclarations() VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i"), <x>Interface i End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", typeParameters:={"x", "y"}), <x>Interface i(Of x, y) End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", interfaceTypes:={_g.IdentifierName("a")}), <x>Interface i Inherits a End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", interfaceTypes:={_g.IdentifierName("a"), _g.IdentifierName("b")}), <x>Interface i Inherits a, b End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", interfaceTypes:={}), <x>Interface i End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", members:={_g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), accessibility:=Accessibility.Public, modifiers:=DeclarationModifiers.Sealed)}), <x>Interface i Function m() As t End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", members:={_g.PropertyDeclaration("p", _g.IdentifierName("t"), accessibility:=Accessibility.Public, modifiers:=DeclarationModifiers.Sealed)}), <x>Interface i Property p As t End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", members:={_g.PropertyDeclaration("p", _g.IdentifierName("t"), accessibility:=Accessibility.Public, modifiers:=DeclarationModifiers.ReadOnly)}), <x>Interface i ReadOnly Property p As t End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", members:={_g.IndexerDeclaration({_g.ParameterDeclaration("y", _g.IdentifierName("x"))}, _g.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed)}), <x>Interface i Default Property Item(y As x) As t End Interface</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.InterfaceDeclaration("i", members:={_g.IndexerDeclaration({_g.ParameterDeclaration("y", _g.IdentifierName("x"))}, _g.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly)}), <x>Interface i Default ReadOnly Property Item(y As x) As t End Interface</x>.Value) End Sub <Fact> Public Sub TestEnumDeclarations() VerifySyntax(Of EnumBlockSyntax)( _g.EnumDeclaration("e"), <x>Enum e End Enum</x>.Value) VerifySyntax(Of EnumBlockSyntax)( _g.EnumDeclaration("e", members:={_g.EnumMember("a"), _g.EnumMember("b"), _g.EnumMember("c")}), <x>Enum e a b c End Enum</x>.Value) VerifySyntax(Of EnumBlockSyntax)( _g.EnumDeclaration("e", members:={_g.IdentifierName("a"), _g.EnumMember("b"), _g.IdentifierName("c")}), <x>Enum e a b c End Enum</x>.Value) VerifySyntax(Of EnumBlockSyntax)( _g.EnumDeclaration("e", members:={_g.EnumMember("a", _g.LiteralExpression(0)), _g.EnumMember("b"), _g.EnumMember("c", _g.LiteralExpression(5))}), <x>Enum e a = 0 b c = 5 End Enum</x>.Value) End Sub <Fact> Public Sub TestDelegateDeclarations() VerifySyntax(Of DelegateStatementSyntax)( _g.DelegateDeclaration("d"), <x>Delegate Sub d()</x>.Value) VerifySyntax(Of DelegateStatementSyntax)( _g.DelegateDeclaration("d", parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t"))}), <x>Delegate Sub d(p As t)</x>.Value) VerifySyntax(Of DelegateStatementSyntax)( _g.DelegateDeclaration("d", returnType:=_g.IdentifierName("t")), <x>Delegate Function d() As t</x>.Value) VerifySyntax(Of DelegateStatementSyntax)( _g.DelegateDeclaration("d", parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t"))}, returnType:=_g.IdentifierName("t")), <x>Delegate Function d(p As t) As t</x>.Value) VerifySyntax(Of DelegateStatementSyntax)( _g.DelegateDeclaration("d", accessibility:=Accessibility.Public), <x>Public Delegate Sub d()</x>.Value) ' ignores modifiers VerifySyntax(Of DelegateStatementSyntax)( _g.DelegateDeclaration("d", modifiers:=DeclarationModifiers.Static), <x>Delegate Sub d()</x>.Value) End Sub <Fact> Public Sub TestNamespaceImportDeclarations() VerifySyntax(Of ImportsStatementSyntax)( _g.NamespaceImportDeclaration(_g.IdentifierName("n")), <x>Imports n</x>.Value) VerifySyntax(Of ImportsStatementSyntax)( _g.NamespaceImportDeclaration("n"), <x>Imports n</x>.Value) VerifySyntax(Of ImportsStatementSyntax)( _g.NamespaceImportDeclaration("n.m"), <x>Imports n.m</x>.Value) End Sub <Fact> Public Sub TestNamespaceDeclarations() VerifySyntax(Of NamespaceBlockSyntax)( _g.NamespaceDeclaration("n"), <x>Namespace n End Namespace</x>.Value) VerifySyntax(Of NamespaceBlockSyntax)( _g.NamespaceDeclaration("n.m"), <x>Namespace n.m End Namespace</x>.Value) VerifySyntax(Of NamespaceBlockSyntax)( _g.NamespaceDeclaration("n", _g.NamespaceImportDeclaration("m")), <x>Namespace n Imports m End Namespace</x>.Value) VerifySyntax(Of NamespaceBlockSyntax)( _g.NamespaceDeclaration("n", _g.ClassDeclaration("c"), _g.NamespaceImportDeclaration("m")), <x>Namespace n Imports m Class c End Class End Namespace</x>.Value) End Sub <Fact> Public Sub TestCompilationUnits() VerifySyntax(Of CompilationUnitSyntax)( _g.CompilationUnit(), "") VerifySyntax(Of CompilationUnitSyntax)( _g.CompilationUnit( _g.NamespaceDeclaration("n")), <x>Namespace n End Namespace </x>.Value) VerifySyntax(Of CompilationUnitSyntax)( _g.CompilationUnit( _g.NamespaceImportDeclaration("n")), <x>Imports n </x>.Value) VerifySyntax(Of CompilationUnitSyntax)( _g.CompilationUnit( _g.ClassDeclaration("c"), _g.NamespaceImportDeclaration("m")), <x>Imports m Class c End Class </x>.Value) VerifySyntax(Of CompilationUnitSyntax)( _g.CompilationUnit( _g.NamespaceImportDeclaration("n"), _g.NamespaceDeclaration("n", _g.NamespaceImportDeclaration("m"), _g.ClassDeclaration("c"))), <x>Imports n Namespace n Imports m Class c End Class End Namespace </x>.Value) End Sub <Fact> Public Sub TestAsPublicInterfaceImplementation() VerifySyntax(Of MethodBlockBaseSyntax)( _g.AsPublicInterfaceImplementation( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract), _g.IdentifierName("i")), <x>Public Function m() As t Implements i.m End Function</x>.Value) VerifySyntax(Of MethodBlockBaseSyntax)( _g.AsPublicInterfaceImplementation( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), modifiers:=DeclarationModifiers.None), _g.IdentifierName("i")), <x>Public Function m() As t Implements i.m End Function</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.AsPublicInterfaceImplementation( _g.PropertyDeclaration("p", _g.IdentifierName("t"), accessibility:=Accessibility.Private, modifiers:=DeclarationModifiers.Abstract), _g.IdentifierName("i")), <x>Public Property p As t Implements i.p Get End Get Set(value As t) End Set End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.AsPublicInterfaceImplementation( _g.PropertyDeclaration("p", _g.IdentifierName("t"), accessibility:=Accessibility.Private, modifiers:=DeclarationModifiers.None), _g.IdentifierName("i")), <x>Public Property p As t Implements i.p Get End Get Set(value As t) End Set End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.AsPublicInterfaceImplementation( _g.IndexerDeclaration({_g.ParameterDeclaration("p", _g.IdentifierName("a"))}, _g.IdentifierName("t"), Accessibility.Internal, DeclarationModifiers.Abstract), _g.IdentifierName("i")), <x>Default Public Property Item(p As a) As t Implements i.Item Get End Get Set(value As t) End Set End Property</x>.Value) End Sub <Fact> Public Sub TestAsPrivateInterfaceImplementation() VerifySyntax(Of MethodBlockBaseSyntax)( _g.AsPrivateInterfaceImplementation( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), accessibility:=Accessibility.Private, modifiers:=DeclarationModifiers.Abstract), _g.IdentifierName("i")), <x>Private Function i_m() As t Implements i.m End Function</x>.Value) VerifySyntax(Of MethodBlockBaseSyntax)( _g.AsPrivateInterfaceImplementation( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), accessibility:=Accessibility.Private, modifiers:=DeclarationModifiers.Abstract), _g.TypeExpression(Me._ienumerableInt)), <x>Private Function IEnumerable_Int32_m() As t Implements Global.System.Collections.Generic.IEnumerable(Of System.Int32).m End Function</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.AsPrivateInterfaceImplementation( _g.PropertyDeclaration("p", _g.IdentifierName("t"), accessibility:=Accessibility.Internal, modifiers:=DeclarationModifiers.Abstract), _g.IdentifierName("i")), <x>Private Property i_p As t Implements i.p Get End Get Set(value As t) End Set End Property</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.AsPrivateInterfaceImplementation( _g.IndexerDeclaration({_g.ParameterDeclaration("p", _g.IdentifierName("a"))}, _g.IdentifierName("t"), Accessibility.Protected, DeclarationModifiers.Abstract), _g.IdentifierName("i")), <x>Private Property i_Item(p As a) As t Implements i.Item Get End Get Set(value As t) End Set End Property</x>.Value) End Sub <Fact> Public Sub TestWithTypeParameters() VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeParameters( _g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), <x>MustInherit Sub m(Of a)()</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithTypeParameters( _g.MethodDeclaration("m", modifiers:=DeclarationModifiers.None), "a"), <x>Sub m(Of a)() End Sub</x>.Value) ' assigning no type parameters is legal VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeParameters( _g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract)), <x>MustInherit Sub m()</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithTypeParameters( _g.MethodDeclaration("m", modifiers:=DeclarationModifiers.None)), <x>Sub m() End Sub</x>.Value) ' removing type parameters VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeParameters(_g.WithTypeParameters( _g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a")), <x>MustInherit Sub m()</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithTypeParameters(_g.WithTypeParameters( _g.MethodDeclaration("m"), "a")), <x>Sub m() End Sub</x>.Value) ' multiple type parameters VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeParameters( _g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a", "b"), <x>MustInherit Sub m(Of a, b)()</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithTypeParameters( _g.MethodDeclaration("m"), "a", "b"), <x>Sub m(Of a, b)() End Sub</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.WithTypeParameters( _g.ClassDeclaration("c"), "a", "b"), <x>Class c(Of a, b) End Class</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.WithTypeParameters( _g.StructDeclaration("s"), "a", "b"), <x>Structure s(Of a, b) End Structure</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.WithTypeParameters( _g.InterfaceDeclaration("i"), "a", "b"), <x>Interface i(Of a, b) End Interface</x>.Value) End Sub <Fact> Public Sub TestWithTypeConstraint() ' single type constraint VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", _g.IdentifierName("b")), <x>MustInherit Sub m(Of a As b)()</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m"), "a"), "a", _g.IdentifierName("b")), <x>Sub m(Of a As b)() End Sub</x>.Value) ' multiple type constraints VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", _g.IdentifierName("b"), _g.IdentifierName("c")), <x>MustInherit Sub m(Of a As {b, c})()</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m"), "a"), "a", _g.IdentifierName("b"), _g.IdentifierName("c")), <x>Sub m(Of a As {b, c})() End Sub</x>.Value) ' no type constraints VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a"), <x>MustInherit Sub m(Of a)()</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m"), "a"), "a"), <x>Sub m(Of a)() End Sub</x>.Value) ' removed type constraints VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint(_g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", _g.IdentifierName("b"), _g.IdentifierName("c")), "a"), <x>MustInherit Sub m(Of a)()</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithTypeConstraint(_g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m"), "a"), "a", _g.IdentifierName("b"), _g.IdentifierName("c")), "a"), <x>Sub m(Of a)() End Sub</x>.Value) ' multipe type parameters with constraints VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a", "x"), "a", _g.IdentifierName("b"), _g.IdentifierName("c")), "x", _g.IdentifierName("y")), <x>MustInherit Sub m(Of a As {b, c}, x As y)()</x>.Value) ' with constructor constraint VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), <x>MustInherit Sub m(Of a As New)()</x>.Value) ' with reference constraint VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), <x>MustInherit Sub m(Of a As Class)()</x>.Value) ' with value type constraint VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), <x>MustInherit Sub m(Of a As Structure)()</x>.Value) ' with reference constraint and constructor constraint VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType Or SpecialTypeConstraintKind.Constructor), <x>MustInherit Sub m(Of a As {Class, New})()</x>.Value) ' with value type constraint and constructor constraint VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType Or SpecialTypeConstraintKind.Constructor), <x>MustInherit Sub m(Of a As {Structure, New})()</x>.Value) ' with reference constraint and type constraints VerifySyntax(Of MethodStatementSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, _g.IdentifierName("b"), _g.IdentifierName("c")), <x>MustInherit Sub m(Of a As {Class, b, c})()</x>.Value) ' class declarations VerifySyntax(Of ClassBlockSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters( _g.ClassDeclaration("c"), "a", "b"), "a", _g.IdentifierName("x")), <x>Class c(Of a As x, b) End Class</x>.Value) ' structure declarations VerifySyntax(Of StructureBlockSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters( _g.StructDeclaration("s"), "a", "b"), "a", _g.IdentifierName("x")), <x>Structure s(Of a As x, b) End Structure</x>.Value) ' interface delcarations VerifySyntax(Of InterfaceBlockSyntax)( _g.WithTypeConstraint( _g.WithTypeParameters( _g.InterfaceDeclaration("i"), "a", "b"), "a", _g.IdentifierName("x")), <x>Interface i(Of a As x, b) End Interface</x>.Value) End Sub <Fact> Public Sub TestAttributeDeclarations() VerifySyntax(Of AttributeListSyntax)( _g.Attribute(_g.IdentifierName("a")), "<a>") VerifySyntax(Of AttributeListSyntax)( _g.Attribute("a"), "<a>") VerifySyntax(Of AttributeListSyntax)( _g.Attribute("a.b"), "<a.b>") VerifySyntax(Of AttributeListSyntax)( _g.Attribute("a", {}), "<a()>") VerifySyntax(Of AttributeListSyntax)( _g.Attribute("a", {_g.IdentifierName("x")}), "<a(x)>") VerifySyntax(Of AttributeListSyntax)( _g.Attribute("a", {_g.AttributeArgument(_g.IdentifierName("x"))}), "<a(x)>") VerifySyntax(Of AttributeListSyntax)( _g.Attribute("a", {_g.AttributeArgument("x", _g.IdentifierName("y"))}), "<a(x:=y)>") VerifySyntax(Of AttributeListSyntax)( _g.Attribute("a", {_g.IdentifierName("x"), _g.IdentifierName("y")}), "<a(x, y)>") End Sub <Fact> Public Sub TestAddAttributes() VerifySyntax(Of FieldDeclarationSyntax)( _g.AddAttributes( _g.FieldDeclaration("y", _g.IdentifierName("x")), _g.Attribute("a")), <x>&lt;a&gt; Dim y As x</x>.Value) VerifySyntax(Of FieldDeclarationSyntax)( _g.AddAttributes( _g.AddAttributes( _g.FieldDeclaration("y", _g.IdentifierName("x")), _g.Attribute("a")), _g.Attribute("b")), <x>&lt;a&gt; &lt;b&gt; Dim y As x</x>.Value) VerifySyntax(Of MethodStatementSyntax)( _g.AddAttributes( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract), _g.Attribute("a")), <x>&lt;a&gt; MustInherit Function m() As t</x>.Value) VerifySyntax(Of MethodStatementSyntax)( _g.AddReturnAttributes( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract), _g.Attribute("a")), <x>MustInherit Function m() As &lt;a&gt; t</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.AddAttributes( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), modifiers:=DeclarationModifiers.None), _g.Attribute("a")), <x>&lt;a&gt; Function m() As t End Function</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.AddReturnAttributes( _g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"), modifiers:=DeclarationModifiers.None), _g.Attribute("a")), <x>Function m() As &lt;a&gt; t End Function</x>.Value) VerifySyntax(Of PropertyStatementSyntax)( _g.AddAttributes( _g.PropertyDeclaration("p", _g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract), _g.Attribute("a")), <x>&lt;a&gt; MustInherit Property p As x</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.AddAttributes( _g.PropertyDeclaration("p", _g.IdentifierName("x")), _g.Attribute("a")), <x>&lt;a&gt; Property p As x Get End Get Set(value As x) End Set End Property</x>.Value) VerifySyntax(Of PropertyStatementSyntax)( _g.AddAttributes( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract), _g.Attribute("a")), <x>&lt;a&gt; Default MustInherit Property Item(z As y) As x</x>.Value) VerifySyntax(Of PropertyBlockSyntax)( _g.AddAttributes( _g.IndexerDeclaration({_g.ParameterDeclaration("z", _g.IdentifierName("y"))}, _g.IdentifierName("x")), _g.Attribute("a")), <x>&lt;a&gt; Default Property Item(z As y) As x Get End Get Set(value As x) End Set End Property</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.AddAttributes( _g.ClassDeclaration("c"), _g.Attribute("a")), <x>&lt;a&gt; Class c End Class</x>.Value) VerifySyntax(Of ParameterSyntax)( _g.AddAttributes( _g.ParameterDeclaration("p", _g.IdentifierName("t")), _g.Attribute("a")), <x>&lt;a&gt; p As t</x>.Value) VerifySyntax(Of CompilationUnitSyntax)( _g.AddAttributes( _g.CompilationUnit(_g.NamespaceDeclaration("n")), _g.Attribute("a")), <x>&lt;Assembly:a&gt; Namespace n End Namespace </x>.Value) VerifySyntax(Of DelegateStatementSyntax)( _g.AddAttributes( _g.DelegateDeclaration("d"), _g.Attribute("a")), <x>&lt;a&gt; Delegate Sub d()</x>.Value) End Sub <Fact> Public Sub TestAddRemoveAttributesPreservesTrivia() Dim cls = ParseCompilationUnit( <x>' comment Class C End Class ' end</x>.Value).Members(0) Dim added = _g.AddAttributes(cls, _g.Attribute("a")) VerifySyntax(Of ClassBlockSyntax)( added, <x>' comment &lt;a&gt; Class C End Class ' end</x>.Value) Dim removed = _g.RemoveAllAttributes(added) VerifySyntax(Of ClassBlockSyntax)( removed, <x>' comment Class C End Class ' end</x>.Value) Dim attrWithComment = _g.GetAttributes(added).First() VerifySyntax(Of AttributeListSyntax)( attrWithComment, <x>' comment &lt;a&gt;</x>.Value) ' added attributes are stripped of trivia Dim added2 = _g.AddAttributes(cls, attrWithComment) VerifySyntax(Of ClassBlockSyntax)( added2, <x>' comment &lt;a&gt; Class C End Class ' end</x>.Value) End Sub <Fact> Public Sub TestDeclarationKind() Assert.Equal(DeclarationKind.CompilationUnit, _g.GetDeclarationKind(_g.CompilationUnit())) Assert.Equal(DeclarationKind.Class, _g.GetDeclarationKind(_g.ClassDeclaration("c"))) Assert.Equal(DeclarationKind.Struct, _g.GetDeclarationKind(_g.StructDeclaration("s"))) Assert.Equal(DeclarationKind.Interface, _g.GetDeclarationKind(_g.InterfaceDeclaration("i"))) Assert.Equal(DeclarationKind.Enum, _g.GetDeclarationKind(_g.EnumDeclaration("e"))) Assert.Equal(DeclarationKind.Delegate, _g.GetDeclarationKind(_g.DelegateDeclaration("d"))) Assert.Equal(DeclarationKind.Method, _g.GetDeclarationKind(_g.MethodDeclaration("m"))) Assert.Equal(DeclarationKind.Method, _g.GetDeclarationKind(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract))) Assert.Equal(DeclarationKind.Constructor, _g.GetDeclarationKind(_g.ConstructorDeclaration())) Assert.Equal(DeclarationKind.Parameter, _g.GetDeclarationKind(_g.ParameterDeclaration("p"))) Assert.Equal(DeclarationKind.Property, _g.GetDeclarationKind(_g.PropertyDeclaration("p", _g.IdentifierName("t")))) Assert.Equal(DeclarationKind.Property, _g.GetDeclarationKind(_g.PropertyDeclaration("p", _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract))) Assert.Equal(DeclarationKind.Indexer, _g.GetDeclarationKind(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t")))) Assert.Equal(DeclarationKind.Indexer, _g.GetDeclarationKind(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract))) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(_g.FieldDeclaration("f", _g.IdentifierName("t")))) Assert.Equal(DeclarationKind.EnumMember, _g.GetDeclarationKind(_g.EnumMember("v"))) Assert.Equal(DeclarationKind.Event, _g.GetDeclarationKind(_g.EventDeclaration("e", _g.IdentifierName("t")))) Assert.Equal(DeclarationKind.CustomEvent, _g.GetDeclarationKind(_g.CustomEventDeclaration("ce", _g.IdentifierName("t")))) Assert.Equal(DeclarationKind.Namespace, _g.GetDeclarationKind(_g.NamespaceDeclaration("n"))) Assert.Equal(DeclarationKind.NamespaceImport, _g.GetDeclarationKind(_g.NamespaceImportDeclaration("u"))) Assert.Equal(DeclarationKind.Variable, _g.GetDeclarationKind(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "loc"))) Assert.Equal(DeclarationKind.Attribute, _g.GetDeclarationKind(_g.Attribute("a"))) End Sub <Fact> Public Sub TestGetName() Assert.Equal("c", _g.GetName(_g.ClassDeclaration("c"))) Assert.Equal("s", _g.GetName(_g.StructDeclaration("s"))) Assert.Equal("i", _g.GetName(_g.EnumDeclaration("i"))) Assert.Equal("e", _g.GetName(_g.EnumDeclaration("e"))) Assert.Equal("d", _g.GetName(_g.DelegateDeclaration("d"))) Assert.Equal("m", _g.GetName(_g.MethodDeclaration("m"))) Assert.Equal("m", _g.GetName(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract))) Assert.Equal("", _g.GetName(_g.ConstructorDeclaration())) Assert.Equal("p", _g.GetName(_g.ParameterDeclaration("p"))) Assert.Equal("p", _g.GetName(_g.PropertyDeclaration("p", _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract))) Assert.Equal("p", _g.GetName(_g.PropertyDeclaration("p", _g.IdentifierName("t")))) Assert.Equal("", _g.GetName(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t")))) Assert.Equal("", _g.GetName(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract))) Assert.Equal("f", _g.GetName(_g.FieldDeclaration("f", _g.IdentifierName("t")))) Assert.Equal("v", _g.GetName(_g.EnumMember("v"))) Assert.Equal("ef", _g.GetName(_g.EventDeclaration("ef", _g.IdentifierName("t")))) Assert.Equal("ep", _g.GetName(_g.CustomEventDeclaration("ep", _g.IdentifierName("t")))) Assert.Equal("n", _g.GetName(_g.NamespaceDeclaration("n"))) Assert.Equal("u", _g.GetName(_g.NamespaceImportDeclaration("u"))) Assert.Equal("loc", _g.GetName(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "loc"))) Assert.Equal("a", _g.GetName(_g.Attribute("a"))) End Sub <Fact> Public Sub TestWithName() Assert.Equal("c", _g.GetName(_g.WithName(_g.ClassDeclaration("x"), "c"))) Assert.Equal("s", _g.GetName(_g.WithName(_g.StructDeclaration("x"), "s"))) Assert.Equal("i", _g.GetName(_g.WithName(_g.EnumDeclaration("x"), "i"))) Assert.Equal("e", _g.GetName(_g.WithName(_g.EnumDeclaration("x"), "e"))) Assert.Equal("d", _g.GetName(_g.WithName(_g.DelegateDeclaration("x"), "d"))) Assert.Equal("m", _g.GetName(_g.WithName(_g.MethodDeclaration("x"), "m"))) Assert.Equal("m", _g.GetName(_g.WithName(_g.MethodDeclaration("x", modifiers:=DeclarationModifiers.Abstract), "m"))) Assert.Equal("", _g.GetName(_g.WithName(_g.ConstructorDeclaration(), ".ctor"))) Assert.Equal("p", _g.GetName(_g.WithName(_g.ParameterDeclaration("x"), "p"))) Assert.Equal("p", _g.GetName(_g.WithName(_g.PropertyDeclaration("x", _g.IdentifierName("t")), "p"))) Assert.Equal("p", _g.GetName(_g.WithName(_g.PropertyDeclaration("x", _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract), "p"))) Assert.Equal("", _g.GetName(_g.WithName(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t")), "this"))) Assert.Equal("", _g.GetName(_g.WithName(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract), "this"))) Assert.Equal("f", _g.GetName(_g.WithName(_g.FieldDeclaration("x", _g.IdentifierName("t")), "f"))) Assert.Equal("v", _g.GetName(_g.WithName(_g.EnumMember("x"), "v"))) Assert.Equal("ef", _g.GetName(_g.WithName(_g.EventDeclaration("x", _g.IdentifierName("t")), "ef"))) Assert.Equal("ep", _g.GetName(_g.WithName(_g.CustomEventDeclaration("x", _g.IdentifierName("t")), "ep"))) Assert.Equal("n", _g.GetName(_g.WithName(_g.NamespaceDeclaration("x"), "n"))) Assert.Equal("u", _g.GetName(_g.WithName(_g.NamespaceImportDeclaration("x"), "u"))) Assert.Equal("loc", _g.GetName(_g.WithName(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "x"), "loc"))) Assert.Equal("a", _g.GetName(_g.WithName(_g.Attribute("x"), "a"))) End Sub <Fact> Public Sub TestGetAccessibility() Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.ClassDeclaration("c", accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.StructDeclaration("s", accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.EnumDeclaration("i", accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.EnumDeclaration("e", accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.DelegateDeclaration("d", accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.MethodDeclaration("m", accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.ConstructorDeclaration(accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.ParameterDeclaration("p"))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.PropertyDeclaration("p", _g.IdentifierName("t"), accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t"), accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.FieldDeclaration("f", _g.IdentifierName("t"), accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.EnumMember("v"))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.EventDeclaration("ef", _g.IdentifierName("t"), accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.Internal, _g.GetAccessibility(_g.CustomEventDeclaration("ep", _g.IdentifierName("t"), accessibility:=Accessibility.Internal))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.NamespaceDeclaration("n"))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.NamespaceImportDeclaration("u"))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "loc"))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.Attribute("a"))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(SyntaxFactory.TypeParameter("tp"))) End Sub <Fact> Public Sub TestWithAccessibility() Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.ClassDeclaration("c", accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.StructDeclaration("s", accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.EnumDeclaration("i", accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.EnumDeclaration("e", accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.DelegateDeclaration("d", accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.MethodDeclaration("m", accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.ConstructorDeclaration(accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.WithAccessibility(_g.ParameterDeclaration("p"), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.PropertyDeclaration("p", _g.IdentifierName("t"), accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t"), accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.FieldDeclaration("f", _g.IdentifierName("t"), accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.WithAccessibility(_g.EnumMember("v"), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.EventDeclaration("ef", _g.IdentifierName("t"), accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(_g.CustomEventDeclaration("ep", _g.IdentifierName("t"), accessibility:=Accessibility.Internal), Accessibility.Private))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.WithAccessibility(_g.NamespaceDeclaration("n"), Accessibility.Private))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.WithAccessibility(_g.NamespaceImportDeclaration("u"), Accessibility.Private))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.WithAccessibility(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "loc"), Accessibility.Private))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.WithAccessibility(_g.Attribute("a"), Accessibility.Private))) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(_g.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))) End Sub <Fact> Public Sub TestGetModifiers() Assert.Equal(DeclarationModifiers.Abstract, _g.GetModifiers(_g.ClassDeclaration("c", modifiers:=DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.Partial, _g.GetModifiers(_g.StructDeclaration("s", modifiers:=DeclarationModifiers.Partial))) Assert.Equal(DeclarationModifiers.[New], _g.GetModifiers(_g.EnumDeclaration("e", modifiers:=DeclarationModifiers.[New]))) Assert.Equal(DeclarationModifiers.[New], _g.GetModifiers(_g.DelegateDeclaration("d", modifiers:=DeclarationModifiers.[New]))) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Static))) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(_g.ConstructorDeclaration(modifiers:=DeclarationModifiers.Static))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.ParameterDeclaration("p"))) Assert.Equal(DeclarationModifiers.Abstract, _g.GetModifiers(_g.PropertyDeclaration("p", _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.Abstract, _g.GetModifiers(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.Const, _g.GetModifiers(_g.FieldDeclaration("f", _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Const))) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(_g.EventDeclaration("ef", _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Static))) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(_g.CustomEventDeclaration("ep", _g.IdentifierName("t"), modifiers:=DeclarationModifiers.Static))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.EnumMember("v"))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.NamespaceDeclaration("n"))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.NamespaceImportDeclaration("u"))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "loc"))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.Attribute("a"))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(SyntaxFactory.TypeParameter("tp"))) End Sub <Fact> Public Sub TestWithModifiers() Assert.Equal(DeclarationModifiers.Abstract, _g.GetModifiers(_g.WithModifiers(_g.ClassDeclaration("c"), DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.Partial, _g.GetModifiers(_g.WithModifiers(_g.StructDeclaration("s"), DeclarationModifiers.Partial))) Assert.Equal(DeclarationModifiers.[New], _g.GetModifiers(_g.WithModifiers(_g.EnumDeclaration("e"), DeclarationModifiers.[New]))) Assert.Equal(DeclarationModifiers.[New], _g.GetModifiers(_g.WithModifiers(_g.DelegateDeclaration("d"), DeclarationModifiers.[New]))) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(_g.WithModifiers(_g.MethodDeclaration("m"), DeclarationModifiers.Static))) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(_g.WithModifiers(_g.ConstructorDeclaration(), DeclarationModifiers.Static))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.WithModifiers(_g.ParameterDeclaration("p"), DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.Abstract, _g.GetModifiers(_g.WithModifiers(_g.PropertyDeclaration("p", _g.IdentifierName("t")), DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.Abstract, _g.GetModifiers(_g.WithModifiers(_g.IndexerDeclaration({_g.ParameterDeclaration("i")}, _g.IdentifierName("t")), DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.Const, _g.GetModifiers(_g.WithModifiers(_g.FieldDeclaration("f", _g.IdentifierName("t")), DeclarationModifiers.Const))) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(_g.WithModifiers(_g.EventDeclaration("ef", _g.IdentifierName("t")), DeclarationModifiers.Static))) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(_g.WithModifiers(_g.CustomEventDeclaration("ep", _g.IdentifierName("t")), DeclarationModifiers.Static))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.WithModifiers(_g.EnumMember("v"), DeclarationModifiers.Partial))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.WithModifiers(_g.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.WithModifiers(_g.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.WithModifiers(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.WithModifiers(_g.Attribute("a"), DeclarationModifiers.Abstract))) Assert.Equal(DeclarationModifiers.None, _g.GetModifiers(_g.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))) End Sub <Fact> Public Sub TestGetType() Assert.Equal("t", _g.GetType(_g.MethodDeclaration("m", returnType:=_g.IdentifierName("t"))).ToString()) Assert.Null(_g.GetType(_g.MethodDeclaration("m"))) Assert.Equal("t", _g.GetType(_g.FieldDeclaration("f", _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.PropertyDeclaration("p", _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.IndexerDeclaration({_g.ParameterDeclaration("p", _g.IdentifierName("pt"))}, _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.ParameterDeclaration("p", _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.EventDeclaration("ef", _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.CustomEventDeclaration("ep", _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.DelegateDeclaration("t", returnType:=_g.IdentifierName("t"))).ToString()) Assert.Null(_g.GetType(_g.DelegateDeclaration("d"))) Assert.Equal("t", _g.GetType(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "v")).ToString()) Assert.Null(_g.GetType(_g.ClassDeclaration("c"))) Assert.Null(_g.GetType(_g.IdentifierName("x"))) End Sub <Fact> Public Sub TestWithType() Assert.Equal("t", _g.GetType(_g.WithType(_g.MethodDeclaration("m", returnType:=_g.IdentifierName("x")), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.MethodDeclaration("m"), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.FieldDeclaration("f", _g.IdentifierName("x")), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.PropertyDeclaration("p", _g.IdentifierName("x")), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.IndexerDeclaration({_g.ParameterDeclaration("p", _g.IdentifierName("pt"))}, _g.IdentifierName("x")), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.ParameterDeclaration("p", _g.IdentifierName("x")), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.DelegateDeclaration("t", returnType:=_g.IdentifierName("x")), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.DelegateDeclaration("t"), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.EventDeclaration("ef", _g.IdentifierName("x")), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.CustomEventDeclaration("ep", _g.IdentifierName("x")), _g.IdentifierName("t"))).ToString()) Assert.Equal("t", _g.GetType(_g.WithType(_g.LocalDeclarationStatement(_g.IdentifierName("x"), "v"), _g.IdentifierName("t"))).ToString()) Assert.Null(_g.GetType(_g.WithType(_g.ClassDeclaration("c"), _g.IdentifierName("t")))) Assert.Null(_g.GetType(_g.WithType(_g.IdentifierName("x"), _g.IdentifierName("t")))) End Sub <Fact> Public Sub TestWithTypeChangesSubFunction() VerifySyntax(Of MethodBlockSyntax)( _g.WithType(_g.MethodDeclaration("m", returnType:=_g.IdentifierName("x")), Nothing), <x>Sub m() End Sub</x>.Value) VerifySyntax(Of MethodBlockSyntax)( _g.WithType(_g.MethodDeclaration("m"), _g.IdentifierName("x")), <x>Function m() As x End Function</x>.Value) VerifySyntax(Of MethodStatementSyntax)( _g.WithType(_g.MethodDeclaration("m", returnType:=_g.IdentifierName("x"), modifiers:=DeclarationModifiers.Abstract), Nothing), <x>MustInherit Sub m()</x>.Value) VerifySyntax(Of MethodStatementSyntax)( _g.WithType(_g.MethodDeclaration("m", modifiers:=DeclarationModifiers.Abstract), _g.IdentifierName("x")), <x>MustInherit Function m() As x</x>.Value) VerifySyntax(Of DelegateStatementSyntax)( _g.WithType(_g.DelegateDeclaration("d", returnType:=_g.IdentifierName("x")), Nothing), <x>Delegate Sub d()</x>.Value) VerifySyntax(Of DelegateStatementSyntax)( _g.WithType(_g.DelegateDeclaration("d"), _g.IdentifierName("x")), <x>Delegate Function d() As x</x>.Value) End Sub <Fact> Public Sub TestGetParameters() Assert.Equal(0, _g.GetParameters(_g.MethodDeclaration("m")).Count) Assert.Equal(1, _g.GetParameters(_g.MethodDeclaration("m", parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) Assert.Equal(2, _g.GetParameters(_g.MethodDeclaration("m", parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t")), _g.ParameterDeclaration("p2", _g.IdentifierName("t2"))})).Count) Assert.Equal(0, _g.GetParameters(_g.ConstructorDeclaration()).Count) Assert.Equal(1, _g.GetParameters(_g.ConstructorDeclaration(parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) Assert.Equal(2, _g.GetParameters(_g.ConstructorDeclaration(parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t")), _g.ParameterDeclaration("p2", _g.IdentifierName("t2"))})).Count) Assert.Equal(0, _g.GetParameters(_g.PropertyDeclaration("p", _g.IdentifierName("t"))).Count) Assert.Equal(1, _g.GetParameters(_g.IndexerDeclaration({_g.ParameterDeclaration("p", _g.IdentifierName("t"))}, _g.IdentifierName("t"))).Count) Assert.Equal(2, _g.GetParameters(_g.IndexerDeclaration({_g.ParameterDeclaration("p", _g.IdentifierName("t")), _g.ParameterDeclaration("p2", _g.IdentifierName("t2"))}, _g.IdentifierName("t"))).Count) Assert.Equal(0, _g.GetParameters(_g.ValueReturningLambdaExpression(_g.IdentifierName("expr"))).Count) Assert.Equal(1, _g.GetParameters(_g.ValueReturningLambdaExpression("p1", _g.IdentifierName("expr"))).Count) Assert.Equal(0, _g.GetParameters(_g.VoidReturningLambdaExpression(_g.IdentifierName("expr"))).Count) Assert.Equal(1, _g.GetParameters(_g.VoidReturningLambdaExpression("p1", _g.IdentifierName("expr"))).Count) Assert.Equal(0, _g.GetParameters(_g.DelegateDeclaration("d")).Count) Assert.Equal(1, _g.GetParameters(_g.DelegateDeclaration("d", parameters:={_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) Assert.Equal(0, _g.GetParameters(_g.ClassDeclaration("c")).Count) Assert.Equal(0, _g.GetParameters(_g.IdentifierName("x")).Count) End Sub <Fact> Public Sub TestAddParameters() Assert.Equal(1, _g.GetParameters(_g.AddParameters(_g.MethodDeclaration("m"), {_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) Assert.Equal(1, _g.GetParameters(_g.AddParameters(_g.ConstructorDeclaration(), {_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) Assert.Equal(3, _g.GetParameters(_g.AddParameters(_g.IndexerDeclaration({_g.ParameterDeclaration("p", _g.IdentifierName("t"))}, _g.IdentifierName("t")), {_g.ParameterDeclaration("p2", _g.IdentifierName("t2")), _g.ParameterDeclaration("p3", _g.IdentifierName("t3"))})).Count) Assert.Equal(1, _g.GetParameters(_g.AddParameters(_g.ValueReturningLambdaExpression(_g.IdentifierName("expr")), {_g.LambdaParameter("p")})).Count) Assert.Equal(1, _g.GetParameters(_g.AddParameters(_g.VoidReturningLambdaExpression(_g.IdentifierName("expr")), {_g.LambdaParameter("p")})).Count) Assert.Equal(1, _g.GetParameters(_g.AddParameters(_g.DelegateDeclaration("d"), {_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) Assert.Equal(0, _g.GetParameters(_g.AddParameters(_g.ClassDeclaration("c"), {_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) Assert.Equal(0, _g.GetParameters(_g.AddParameters(_g.IdentifierName("x"), {_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) Assert.Equal(0, _g.GetParameters(_g.AddParameters(_g.PropertyDeclaration("p", _g.IdentifierName("t")), {_g.ParameterDeclaration("p", _g.IdentifierName("t"))})).Count) End Sub <Fact> Public Sub TestGetExpression() ' initializers Assert.Equal("x", _g.GetExpression(_g.FieldDeclaration("f", _g.IdentifierName("t"), initializer:=_g.IdentifierName("x"))).ToString()) Assert.Equal("x", _g.GetExpression(_g.ParameterDeclaration("p", _g.IdentifierName("t"), initializer:=_g.IdentifierName("x"))).ToString()) Assert.Equal("x", _g.GetExpression(_g.LocalDeclarationStatement("loc", initializer:=_g.IdentifierName("x"))).ToString()) ' lambda bodies Assert.Null(_g.GetExpression(_g.ValueReturningLambdaExpression("p", {_g.IdentifierName("x")}))) Assert.Equal(1, _g.GetStatements(_g.ValueReturningLambdaExpression("p", {_g.IdentifierName("x")})).Count) Assert.Equal("x", _g.GetExpression(_g.ValueReturningLambdaExpression(_g.IdentifierName("x"))).ToString()) Assert.Equal("x", _g.GetExpression(_g.VoidReturningLambdaExpression(_g.IdentifierName("x"))).ToString()) Assert.Equal("x", _g.GetExpression(_g.ValueReturningLambdaExpression("p", _g.IdentifierName("x"))).ToString()) Assert.Equal("x", _g.GetExpression(_g.VoidReturningLambdaExpression("p", _g.IdentifierName("x"))).ToString()) Assert.Null(_g.GetExpression(_g.IdentifierName("e"))) End Sub <Fact> Public Sub TestWithExpression() ' initializers Assert.Equal("x", _g.GetExpression(_g.WithExpression(_g.FieldDeclaration("f", _g.IdentifierName("t")), _g.IdentifierName("x"))).ToString()) Assert.Equal("x", _g.GetExpression(_g.WithExpression(_g.ParameterDeclaration("p", _g.IdentifierName("t")), _g.IdentifierName("x"))).ToString()) Assert.Equal("x", _g.GetExpression(_g.WithExpression(_g.LocalDeclarationStatement(_g.IdentifierName("t"), "loc"), _g.IdentifierName("x"))).ToString()) ' lambda bodies Assert.Equal("y", _g.GetExpression(_g.WithExpression(_g.ValueReturningLambdaExpression("p", {_g.IdentifierName("x")}), _g.IdentifierName("y"))).ToString()) Assert.Equal("y", _g.GetExpression(_g.WithExpression(_g.VoidReturningLambdaExpression("p", {_g.IdentifierName("x")}), _g.IdentifierName("y"))).ToString()) Assert.Equal("y", _g.GetExpression(_g.WithExpression(_g.ValueReturningLambdaExpression({_g.IdentifierName("x")}), _g.IdentifierName("y"))).ToString()) Assert.Equal("y", _g.GetExpression(_g.WithExpression(_g.VoidReturningLambdaExpression({_g.IdentifierName("x")}), _g.IdentifierName("y"))).ToString()) Assert.Equal("y", _g.GetExpression(_g.WithExpression(_g.ValueReturningLambdaExpression("p", _g.IdentifierName("x")), _g.IdentifierName("y"))).ToString()) Assert.Equal("y", _g.GetExpression(_g.WithExpression(_g.VoidReturningLambdaExpression("p", _g.IdentifierName("x")), _g.IdentifierName("y"))).ToString()) Assert.Equal("y", _g.GetExpression(_g.WithExpression(_g.ValueReturningLambdaExpression(_g.IdentifierName("x")), _g.IdentifierName("y"))).ToString()) Assert.Equal("y", _g.GetExpression(_g.WithExpression(_g.VoidReturningLambdaExpression(_g.IdentifierName("x")), _g.IdentifierName("y"))).ToString()) VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.WithExpression(_g.ValueReturningLambdaExpression({_g.IdentifierName("s")}), _g.IdentifierName("e")), <x>Function() e</x>.Value) Assert.Null(_g.GetExpression(_g.WithExpression(_g.IdentifierName("e"), _g.IdentifierName("x")))) End Sub <Fact> Public Sub TestWithExpression_LambdaChanges() ' multi line function changes to single line function VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.WithExpression(_g.ValueReturningLambdaExpression({_g.IdentifierName("s")}), _g.IdentifierName("e")), <x>Function() e</x>.Value) ' multi line sub changes to single line sub VerifySyntax(Of SingleLineLambdaExpressionSyntax)( _g.WithExpression(_g.VoidReturningLambdaExpression({_g.IdentifierName("s")}), _g.IdentifierName("e")), <x>Sub() e</x>.Value) ' single line function changes to multi-line function with null expression VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithExpression(_g.ValueReturningLambdaExpression(_g.IdentifierName("e")), Nothing), <x>Function() End Function</x>.Value) ' single line sub changes to multi line sub with null expression VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithExpression(_g.VoidReturningLambdaExpression(_g.IdentifierName("e")), Nothing), <x>Sub() End Sub</x>.Value) ' multi line function no-op when assigned null expression VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithExpression(_g.ValueReturningLambdaExpression({_g.IdentifierName("s")}), Nothing), <x>Function() s End Function</x>.Value) ' multi line sub no-op when assigned null expression VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithExpression(_g.VoidReturningLambdaExpression({_g.IdentifierName("s")}), Nothing), <x>Sub() s End Sub</x>.Value) Assert.Null(_g.GetExpression(_g.WithExpression(_g.IdentifierName("e"), _g.IdentifierName("x")))) End Sub <Fact> Public Sub TestGetStatements() Dim stmts = {_g.ExpressionStatement(_g.AssignmentStatement(_g.IdentifierName("x"), _g.IdentifierName("y"))), _g.ExpressionStatement(_g.InvocationExpression(_g.IdentifierName("fn"), _g.IdentifierName("arg")))} Assert.Equal(0, _g.GetStatements(_g.MethodDeclaration("m")).Count) Assert.Equal(2, _g.GetStatements(_g.MethodDeclaration("m", statements:=stmts)).Count) Assert.Equal(0, _g.GetStatements(_g.ConstructorDeclaration()).Count) Assert.Equal(2, _g.GetStatements(_g.ConstructorDeclaration(statements:=stmts)).Count) Assert.Equal(0, _g.GetStatements(_g.VoidReturningLambdaExpression(_g.IdentifierName("e"))).Count) Assert.Equal(0, _g.GetStatements(_g.VoidReturningLambdaExpression({})).Count) Assert.Equal(2, _g.GetStatements(_g.VoidReturningLambdaExpression(stmts)).Count) Assert.Equal(0, _g.GetStatements(_g.ValueReturningLambdaExpression(_g.IdentifierName("e"))).Count) Assert.Equal(0, _g.GetStatements(_g.ValueReturningLambdaExpression({})).Count) Assert.Equal(2, _g.GetStatements(_g.ValueReturningLambdaExpression(stmts)).Count) Assert.Equal(0, _g.GetStatements(_g.IdentifierName("x")).Count) End Sub <Fact> Public Sub TestWithStatements() Dim stmts = {_g.ExpressionStatement(_g.AssignmentStatement(_g.IdentifierName("x"), _g.IdentifierName("y"))), _g.ExpressionStatement(_g.InvocationExpression(_g.IdentifierName("fn"), _g.IdentifierName("arg")))} Assert.Equal(2, _g.GetStatements(_g.WithStatements(_g.MethodDeclaration("m"), stmts)).Count) Assert.Equal(2, _g.GetStatements(_g.WithStatements(_g.ConstructorDeclaration(), stmts)).Count) Assert.Equal(2, _g.GetStatements(_g.WithStatements(_g.VoidReturningLambdaExpression({}), stmts)).Count) Assert.Equal(2, _g.GetStatements(_g.WithStatements(_g.ValueReturningLambdaExpression({}), stmts)).Count) Assert.Equal(2, _g.GetStatements(_g.WithStatements(_g.VoidReturningLambdaExpression(_g.IdentifierName("e")), stmts)).Count) Assert.Equal(2, _g.GetStatements(_g.WithStatements(_g.ValueReturningLambdaExpression(_g.IdentifierName("e")), stmts)).Count) Assert.Equal(0, _g.GetStatements(_g.WithStatements(_g.IdentifierName("x"), stmts)).Count) End Sub <Fact> Public Sub TestWithStatements_LambdaChanges() Dim stmts = {_g.ExpressionStatement(_g.IdentifierName("x")), _g.ExpressionStatement(_g.IdentifierName("y"))} VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithStatements(_g.VoidReturningLambdaExpression({}), stmts), <x>Sub() x y End Sub</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithStatements(_g.ValueReturningLambdaExpression({}), stmts), <x>Function() x y End Function</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithStatements(_g.VoidReturningLambdaExpression(_g.IdentifierName("e")), stmts), <x>Sub() x y End Sub</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithStatements(_g.ValueReturningLambdaExpression(_g.IdentifierName("e")), stmts), <x>Function() x y End Function</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithStatements(_g.VoidReturningLambdaExpression(stmts), {}), <x>Sub() End Sub</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithStatements(_g.ValueReturningLambdaExpression(stmts), {}), <x>Function() End Function</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithStatements(_g.VoidReturningLambdaExpression(_g.IdentifierName("e")), {}), <x>Sub() End Sub</x>.Value) VerifySyntax(Of MultiLineLambdaExpressionSyntax)( _g.WithStatements(_g.ValueReturningLambdaExpression(_g.IdentifierName("e")), {}), <x>Function() End Function</x>.Value) End Sub <Fact> Public Sub TestAccessorDeclarations() Dim _g = Me._g Dim prop = _g.PropertyDeclaration("p", _g.IdentifierName("T")) Assert.Equal(2, _g.GetAccessors(prop).Count) ' get accessors from property Dim getAccessor = _g.GetAccessor(prop, DeclarationKind.GetAccessor) Assert.NotNull(getAccessor) VerifySyntax(Of AccessorBlockSyntax)(getAccessor, <x>Get End Get</x>.Value) Assert.NotNull(getAccessor) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(getAccessor)) ' get accessors from property Dim setAccessor = _g.GetAccessor(prop, DeclarationKind.SetAccessor) Assert.NotNull(setAccessor) Assert.Equal(Accessibility.NotApplicable, _g.GetAccessibility(setAccessor)) ' remove accessors Assert.Null(_g.GetAccessor(_g.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)) Assert.Null(_g.GetAccessor(_g.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)) ' change accessor accessibility Assert.Equal(Accessibility.Public, _g.GetAccessibility(_g.WithAccessibility(getAccessor, Accessibility.Public))) Assert.Equal(Accessibility.Private, _g.GetAccessibility(_g.WithAccessibility(setAccessor, Accessibility.Private))) ' change accessor statements Assert.Equal(0, _g.GetStatements(getAccessor).Count) Assert.Equal(0, _g.GetStatements(setAccessor).Count) Dim newGetAccessor = _g.WithStatements(getAccessor, Nothing) VerifySyntax(Of AccessorBlockSyntax)(newGetAccessor, <x>Get End Get</x>.Value) ' change accessors Dim newProp = _g.ReplaceNode(prop, getAccessor, _g.WithAccessibility(getAccessor, Accessibility.Public)) Assert.Equal(Accessibility.Public, _g.GetAccessibility(_g.GetAccessor(newProp, DeclarationKind.GetAccessor))) newProp = _g.ReplaceNode(prop, setAccessor, _g.WithAccessibility(setAccessor, Accessibility.Public)) Assert.Equal(Accessibility.Public, _g.GetAccessibility(_g.GetAccessor(newProp, DeclarationKind.SetAccessor))) End Sub <Fact> Public Sub TestGetAccessorStatements() Dim stmts = {_g.ExpressionStatement(_g.AssignmentStatement(_g.IdentifierName("x"), _g.IdentifierName("y"))), _g.ExpressionStatement(_g.InvocationExpression(_g.IdentifierName("fn"), _g.IdentifierName("arg")))} Dim p = _g.ParameterDeclaration("p", _g.IdentifierName("t")) ' get-accessor Assert.Equal(0, _g.GetGetAccessorStatements(_g.PropertyDeclaration("p", _g.IdentifierName("t"))).Count) Assert.Equal(2, _g.GetGetAccessorStatements(_g.PropertyDeclaration("p", _g.IdentifierName("t"), getAccessorStatements:=stmts)).Count) Assert.Equal(0, _g.GetGetAccessorStatements(_g.IndexerDeclaration({p}, _g.IdentifierName("t"))).Count) Assert.Equal(2, _g.GetGetAccessorStatements(_g.IndexerDeclaration({p}, _g.IdentifierName("t"), getAccessorStatements:=stmts)).Count) Assert.Equal(0, _g.GetGetAccessorStatements(_g.IdentifierName("x")).Count) ' set-accessor Assert.Equal(0, _g.GetSetAccessorStatements(_g.PropertyDeclaration("p", _g.IdentifierName("t"))).Count) Assert.Equal(2, _g.GetSetAccessorStatements(_g.PropertyDeclaration("p", _g.IdentifierName("t"), setAccessorStatements:=stmts)).Count) Assert.Equal(0, _g.GetSetAccessorStatements(_g.IndexerDeclaration({p}, _g.IdentifierName("t"))).Count) Assert.Equal(2, _g.GetSetAccessorStatements(_g.IndexerDeclaration({p}, _g.IdentifierName("t"), setAccessorStatements:=stmts)).Count) Assert.Equal(0, _g.GetSetAccessorStatements(_g.IdentifierName("x")).Count) End Sub <Fact> Public Sub TestWithAccessorStatements() Dim stmts = {_g.ExpressionStatement(_g.AssignmentStatement(_g.IdentifierName("x"), _g.IdentifierName("y"))), _g.ExpressionStatement(_g.InvocationExpression(_g.IdentifierName("fn"), _g.IdentifierName("arg")))} Dim p = _g.ParameterDeclaration("p", _g.IdentifierName("t")) ' get-accessor Assert.Equal(2, _g.GetGetAccessorStatements(_g.WithGetAccessorStatements(_g.PropertyDeclaration("p", _g.IdentifierName("t")), stmts)).Count) Assert.Equal(2, _g.GetGetAccessorStatements(_g.WithGetAccessorStatements(_g.IndexerDeclaration({p}, _g.IdentifierName("t")), stmts)).Count) Assert.Equal(0, _g.GetGetAccessorStatements(_g.WithGetAccessorStatements(_g.IdentifierName("x"), stmts)).Count) ' set-accessor Assert.Equal(2, _g.GetSetAccessorStatements(_g.WithSetAccessorStatements(_g.PropertyDeclaration("p", _g.IdentifierName("t")), stmts)).Count) Assert.Equal(2, _g.GetSetAccessorStatements(_g.WithSetAccessorStatements(_g.IndexerDeclaration({p}, _g.IdentifierName("t")), stmts)).Count) Assert.Equal(0, _g.GetSetAccessorStatements(_g.WithSetAccessorStatements(_g.IdentifierName("x"), stmts)).Count) End Sub Private Sub AssertNamesEqual(expectedNames As String(), actualNodes As IReadOnlyList(Of SyntaxNode)) Dim actualNames = actualNodes.Select(Function(n) _g.GetName(n)).ToArray() Assert.Equal(expectedNames.Length, actualNames.Length) Dim expected = String.Join(", ", expectedNames) Dim actual = String.Join(", ", actualNames) Assert.Equal(expected, actual) End Sub Private Sub AssertMemberNamesEqual(expectedNames As String(), declaration As SyntaxNode) AssertNamesEqual(expectedNames, _g.GetMembers(declaration)) End Sub Private Sub AssertMemberNamesEqual(expectedName As String, declaration As SyntaxNode) AssertMemberNamesEqual({expectedName}, declaration) End Sub <Fact> Public Sub TestGetMembers() AssertMemberNamesEqual("m", _g.ClassDeclaration("c", members:={_g.MethodDeclaration("m")})) AssertMemberNamesEqual("m", _g.StructDeclaration("s", members:={_g.MethodDeclaration("m")})) AssertMemberNamesEqual("m", _g.InterfaceDeclaration("i", members:={_g.MethodDeclaration("m")})) AssertMemberNamesEqual("v", _g.EnumDeclaration("e", members:={_g.EnumMember("v")})) AssertMemberNamesEqual("c", _g.NamespaceDeclaration("n", declarations:={_g.ClassDeclaration("c")})) AssertMemberNamesEqual("c", _g.CompilationUnit(declarations:={_g.ClassDeclaration("c")})) End Sub <Fact> Public Sub TestAddMembers() AssertMemberNamesEqual("m", _g.AddMembers(_g.ClassDeclaration("d"), {_g.MethodDeclaration("m")})) AssertMemberNamesEqual("m", _g.AddMembers(_g.StructDeclaration("s"), {_g.MethodDeclaration("m")})) AssertMemberNamesEqual("m", _g.AddMembers(_g.InterfaceDeclaration("i"), {_g.MethodDeclaration("m")})) AssertMemberNamesEqual("v", _g.AddMembers(_g.EnumDeclaration("e"), {_g.EnumMember("v")})) AssertMemberNamesEqual("n2", _g.AddMembers(_g.NamespaceDeclaration("n"), {_g.NamespaceDeclaration("n2")})) AssertMemberNamesEqual("n", _g.AddMembers(_g.CompilationUnit(), {_g.NamespaceDeclaration("n")})) AssertMemberNamesEqual({"m", "m2"}, _g.AddMembers(_g.ClassDeclaration("d", members:={_g.MethodDeclaration("m")}), {_g.MethodDeclaration("m2")})) AssertMemberNamesEqual({"m", "m2"}, _g.AddMembers(_g.StructDeclaration("s", members:={_g.MethodDeclaration("m")}), {_g.MethodDeclaration("m2")})) AssertMemberNamesEqual({"m", "m2"}, _g.AddMembers(_g.InterfaceDeclaration("i", members:={_g.MethodDeclaration("m")}), {_g.MethodDeclaration("m2")})) AssertMemberNamesEqual({"v", "v2"}, _g.AddMembers(_g.EnumDeclaration("i", members:={_g.EnumMember("v")}), {_g.EnumMember("v2")})) AssertMemberNamesEqual({"n1", "n2"}, _g.AddMembers(_g.NamespaceDeclaration("n", {_g.NamespaceDeclaration("n1")}), {_g.NamespaceDeclaration("n2")})) AssertMemberNamesEqual({"n1", "n2"}, _g.AddMembers(_g.CompilationUnit(declarations:={_g.NamespaceDeclaration("n1")}), {_g.NamespaceDeclaration("n2")})) End Sub <Fact> Public Sub TestRemoveMembers() TestRemoveAllMembers(_g.ClassDeclaration("d", members:={_g.MethodDeclaration("m")})) TestRemoveAllMembers(_g.StructDeclaration("s", members:={_g.MethodDeclaration("m")})) TestRemoveAllMembers(_g.InterfaceDeclaration("i", members:={_g.MethodDeclaration("m")})) TestRemoveAllMembers(_g.EnumDeclaration("i", members:={_g.EnumMember("v")})) TestRemoveAllMembers(_g.AddMembers(_g.NamespaceDeclaration("n", {_g.NamespaceDeclaration("n1")}))) TestRemoveAllMembers(_g.AddMembers(_g.CompilationUnit(declarations:={_g.NamespaceDeclaration("n1")}))) End Sub Private Sub TestRemoveAllMembers(declaration As SyntaxNode) Assert.Equal(0, _g.GetMembers(_g.RemoveNodes(declaration, _g.GetMembers(declaration))).Count) End Sub Private Sub TestRemoveMember(declaration As SyntaxNode, name As String, remainingNames As String()) Dim newDecl = _g.RemoveNode(declaration, _g.GetMembers(declaration).First(Function(m) _g.GetName(m) = name)) AssertMemberNamesEqual(remainingNames, newDecl) End Sub <Fact> Public Sub TestGetBaseAndInterfaceTypes() Dim classBI = SyntaxFactory.ParseCompilationUnit( <x>Class C Inherits B Implements I End Class</x>.Value).Members(0) Dim baseListBI = _g.GetBaseAndInterfaceTypes(classBI) Assert.NotNull(baseListBI) Assert.Equal(2, baseListBI.Count) Assert.Equal("B", baseListBI(0).ToString()) Assert.Equal("I", baseListBI(1).ToString()) Dim ifaceI = SyntaxFactory.ParseCompilationUnit( <x>Interface I Inherits X Inherits Y End Class</x>.Value).Members(0) Dim baseListXY = _g.GetBaseAndInterfaceTypes(ifaceI) Assert.NotNull(baseListXY) Assert.Equal(2, baseListXY.Count) Assert.Equal("X", baseListXY(0).ToString()) Assert.Equal("Y", baseListXY(1).ToString()) Dim classN = SyntaxFactory.ParseCompilationUnit( <x>Class C End Class</x>.Value).Members(0) Dim baseListN = _g.GetBaseAndInterfaceTypes(classN) Assert.NotNull(baseListN) Assert.Equal(0, baseListN.Count) End Sub <Fact> Public Sub TestRemoveBaseAndInterfaceTypes() Dim classC = SyntaxFactory.ParseCompilationUnit( <x>Class C Inherits A Implements X, Y End Class</x>.Value).Members(0) Dim baseList = _g.GetBaseAndInterfaceTypes(classC) Assert.Equal(3, baseList.Count) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(classC, baseList(0)), <x>Class C Implements X, Y End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(classC, baseList(1)), <x>Class C Inherits A Implements Y End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(classC, baseList(2)), <x>Class C Inherits A Implements X End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(classC, {baseList(1), baseList(2)}), <x>Class C Inherits A End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(classC, baseList), <x>Class C End Class</x>.Value) End Sub <Fact> Public Sub TestAddBaseType() Dim classC = SyntaxFactory.ParseCompilationUnit( <x>Class C End Class</x>.Value).Members(0) Dim classCB = SyntaxFactory.ParseCompilationUnit( <x>Class C Inherits B End Class</x>.Value).Members(0) Dim structS = SyntaxFactory.ParseCompilationUnit( <x>Structure S End Structure</x>.Value).Members(0) Dim ifaceI = SyntaxFactory.ParseCompilationUnit( <x>Interface I End Interface</x>.Value).Members(0) VerifySyntax(Of ClassBlockSyntax)( _g.AddBaseType(classC, _g.IdentifierName("T")), <x>Class C Inherits T End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.AddBaseType(classCB, _g.IdentifierName("T")), <x>Class C Inherits T End Class</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.AddBaseType(structS, _g.IdentifierName("T")), <x>Structure S End Structure</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.AddBaseType(ifaceI, _g.IdentifierName("T")), <x>Interface I End Interface</x>.Value) End Sub <Fact> Public Sub TestAddInterfaceType() Dim classC = SyntaxFactory.ParseCompilationUnit( <x>Class C End Class</x>.Value).Members(0) Dim classCB = SyntaxFactory.ParseCompilationUnit( <x>Class C Inherits B End Class</x>.Value).Members(0) Dim classCI = SyntaxFactory.ParseCompilationUnit( <x>Class C Implements I End Class</x>.Value).Members(0) Dim structS = SyntaxFactory.ParseCompilationUnit( <x>Structure S End Structure</x>.Value).Members(0) Dim ifaceI = SyntaxFactory.ParseCompilationUnit( <x>Interface I End Interface</x>.Value).Members(0) VerifySyntax(Of ClassBlockSyntax)( _g.AddInterfaceType(classC, _g.IdentifierName("T")), <x>Class C Implements T End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.AddInterfaceType(classCB, _g.IdentifierName("T")), <x>Class C Inherits B Implements T End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.AddInterfaceType(classCI, _g.IdentifierName("T")), <x>Class C Implements I, T End Class</x>.Value) VerifySyntax(Of StructureBlockSyntax)( _g.AddInterfaceType(structS, _g.IdentifierName("T")), <x>Structure S Implements T End Structure</x>.Value) VerifySyntax(Of InterfaceBlockSyntax)( _g.AddInterfaceType(ifaceI, _g.IdentifierName("T")), <x>Interface I Inherits T End Interface</x>.Value) End Sub <Fact> Public Sub TestMultiFieldMembers() Dim comp = Compile( <x>' Comment Public Class C Public Shared X, Y, Z As Integer End Class</x>.Value) Dim symbolC = DirectCast(comp.GlobalNamespace.GetMembers("C").First(), INamedTypeSymbol) Dim symbolX = DirectCast(symbolC.GetMembers("X").First(), IFieldSymbol) Dim symbolY = DirectCast(symbolC.GetMembers("Y").First(), IFieldSymbol) Dim symbolZ = DirectCast(symbolC.GetMembers("Z").First(), IFieldSymbol) Dim declC = _g.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(Function(x) x.GetSyntax()).First()) Dim declX = _g.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(Function(x) x.GetSyntax()).First()) Dim declY = _g.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(Function(x) x.GetSyntax()).First()) Dim declZ = _g.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(Function(x) x.GetSyntax()).First()) Assert.Equal(SyntaxKind.ModifiedIdentifier, declX.Kind) Assert.Equal(SyntaxKind.ModifiedIdentifier, declY.Kind) Assert.Equal(SyntaxKind.ModifiedIdentifier, declZ.Kind) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(declX)) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(declY)) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(declZ)) Assert.NotNull(_g.GetType(declX)) Assert.Equal("Integer", _g.GetType(declX).ToString()) Assert.Equal("X", _g.GetName(declX)) Assert.Equal(Accessibility.Public, _g.GetAccessibility(declX)) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(declX)) Assert.NotNull(_g.GetType(declY)) Assert.Equal("Integer", _g.GetType(declY).ToString()) Assert.Equal("Y", _g.GetName(declY)) Assert.Equal(Accessibility.Public, _g.GetAccessibility(declY)) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(declY)) Assert.NotNull(_g.GetType(declZ)) Assert.Equal("Integer", _g.GetType(declZ).ToString()) Assert.Equal("Z", _g.GetName(declZ)) Assert.Equal(Accessibility.Public, _g.GetAccessibility(declZ)) Assert.Equal(DeclarationModifiers.Static, _g.GetModifiers(declZ)) Dim xTypedT = _g.WithType(declX, _g.IdentifierName("T")) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(xTypedT)) Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind) Assert.Equal("T", _g.GetType(xTypedT).ToString()) Dim xNamedQ = _g.WithName(declX, "Q") Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(xNamedQ)) Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind) Assert.Equal("Q", _g.GetName(xNamedQ).ToString()) Dim xInitialized = _g.WithExpression(declX, _g.IdentifierName("e")) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(xInitialized)) Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind) Assert.Equal("e", _g.GetExpression(xInitialized).ToString()) Dim xPrivate = _g.WithAccessibility(declX, Accessibility.Private) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(xPrivate)) Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind) Assert.Equal(Accessibility.Private, _g.GetAccessibility(xPrivate)) Dim xReadOnly = _g.WithModifiers(declX, DeclarationModifiers.ReadOnly) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(xReadOnly)) Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind) Assert.Equal(DeclarationModifiers.ReadOnly, _g.GetModifiers(xReadOnly)) Dim xAttributed = _g.AddAttributes(declX, _g.Attribute("A")) Assert.Equal(DeclarationKind.Field, _g.GetDeclarationKind(xAttributed)) Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind) Assert.Equal(1, _g.GetAttributes(xAttributed).Count) Assert.Equal("<A>", _g.GetAttributes(xAttributed)(0).ToString()) Dim membersC = _g.GetMembers(declC) Assert.Equal(3, membersC.Count) Assert.Equal(declX, membersC(0)) Assert.Equal(declY, membersC(1)) Assert.Equal(declZ, membersC(2)) ' create new class from existing members, now appear as separate declarations VerifySyntax(Of ClassBlockSyntax)( _g.ClassDeclaration("C", members:={declX, declY}), <x>Class C Public Shared X As Integer Public Shared Y As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.InsertMembers(declC, 0, _g.FieldDeclaration("A", _g.IdentifierName("T"))), <x>' Comment Public Class C Dim A As T Public Shared X, Y, Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.InsertMembers(declC, 1, _g.FieldDeclaration("A", _g.IdentifierName("T"))), <x>' Comment Public Class C Public Shared X As Integer Dim A As T Public Shared Y, Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.InsertMembers(declC, 2, _g.FieldDeclaration("A", _g.IdentifierName("T"))), <x>' Comment Public Class C Public Shared X, Y As Integer Dim A As T Public Shared Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.InsertMembers(declC, 3, _g.FieldDeclaration("A", _g.IdentifierName("T"))), <x>' Comment Public Class C Public Shared X, Y, Z As Integer Dim A As T End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ReplaceNode(declC, declX, _g.WithType(declX, _g.IdentifierName("T"))), <x>' Comment Public Class C Public Shared X As T Public Shared Y, Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ReplaceNode(declC, declX, _g.WithExpression(declX, _g.IdentifierName("e"))), <x>' Comment Public Class C Public Shared X As Integer = e Public Shared Y, Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ReplaceNode(declC, declX, _g.WithName(declX, "Q")), <x>' Comment Public Class C Public Shared Q, Y, Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ReplaceNode(declC, declY, _g.WithType(declY, _g.IdentifierName("T"))), <x>' Comment Public Class C Public Shared X As Integer Public Shared Y As T Public Shared Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ReplaceNode(declC, declZ, _g.WithType(declZ, _g.IdentifierName("T"))), <x>' Comment Public Class C Public Shared X, Y As Integer Public Shared Z As T End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ReplaceNode(declC, declX, declZ), <x>' Comment Public Class C Public Shared Z, Y, Z As Integer End Class</x>.Value) ' Removing VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(declC, declX), <x>' Comment Public Class C Public Shared Y, Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(declC, declY), <x>' Comment Public Class C Public Shared X, Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(declC, declZ), <x>' Comment Public Class C Public Shared X, Y As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(declC, {declX, declY}), <x>' Comment Public Class C Public Shared Z As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(declC, {declX, declZ}), <x>' Comment Public Class C Public Shared Y As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(declC, {declY, declZ}), <x>' Comment Public Class C Public Shared X As Integer End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(declC, {declX, declY, declZ}), <x>' Comment Public Class C End Class</x>.Value) End Sub <Fact> Public Sub TestMultiAttributes() Dim comp = Compile( <x>' Comment &lt;X, Y, Z&gt; Public Class C End Class</x>.Value) Dim symbolC = DirectCast(comp.GlobalNamespace.GetMembers("C").First(), INamedTypeSymbol) Dim declC = _g.GetDeclaration(symbolC.DeclaringSyntaxReferences.First().GetSyntax()) Dim attrs = _g.GetAttributes(declC) Assert.Equal(3, attrs.Count) Dim declX = attrs(0) Dim declY = attrs(1) Dim declZ = attrs(2) Assert.Equal(SyntaxKind.Attribute, declX.Kind) Assert.Equal(SyntaxKind.Attribute, declY.Kind) Assert.Equal(SyntaxKind.Attribute, declZ.Kind) Assert.Equal("X", _g.GetName(declX)) Assert.Equal("Y", _g.GetName(declY)) Assert.Equal("Z", _g.GetName(declZ)) Dim xNamedQ = _g.WithName(declX, "Q") Assert.Equal(DeclarationKind.Attribute, _g.GetDeclarationKind(xNamedQ)) Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind) Assert.Equal("<Q>", xNamedQ.ToString()) Dim xWithArg = _g.AddAttributeArguments(declX, {_g.AttributeArgument(_g.IdentifierName("e"))}) Assert.Equal(DeclarationKind.Attribute, _g.GetDeclarationKind(xWithArg)) Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind) Assert.Equal("<X(e)>", xWithArg.ToString()) ' inserting VerifySyntax(Of ClassBlockSyntax)( _g.InsertAttributes(declC, 0, _g.Attribute("A")), <x>' Comment &lt;A&gt; &lt;X, Y, Z&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.InsertAttributes(declC, 1, _g.Attribute("A")), <x>' Comment &lt;X&gt; &lt;A&gt; &lt;Y, Z&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.InsertAttributes(declC, 2, _g.Attribute("A")), <x>' Comment &lt;X, Y&gt; &lt;A&gt; &lt;Z&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.InsertAttributes(declC, 3, _g.Attribute("A")), <x>' Comment &lt;X, Y, Z&gt; &lt;A&gt; Public Class C End Class</x>.Value) ' replacing VerifySyntax(Of ClassBlockSyntax)( _g.ReplaceNode(declC, declX, _g.Attribute("A")), <x>' Comment &lt;A, Y, Z&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.ReplaceNode(declC, declX, _g.InsertAttributeArguments(declX, 0, {_g.AttributeArgument(_g.IdentifierName("e"))})), <x>' Comment &lt;X(e), Y, Z&gt; Public Class C End Class</x>.Value) ' removing VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(declC, declX), <x>' Comment &lt;Y, Z&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(declC, declY), <x>' Comment &lt;X, Z&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNode(declC, declZ), <x>' Comment &lt;X, Y&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(declC, {declX, declY}), <x>' Comment &lt;Z&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(declC, {declX, declZ}), <x>' Comment &lt;Y&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(declC, {declY, declZ}), <x>' Comment &lt;X&gt; Public Class C End Class</x>.Value) VerifySyntax(Of ClassBlockSyntax)( _g.RemoveNodes(declC, {declX, declY, declZ}), <x>' Comment Public Class C End Class</x>.Value) End Sub <Fact> Public Sub TestMultiImports() Dim comp = Compile( <x>' Comment Imports X, Y, Z </x>.Value) Dim declCU = comp.SyntaxTrees.First().GetRoot() Assert.Equal(SyntaxKind.CompilationUnit, declCU.Kind) Dim imps = _g.GetNamespaceImports(declCU) Assert.Equal(3, imps.Count) Dim declX = imps(0) Dim declY = imps(1) Dim declZ = imps(2) Dim xRenamedQ = _g.WithName(declX, "Q") Assert.Equal(DeclarationKind.NamespaceImport, _g.GetDeclarationKind(xRenamedQ)) Assert.Equal(SyntaxKind.ImportsStatement, xRenamedQ.Kind) Assert.Equal("Imports Q", xRenamedQ.ToString()) ' inserting VerifySyntax(Of CompilationUnitSyntax)( _g.InsertNamespaceImports(declCU, 0, _g.NamespaceImportDeclaration("N")), <x>' Comment Imports N Imports X, Y, Z </x>.Value) VerifySyntax(Of CompilationUnitSyntax)( _g.InsertNamespaceImports(declCU, 1, _g.NamespaceImportDeclaration("N")), <x>' Comment Imports X Imports N Imports Y, Z </x>.Value) VerifySyntax(Of CompilationUnitSyntax)( _g.InsertNamespaceImports(declCU, 2, _g.NamespaceImportDeclaration("N")), <x>' Comment Imports X, Y Imports N Imports Z </x>.Value) VerifySyntax(Of CompilationUnitSyntax)( _g.InsertNamespaceImports(declCU, 3, _g.NamespaceImportDeclaration("N")), <x>' Comment Imports X, Y, Z Imports N </x>.Value) ' Replacing VerifySyntax(Of CompilationUnitSyntax)( _g.ReplaceNode(declCU, declX, _g.NamespaceImportDeclaration("N")), <x>' Comment Imports N, Y, Z </x>.Value) ' Removing VerifySyntax(Of CompilationUnitSyntax)( _g.RemoveNode(declCU, declX), <x>' Comment Imports Y, Z </x>.Value) ' Removing VerifySyntax(Of CompilationUnitSyntax)( _g.RemoveNode(declCU, declY), <x>' Comment Imports X, Z </x>.Value) ' Removing VerifySyntax(Of CompilationUnitSyntax)( _g.RemoveNode(declCU, declZ), <x>' Comment Imports X, Y </x>.Value) ' Removing VerifySyntax(Of CompilationUnitSyntax)( _g.RemoveNodes(declCU, {declX, declY}), <x>' Comment Imports Z </x>.Value) ' Removing VerifySyntax(Of CompilationUnitSyntax)( _g.RemoveNodes(declCU, {declX, declZ}), <x>' Comment Imports Y </x>.Value) ' Removing VerifySyntax(Of CompilationUnitSyntax)( _g.RemoveNodes(declCU, {declY, declZ}), <x>' Comment Imports X </x>.Value) ' Removing VerifySyntax(Of CompilationUnitSyntax)( _g.RemoveNodes(declCU, {declX, declY, declZ}), <x>' Comment </x>.Value) End Sub End Class End Namespace
akoeplinger/roslyn
src/Workspaces/VisualBasicTest/CodeGeneration/SyntaxGeneratorTests.vb
Visual Basic
apache-2.0
140,508
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition Imports Microsoft.CodeAnalysis.Navigation Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename Public Class RenameNonRenameableSymbols <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameInheritedMetadataButRenameCascade() Using result = RenameEngineResult.Create( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using A; class B : A { public override int {|conflict:prop|} { get; set; } } class C : A { public override int [|prop$$|] { get; set; } } </Document> <MetadataReferenceFromSource Language="C#" CommonReferences="true"> <Document FilePath="ReferencedDocument"> public class A { public virtual int prop { get; set; } } </Document> </MetadataReferenceFromSource> </Project> </Workspace>, renameTo:="proper") result.AssertLabeledSpansAre("conflict", "proper", RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameEventWithInvalidNames() Using result = RenameEngineResult.Create( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public delegate void MyDelegate(); class B { public event MyDelegate {|Invalid:$$x|}; } </Document> </Project> </Workspace>, renameTo:="!x") result.AssertReplacementTextInvalid() result.AssertLabeledSpansAre("Invalid", "!x", RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameSpecialNames() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class B { public static B operator $$|(B x, B y) { return x; } } </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameTrivia() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class B {[|$$ |]} </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <WorkItem(883263)> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameCandidateSymbol() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void X(int x) { $$X(); } } </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameSyntheticDefinition() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public int X { set { int y = $$value; } } } </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameXmlLiteralProperty() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Module M Dim x = <x/>.<x>.$$Value End Module ]]></Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameSymbolDefinedInMetaData() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { System.Con$$sole.Write(5); } } </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameSymbolInReadOnlyBuffer() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { $$M(); } } </Document> </Project> </Workspace>) Dim textBuffer = workspace.Documents.Single().TextBuffer Using readOnlyEdit = textBuffer.CreateReadOnlyRegionEdit() readOnlyEdit.CreateReadOnlyRegion(New Span(0, textBuffer.CurrentSnapshot.Length)) readOnlyEdit.Apply() End Using AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameSymbolThatBindsToErrorType() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { int ^^$$x = 0; } } </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543018)> Public Sub CannotRenameSynthesizedParameters() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Delegate Sub F Module Program Sub Main(args As String()) Dim f As F f.EndInvoke($$DelegateAsyncResult:=Nothing) End Sub End Module </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <WorkItem(539554)> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenamePredefinedType() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Dim x As $$String End Module </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <WorkItem(542937)> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameContextualKeyword() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim query = From i In New C $$Group Join j In New C On i Equals j Into g = Group End Sub End Module </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <WorkItem(543714)> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameOperator() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class MyClass { public static MyClass operator ++(MyClass c) { return null; } public static void M() { $$op_Increment(null); } } </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <Fact> <WorkItem(529751)> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameExternAlias() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> extern alias foo; // foo is unresolved class A { object x = new $$foo::X(); } </Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <WorkItem(543969)> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameElementFromPreviousSubmission() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Submission Language="C#" CommonReferences="true"> int foo; </Submission> <Submission Language="C#" CommonReferences="true"> $$foo = 42; </Submission> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <WorkItem(689002)> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameHiddenElement() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class $$R End Class ]]></Document> </Project> </Workspace>) Dim navigationService = DirectCast(workspace.Services.GetService(Of IDocumentNavigationService)(), MockDocumentNavigationService) navigationService._canNavigateToSpan = False AssertTokenNotRenamable(workspace) End Using End Sub <WorkItem(767187)> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameConstructorInVb() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class R ''' <summary> ''' <see cref="R.New()"/> ''' </summary> Shared Sub New() End Sub ''' <summary> ''' <see cref="R.$$New()"/> ''' </summary> Public Sub New() End Sub End Class ]]></Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <WorkItem(767187)> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameConstructorInVb2() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class R ''' <summary> ''' <see cref="R.$$New()"/> ''' </summary> Shared Sub New() End Sub End Class ]]></Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub <WorkItem(767187)> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameConstructorInVb3() Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class Base End Class Class R Inherits Base Public Sub New() Mybase.$$New() End Sub End Class ]]></Document> </Project> </Workspace>) AssertTokenNotRenamable(workspace) End Using End Sub End Class End Namespace
droyad/roslyn
src/EditorFeatures/Test2/Rename/RenameNonRenameableSymbols.vb
Visual Basic
apache-2.0
17,667
Namespace Security.BackStage_Help Public Class SupportForum Inherits SecurityItemBase Public Sub New() _ConceptItemName = "Support Forum" _ConceptName = "BackStage_Help" _Description = "Allow access to 'Support Forum' button" _IsEnterprise = True _IsSmallBusiness = True _IsViewer = False _IsWeb = True _IsWebPlus = True End Sub End Class End Namespace
nublet/DMS
DMS.Forms.Shared/Security/Items/Backstage/Help/SupportForum.vb
Visual Basic
mit
490
Namespace IBM Partial Public Class PowerSupply Implements IMonitorable #Region " IMonitorable Implementation " Public ReadOnly Property IsPowerSupplyHealthy() As Health Implements IMonitorable.IsHealthy Get If Exists Then If State = PowerSupplyState.NotAvailable Then Return New Health(HealthStatus.Down, String.Format(Resources.HEALTH_IBM_POWERSUPPLYSTATUS, Index, State)) ElseIf State = PowerSupplyState.Warning Then Return New Health(HealthStatus.Degraded, String.Format(Resources.HEALTH_IBM_POWERSUPPLYSTATUS, Index, State)) End If End If Return New Health(HealthStatus.Healthy) End Get End Property #End Region End Class End Namespace
thiscouldbejd/Caerus
_IBM/Partials/PowerSupply.vb
Visual Basic
mit
727
Imports System.Text Imports System.Globalization Friend Class Normalization Public Shared Function Normalize(ByVal text As String) As String Dim removedPunctuation = RemovePunctuationStart(text) Dim removedDiacritics = RemoveDiacritics(removedPunctuation) Dim byteEncoding = RemoveByteEncoding(removedDiacritics) Dim tolower = byteEncoding.ToLowerInvariant() Dim normalized = tolower Return normalized End Function Private Shared Function RemovePunctuationStart(ByVal text As String) As String Dim charstoRemove() As Char = {"!", "¡", """", "#", "%", "&", "'", "(", ")", "*", ",", "-", ".", "/", ":", ";", "?", "¿", "@", "[", "\\", "]", "_", "{", "}"} Dim newString As String = text.TrimStart(charstoRemove) Return newString End Function Private Shared Function RemoveByteEncoding(ByVal accentedStr As String) Dim tempBytes As Byte() tempBytes = System.Text.Encoding.GetEncoding("ISO-8859-8").GetBytes(accentedStr) Dim asciiStr As String = System.Text.Encoding.UTF8.GetString(tempBytes) Return asciiStr End Function Private Shared Function RemoveDiacritics(text As String) As String Dim normalizedString = text.Normalize(NormalizationForm.FormD) Dim stringBuilder = New StringBuilder() For Each c In normalizedString Dim unicodeCategory1 = CharUnicodeInfo.GetUnicodeCategory(c) If unicodeCategory1 <> UnicodeCategory.NonSpacingMark Then stringBuilder.Append(c) End If Next Return stringBuilder.ToString().Normalize(NormalizationForm.FormC) End Function End Class
JonathanDDuncan/SignWriterStudio
SignWriterStudio.Dictionary/Normalization.vb
Visual Basic
mit
1,705
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Class Language Private Shared resourceMan As Global.System.Resources.ResourceManager Private Shared resourceCulture As Global.System.Globalization.CultureInfo <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend Sub New() MyBase.New End Sub '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Shared 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("DotNet3dsToolkit.Language", GetType(Language).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 Shared Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property '''<summary> ''' Looks up a localized string similar to Complete. '''</summary> Friend Shared ReadOnly Property Complete() As String Get Return ResourceManager.GetString("Complete", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to StepCount cannot be 0.. '''</summary> Friend Shared ReadOnly Property ErrorAsyncForInfiniteLoop() As String Get Return ResourceManager.GetString("ErrorAsyncForInfiniteLoop", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to Neither file nor directory not found at &quot;{0}&quot;.. '''</summary> Friend Shared ReadOnly Property ErrorFileDirNotFound() As String Get Return ResourceManager.GetString("ErrorFileDirNotFound", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to Input ROM cannot be inside output directory.. '''</summary> Friend Shared ReadOnly Property ErrorInputFileCannotBeInOutput() As String Get Return ResourceManager.GetString("ErrorInputFileCannotBeInOutput", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to The file format is invalid or unsupported.. '''</summary> Friend Shared ReadOnly Property ErrorInvalidFileFormat() As String Get Return ResourceManager.GetString("ErrorInvalidFileFormat", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to The given path is in an incorrect format: &quot;{0}&quot;. '''</summary> Friend Shared ReadOnly Property ErrorInvalidPathFormat() As String Get Return ResourceManager.GetString("ErrorInvalidPathFormat", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to A file required for building is missing: &quot;{0}&quot;. '''</summary> Friend Shared ReadOnly Property ErrorMissingFile() As String Get Return ResourceManager.GetString("ErrorMissingFile", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to Using GenericFile.Save() requires GenericFile.OriginalFilename to not be null.. '''</summary> Friend Shared ReadOnly Property ErrorNoSaveFilename() As String Get Return ResourceManager.GetString("ErrorNoSaveFilename", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to File at the given path in the ROM could not be found.. '''</summary> Friend Shared ReadOnly Property ErrorROMFileNotFound() As String Get Return ResourceManager.GetString("ErrorROMFileNotFound", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to Unsupported system format {0}. '''</summary> Friend Shared ReadOnly Property ErrorSystemNotSupported() As String Get Return ResourceManager.GetString("ErrorSystemNotSupported", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to Attempted to write to a read-only file.. '''</summary> Friend Shared ReadOnly Property ErrorWrittenReadonly() As String Get Return ResourceManager.GetString("ErrorWrittenReadonly", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to Unpacking.... '''</summary> Friend Shared ReadOnly Property LoadingUnpacking() As String Get Return ResourceManager.GetString("LoadingUnpacking", resourceCulture) End Get End Property End Class End Namespace
evandixon/DotNet3dsToolkit
Old/DotNet3dsToolkit/Language.Designer.vb
Visual Basic
mit
7,302
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' Общие сведения об этой сборке предоставляются следующим набором ' атрибутов. Отредактируйте значения этих атрибутов, чтобы изменить ' общие сведения об этой сборке. ' Проверьте значения атрибутов сборки <Assembly: AssemblyTitle("WindowsApplication2")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("WindowsApplication2")> <Assembly: AssemblyCopyright("Copyright © 2015")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM <Assembly: Guid("1f586b42-92a3-4397-bb03-da9022f94374")> ' Сведения о версии сборки состоят из следующих четырех значений: ' ' Основной номер версии ' Дополнительный номер версии ' Номер сборки ' Редакция ' ' Можно задать все значения или принять номера сборки и редакции по умолчанию ' используя "*", как показано ниже: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.15")> <Assembly: AssemblyFileVersion("1.0.0.15")>
Denchick777/wwtbam_control_program
WindowsApplication1/WindowsApplication2/My Project/AssemblyInfo.vb
Visual Basic
mit
1,636
 Partial Class login_Default Inherits System.Web.UI.Page End Class
select-interactive/SI-CRE
login/Default.aspx.vb
Visual Basic
mit
75
Imports GemBox.Document Module Program Sub Main() ' If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY") Dim document As New DocumentModel() Dim bookmarkName = "TopOfDocument" document.Sections.Add( New Section(document, New Paragraph(document, New BookmarkStart(document, bookmarkName), New Run(document, "This is a 'TopOfDocument' bookmark."), New BookmarkEnd(document, bookmarkName)), New Paragraph(document, New Run(document, "The following is a link to "), New Hyperlink(document, "https://www.gemboxsoftware.com/document", "GemBox.Document Overview"), New Run(document, " page.")), New Paragraph(document, New SpecialCharacter(document, SpecialCharacterType.PageBreak), New Run(document, "This is a document's second page."), New SpecialCharacter(document, SpecialCharacterType.LineBreak), New Hyperlink(document, bookmarkName, "Return to 'TopOfDocument'.") With {.IsBookmarkLink = True}))) document.Save("Bookmarks and Hyperlinks.docx") End Sub End Module
gemboxsoftware-dev-team/GemBox.Document.Examples
VB.NET/Basic Features/Bookmarks And Hyperlinks/Program.vb
Visual Basic
mit
1,337
Imports System.Reflection Imports System.Runtime.InteropServices ' Information about this assembly is defined by the following ' attributes. ' ' change them to the information which is associated with the assembly ' you compile. <assembly: AssemblyTitle("snmpbulkget")> <assembly: AssemblyDescription("")> <assembly: AssemblyConfiguration("")> <assembly: AssemblyCompany("")> <assembly: AssemblyProduct("snmpbulkget")> <assembly: AssemblyCopyright("Copyright 2010")> <assembly: AssemblyTrademark("")> <assembly: AssemblyCulture("")> ' This sets the default COM visibility of types in the assembly to invisible. ' If you need to expose a type to COM, use <ComVisible(true)> on that type. <assembly: ComVisible(False)>
yonglehou/sharpsnmplib
Samples/VB.NET/snmpbulkget/Properties/AssemblyInfo.vb
Visual Basic
mit
724
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18444 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.Shapes.My.MySettings Get Return Global.Shapes.My.MySettings.Default End Get End Property End Module End Namespace
tima-t/codesCSharp
C#OOP/OOP-Principles - Part 2/Shapes/My Project/Settings.Designer.vb
Visual Basic
mit
2,918
Imports System Imports Csla Namespace TestProject.Business Public Partial Class DocTypeEditColl #Region " OnDeserialized actions " ''' <summary> ''' This method is called on a newly deserialized object ''' after deserialization is complete. ''' </summary> Protected Overrides Sub OnDeserialized() MyBase.OnDeserialized() AddHandler Saved, AddressOf OnDocTypeEditCollSaved ' add your custom OnDeserialized actions here. End Sub #End Region #Region " Implementation of DataPortal Hooks " ' Private Sub OnFetchPre(args As DataPortalHookArgs) ' Throw New NotImplementedException() ' End Sub ' Private Sub OnFetchPost(args As DataPortalHookArgs) ' Throw New NotImplementedException() ' End Sub #End Region End Class End Namespace
CslaGenFork/CslaGenFork
trunk/CoverageTest/TestProject/VB/TestProject.Business/DocTypeEditColl.vb
Visual Basic
mit
952
Partial Public Class ContentFrame2 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load jQueryLibrary.ThemeAdder.AddThemeToIframe(Me) End Sub End Class
Micmaz/DTIControls
JqueryUIControls/JqueryUIControlsTest/ContentFrame2.aspx.vb
Visual Basic
mit
242
' 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.Hosting Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion Public Class AutomaticParenthesesCompletionTests Inherits AbstractAutomaticBraceCompletionTests <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestCreation() As Task Using session = Await CreateSessionAsync("$$") Assert.NotNull(session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_TopLevel() As Task Using session = Await CreateSessionAsync("$$") Assert.NotNull(session) CheckStart(session.Session, expectValidSession:=False) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_TopLevel2() As Task Using session = Await CreateSessionAsync("Imports System$$") Assert.NotNull(session) CheckStart(session.Session, expectValidSession:=False) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_String() As Task Dim code = <code>Class C Dim s As String = "$$ End Class</code> Using session = Await CreateSessionAsync(code) Assert.Null(session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_Comment() As Task Dim code = <code>Class C ' $$ End Class</code> Using session = Await CreateSessionAsync(code) Assert.Null(session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_DocComment() As Task Dim code = <code>Class C ''' $$ End Class</code> Using session = Await CreateSessionAsync(code) Assert.Null(session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestRightAfterStringLiteral() As Task Dim code = <code>Class C Sub Method() Dim a = ""$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestTypeParameterListSyntax() As Task Dim code = <code>Class C$$ End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestParameterListSyntax() As Task Dim code = <code>Class C Sub Method$$ End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestArrayRankSpecifierSyntax() As Task Dim code = <code>Class C Sub Method() Dim a as String$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestParenthesizedExpressionSyntax() As Task Dim code = <code>Class C Sub Method() Dim a = $$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestGetTypeExpressionSyntax() As Task Dim code = <code>Class C Sub Method() Dim a = GetType$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestGetXmlNamespaceExpressionSyntax() As Task Dim code = <code>Class C Sub Method() Dim a = GetXmlNamespace$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestCTypeExpressionSyntax() As Task Dim code = <code>Class C Sub Method() Dim a = CType$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestDirectCastExpressionSyntax() As Task Dim code = <code>Class C Sub Method() Dim a = DirectCast$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestTryCastExpressionSyntax() As Task Dim code = <code>Class C Sub Method() Dim a = TryCast$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestPredefinedCastExpressionSyntax() As Task Dim code = <code>Class C Sub Method() Dim a = CInt$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestBinaryConditionalExpressionSyntax() As Task Dim code = <code>Class C Sub Method() Dim a = If$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestArgumentListSyntax() As Task Dim code = <code>Class C Sub Method() Method$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestFunctionAggregationSyntax() As Task Dim code = <code>Class C Sub Method() Dim max = Aggregate o In metaData.Order Into m = Max$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestTypeArgumentListSyntax() As Task Dim code = <code>Class C Sub Method() Dim d = new List$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestExternalSourceDirectiveSyntax() As Task Dim code = <code>Imports System Public Class ExternalSourceClass Sub TestExternalSource() #ExternalSource $$ #End ExternalSource End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestExternalChecksumDirectiveSyntax() As Task Dim code = "#ExternalChecksum$$" Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function Friend Overloads Function CreateSessionAsync(code As XElement) As Threading.Tasks.Task(Of Holder) Return CreateSessionAsync(code.NormalizedValue()) End Function Friend Overloads Async Function CreateSessionAsync(code As String) As Threading.Tasks.Task(Of Holder) Return CreateSession( Await VisualBasicWorkspaceFactory.CreateWorkspaceFromFileAsync(code), BraceCompletionSessionProvider.Parenthesis.OpenCharacter, BraceCompletionSessionProvider.Parenthesis.CloseCharacter) End Function End Class End Namespace
managed-commons/roslyn
src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticParenthesesCompletion.vb
Visual Basic
apache-2.0
11,005
' 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.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PullMemberUp Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp Imports Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.PullMemberUp <[UseExportProvider]> Public Class PullMemberUpViewModelTest <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_VerifySameBaseTypeAppearMultipleTimes() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1BaseClass", baseTypeTree(0).SymbolName) Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) Assert.Equal("Level2Interface", baseTypeTree(0).BaseTypeNodes(0).SymbolName) Assert.Equal("Level2Interface", baseTypeTree(1).BaseTypeNodes(0).SymbolName) Assert.Empty(baseTypeTree(0).BaseTypeNodes(0).BaseTypeNodes) Assert.Empty(baseTypeTree(1).BaseTypeNodes(0).BaseTypeNodes) Assert.False(viewModel.OkButtonEnabled) viewModel.SelectedDestination = baseTypeTree(0) Assert.True(viewModel.OkButtonEnabled) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_NoVBDestinationAppearInCSharpProject() As Task Dim markUp = <Text><![CDATA[ <Workspace> <Project Language="C#" AssemblyName="CSAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public interface ITestInterface { } public class TestClass : VBClass, ITestInterface { public int Bar$$bar() { return 12345; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes ' C# types will be showed Assert.Equal("ITestInterface", baseTypeTree(0).SymbolName) ' Make sure Visual basic types are not showed since we are not ready to support cross language scenario Assert.Single(baseTypeTree) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectInterfaceDisableMakeAbstractCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) For Each member In viewModel.MemberSelectionViewModel.Members.WhereAsArray( Function(memberViewModel) Return Not memberViewModel.Symbol.IsKind(SymbolKind.Field) And Not memberViewModel.Symbol.IsAbstract End Function) Assert.False(member.IsMakeAbstractCheckable) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectInterfaceDisableFieldCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) For Each member In viewModel.MemberSelectionViewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.IsKind(SymbolKind.Field)) Assert.False(member.IsCheckable) Assert.False(String.IsNullOrEmpty(member.TooltipText)) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)> Public Async Function TestPullMemberUp_SelectClassEnableFieldCheckbox() As Task Dim markUp = <Text><![CDATA[ interface Level2Interface { } interface Level1Interface : Level2Interface { } class Level1BaseClass: Level2Interface { } class MyClass : Level1BaseClass, Level1Interface { public void G$$oo() { } public double e => 2.717; public const days = 365; private double pi => 3.1416; protected float goldenRadio = 0.618; internal float gravitational = 6.67e-11; }"]]></Text> Dim viewModel = Await GetViewModelAsync(markUp, LanguageNames.CSharp) Dim baseTypeTree = viewModel.DestinationTreeNodeViewModel.BaseTypeNodes ' First select an interface, all checkbox will be disable as the previous test. Assert.Equal("Level1Interface", baseTypeTree(1).SymbolName) viewModel.SelectedDestination = baseTypeTree(1) ' Second select a class, check all checkboxs will be resumed. Assert.Equal("Level1BaseClass", baseTypeTree(0).SymbolName) viewModel.SelectedDestination = baseTypeTree(0) For Each member In viewModel.MemberSelectionViewModel.Members.Where(Function(memberViewModel) memberViewModel.Symbol.IsKind(SymbolKind.Field)) Assert.True(member.IsCheckable) Assert.True(String.IsNullOrEmpty(member.TooltipText)) Next End Function Private Shared Function FindMemberByName(name As String, memberArray As ImmutableArray(Of PullMemberUpSymbolViewModel)) As PullMemberUpSymbolViewModel Dim member = memberArray.FirstOrDefault(Function(memberViewModel) memberViewModel.SymbolName.Equals(name)) If (member Is Nothing) Then Assert.True(False, $"No member called {name} found") End If Return member End Function Private Shared Async Function GetViewModelAsync(markup As XElement, languageName As String) As Task(Of PullMemberUpDialogViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.Value %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Throw New ArgumentException("Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim memberSymbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim baseTypeTree = BaseTypeTreeNodeViewModel.CreateBaseTypeTree(glyphService:=Nothing, workspaceDoc.Project.Solution, memberSymbol.ContainingType, CancellationToken.None) Dim membersInType = memberSymbol.ContainingType.GetMembers().WhereAsArray(Function(member) MemberAndDestinationValidator.IsMemberValid(member)) Dim membersViewModel = membersInType.SelectAsArray( Function(member) New PullMemberUpSymbolViewModel(member, glyphService:=Nothing) With {.IsChecked = member.Equals(memberSymbol), .IsCheckable = True, .MakeAbstract = False}) Dim memberToDependents = SymbolDependentsBuilder.FindMemberToDependentsMap(membersInType, workspaceDoc.Project, CancellationToken.None) Return New PullMemberUpDialogViewModel( workspace.GetService(Of IUIThreadOperationExecutor), membersViewModel, baseTypeTree, memberToDependents) End Using End Function End Class End Namespace
mavasani/roslyn
src/VisualStudio/Core/Test/PullMemberUp/PullMemberUpViewModelTest.vb
Visual Basic
mit
10,255
' 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.GenerateConstructor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateConstructor Public Class GenerateConstructorTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New GenerateConstructorCodeFixProvider()) End Function Private ReadOnly options As NamingStylesTestOptionSets = New NamingStylesTestOptionSets(LanguageNames.VisualBasic) <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateIntoContainingType() As Task Await TestInRegularAndScriptAsync( "Class C Sub Main() Dim f = New C([|4|], 5, 6) End Sub End Class", "Class C Private v1 As Integer Private v2 As Integer Private v3 As Integer Public Sub New(v1 As Integer, v2 As Integer, v3 As Integer) Me.v1 = v1 Me.v2 = v2 Me.v3 = v3 End Sub Sub Main() Dim f = New C(4, 5, 6) End Sub End Class") End Function <WorkItem(44537, "https://github.com/dotnet/roslyn/issues/44537")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateIntoContainingType_WithProperties() As Task Await TestInRegularAndScriptAsync( "Class C Sub Main() Dim f = New C([|4|], 5, 6) End Sub End Class", "Class C Public Sub New(v1 As Integer, v2 As Integer, v3 As Integer) Me.V1 = v1 Me.V2 = v2 Me.V3 = v3 End Sub Public ReadOnly Property V1 As Integer Public ReadOnly Property V2 As Integer Public ReadOnly Property V3 As Integer Sub Main() Dim f = New C(4, 5, 6) End Sub End Class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateIntoContainingType_NoMembers() As Task Await TestInRegularAndScriptAsync( "Class C Sub Main() Dim f = New C([|4|], 5, 6) End Sub End Class", "Class C Public Sub New(v1 As Integer, v2 As Integer, v3 As Integer) End Sub Sub Main() Dim f = New C(4, 5, 6) End Sub End Class", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestInvokingFromInsideAnotherConstructor() As Task Await TestInRegularAndScriptAsync( "Class A Private v As B Public Sub New() Me.v = New B([|5|]) End Sub End Class Friend Class B End Class", "Class A Private v As B Public Sub New() Me.v = New B(5) End Sub End Class Friend Class B Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMissingGenerateDefaultConstructor() As Task Await TestMissingInRegularAndScriptAsync( "Class Test Sub Main() Dim a = New [|A|]() End Sub End Class Class A End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMissingGenerateDefaultConstructorInStructure() As Task Await TestMissingInRegularAndScriptAsync( "Class Test Sub Main() Dim a = New [|A|]() End Sub End Class Structure A End Structure") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestOfferDefaultConstructorWhenOverloadExists() As Task Await TestInRegularAndScriptAsync( "Class Test Sub Main() Dim a = [|New A()|] End Sub End Class Class A Sub New(x As Integer) End Sub End Class", "Class Test Sub Main() Dim a = New A() End Sub End Class Class A Public Sub New() End Sub Sub New(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestParameterizedConstructorOffered1() As Task Await TestInRegularAndScriptAsync( "Class Test Sub Main() Dim a = New A([|1|]) End Sub End Class Class A End Class", "Class Test Sub Main() Dim a = New A(1) End Sub End Class Class A Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestParameterizedConstructorOffered2() As Task Await TestInRegularAndScriptAsync( "Class Test Sub Main() Dim a = New A([|1|]) End Sub End Class Class A Public Sub New() End Sub End Class", "Class Test Sub Main() Dim a = New A(1) End Sub End Class Class A Private v As Integer Public Sub New() End Sub Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <WorkItem(527627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527627"), WorkItem(539735, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539735"), WorkItem(539735, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539735")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestInAsNewExpression() As Task Await TestInRegularAndScriptAsync( "Class Test Sub Main() Dim a As New A([|1|]) End Sub End Class Class A Public Sub New() End Sub End Class", "Class Test Sub Main() Dim a As New A(1) End Sub End Class Class A Private v As Integer Public Sub New() End Sub Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInPartialClass1() As Task Await TestInRegularAndScriptAsync( "Public Partial Class Test Public Sub S1() End Sub End Class Public Class Test Public Sub S2() End Sub End Class Public Class A Sub Main() Dim s = New Test([|5|]) End Sub End Class", "Public Partial Class Test Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub Public Sub S1() End Sub End Class Public Class Test Public Sub S2() End Sub End Class Public Class A Sub Main() Dim s = New Test(5) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInPartialClassWhenArityDoesntMatch() As Task Await TestInRegularAndScriptAsync( "Public Partial Class Test Public Sub S1() End Sub End Class Public Class Test(Of T) Public Sub S2() End Sub End Class Public Class A Sub Main() Dim s = New Test([|5|]) End Sub End Class", "Public Partial Class Test Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub Public Sub S1() End Sub End Class Public Class Test(Of T) Public Sub S2() End Sub End Class Public Class A Sub Main() Dim s = New Test(5) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInPartialClassWithConflicts() As Task Await TestInRegularAndScriptAsync( "Public Partial Class Test2 End Class Private Partial Class Test2 End Class Public Class A Sub Main() Dim s = New Test2([|5|]) End Sub End Class", "Public Partial Class Test2 Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class Private Partial Class Test2 End Class Public Class A Sub Main() Dim s = New Test2(5) End Sub End Class") End Function <WorkItem(528257, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528257")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateIntoInaccessibleType() As Task Await TestMissingInRegularAndScriptAsync( "Class Goo Private Class Bar End Class End Class Class A Sub Main() Dim s = New Goo.Bar([|5|]) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestOnNestedTypes() As Task Await TestInRegularAndScriptAsync( "Class Goo Class Bar End Class End Class Class A Sub Main() Dim s = New Goo.Bar([|5|]) End Sub End Class", "Class Goo Class Bar Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class End Class Class A Sub Main() Dim s = New Goo.Bar(5) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestOnNestedPartialTypes() As Task Await TestInRegularAndScriptAsync( "Public Partial Class Test Public Partial Class NestedTest Public Sub S1() End Sub End Class End Class Public Partial Class Test Public Partial Class NestedTest Public Sub S2() End Sub End Class End Class Class A Sub Main() Dim s = New Test.NestedTest([|5|]) End Sub End Class", "Public Partial Class Test Public Partial Class NestedTest Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub Public Sub S1() End Sub End Class End Class Public Partial Class Test Public Partial Class NestedTest Public Sub S2() End Sub End Class End Class Class A Sub Main() Dim s = New Test.NestedTest(5) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestOnNestedGenericType() As Task Await TestInRegularAndScriptAsync( "Class Outer(Of T) Public Class Inner End Class Public i = New Inner([|5|]) End Class", "Class Outer(Of T) Public Class Inner Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class Public i = New Inner(5) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestOnGenericTypes1() As Task Await TestInRegularAndScriptAsync( "Class Base(Of T, V) End Class Class Test Sub Goo() Dim a = New Base(Of Integer, Integer)([|5|], 5) End Sub End Class", "Class Base(Of T, V) Private v1 As Integer Private v2 As Integer Public Sub New(v1 As Integer, v2 As Integer) Me.v1 = v1 Me.v2 = v2 End Sub End Class Class Test Sub Goo() Dim a = New Base(Of Integer, Integer)(5, 5) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestOnGenericTypes2() As Task Await TestInRegularAndScriptAsync( "Class Base(Of T, V) End Class Class Derived(Of V) Inherits Base(Of Integer, V) End Class Class Test Sub Goo() Dim a = New Base(Of Integer, Integer)(5, 5) Dim b = New Derived(Of Integer)([|5|]) End Sub End Class", "Class Base(Of T, V) End Class Class Derived(Of V) Inherits Base(Of Integer, V) Private v1 As Integer Public Sub New(v1 As Integer) Me.v1 = v1 End Sub End Class Class Test Sub Goo() Dim a = New Base(Of Integer, Integer)(5, 5) Dim b = New Derived(Of Integer)(5) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestOnGenericTypes3() As Task Await TestInRegularAndScriptAsync( "Class Base(Of T, V) End Class Class Derived(Of V) Inherits Base(Of Integer, V) End Class Class MoreDerived Inherits Derived(Of Double) End Class Class Test Sub Goo() Dim a = New Base(Of Integer, Integer)(5, 5) Dim b = New Derived(Of Integer)(5) Dim c = New MoreDerived([|5.5|]) End Sub End Class", "Class Base(Of T, V) End Class Class Derived(Of V) Inherits Base(Of Integer, V) End Class Class MoreDerived Inherits Derived(Of Double) Private v As Double Public Sub New(v As Double) Me.v = v End Sub End Class Class Test Sub Goo() Dim a = New Base(Of Integer, Integer)(5, 5) Dim b = New Derived(Of Integer)(5) Dim c = New MoreDerived(5.5) End Sub End Class") End Function <WorkItem(528244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528244")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDateTypeForInference() As Task Await TestInRegularAndScriptAsync( "Class Goo End Class Class A Sub Main() Dim s = New Goo([|Date.Now|]) End Sub End Class", "Class Goo Private now As Date Public Sub New(now As Date) Me.now = now End Sub End Class Class A Sub Main() Dim s = New Goo(Date.Now) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestBaseConstructor() As Task Await TestInRegularAndScriptAsync( "Class Base End Class Class Derived Inherits Base Private x As Integer Public Sub New(x As Integer) MyBase.New([|x|]) Me.x = x End Sub End Class", "Class Base Private x As Integer Public Sub New(x As Integer) Me.x = x End Sub End Class Class Derived Inherits Base Private x As Integer Public Sub New(x As Integer) MyBase.New(x) Me.x = x End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMustInheritBase() As Task Await TestInRegularAndScriptAsync( "MustInherit Class Base End Class Class Derived Inherits Base Shared x As Integer Public Sub New(x As Integer) MyBase.New([|x|]) 'This should generate a protected ctor in Base Derived.x = x End Sub Sub Test1() Dim a As New Derived(1) End Sub End Class", "MustInherit Class Base Private x As Integer Protected Sub New(x As Integer) Me.x = x End Sub End Class Class Derived Inherits Base Shared x As Integer Public Sub New(x As Integer) MyBase.New(x) 'This should generate a protected ctor in Base Derived.x = x End Sub Sub Test1() Dim a As New Derived(1) End Sub End Class") End Function <WorkItem(540586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540586")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMissingOnNoCloseParen() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim c = New [|goo|]( End Sub End Module Class goo End Class") End Function <WorkItem(540545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540545")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestConversionError() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main(args As String()) Dim i As Char Dim cObject As C = New C([|i|]) Console.WriteLine(cObject.v1) End Sub End Module Class C Public v1 As Integer Public Sub New(v1 As Integer) Me.v1 = v1 End Sub End Class", "Imports System Module Program Sub Main(args As String()) Dim i As Char Dim cObject As C = New C(i) Console.WriteLine(cObject.v1) End Sub End Module Class C Public v1 As Integer Private i As Char Public Sub New(v1 As Integer) Me.v1 = v1 End Sub Public Sub New(i As Char) Me.i = i End Sub End Class") End Function <WorkItem(540642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540642")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestNotOnNestedConstructor() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As C = New C([|New C()|]) End Sub End Module Friend Class C End Class", "Module Program Sub Main(args As String()) Dim x As C = New C(New C()) End Sub End Module Friend Class C Private c As C Public Sub New(c As C) Me.c = c End Sub End Class") End Function <WorkItem(540607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540607")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestUnavailableTypeParameters() As Task Await TestInRegularAndScriptAsync( "Class C(Of T1, T2) Sub M(x As T1, y As T2) Dim a As Test = New Test([|x|], y) End Sub End Class Friend Class Test End Class", "Class C(Of T1, T2) Sub M(x As T1, y As T2) Dim a As Test = New Test(x, y) End Sub End Class Friend Class Test Private x As Object Private y As Object Public Sub New(x As Object, y As Object) Me.x = x Me.y = y End Sub End Class") End Function <WorkItem(540748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540748")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestKeywordArgument1() As Task Await TestInRegularAndScriptAsync( "Class Test Private [Class] As Integer = 5 Sub Main() Dim a = New A([|[Class]|]) End Sub End Class Class A End Class", "Class Test Private [Class] As Integer = 5 Sub Main() Dim a = New A([Class]) End Sub End Class Class A Private [class] As Integer Public Sub New([class] As Integer) Me.class = [class] End Sub End Class") End Function <WorkItem(540747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540747")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestKeywordArgument2() As Task Await TestInRegularAndScriptAsync( "Class Test Sub Main() Dim a = New A([|Class|]) End Sub End Class Class A End Class", "Class Test Sub Main() Dim a = New A(Class) End Sub End Class Class A Private value As Object Public Sub New(value As Object) Me.value = value End Sub End Class") End Function <WorkItem(540746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540746")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestConflictWithTypeParameterName() As Task Await TestInRegularAndScriptAsync( "Class Test Sub Goo() Dim a = New Bar(Of Integer)([|5|]) End Sub End Class Class Bar(Of V) End Class", "Class Test Sub Goo() Dim a = New Bar(Of Integer)(5) End Sub End Class Class Bar(Of V) Private v1 As Integer Public Sub New(v1 As Integer) Me.v1 = v1 End Sub End Class") End Function <WorkItem(541174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541174")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestExistingReadonlyField() As Task Await TestInRegularAndScriptAsync( "Class C ReadOnly x As Integer Sub Test() Dim x As Integer = 1 Dim obj As New C([|x|]) End Sub End Class", "Class C ReadOnly x As Integer Public Sub New(x As Integer) Me.x = x End Sub Sub Test() Dim x As Integer = 1 Dim obj As New C(x) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestExistingProperty() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Test() Dim x = New A([|P|]:=5) End Sub End Class Class A Public Property P As Integer End Class", "Class Program Sub Test() Dim x = New A(P:=5) End Sub End Class Class A Public Sub New(P As Integer) Me.P = P End Sub Public Property P As Integer End Class") End Function <WorkItem(542055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542055")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestExistingMethod() As Task Await TestInRegularAndScriptAsync( "Class A Sub Test() Dim t As New C([|u|]:=5) End Sub End Class Class C Public Sub u() End Sub End Class", "Class A Sub Test() Dim t As New C(u:=5) End Sub End Class Class C Private u1 As Integer Public Sub New(u As Integer) u1 = u End Sub Public Sub u() End Sub End Class") End Function <WorkItem(542055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542055")> <WorkItem(14077, "https://github.com/dotnet/roslyn/issues/14077")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDetectAssignmentToSharedFieldFromInstanceConstructor() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Test() Dim x = New A([|P|]:=5) End Sub End Class Class A Shared Property P As Integer End Class", "Class Program Sub Test() Dim x = New A(P:=5) End Sub End Class Class A Private p As Integer Public Sub New(P As Integer) Me.p = P End Sub Shared Property P As Integer End Class") End Function <WorkItem(542055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542055")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestExistingFieldWithSameNameButIncompatibleType() As Task Await TestInRegularAndScriptAsync( "Class A Sub Test() Dim t As New B([|x|]:=5) End Sub End Class Class B Private x As String End Class", "Class A Sub Test() Dim t As New B(x:=5) End Sub End Class Class B Private x As String Private x1 As Integer Public Sub New(x As Integer) x1 = x End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestExistingFieldFromBaseClass() As Task Await TestInRegularAndScriptAsync( "Class A Sub Test() Dim t As New C([|u|]:=5) End Sub End Class Class C Inherits B Private x As String End Class Class B Protected u As Integer End Class", "Class A Sub Test() Dim t As New C(u:=5) End Sub End Class Class C Inherits B Private x As String Public Sub New(u As Integer) Me.u = u End Sub End Class Class B Protected u As Integer End Class") End Function <WorkItem(542098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542098")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMeConstructorInitializer() As Task Await TestInRegularAndScriptAsync( "Class C Sub New Me.New([|1|]) End Sub End Class", "Class C Private v As Integer Sub New Me.New(1) End Sub Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <WorkItem(542098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542098")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestExistingMeConstructorInitializer() As Task Await TestMissingInRegularAndScriptAsync( "Class C Private v As Integer Sub New Me.[|New|](1) End Sub Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <WorkItem(542098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542098")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMyBaseConstructorInitializer() As Task Await TestInRegularAndScriptAsync( "Class C Sub New MyClass.New([|1|]) End Sub End Class", "Class C Private v As Integer Sub New MyClass.New(1) End Sub Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <WorkItem(542098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542098")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestExistingMyBaseConstructorInitializer() As Task Await TestMissingInRegularAndScriptAsync( "Class C Private v As Integer Sub New MyClass.[|New|](1) End Sub Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <WorkItem(542098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542098")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMyClassConstructorInitializer() As Task Await TestInRegularAndScriptAsync( "Class C Inherits B Sub New MyBase.New([|1|]) End Sub End Class Class B End Class", "Class C Inherits B Sub New MyBase.New(1) End Sub End Class Class B Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class") End Function <WorkItem(542098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542098")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestExistingMyClassConstructorInitializer() As Task Await TestMissingInRegularAndScriptAsync( "Class C Inherits B Sub New MyBase.New([|1|]) End Sub End Class Class B Protected Sub New(v As Integer) End Sub End Class") End Function <WorkItem(542056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542056")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestConflictingFieldNameInSubclass() As Task Await TestInRegularAndScriptAsync( "Class A Sub Test() Dim t As New C([|u|]:=5) End Sub End Class Class C Inherits B Private x As String End Class Class B Protected u As String End Class", "Class A Sub Test() Dim t As New C(u:=5) End Sub End Class Class C Inherits B Private x As String Private u1 As Integer Public Sub New(u As Integer) u1 = u End Sub End Class Class B Protected u As String End Class") End Function <WorkItem(542442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542442")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestNothingArgument() As Task Await TestMissingInRegularAndScriptAsync( "Class C1 Public Sub New(ByVal accountKey As Integer) Me.new() Me.[|new|](accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) End Sub End Class") End Function <WorkItem(540641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540641")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMissingOnExistingConstructor() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub M() Dim x As C = New [|C|](P) End Sub End Module Class C Private v As Object Public Sub New(v As Object) Me.v = v End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerationIntoVisibleType() As Task Await TestInRegularAndScriptAsync( "#ExternalSource (""Default.aspx"", 1) Class C Sub Goo() Dim x As New D([|5|]) End Sub End Class Class D End Class #End ExternalSource", "#ExternalSource (""Default.aspx"", 1) Class C Sub Goo() Dim x As New D(5) End Sub End Class Class D Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class #End ExternalSource") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestNoGenerationIntoEntirelyHiddenType() As Task Await TestMissingInRegularAndScriptAsync( <Text>#ExternalSource (""Default.aspx"", 1) Class C Sub Goo() Dim x As New D([|5|]) End Sub End Class #End ExternalSource Class D End Class </Text>.Value) End Function <WorkItem(546030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546030")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestConflictingDelegatedParameterNameAndNamedArgumentName1() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim objc As New C(1, [|prop|]:=""Property"") End Sub End Module Class C Private prop As String Public Sub New(prop As String) Me.prop = prop End Sub End Class", "Module Program Sub Main(args As String()) Dim objc As New C(1, prop:=""Property"") End Sub End Module Class C Private prop As String Private v As Integer Public Sub New(prop As String) Me.prop = prop End Sub Public Sub New(v As Integer, prop As String) Me.v = v Me.prop = prop End Sub End Class") End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestFormattingInGenerateConstructor() As Task Await TestInRegularAndScriptAsync( <Text>Class C Sub New() MyClass.New([|1|]) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Private v As Integer Sub New() MyClass.New(1) End Sub Public Sub New(v As Integer) Me.v = v End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(530003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestAttributesWithArgument() As Task Await TestInRegularAndScriptAsync( "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute End Class [|<MyAttribute(123)>|] Public Class D End Class", "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class <MyAttribute(123)> Public Class D End Class") End Function <WorkItem(530003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestAttributesWithMultipleArguments() As Task Await TestInRegularAndScriptAsync( "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute End Class [|<MyAttribute(true, 1, ""hello"")>|] Public Class D End Class", "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute Private v1 As Boolean Private v2 As Integer Private v3 As String Public Sub New(v1 As Boolean, v2 As Integer, v3 As String) Me.v1 = v1 Me.v2 = v2 Me.v3 = v3 End Sub End Class <MyAttribute(true, 1, ""hello"")> Public Class D End Class") End Function <WorkItem(530003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")> <WorkItem(14077, "https://github.com/dotnet/roslyn/issues/14077")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestAttributesWithNamedArguments() As Task Await TestInRegularAndScriptAsync( "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute End Class [|<MyAttribute(true, 1, Topic:=""hello"")>|] Public Class D End Class", "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute Private v1 As Boolean Private v2 As Integer Private topic As String Public Sub New(v1 As Boolean, v2 As Integer, Topic As String) Me.v1 = v1 Me.v2 = v2 Me.topic = Topic End Sub End Class <MyAttribute(true, 1, Topic:=""hello"")> Public Class D End Class") End Function <WorkItem(530003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestAttributesWithAdditionalConstructors() As Task Await TestInRegularAndScriptAsync( "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class [|<MyAttribute(True, 2)>|] Public Class D End Class", "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute Private v As Integer Private v1 As Boolean Private v2 As Integer Public Sub New(v As Integer) Me.v = v End Sub Public Sub New(v1 As Boolean, v2 As Integer) Me.v1 = v1 Me.v2 = v2 End Sub End Class <MyAttribute(True, 2)> Public Class D End Class") End Function <WorkItem(530003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestAttributesWithAllValidArguments() As Task Await TestInRegularAndScriptAsync( "Enum A A1 End Enum <AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute End Class [|<MyAttribute(New Short(1) {1, 2, 3}, A.A1, True, 1, ""Z""c, 5S, 1I, 5L, 6.0R, 2.1F, ""abc"")>|] Public Class D End Class", "Enum A A1 End Enum <AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute Private shorts As Short() Private a1 As A Private v1 As Boolean Private v2 As Integer Private v3 As Char Private v4 As Short Private v5 As Integer Private v6 As Long Private v7 As Double Private v8 As Single Private v9 As String Public Sub New(shorts() As Short, a1 As A, v1 As Boolean, v2 As Integer, v3 As Char, v4 As Short, v5 As Integer, v6 As Long, v7 As Double, v8 As Single, v9 As String) Me.shorts = shorts Me.a1 = a1 Me.v1 = v1 Me.v2 = v2 Me.v3 = v3 Me.v4 = v4 Me.v5 = v5 Me.v6 = v6 Me.v7 = v7 Me.v8 = v8 Me.v9 = v9 End Sub End Class <MyAttribute(New Short(1) {1, 2, 3}, A.A1, True, 1, ""Z""c, 5S, 1I, 5L, 6.0R, 2.1F, ""abc"")> Public Class D End Class") End Function <WorkItem(530003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530003")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestAttributesWithLambda() As Task Await TestMissingInRegularAndScriptAsync( "<AttributeUsage(AttributeTargets.Class)> Public Class MyAttribute Inherits System.Attribute End Class [|<MyAttribute(Function(x) x + 1)>|] Public Class D End Class") End Function <WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestConstructorGenerationForDifferentNamedParameter() As Task Await TestInRegularAndScriptAsync( <Text>Class Program Sub Main(args As String()) Dim a = New Program([|y:=4|]) End Sub Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class Program Private y As Integer Sub Main(args As String()) Dim a = New Program(y:=4) End Sub Sub New(x As Integer) End Sub Public Sub New(y As Integer) Me.y = y End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(897355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897355")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestOptionStrictOn() As Task Await TestInRegularAndScriptAsync( "Option Strict On Module Module1 Sub Main() Dim int As Integer = 3 Dim obj As Object = New Object() Dim c1 As Classic = New Classic(int) Dim c2 As Classic = [|New Classic(obj)|] End Sub Class Classic Private int As Integer Public Sub New(int As Integer) Me.int = int End Sub End Class End Module", "Option Strict On Module Module1 Sub Main() Dim int As Integer = 3 Dim obj As Object = New Object() Dim c1 As Classic = New Classic(int) Dim c2 As Classic = New Classic(obj) End Sub Class Classic Private int As Integer Private obj As Object Public Sub New(int As Integer) Me.int = int End Sub Public Sub New(obj As Object) Me.obj = obj End Sub End Class End Module") End Function <WorkItem(528257, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528257")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInInaccessibleType() As Task Await TestInRegularAndScriptAsync( "Class Goo Private Class Bar End Class End Class Class A Sub Main() Dim s = New [|Goo.Bar(5)|] End Sub End Class", "Class Goo Private Class Bar Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class End Class Class A Sub Main() Dim s = New Goo.Bar(5) End Sub End Class") End Function <WorkItem(1241, "https://github.com/dotnet/roslyn/issues/1241")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateConstructorInIncompleteLambda() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Linq Class C Sub New() Dim s As Action = Sub() Dim a = New C([|0|])", "Imports System Imports System.Linq Class C Private v As Integer Sub New() Dim s As Action = Sub() Dim a = New C(0)Public Sub New(v As Integer) Me.v = v End Sub End Class ") End Function <WorkItem(5920, "https://github.com/dotnet/roslyn/issues/5920")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateConstructorInIncompleteLambda2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Linq Class C Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub Sub New() Dim s As Action = Sub() Dim a = New [|C|](0, 0)", "Imports System Imports System.Linq Class C Private v As Integer Private v1 As Integer Public Sub New(v As Integer) Me.v = v End Sub Sub New() Dim s As Action = Sub() Dim a = New C(0, 0)Public Sub New(v As Integer, v1 As Integer) Me.New(v) Me.v1 = v1 End Sub End Class ") End Function <WorkItem(1241, "https://github.com/dotnet/roslyn/issues/1241")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/53238"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateConstructorInIncompleteLambda_WithoutImport() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Class C Sub New() Dim s As Action = Sub() Dim a = New C([|0|])", "Imports System.Linq Class C Private v As Integer Sub New() Dim s As Action = Sub() Dim a = New C(0)Public Sub New(v As Integer) Me.v = v End Sub End Class ") End Function <WorkItem(5920, "https://github.com/dotnet/roslyn/issues/5920")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/53238"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateConstructorInIncompleteLambda2_WithoutImport() As Task Await TestInRegularAndScriptAsync( "Imports System.Linq Class C Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub Sub New() Dim s As Action = Sub() Dim a = New [|C|](0, 0)", "Imports System.Linq Class C Private v As Integer Private v1 As Integer Public Sub New(v As Integer) Me.v = v End Sub Sub New() Dim s As Action = Sub() Dim a = New C(0, 0)Public Sub New(v As Integer, v1 As Integer) Me.New(v) Me.v1 = v1 End Sub End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateConstructorNotOfferedForDuplicate() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Class X Private v As String Public Sub New(v As String) Me.v = v End Sub Sub Test() Dim x As X = New X(New [|String|]()) End Sub End Class") End Function <WorkItem(9575, "https://github.com/dotnet/roslyn/issues/9575")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestMissingOnMethodCall() As Task Await TestMissingInRegularAndScriptAsync( "class C public sub new(int arg) end sub public function M(s as string, i as integer, b as boolean) as boolean return [|M|](i, b) end function end class") End Function <WorkItem(13749, "https://github.com/dotnet/roslyn/issues/13749")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function Support_Readonly_Properties() As Task Await TestInRegularAndScriptAsync( "Class C ReadOnly Property Prop As Integer End Class Module P Sub M() Dim prop = 42 Dim c = New C([|prop|]) End Sub End Module", "Class C Public Sub New(prop As Integer) Me.Prop = prop End Sub ReadOnly Property Prop As Integer End Class Module P Sub M() Dim prop = 42 Dim c = New C(prop) End Sub End Module") End Function <WorkItem(21692, "https://github.com/dotnet/roslyn/issues/21692")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDelegateConstructor1() As Task Await TestInRegularAndScriptAsync( "Public Class B Public Sub New(a As Integer) [|Me.New(a, 1)|] End Sub End Class", "Public Class B Private a As Integer Private v As Integer Public Sub New(a As Integer) Me.New(a, 1) End Sub Public Sub New(a As Integer, v As Integer) Me.a = a Me.v = v End Sub End Class") End Function <WorkItem(21692, "https://github.com/dotnet/roslyn/issues/21692")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDelegateConstructor2() As Task Await TestInRegularAndScriptAsync( "Public Class B Public Sub New(x As Integer) Me.New(x, 0, 0) End Sub Public Sub New(x As Integer, y As Integer, z As Integer) [|Me.New(x, y)|] End Sub End Class", "Public Class B Private x As Integer Private y As Integer Public Sub New(x As Integer) Me.New(x, 0, 0) End Sub Public Sub New(x As Integer, y As Integer) Me.x = x Me.y = y End Sub Public Sub New(x As Integer, y As Integer, z As Integer) Me.New(x, y) End Sub End Class") End Function <WorkItem(21692, "https://github.com/dotnet/roslyn/issues/21692")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDelegateConstructor3() As Task Await TestInRegularAndScriptAsync( "Public Class B Public Sub New(x As Integer) End Sub Public Sub New(x As Integer, y As Integer, z As Integer) [|Me.New(x, y)|] End Sub End Class", "Public Class B Private y As Integer Public Sub New(x As Integer) End Sub Public Sub New(x As Integer, y As Integer) Me.New(x) Me.y = y End Sub Public Sub New(x As Integer, y As Integer, z As Integer) Me.New(x, y) End Sub End Class") End Function <WorkItem(21692, "https://github.com/dotnet/roslyn/issues/21692")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDelegateConstructor4() As Task Await TestInRegularAndScriptAsync( "Public Class B Public Sub New(x As Integer) Me.New(x, 0) End Sub Public Sub New(x As Integer, y As Integer) [|Me.New(x, y, 0)|] End Sub End Class", "Public Class B Private x As Integer Private y As Integer Private v As Integer Public Sub New(x As Integer) Me.New(x, 0) End Sub Public Sub New(x As Integer, y As Integer) Me.New(x, y, 0) End Sub Public Sub New(x As Integer, y As Integer, v As Integer) Me.x = x Me.y = y Me.v = v End Sub End Class") End Function <WorkItem(21692, "https://github.com/dotnet/roslyn/issues/21692")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDelegateConstructor5() As Task Await TestInRegularAndScriptAsync( "Class C Public Sub New(a As Integer) End Sub Public Sub New(a As Integer, b As Integer) Me.New(True, True) End Sub Public Sub New(a As Boolean, b As Boolean) Me.New(1, 1) End Sub Public Sub New(a As Integer, b As Integer, c As Integer, e As Integer) [|Me.New(a, b, c)|] End Sub End Class", "Class C Private b As Integer Private c As Integer Public Sub New(a As Integer) End Sub Public Sub New(a As Integer, b As Integer) Me.New(True, True) End Sub Public Sub New(a As Boolean, b As Boolean) Me.New(1, 1) End Sub Public Sub New(a As Integer, b As Integer, c As Integer) Me.New(a) Me.b = b Me.c = c End Sub Public Sub New(a As Integer, b As Integer, c As Integer, e As Integer) Me.New(a, b, c) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDelegateConstructorCrossLanguageCycleAvoidance() As Task Await TestInRegularAndScriptAsync( <Workspace> <Project Language="C#" Name="CSharpProject" CommonReferences="true"> <Document> public class BaseType { public BaseType(int x, int y) { } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>CSharpProject</ProjectReference> <Document> Public Class B Inherits BaseType Public Sub New(a As Integer) [|Me.New(a, 1)|] End Sub End Class</Document> </Project> </Workspace>.ToString(), " Public Class B Inherits BaseType Public Sub New(a As Integer) Me.New(a, 1) End Sub Public Sub New(x As Integer, y As Integer) MyBase.New(x, y) End Sub End Class") End Function <WorkItem(49850, "https://github.com/dotnet/roslyn/issues/49850")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDelegateConstructorCrossLanguage() As Task Await TestInRegularAndScriptAsync( <Workspace> <Project Language="C#" Name="CSharpProject" CommonReferences="true"> <Document> public class BaseType { public BaseType(string x) { } }</Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>CSharpProject</ProjectReference> <Document> Option Strict On Public Class B Public Sub M() Dim x = [|New BaseType(42)|] End Sub End Class </Document> </Project> </Workspace>.ToString(), " public class BaseType { private int v; public BaseType(string x) { } public BaseType(int v) { this.v = v; } }") End Function <WorkItem(50765, "https://github.com/dotnet/roslyn/issues/50765")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestDelegateConstructorCrossLanguageWithMissingType() As Task Await TestAsync( <Workspace> <Project Language="C#" Name="CSharpProjectWithExtraType" CommonReferences="true"> <Document> public class ExtraType { } </Document> </Project> <Project Language="C#" Name="CSharpProjectGeneratingInto" CommonReferences="true"> <ProjectReference>CSharpProjectWithExtraType</ProjectReference> <Document> public class C { public C(ExtraType t) { } public C(string s, int i) { } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>CSharpProjectGeneratingInto</ProjectReference> <Document> Option Strict On Public Class B Public Sub M() Dim x = [|New C(42, 42)|] End Sub End Class </Document> </Project> </Workspace>.ToString(), " public class C { private int v1; private int v2; public C(ExtraType t) { } public C(string s, int i) { } public C(int v1, int v2) { this.v1 = v1; this.v2 = v2; } } ", TestOptions.Regular) End Function <WorkItem(14077, "https://github.com/dotnet/roslyn/issues/14077")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function CreateFieldDefaultNamingStyle() As Task Await TestInRegularAndScriptAsync( "Class C Sub Test() Dim x As Integer = 1 Dim obj As New C([|x|]) End Sub End Class", "Class C Private x As Integer Public Sub New(x As Integer) Me.x = x End Sub Sub Test() Dim x As Integer = 1 Dim obj As New C(x) End Sub End Class") End Function <WorkItem(14077, "https://github.com/dotnet/roslyn/issues/14077")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function CreateFieldSpecifiedNamingStyle() As Task Await TestInRegularAndScriptAsync( "Class C Sub Test() Dim x As Integer = 1 Dim obj As New C([|x|]) End Sub End Class", "Class C Private _x As Integer Public Sub New(x As Integer) _x = x End Sub Sub Test() Dim x As Integer = 1 Dim obj As New C(x) End Sub End Class", options:=options.FieldNamesAreCamelCaseWithUnderscorePrefix) End Function <WorkItem(542055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542055")> <WorkItem(14077, "https://github.com/dotnet/roslyn/issues/14077")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestFieldWithNamingStyleAlreadyExists() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Test() Dim x = New A([|P|]:=5) End Sub End Class Class A Shared Property _p As Integer End Class", "Class Program Sub Test() Dim x = New A(P:=5) End Sub End Class Class A Private _p1 As Integer Public Sub New(P As Integer) _p1 = P End Sub Shared Property _p As Integer End Class", options:=options.FieldNamesAreCamelCaseWithUnderscorePrefix) End Function <WorkItem(14077, "https://github.com/dotnet/roslyn/issues/14077")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestFieldAndPropertyNamingStyles() As Task Await TestInRegularAndScriptAsync( "Class C Sub Test() Dim x As Integer = 1 Dim obj As New C([|x|]) End Sub End Class", "Class C Private _x As Integer Public Sub New(p_x As Integer) _x = p_x End Sub Sub Test() Dim x As Integer = 1 Dim obj As New C(x) End Sub End Class", options:=options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefix)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> <WorkItem(23807, "https://github.com/dotnet/roslyn/issues/23807")> Public Async Function TestAsNewClause() As Task Await TestInRegularAndScriptAsync( " Class Test Private field As New Test([|1|]) End Class ", " Class Test Private field As New Test(1) Private v As Integer Public Sub New(v As Integer) Me.v = v End Sub End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> <WorkItem(44708, "https://github.com/dotnet/roslyn/issues/44708")> Public Async Function TestGenerateNameFromTypeArgument() As Task Await TestInRegularAndScriptAsync( "Imports System.Collections.Generic Class Frog End Class Class C Private Function M() As C Return New C([||]New List(Of Frog)()) End Function End Class ", "Imports System.Collections.Generic Class Frog End Class Class C Private frogs As List(Of Frog) Public Sub New(frogs As List(Of Frog)) Me.frogs = frogs End Sub Private Function M() As C Return New C(New List(Of Frog)()) End Function End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> <WorkItem(44708, "https://github.com/dotnet/roslyn/issues/44708")> Public Async Function TestDoNotGenerateNameFromTypeArgumentIfNotEnumerable() As Task Await TestInRegularAndScriptAsync( "Class Frog(Of T) End Class Class C Private Function M() As C Return New C([||]New Frog(Of Integer)()) End Function End Class ", "Class Frog(Of T) End Class Class C Private frog As Frog(Of Integer) Public Sub New(frog As Frog(Of Integer)) Me.frog = frog End Sub Private Function M() As C Return New C(New Frog(Of Integer)()) End Function End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> <WorkItem(51040, "https://github.com/dotnet/roslyn/issues/51040")> Public Async Function TestOmittedParameter() As Task Await TestInRegularAndScriptAsync( "Class C Private _a As Integer Public Sub New(Optional a As Integer = 1) Me._a = a End Sub Public Function M() As C Return New C(, [||]2) End Function End Class ", "Class C Private _a As Integer Private v As Integer Public Sub New(Optional a As Integer = 1) Me._a = a End Sub Public Sub New(Optional a As Integer = 1, Optional v As Integer = Nothing) Me.New(a) Me.v = v End Sub Public Function M() As C Return New C(, 2) End Function End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> <WorkItem(51040, "https://github.com/dotnet/roslyn/issues/51040")> Public Async Function TestOmittedParameterAtEnd() As Task Await TestInRegularAndScriptAsync( "Class C Private _a As Integer Public Sub New(Optional a As Integer = 1) Me._a = a End Sub Public Function M() As C Return New C(1,[||]) End Function End Class ", "Class C Private _a As Integer Private value As Object Public Sub New(Optional a As Integer = 1) Me._a = a End Sub Public Sub New(Optional a As Integer = 1, Optional value As Object = Nothing) Me.New(a) Me.value = value End Sub Public Function M() As C Return New C(1,) End Function End Class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> <WorkItem(51040, "https://github.com/dotnet/roslyn/issues/51040")> Public Async Function TestOmittedParameterAtStartAndEnd() As Task Await TestInRegularAndScriptAsync( "Class C Private _a As Integer Public Sub New(Optional a As Integer = 1) Me._a = a End Sub Public Function M() As C Return New C(,[||]) End Function End Class ", "Class C Private _a As Integer Private value As Object Public Sub New(Optional a As Integer = 1) Me._a = a End Sub Public Sub New(Optional a As Integer = 1, Optional value As Object = Nothing) Me.New(a) Me.value = value End Sub Public Function M() As C Return New C(,) End Function End Class ") End Function End Class End Namespace
CyrusNajmabadi/roslyn
src/EditorFeatures/VisualBasicTest/GenerateConstructor/GenerateConstructorTests.vb
Visual Basic
mit
60,366
' 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 System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Module SyntaxHelpers Friend ReadOnly ParseOptions As VisualBasicParseOptions = VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersionFacts.CurrentVersion) ''' <summary> ''' Parse expression. Returns null if there are any errors. ''' </summary> <Extension> Friend Function ParseExpression(expr As String, diagnostics As DiagnosticBag, allowFormatSpecifiers As Boolean, <Out> ByRef formatSpecifiers As ReadOnlyCollection(Of String)) As ExecutableStatementSyntax Dim syntax = ParseDebuggerExpression(expr, consumeFullText:=Not allowFormatSpecifiers) diagnostics.AddRange(syntax.GetDiagnostics()) formatSpecifiers = Nothing If allowFormatSpecifiers Then Dim builder = ArrayBuilder(Of String).GetInstance() If ParseFormatSpecifiers(builder, expr, syntax.Expression.FullWidth, diagnostics) AndAlso builder.Count > 0 Then formatSpecifiers = New ReadOnlyCollection(Of String)(builder.ToArray()) End If builder.Free() End If Return If(diagnostics.HasAnyErrors(), Nothing, syntax) End Function <Extension> Friend Function ParseAssignment(target As String, expr As String, diagnostics As DiagnosticBag) As AssignmentStatementSyntax Dim text = SourceText.From(expr) Dim expression = SyntaxHelpers.ParseDebuggerExpressionInternal(text, consumeFullText:=True) ' We're creating a SyntaxTree for just the RHS so that the Diagnostic spans for parse errors ' will be correct (with respect to the original input text). If we ever expose a SemanticModel ' for debugger expressions, we should use this SyntaxTree. Dim syntaxTree = expression.CreateSyntaxTree() diagnostics.AddRange(syntaxTree.GetDiagnostics()) If diagnostics.HasAnyErrors Then Return Nothing End If ' Any Diagnostic spans produced in binding will be offset by the length of the "target" expression text. ' If we want to support live squiggles in debugger windows, SemanticModel, etc, we'll want to address this. Dim targetSyntax = SyntaxHelpers.ParseDebuggerExpressionInternal(SourceText.From(target), consumeFullText:=True) Debug.Assert(Not targetSyntax.GetDiagnostics().Any(), "The target of an assignment should never contain Diagnostics if we're being allowed to assign to it in the debugger.") Dim assignment = InternalSyntax.SyntaxFactory.SimpleAssignmentStatement( targetSyntax, New InternalSyntax.PunctuationSyntax(SyntaxKind.EqualsToken, "=", Nothing, Nothing), expression) syntaxTree = assignment.MakeDebuggerStatementContext().CreateSyntaxTree() Return DirectCast(syntaxTree.GetDebuggerStatement(), AssignmentStatementSyntax) End Function ''' <summary> ''' Parse statement. Returns null if there are any errors. ''' </summary> <Extension> Friend Function ParseStatement(statement As String, diagnostics As DiagnosticBag) As StatementSyntax Dim syntax = ParseDebuggerStatement(statement) diagnostics.AddRange(syntax.GetDiagnostics()) Return If(diagnostics.HasAnyErrors(), Nothing, syntax) End Function ''' <summary> ''' Return set of identifier tokens, with leading And ''' trailing spaces And comma separators removed. ''' </summary> ''' <remarks> ''' The native VB EE didn't support format specifiers. ''' </remarks> Private Function ParseFormatSpecifiers( builder As ArrayBuilder(Of String), expr As String, offset As Integer, diagnostics As DiagnosticBag) As Boolean Dim expectingComma = True Dim start = -1 Dim n = expr.Length While offset < n Dim c = expr(offset) If SyntaxFacts.IsWhitespace(c) OrElse c = ","c Then If start >= 0 Then Dim token = expr.Substring(start, offset - start) If expectingComma Then ReportInvalidFormatSpecifier(token, diagnostics) Return False End If builder.Add(token) start = -1 expectingComma = c <> ","c ElseIf c = ","c Then If Not expectingComma Then ReportInvalidFormatSpecifier(",", diagnostics) Return False End If expectingComma = False End If ElseIf start < 0 Then start = offset End If offset = offset + 1 End While If start >= 0 Then Dim token = expr.Substring(start) If expectingComma Then ReportInvalidFormatSpecifier(token, diagnostics) Return False End If builder.Add(token) ElseIf Not expectingComma Then ReportInvalidFormatSpecifier(",", diagnostics) Return False End If ' Verify format specifiers are valid identifiers. For Each token In builder If Not token.All(AddressOf SyntaxFacts.IsIdentifierPartCharacter) Then ReportInvalidFormatSpecifier(token, diagnostics) Return False End If Next Return True End Function Private Sub ReportInvalidFormatSpecifier(token As String, diagnostics As DiagnosticBag) diagnostics.Add(ERRID.ERR_InvalidFormatSpecifier, Location.None, token) End Sub ''' <summary> ''' Parse a debugger expression (e.g. possibly including pseudo-variables). ''' </summary> ''' <param name="text">The input string</param> ''' <remarks> ''' It would be better if this method returned ExpressionStatementSyntax, but this is the best we can do for ''' the time being due to issues in the binder resolving ambiguities between invocations and array access. ''' </remarks> Friend Function ParseDebuggerExpression(text As String, consumeFullText As Boolean) As PrintStatementSyntax Dim expression = ParseDebuggerExpressionInternal(SourceText.From(text), consumeFullText) Dim statement = InternalSyntax.SyntaxFactory.PrintStatement( New InternalSyntax.PunctuationSyntax(SyntaxKind.QuestionToken, "?", Nothing, Nothing), expression) Dim syntaxTree = statement.MakeDebuggerStatementContext().CreateSyntaxTree() Return DirectCast(syntaxTree.GetDebuggerStatement(), PrintStatementSyntax) End Function Private Function ParseDebuggerExpressionInternal(source As SourceText, consumeFullText As Boolean) As InternalSyntax.ExpressionSyntax Using scanner As New InternalSyntax.Scanner(source, ParseOptions, isScanningForExpressionCompiler:=True) ' NOTE: Default options should be enough Using p = New InternalSyntax.Parser(scanner) p.GetNextToken() Dim node = p.ParseExpression() If consumeFullText Then node = p.ConsumeUnexpectedTokens(node) Return node End Using End Using End Function Private Function ParseDebuggerStatement(text As String) As StatementSyntax Using scanner As New InternalSyntax.Scanner(SourceText.From(text), ParseOptions, isScanningForExpressionCompiler:=True) ' NOTE: Default options should be enough Using p = New InternalSyntax.Parser(scanner) p.GetNextToken() Dim node = p.ParseStatementInMethodBody() node = p.ConsumeUnexpectedTokens(node) Dim syntaxTree = node.MakeDebuggerStatementContext().CreateSyntaxTree() Return syntaxTree.GetDebuggerStatement() End Using End Using End Function <Extension> Private Function CreateSyntaxTree(root As InternalSyntax.VisualBasicSyntaxNode) As SyntaxTree Return VisualBasicSyntaxTree.Create(DirectCast(root.CreateRed(Nothing, 0), VisualBasicSyntaxNode), ParseOptions) End Function <Extension> Private Function MakeDebuggerStatementContext(statement As InternalSyntax.StatementSyntax) As InternalSyntax.CompilationUnitSyntax Return InternalSyntax.SyntaxFactory.CompilationUnit( options:=Nothing, [imports]:=Nothing, attributes:=Nothing, members:=Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList.List(statement), endOfFileToken:=InternalSyntax.SyntaxFactory.EndOfFileToken) End Function <Extension> Private Function GetDebuggerStatement(syntaxTree As SyntaxTree) As StatementSyntax Return DirectCast(DirectCast(syntaxTree.GetRoot(), CompilationUnitSyntax).Members.Single(), StatementSyntax) End Function ''' <summary> ''' This list is based on the statements found in StatementAnalyzer::IsSupportedStatement ''' (vb\language\debugger\statementanalyzer.cpp). ''' We'll add to that list some additional statements that can easily be supported by the new implementation ''' (include all compound assignments, not just "+=", etc). ''' For now, we'll leave out single line If statements, as the parsing for those would require extra ''' complexity on the EE side (ParseStatementInMethodBody should handle them, but it doesn't...). ''' </summary> Friend Function IsSupportedDebuggerStatement(syntax As StatementSyntax) As Boolean Select Case syntax.Kind Case SyntaxKind.AddAssignmentStatement, SyntaxKind.CallStatement, SyntaxKind.ConcatenateAssignmentStatement, SyntaxKind.DivideAssignmentStatement, SyntaxKind.ExponentiateAssignmentStatement, SyntaxKind.ExpressionStatement, SyntaxKind.IntegerDivideAssignmentStatement, SyntaxKind.LeftShiftAssignmentStatement, SyntaxKind.MultiplyAssignmentStatement, SyntaxKind.PrintStatement, SyntaxKind.ReDimStatement, SyntaxKind.ReDimPreserveStatement, SyntaxKind.RightShiftAssignmentStatement, SyntaxKind.SimpleAssignmentStatement, SyntaxKind.SubtractAssignmentStatement Return True Case Else Return False End Select End Function Friend Function EscapeKeywordIdentifiers(identifier As String) As String If SyntaxFacts.IsKeywordKind(SyntaxFacts.GetKeywordKind(identifier)) Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append("["c) builder.Append(identifier) builder.Append("]"c) Return pooled.ToStringAndFree() Else Return identifier End If End Function End Module End Namespace
aelij/roslyn
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/SyntaxHelpers.vb
Visual Basic
apache-2.0
12,358
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Enum ResumeStatementKind As Byte Plain ' Resume [Next] ' Resume Next Label ' Resume Label End Enum Partial Class BoundResumeStatement Public Sub New(syntax As VisualBasicSyntaxNode, Optional isNext As Boolean = False) Me.New(syntax, If(isNext, ResumeStatementKind.Next, ResumeStatementKind.Plain), Nothing, Nothing) End Sub Public Sub New(syntax As VisualBasicSyntaxNode, label As LabelSymbol, labelExpressionOpt As BoundExpression, Optional hasErrors As Boolean = False) Me.New(syntax, ResumeStatementKind.Label, label, labelExpressionOpt, hasErrors) Debug.Assert(labelExpressionOpt IsNot Nothing) End Sub #If DEBUG Then Private Sub Validate() Debug.Assert((Me.ResumeKind = ResumeStatementKind.Label) = Not (Me.LabelOpt Is Nothing AndAlso Me.LabelExpressionOpt Is Nothing)) Debug.Assert(Me.LabelExpressionOpt Is Nothing OrElse Me.LabelOpt IsNot Nothing OrElse Me.HasErrors) End Sub #End If End Class End Namespace
DavidKarlas/roslyn
src/Compilers/VisualBasic/Portable/BoundTree/BoundResumeStatement.vb
Visual Basic
apache-2.0
1,425
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Collections.ObjectModel Imports System.Globalization Imports Microsoft.CodeAnalysis.VisualBasic Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class VisualBasicCompilationOptionsTests Inherits BasicTestBase ''' <summary> ''' Using an instance of <see cref="VisualBasicCompilationOptions"/>, tests a property in <see cref="CompilationOptions"/> , even it is hidden by <see cref="VisualBasicCompilationOptions"/>. ''' </summary> Private Sub TestHiddenProperty(Of T)(factory As Func(Of CompilationOptions, T, CompilationOptions), getter As Func(Of CompilationOptions, T), validNonDefaultValue As T) TestPropertyGeneric(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), factory, getter, validNonDefaultValue) End Sub <Fact> Public Sub ShadowInvariants() TestHiddenProperty(Function(old, value) old.WithOutputKind(value), Function(opt) opt.OutputKind, OutputKind.DynamicallyLinkedLibrary) TestHiddenProperty(Function(old, value) old.WithModuleName(value), Function(opt) opt.ModuleName, "foo.dll") TestHiddenProperty(Function(old, value) old.WithMainTypeName(value), Function(opt) opt.MainTypeName, "Foo.Bar") TestHiddenProperty(Function(old, value) old.WithScriptClassName(value), Function(opt) opt.ScriptClassName, "<Script>") TestHiddenProperty(Function(old, value) old.WithOptimizationLevel(value), Function(opt) opt.OptimizationLevel, OptimizationLevel.Release) TestHiddenProperty(Function(old, value) old.WithOverflowChecks(value), Function(opt) opt.CheckOverflow, False) TestHiddenProperty(Function(old, value) old.WithCryptoKeyContainer(value), Function(opt) opt.CryptoKeyContainer, "foo") TestHiddenProperty(Function(old, value) old.WithCryptoKeyFile(value), Function(opt) opt.CryptoKeyFile, "foo") TestHiddenProperty(Function(old, value) old.WithCryptoPublicKey(value), Function(opt) opt.CryptoPublicKey, ImmutableArray.CreateRange(Of Byte)({1, 2, 3, 4})) TestHiddenProperty(Function(old, value) old.WithDelaySign(value), Function(opt) opt.DelaySign, True) TestHiddenProperty(Function(old, value) old.WithPlatform(value), Function(opt) opt.Platform, Platform.X64) TestHiddenProperty(Function(old, value) old.WithGeneralDiagnosticOption(value), Function(opt) opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress) TestHiddenProperty(Function(old, value) old.WithSpecificDiagnosticOptions(value), Function(opt) opt.SpecificDiagnosticOptions, New Dictionary(Of String, ReportDiagnostic) From {{"VB0001", ReportDiagnostic.Error}}.ToImmutableDictionary()) TestHiddenProperty(Function(old, value) old.WithReportSuppressedDiagnostics(value), Function(opt) opt.ReportSuppressedDiagnostics, True) TestHiddenProperty(Function(old, value) old.WithConcurrentBuild(value), Function(opt) opt.ConcurrentBuild, False) TestHiddenProperty(Function(old, value) old.WithXmlReferenceResolver(value), Function(opt) opt.XmlReferenceResolver, New XmlFileResolver(Nothing)) TestHiddenProperty(Function(old, value) old.WithSourceReferenceResolver(value), Function(opt) opt.SourceReferenceResolver, New SourceFileResolver(ImmutableArray(Of String).Empty, Nothing)) TestHiddenProperty(Function(old, value) old.WithMetadataReferenceResolver(value), Function(opt) opt.MetadataReferenceResolver, New TestMetadataReferenceResolver()) TestHiddenProperty(Function(old, value) old.WithAssemblyIdentityComparer(value), Function(opt) opt.AssemblyIdentityComparer, New DesktopAssemblyIdentityComparer(New AssemblyPortabilityPolicy())) End Sub Private Sub TestProperty(Of T)(factory As Func(Of VisualBasicCompilationOptions, T, VisualBasicCompilationOptions), getter As Func(Of VisualBasicCompilationOptions, T), validNonDefaultValue As T) TestPropertyGeneric(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), factory, getter, validNonDefaultValue) End Sub Private Shared Sub TestPropertyGeneric(Of TOptions As CompilationOptions, T)(oldOptions As TOptions, factory As Func(Of TOptions, T, TOptions), getter As Func(Of TOptions, T), validNonDefaultValue As T) Dim validDefaultValue = getter(oldOptions) ' we need non-default value to test Equals And GetHashCode Assert.NotEqual(validNonDefaultValue, validDefaultValue) ' check that the assigned value can be read Dim newOpt1 = factory(oldOptions, validNonDefaultValue) Assert.Equal(validNonDefaultValue, getter(newOpt1)) Assert.Equal(0, newOpt1.Errors.Length) 'check that creating new options with the same value yields the same options instance Dim newOpt1_alias = factory(newOpt1, validNonDefaultValue) Assert.Same(newOpt1_alias, newOpt1) ' check that Equals And GetHashCode work Dim newOpt2 = factory(oldOptions, validNonDefaultValue) Assert.False(newOpt1.Equals(oldOptions)) Assert.True(newOpt1.Equals(newOpt2)) Assert.Equal(newOpt1.GetHashCode(), newOpt2.GetHashCode()) ' test Nothing: Assert.NotNull(factory(oldOptions, Nothing)) End Sub <Fact> Public Sub Invariants() TestProperty(Function(old, value) old.WithOutputKind(value), Function(opt) opt.OutputKind, OutputKind.DynamicallyLinkedLibrary) TestProperty(Function(old, value) old.WithModuleName(value), Function(opt) opt.ModuleName, "foo.dll") TestProperty(Function(old, value) old.WithMainTypeName(value), Function(opt) opt.MainTypeName, "Foo.Bar") TestProperty(Function(old, value) old.WithScriptClassName(value), Function(opt) opt.ScriptClassName, "<Script>") TestProperty(Function(old, value) old.WithGlobalImports(value), Function(opt) opt.GlobalImports, ImmutableArray.Create(GlobalImport.Parse("Foo.Bar"), GlobalImport.Parse("Baz"))) TestProperty(Function(old, value) old.WithRootNamespace(value), Function(opt) opt.RootNamespace, "A.B.C") TestProperty(Function(old, value) old.WithOptionStrict(value), Function(opt) opt.OptionStrict, OptionStrict.On) TestProperty(Function(old, value) old.WithOptionInfer(value), Function(opt) opt.OptionInfer, False) TestProperty(Function(old, value) old.WithOptionExplicit(value), Function(opt) opt.OptionExplicit, False) TestProperty(Function(old, value) old.WithOptionCompareText(value), Function(opt) opt.OptionCompareText, True) TestProperty(Function(old, value) old.WithParseOptions(value), Function(opt) opt.ParseOptions, New VisualBasicParseOptions(kind:=SourceCodeKind.Script)) TestProperty(Function(old, value) old.WithEmbedVbCoreRuntime(value), Function(opt) opt.EmbedVbCoreRuntime, True) TestProperty(Function(old, value) old.WithOptimizationLevel(value), Function(opt) opt.OptimizationLevel, OptimizationLevel.Release) TestProperty(Function(old, value) old.WithOverflowChecks(value), Function(opt) opt.CheckOverflow, False) TestProperty(Function(old, value) old.WithCryptoKeyContainer(value), Function(opt) opt.CryptoKeyContainer, "foo") TestProperty(Function(old, value) old.WithCryptoKeyFile(value), Function(opt) opt.CryptoKeyFile, "foo") TestProperty(Function(old, value) old.WithCryptoPublicKey(value), Function(opt) opt.CryptoPublicKey, ImmutableArray.CreateRange(Of Byte)({1, 2, 3, 4})) TestProperty(Function(old, value) old.WithDelaySign(value), Function(opt) opt.DelaySign, True) TestProperty(Function(old, value) old.WithPlatform(value), Function(opt) opt.Platform, Platform.X64) TestProperty(Function(old, value) old.WithGeneralDiagnosticOption(value), Function(opt) opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress) TestProperty(Function(old, value) old.WithSpecificDiagnosticOptions(value), Function(opt) opt.SpecificDiagnosticOptions, New Dictionary(Of String, ReportDiagnostic) From {{"VB0001", ReportDiagnostic.Error}}.ToImmutableDictionary()) TestProperty(Function(old, value) old.WithReportSuppressedDiagnostics(value), Function(opt) opt.ReportSuppressedDiagnostics, True) TestProperty(Function(old, value) old.WithConcurrentBuild(value), Function(opt) opt.ConcurrentBuild, False) TestProperty(Function(old, value) old.WithCurrentLocalTime(value), Function(opt) opt.CurrentLocalTime, #2015/1/1#) TestProperty(Function(old, value) old.WithDebugPlusMode(value), Function(opt) opt.DebugPlusMode, True) TestProperty(Function(old, value) old.WithXmlReferenceResolver(value), Function(opt) opt.XmlReferenceResolver, New XmlFileResolver(Nothing)) TestProperty(Function(old, value) old.WithSourceReferenceResolver(value), Function(opt) opt.SourceReferenceResolver, New SourceFileResolver(ImmutableArray(Of String).Empty, Nothing)) TestProperty(Function(old, value) old.WithMetadataReferenceResolver(value), Function(opt) opt.MetadataReferenceResolver, New TestMetadataReferenceResolver()) TestProperty(Function(old, value) old.WithAssemblyIdentityComparer(value), Function(opt) opt.AssemblyIdentityComparer, New DesktopAssemblyIdentityComparer(New AssemblyPortabilityPolicy())) TestProperty(Function(old, value) old.WithStrongNameProvider(value), Function(opt) opt.StrongNameProvider, New DesktopStrongNameProvider()) End Sub <Fact> Public Sub WithXxx() AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName(Nothing).Errors, <expected> BC2014: the value 'Nothing' is invalid for option 'ScriptClassName' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("blah" & ChrW(0) & "foo").Errors, <expected> BC2014: the value '<%= "blah" & ChrW(0) & "foo" %>' is invalid for option 'ScriptClassName' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("").Errors, <expected> BC2014: the value '' is invalid for option 'ScriptClassName' </expected>) Assert.True(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName(Nothing).Errors.IsEmpty) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("blah" & ChrW(0) & "foo").Errors, <expected> BC2014: the value '<%= "blah" & ChrW(0) & "foo" %>' is invalid for option 'MainTypeName' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("").Errors, <expected> BC2014: the value '' is invalid for option 'MainTypeName' </expected>) Assert.True(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace(Nothing).Errors.IsEmpty) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("blah" & ChrW(0) & "foo").Errors, <expected> BC2014: the value '<%= "blah" & ChrW(0) & "foo" %>' is invalid for option 'RootNamespace' </expected>) Assert.True(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("").Errors.IsEmpty) Assert.Equal(0, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("Foo.Bar")).WithGlobalImports(DirectCast(Nothing, IEnumerable(Of GlobalImport))).GlobalImports.Count) Assert.Equal(0, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("Foo.Bar")).WithGlobalImports(DirectCast(Nothing, GlobalImport())).GlobalImports.Count) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind(CType(Int32.MaxValue, OutputKind)).Errors, <expected> BC2014: the value '<%= Int32.MaxValue %>' is invalid for option 'OutputKind' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind(CType(Int32.MinValue, OutputKind)).Errors, <expected> BC2014: the value '<%= Int32.MinValue %>' is invalid for option 'OutputKind' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel(CType(Int32.MaxValue, OptimizationLevel)).Errors, <expected> BC2014: the value '<%= Int32.MaxValue %>' is invalid for option 'OptimizationLevel' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel(CType(Int32.MinValue, OptimizationLevel)).Errors, <expected> BC2014: the value '<%= Int32.MinValue %>' is invalid for option 'OptimizationLevel' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(CType(3, OptionStrict)).Errors, <expected> BC2014: the value '3' is invalid for option 'OptionStrict' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithPlatform(CType(Int32.MaxValue, Platform)).Errors, <expected> BC2014: the value '<%= Int32.MaxValue %>' is invalid for option 'Platform' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithPlatform(CType(Int32.MinValue, Platform)).Errors, <expected> BC2014: the value '<%= Int32.MinValue %>' is invalid for option 'Platform' </expected>) Assert.Equal(Nothing, TestOptions.ReleaseDll.WithModuleName("foo").WithModuleName(Nothing).ModuleName) AssertTheseDiagnostics(TestOptions.ReleaseDll.WithModuleName("").Errors, <expected> BC37206: Invalid module name: Name cannot be empty. </expected>) AssertTheseDiagnostics(TestOptions.ReleaseDll.WithModuleName("a\0a").Errors, <expected> BC37206: Invalid module name: Name contains invalid characters. </expected>) AssertTheseDiagnostics(TestOptions.ReleaseDll.WithModuleName("a\uD800b").Errors, <expected> BC37206: Invalid module name: Name contains invalid characters. </expected>) AssertTheseDiagnostics(TestOptions.ReleaseDll.WithModuleName("a\\b").Errors, <expected> BC37206: Invalid module name: Name contains invalid characters. </expected>) AssertTheseDiagnostics(TestOptions.ReleaseDll.WithModuleName("a/b").Errors, <expected> BC37206: Invalid module name: Name contains invalid characters. </expected>) AssertTheseDiagnostics(TestOptions.ReleaseDll.WithModuleName("a:b").Errors, <expected> BC37206: Invalid module name: Name contains invalid characters. </expected>) End Sub <Fact> Public Sub ConstructorValidation() Dim options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, scriptClassName:=Nothing) Assert.Equal("Script", options.ScriptClassName) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, scriptClassName:="blah" & ChrW(0) & "foo").Errors, <expected> BC2014: the value '<%= "blah" & ChrW(0) & "foo" %>' is invalid for option 'ScriptClassName' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, scriptClassName:="").Errors, <expected> BC2014: the value '' is invalid for option 'ScriptClassName' </expected>) Assert.True(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, mainTypeName:=Nothing).Errors.IsEmpty) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, mainTypeName:=("blah" & ChrW(0) & "foo")).Errors, <expected> BC2014: the value '<%= "blah" & ChrW(0) & "foo" %>' is invalid for option 'MainTypeName' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, mainTypeName:="").Errors, <expected> BC2014: the value '' is invalid for option 'MainTypeName' </expected>) Assert.True(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, rootNamespace:=Nothing).Errors.IsEmpty) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, rootNamespace:=("blah" & ChrW(0) & "foo")).Errors, <expected> BC2014: the value '<%= "blah" & ChrW(0) & "foo" %>' is invalid for option 'RootNamespace' </expected>) Assert.True(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, rootNamespace:="").Errors.IsEmpty) AssertTheseDiagnostics(New VisualBasicCompilationOptions(outputKind:=CType(Int32.MaxValue, OutputKind)).Errors, <expected> BC2014: the value '<%= Int32.MaxValue %>' is invalid for option 'OutputKind' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(outputKind:=CType(Int32.MinValue, OutputKind)).Errors, <expected> BC2014: the value '<%= Int32.MinValue %>' is invalid for option 'OutputKind' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=CType(Int32.MaxValue, OptimizationLevel)).Errors, <expected> BC2014: the value '<%= Int32.MaxValue %>' is invalid for option 'OptimizationLevel' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=CType(Int32.MinValue, OptimizationLevel)).Errors, <expected> BC2014: the value '<%= Int32.MinValue %>' is invalid for option 'OptimizationLevel' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optionStrict:=CType(3, OptionStrict)).Errors, <expected> BC2014: the value '3' is invalid for option 'OptionStrict' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, platform:=CType(Int32.MaxValue, Platform)).Errors, <expected> BC2014: the value '<%= Int32.MaxValue %>' is invalid for option 'Platform' </expected>) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, platform:=CType(Int32.MinValue, Platform)).Errors, <expected> BC2014: the value '<%= Int32.MinValue %>' is invalid for option 'Platform' </expected>) End Sub ' Make sure the given root namespace is good and parses as expected Private Sub CheckRootNamespaceIsGood(rootNs As String, rootNsArray As String()) Dim options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace(rootNs) Assert.Equal(options.RootNamespace, rootNs) Assert.True(options.Errors.IsEmpty) End Sub ' Make sure the given root namespace is bad, the correct error is generated, and ' we have an empty root namespace as a result. Private Sub CheckRootNamespaceIsBad(rootNs As String) If rootNs Is Nothing Then Assert.True(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace(rootNs).Errors.IsEmpty) Else AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace(rootNs).Errors, <expected> BC2014: the value '<%= rootNs %>' is invalid for option 'RootNamespace' </expected>) End If End Sub <Fact> Public Sub TestRootNamespace() CheckRootNamespaceIsGood("", {}) CheckRootNamespaceIsGood("Foo", {"Foo"}) CheckRootNamespaceIsGood("Foo.Bar", {"Foo", "Bar"}) CheckRootNamespaceIsGood("Foo.Bar.q9", {"Foo", "Bar", "q9"}) CheckRootNamespaceIsBad(Nothing) CheckRootNamespaceIsBad(" ") CheckRootNamespaceIsBad(".") CheckRootNamespaceIsBad("Foo.") CheckRootNamespaceIsBad("Foo. Bar") CheckRootNamespaceIsBad(".Foo") CheckRootNamespaceIsBad("X.7Y") CheckRootNamespaceIsBad("#") CheckRootNamespaceIsBad("A.$B") End Sub Private Sub CheckImportsAreGood(importStrings As String()) Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse(importStrings)) Assert.Equal(importStrings.Length, opt.GlobalImports.Count) For i = 0 To importStrings.Length - 1 Assert.Equal(importStrings(i).Trim(), opt.GlobalImports(i).Clause.ToString) Next End Sub Private Sub CheckImportsAreBad(importStrings As String(), expectedErrors As String()) Assert.Throws(Of ArgumentException)(Function() GlobalImport.Parse(importStrings)) Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing Dim globalImports = GlobalImport.Parse(importStrings, diagnostics) Assert.Equal(0, globalImports.Count) Assert.NotNull(diagnostics) Assert.NotEmpty(diagnostics) Dim errorTexts = (From e In diagnostics Let text = e.GetMessage(CultureInfo.GetCultureInfo("en")) Order By text Select text).ToArray() Dim expectedTexts = (From e In expectedErrors Order By e Select e).ToArray() For i = 0 To diagnostics.Length - 1 Assert.Equal(expectedTexts(i), errorTexts(i)) Next End Sub <Fact> Public Sub TestImports() CheckImportsAreGood({}) CheckImportsAreGood({"A.B", "G.F(Of G)", "Q", "A = G.X"}) CheckImportsAreBad({"A.B.435", "Global.Foo"}, {"Error in project-level import 'A.B.435' at '.435' : End of statement expected.", "Error in project-level import 'Global.Foo' at 'Global' : 'Global' not allowed in this context; identifier expected."}) End Sub <Fact> Public Sub TestGlobalOptionsParseReturnsNonNullDiagnostics() Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing Dim globalImports = GlobalImport.Parse({"System"}, diagnostics) Assert.Equal(1, globalImports.Count()) Assert.NotNull(diagnostics) Assert.Empty(diagnostics) End Sub <Fact> Public Sub WarningTest() Assert.Equal(0, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(Nothing).SpecificDiagnosticOptions.Count) Dim source = <compilation name="WarningTest"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x As Integer Dim y As Integer Const z As Long = 0 End Sub Function foo() End Function End Module </file> </compilation> ' Baseline Dim commonoption = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication) Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source, commonoption) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocal, "x").WithArguments("x"), Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y"), Diagnostic(ERRID.WRN_UnusedLocalConst, "z").WithArguments("z"), Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("foo")) ' Suppress All ' vbc a.vb /nowarn Dim options = commonoption.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress) comp = CreateCompilationWithMscorlibAndVBRuntime(source, options) comp.VerifyDiagnostics() ' Suppress 42024 ' vbc a.vb /nowarn:42024 Dim warnings As IDictionary(Of String, ReportDiagnostic) = New Dictionary(Of String, ReportDiagnostic)() warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42024), ReportDiagnostic.Suppress) options = commonoption.WithSpecificDiagnosticOptions(New ReadOnlyDictionary(Of String, ReportDiagnostic)(warnings)) comp = CreateCompilationWithMscorlibAndVBRuntime(source, options) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocalConst, "z").WithArguments("z"), Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("foo")) ' Suppress 42024, 42099 ' vbc a.vb /nowarn:42024,42099 warnings = New Dictionary(Of String, ReportDiagnostic)() warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42024), ReportDiagnostic.Suppress) warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42099), ReportDiagnostic.Suppress) options = commonoption.WithSpecificDiagnosticOptions(New ReadOnlyDictionary(Of String, ReportDiagnostic)(warnings)) comp = CreateCompilationWithMscorlibAndVBRuntime(source, options) comp.VerifyDiagnostics(Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("foo")) ' Treat All as Errors ' vbc a.vb /warnaserror options = commonoption.WithGeneralDiagnosticOption(ReportDiagnostic.Error) comp = CreateCompilationWithMscorlibAndVBRuntime(source, options) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocal, "x").WithArguments("x").WithWarningAsError(True), Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y").WithWarningAsError(True), Diagnostic(ERRID.WRN_UnusedLocalConst, "z").WithArguments("z").WithWarningAsError(True), Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("foo").WithWarningAsError(True)) ' Treat 42105 as Error ' vbc a.vb /warnaserror:42105 warnings = New Dictionary(Of String, ReportDiagnostic)() warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42105), ReportDiagnostic.Error) options = commonoption.WithSpecificDiagnosticOptions(New ReadOnlyDictionary(Of String, ReportDiagnostic)(warnings)) comp = CreateCompilationWithMscorlibAndVBRuntime(source, options) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocal, "x").WithArguments("x"), Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y"), Diagnostic(ERRID.WRN_UnusedLocalConst, "z").WithArguments("z"), Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("foo").WithWarningAsError(True)) ' Treat 42105 and 42099 as Errors ' vbc a.vb /warnaserror:42105,42099 warnings = New Dictionary(Of String, ReportDiagnostic)() warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42105), ReportDiagnostic.Error) warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42099), ReportDiagnostic.Error) options = commonoption.WithSpecificDiagnosticOptions(New ReadOnlyDictionary(Of String, ReportDiagnostic)(warnings)) comp = CreateCompilationWithMscorlibAndVBRuntime(source, options) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocal, "x").WithArguments("x"), Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y"), Diagnostic(ERRID.WRN_UnusedLocalConst, "z").WithArguments("z").WithWarningAsError(True), Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("foo").WithWarningAsError(True)) ' Treat All as Errors but Suppress 42024 ' vbc a.vb /warnaserror /nowarn:42024 warnings = New Dictionary(Of String, ReportDiagnostic)() warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42024), ReportDiagnostic.Suppress) options = commonoption.WithSpecificDiagnosticOptions(New ReadOnlyDictionary(Of String, ReportDiagnostic)(warnings)).WithGeneralDiagnosticOption(ReportDiagnostic.Error) comp = CreateCompilationWithMscorlibAndVBRuntime(source, options) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocalConst, "z").WithArguments("z").WithWarningAsError(True), Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("foo").WithWarningAsError(True)) ' Suppress All with treating 42024 as an error, which will be ignored ' vbc a.vb /warnaserror:42024 /nowarn or ' vbc a.vb /nowarn /warnaserror warnings = New Dictionary(Of String, ReportDiagnostic)() warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42024), ReportDiagnostic.Error) options = commonoption.WithSpecificDiagnosticOptions(New ReadOnlyDictionary(Of String, ReportDiagnostic)(warnings)).WithGeneralDiagnosticOption(ReportDiagnostic.Suppress) comp = CreateCompilationWithMscorlibAndVBRuntime(source, options) comp.VerifyDiagnostics() End Sub <Fact, WorkItem(529809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529809")> Public Sub NetModuleWithVbCore() Dim options As New VisualBasicCompilationOptions(OutputKind.NetModule, embedVbCoreRuntime:=True) Assert.Equal(2042, options.Errors.Single().Code) AssertTheseDiagnostics(CreateCompilationWithMscorlibAndVBRuntime(<compilation><file/></compilation>, options), <expected> BC2042: The options /vbruntime* and /target:module cannot be combined. </expected>) End Sub ''' <summary> ''' If this test fails, please update the <see cref="VisualBasicCompilationOptions.GetHashCode" /> ''' and <see cref="VisualBasicCompilationOptions.Equals" /> methods and <see cref="VisualBasicCompilationOptions.New"/> to ''' make sure they are doing the right thing with your new field And then update the baseline ''' here. ''' </summary> <Fact> Public Sub TestFieldsForEqualsAndGetHashCode() ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( (GetType(VisualBasicCompilationOptions)), "GlobalImports", "Language", "RootNamespace", "OptionStrict", "OptionInfer", "OptionExplicit", "OptionCompareText", "EmbedVbCoreRuntime", "SuppressEmbeddedDeclarations", "ParseOptions", "IgnoreCorLibraryDuplicatedTypes") End Sub <Fact> Public Sub WithCryptoPublicKey() Dim options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication) Assert.Equal(ImmutableArray(Of Byte).Empty, options.CryptoPublicKey) Assert.Equal(ImmutableArray(Of Byte).Empty, options.WithCryptoPublicKey(Nothing).CryptoPublicKey) Assert.Same(options, options.WithCryptoPublicKey(Nothing)) Assert.Same(options, options.WithCryptoPublicKey(ImmutableArray(Of Byte).Empty)) End Sub <Fact> Public Sub WithIgnoreCorLibraryDuplicatedTypes() Dim optionFalse = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication) Dim optionTrue = optionFalse.WithIgnoreCorLibraryDuplicatedTypes(True) Assert.False(optionFalse.IgnoreCorLibraryDuplicatedTypes) Assert.True(optionTrue.IgnoreCorLibraryDuplicatedTypes) Assert.Same(optionFalse, optionFalse.WithIgnoreCorLibraryDuplicatedTypes(False)) Assert.True(optionTrue.Equals(optionFalse.WithIgnoreCorLibraryDuplicatedTypes(True))) Assert.False(optionTrue.Equals(optionFalse)) Dim optionTrueClone = New VisualBasicCompilationOptions(optionTrue) Assert.Equal(optionTrue, optionTrueClone) Assert.NotEqual(optionFalse, optionTrueClone) End Sub End Class End Namespace
amcasey/roslyn
src/Compilers/VisualBasic/Test/Semantic/Compilation/VisualBasicCompilationOptionsTests.vb
Visual Basic
apache-2.0
33,046
' 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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the various list of operators you can overload after the "Operator" keyword ''' </summary> Friend Class OverloadableOperatorRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken If Not targetToken.IsKind(SyntaxKind.OperatorKeyword) OrElse Not targetToken.Parent.IsKind(SyntaxKind.OperatorStatement) Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim modifierFacts = context.ModifierCollectionFacts ' If we have a Widening or Narrowing declaration, then we must be a CType operator If modifierFacts.NarrowingOrWideningKeyword.Kind <> SyntaxKind.None Then Return ImmutableArray.Create(New RecommendedKeyword("CType", VBFeaturesResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type)) Else ' We could just be a normal name, so we list all possible options here. Dev10 allows you to type ' "Operator Narrowing", so we also list the Narrowing/Widening options as well. ' TODO: fix parser to actually deal with such stupidities like "Operator Narrowing" Return {"+", "-", "IsFalse", "IsTrue", "Not", "*", "/", "\", "&", "^", ">>", "<<", "=", "<>", ">", ">=", "<", "<=", "And", "Like", "Mod", "Or", "Xor", "Narrowing", "Widening"}.Select(Function(s) New RecommendedKeyword(s, GetToolTipForKeyword(s))).ToImmutableArray() End If End Function Private Shared Function GetToolTipForKeyword([operator] As String) As String Select Case [operator] Case "+" Return VBFeaturesResources.Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression Case "-" Return VBFeaturesResources.Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression Case "IsFalse" Return VBFeaturesResources.Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure Case "IsTrue" Return VBFeaturesResources.Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure Case "Not" Return VBFeaturesResources.Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression Case "*" Return VBFeaturesResources.Multiplies_two_numbers_and_returns_the_product Case "/" Return VBFeaturesResources.Divides_two_numbers_and_returns_a_floating_point_result Case "\" Return VBFeaturesResources.Divides_two_numbers_and_returns_an_integer_result Case "&" Return VBFeaturesResources.Generates_a_string_concatenation_of_two_expressions Case "^" Return VBFeaturesResources.Raises_a_number_to_the_power_of_another_number Case ">>" Return VBFeaturesResources.Performs_an_arithmetic_right_shift_on_a_bit_pattern Case "<<" Return VBFeaturesResources.Performs_an_arithmetic_left_shift_on_a_bit_pattern Case "=" Return VBFeaturesResources.Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False Case "<>" Return VBFeaturesResources.Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False Case ">" Return VBFeaturesResources.Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False Case ">=" Return VBFeaturesResources.Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False Case "<" Return VBFeaturesResources.Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False Case "<=" Return VBFeaturesResources.Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False Case "And" Return VBFeaturesResources.Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2 Case "Like" Return VBFeaturesResources.Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern Case "Mod" Return VBFeaturesResources.Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2 Case "Or" Return VBFeaturesResources.Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2 Case "Xor" Return VBFeaturesResources.Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2 Case "Narrowing" Return VBFeaturesResources.Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure Case "Widening" Return VBFeaturesResources.Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure Case Else Return String.Empty End Select End Function End Class End Namespace
physhi/roslyn
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/OverloadableOperatorRecommender.vb
Visual Basic
apache-2.0
7,544
' 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Turns the bound initializers into a list of bound assignment statements ''' </summary> Friend Class InitializerRewriter ''' <summary> ''' Builds a constructor body. ''' </summary> ''' <remarks> ''' Lowers initializers to fields assignments if not lowered yet and the first statement of the body isn't ''' a call to another constructor of the containing class. ''' </remarks> ''' <returns> ''' Bound block including ''' - call to a base constructor ''' - field initializers and top-level code ''' - remaining constructor statements (empty for a submission) ''' </returns> Friend Shared Function BuildConstructorBody( compilationState As TypeCompilationState, constructorMethod As MethodSymbol, constructorInitializerOpt As BoundStatement, processedInitializers As Binder.ProcessedFieldOrPropertyInitializers, block As BoundBlock) As BoundBlock Dim hasMyBaseConstructorCall As Boolean = False Dim containingType = constructorMethod.ContainingType If HasExplicitMeConstructorCall(block, containingType, hasMyBaseConstructorCall) AndAlso Not hasMyBaseConstructorCall Then Return block End If ' rewrite initializers just once, statements will be reused when emitting all constructors with field initializers: If Not processedInitializers.BoundInitializers.IsDefaultOrEmpty AndAlso processedInitializers.InitializerStatements.IsDefault Then processedInitializers.InitializerStatements = RewriteInitializersAsStatements(constructorMethod, processedInitializers.BoundInitializers) Debug.Assert(processedInitializers.BoundInitializers.Length = processedInitializers.InitializerStatements.Length) End If Dim initializerStatements = processedInitializers.InitializerStatements Dim blockStatements As ImmutableArray(Of BoundStatement) = block.Statements Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance() If constructorInitializerOpt IsNot Nothing Then ' Inserting base constructor call Debug.Assert(Not hasMyBaseConstructorCall) boundStatements.Add(constructorInitializerOpt) ElseIf hasMyBaseConstructorCall Then ' Using existing constructor call -- it must be the first statement in the block boundStatements.Add(blockStatements(0)) ElseIf Not constructorMethod.IsShared AndAlso containingType.IsValueType Then ' TODO: this can be skipped if we have equal number of initializers and fields ' assign all fields ' Me = Nothing Dim syntax = block.Syntax boundStatements.Add( New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, New BoundValueTypeMeReference(syntax, containingType), New BoundConversion( syntax, New BoundLiteral(syntax, ConstantValue.Null, Nothing), ConversionKind.WideningNothingLiteral, checked:=False, explicitCastInCode:=False, type:=containingType), suppressObjectClone:=True, type:=containingType))) End If ' add hookups for Handles if needed For Each member In containingType.GetMembers() If member.Kind = SymbolKind.Method Then Dim methodMember = DirectCast(member, MethodSymbol) Dim handledEvents = methodMember.HandledEvents If handledEvents.IsEmpty Then Continue For End If ' if method has definition and implementation parts ' their "Handles" should be merged. If methodMember.IsPartial Then Dim implementationPart = methodMember.PartialImplementationPart If implementationPart IsNot Nothing Then handledEvents = handledEvents.Concat(implementationPart.HandledEvents) Else ' partial methods with no implementation do not handle anything Continue For End If End If For Each handledEvent In handledEvents ' it should be either Constructor or SharedConstructor ' if it is an instance constructor it should apply to all instance constructors. If handledEvent.hookupMethod.MethodKind = constructorMethod.MethodKind Then Dim eventSymbol = DirectCast(handledEvent.EventSymbol, EventSymbol) Dim addHandlerMethod = eventSymbol.AddMethod Dim delegateCreation = handledEvent.delegateCreation Dim syntax = delegateCreation.Syntax Dim receiver As BoundExpression = Nothing If Not addHandlerMethod.IsShared Then Dim meParam = constructorMethod.MeParameter If addHandlerMethod.ContainingType = containingType Then receiver = New BoundMeReference(syntax, meParam.Type).MakeCompilerGenerated() Else 'Dev10 always performs base call if event is in the base class. 'Even if Me/MyClass syntax was used. It seems to be somewhat of a bug 'that noone cared about. For compat reasons we will do the same. receiver = New BoundMyBaseReference(syntax, meParam.Type).MakeCompilerGenerated() End If End If ' Normally, we would synthesize lowered bound nodes, but we know that these nodes will ' be run through the LocalRewriter. Let the LocalRewriter handle the special code for ' WinRT events. boundStatements.Add( New BoundAddHandlerStatement( syntax:=syntax, eventAccess:=New BoundEventAccess(syntax, receiver, eventSymbol, eventSymbol.Type).MakeCompilerGenerated(), handler:=delegateCreation).MakeCompilerGenerated()) End If Next End If Next ' insert initializers AFTER implicit or explicit call to a base constructor ' and after Handles hookup if there were any If Not initializerStatements.IsDefault Then For Each initializer In initializerStatements boundStatements.Add(initializer) Next End If ' Add InitializeComponent call, if need to. If Not constructorMethod.IsShared AndAlso compilationState.InitializeComponentOpt IsNot Nothing AndAlso constructorMethod.IsImplicitlyDeclared Then boundStatements.Add(New BoundCall(constructorMethod.Syntax, compilationState.InitializeComponentOpt, Nothing, New BoundMeReference(constructorMethod.Syntax, compilationState.InitializeComponentOpt.ContainingType), ImmutableArray(Of BoundExpression).Empty, Nothing, compilationState.InitializeComponentOpt.ReturnType). MakeCompilerGenerated().ToStatement().MakeCompilerGenerated()) End If ' nothing was added If boundStatements.Count = 0 Then boundStatements.Free() Return block End If ' move the rest of the statements For statementIndex = If(hasMyBaseConstructorCall, 1, 0) To blockStatements.Length - 1 boundStatements.Add(blockStatements(statementIndex)) Next Return New BoundBlock(block.Syntax, block.StatementListSyntax, block.Locals, boundStatements.ToImmutableAndFree(), block.HasErrors) End Function ''' <summary> ''' Rewrites GlobalStatementInitializers to ExpressionStatements and gets the initializers for fields and properties. ''' </summary> ''' <remarks> ''' Initializers for fields and properties cannot be rewritten to their final form at this place because they might need ''' to be rewritten to replace their placeholder expressions to the final locals or temporaries (e.g. in case of a field ''' declaration with "AsNew" and multiple variable names. The final rewriting will during local rewriting. ''' The statement list returned by this function can be copied into all constructors without reprocessing it. ''' </remarks> Private Shared Function RewriteInitializersAsStatements(constructor As MethodSymbol, boundInitializers As ImmutableArray(Of BoundInitializer)) As ImmutableArray(Of BoundStatement) Debug.Assert(Not boundInitializers.IsEmpty) Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance(boundInitializers.Length) For Each init In boundInitializers Select Case init.Kind Case BoundKind.FieldOrPropertyInitializer boundStatements.Add(init) Case BoundKind.GlobalStatementInitializer Dim stmtInit = DirectCast(init, BoundGlobalStatementInitializer) Dim syntax = init.Syntax If constructor.IsSubmissionConstructor AndAlso init Is boundInitializers.Last AndAlso stmtInit.Statement.Kind = BoundKind.ExpressionStatement Then Dim submissionResultVariable = New BoundParameter(syntax, constructor.Parameters(1), constructor.Parameters(1).Type) Dim expr = DirectCast(stmtInit.Statement, BoundExpressionStatement).Expression Debug.Assert(expr.Type IsNot Nothing) If expr.Type.SpecialType <> SpecialType.System_Void Then boundStatements.Add(New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, submissionResultVariable, expr, False, expr.Type))) Exit Select End If End If boundStatements.Add(stmtInit.Statement) Case Else Throw ExceptionUtilities.UnexpectedValue(init.Kind) End Select Next Return boundStatements.ToImmutableAndFree() End Function ''' <summary> ''' Determines if this constructor calls another constructor of the constructor's containing class. ''' </summary> Friend Shared Function HasExplicitMeConstructorCall(block As BoundBlock, container As TypeSymbol, <Out()> ByRef isMyBaseConstructorCall As Boolean) As Boolean isMyBaseConstructorCall = False If block.Statements.Any Then Dim firstBoundStatement As BoundStatement = block.Statements.First() ' NOTE: it is assumed that an explicit constructor call from another constructor should ' NOT be nested into any statement lists and to be the first constructor of the ' block's statements; otherwise it would complicate this rewriting because we ' will have to insert field initializers right after constructor call ' NOTE: If in future some rewriters break this assumption, the insersion ' of initializers as well as the following code should be revised If firstBoundStatement.Kind = BoundKind.ExpressionStatement Then Dim expression = DirectCast(firstBoundStatement, BoundExpressionStatement).Expression If expression.Kind = BoundKind.Call Then Dim callExpression = DirectCast(expression, BoundCall) Dim receiver = callExpression.ReceiverOpt If receiver IsNot Nothing AndAlso receiver.IsInstanceReference Then Dim methodSymbol = callExpression.Method If methodSymbol.MethodKind = MethodKind.Constructor Then isMyBaseConstructorCall = receiver.IsMyBaseReference Return methodSymbol.ContainingType = container End If End If End If End If End If Return False End Function End Class End Namespace
furesoft/roslyn
src/Compilers/VisualBasic/Portable/Analysis/InitializerRewriter.vb
Visual Basic
apache-2.0
14,787
' 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.Threading Imports Microsoft.CodeAnalysis.GenerateMember.GenerateDefaultConstructors Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateDefaultConstructors <ExportLanguageService(GetType(IGenerateDefaultConstructorsService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicGenerateDefaultConstructorsService Inherits AbstractGenerateDefaultConstructorsService(Of VisualBasicGenerateDefaultConstructorsService) Protected Overrides Function TryInitializeState( document As SemanticDocument, textSpan As TextSpan, cancellationToken As CancellationToken, ByRef baseTypeNode As SyntaxNode, ByRef classType As INamedTypeSymbol) As Boolean If cancellationToken.IsCancellationRequested Then Return False End If Dim token = DirectCast(document.Root, SyntaxNode).FindToken(textSpan.Start) Dim type = token.GetAncestor(Of TypeSyntax)() If type IsNot Nothing AndAlso type.IsParentKind(SyntaxKind.InheritsStatement) Then Dim baseList = DirectCast(type.Parent, InheritsStatementSyntax) If baseList.Types.Count > 0 AndAlso baseList.Types(0) Is type AndAlso baseList.IsParentKind(SyntaxKind.ClassBlock) Then classType = TryCast(document.SemanticModel.GetDeclaredSymbol(baseList.Parent, cancellationToken), INamedTypeSymbol) baseTypeNode = type Return classType IsNot Nothing End If End If baseTypeNode = Nothing classType = Nothing Return False End Function End Class End Namespace
Pvlerick/roslyn
src/Features/VisualBasic/Portable/GenerateMember/GenerateDefaultConstructors/VisualBasicGenerateDefaultConstructorsService.vb
Visual Basic
apache-2.0
2,076
' 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 Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue Imports Microsoft.CodeAnalysis.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests Friend Module Extensions Friend Sub VerifyUnchangedDocument( source As String, description As ActiveStatementsDescription) VisualBasicEditAndContinueTestHelpers.CreateInstance().VerifyUnchangedDocument( ActiveStatementsDescription.ClearTags(source), description.OldStatements, description.OldTrackingSpans, description.NewSpans, description.NewRegions) End Sub <Extension> Friend Sub VerifyRudeDiagnostics(editScript As EditScript(Of SyntaxNode), ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifyRudeDiagnostics(editScript, ActiveStatementsDescription.Empty, expectedDiagnostics) End Sub <Extension> Friend Sub VerifyRudeDiagnostics(editScript As EditScript(Of SyntaxNode), description As ActiveStatementsDescription, ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VisualBasicEditAndContinueTestHelpers.CreateInstance().VerifyRudeDiagnostics(editScript, description, expectedDiagnostics) End Sub <Extension> Friend Sub VerifyLineEdits(editScript As EditScript(Of SyntaxNode), expectedLineEdits As IEnumerable(Of LineChange), expectedNodeUpdates As IEnumerable(Of String), ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VisualBasicEditAndContinueTestHelpers.CreateInstance().VerifyLineEdits(editScript, expectedLineEdits, expectedNodeUpdates, expectedDiagnostics) End Sub <Extension> Friend Sub VerifySemanticDiagnostics(editScript As EditScript(Of SyntaxNode), ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifySemanticDiagnostics(editScript, Nothing, expectedDiagnostics) End Sub <Extension> Friend Sub VerifySemanticDiagnostics(editScript As EditScript(Of SyntaxNode), expectedDeclarationError As DiagnosticDescription, ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifySemantics(editScript, ActiveStatementsDescription.Empty, Nothing, expectedDeclarationError, expectedDiagnostics) End Sub <Extension> Friend Sub VerifySemantics(editScript As EditScript(Of SyntaxNode), activeStatements As ActiveStatementsDescription, expectedSemanticEdits As SemanticEditDescription(), ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifySemantics(editScript, activeStatements, Nothing, Nothing, expectedSemanticEdits, Nothing, expectedDiagnostics) End Sub <Extension> Friend Sub VerifySemantics(editScript As EditScript(Of SyntaxNode), activeStatements As ActiveStatementsDescription, expectedSemanticEdits As SemanticEditDescription(), expectedDeclarationError As DiagnosticDescription, ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifySemantics(editScript, activeStatements, Nothing, Nothing, expectedSemanticEdits, expectedDeclarationError, expectedDiagnostics) End Sub <Extension> Friend Sub VerifySemantics(editScript As EditScript(Of SyntaxNode), activeStatements As ActiveStatementsDescription, additionalOldSources As IEnumerable(Of String), additionalNewSources As IEnumerable(Of String), expectedSemanticEdits As SemanticEditDescription(), ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifySemantics(editScript, activeStatements, additionalOldSources, additionalNewSources, expectedSemanticEdits, Nothing, expectedDiagnostics) End Sub <Extension> Friend Sub VerifySemantics(editScript As EditScript(Of SyntaxNode), activeStatements As ActiveStatementsDescription, additionalOldSources As IEnumerable(Of String), additionalNewSources As IEnumerable(Of String), expectedSemanticEdits As SemanticEditDescription(), expectedDeclarationError As DiagnosticDescription, ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VisualBasicEditAndContinueTestHelpers.CreateInstance().VerifySemantics( editScript, activeStatements, additionalOldSources, additionalNewSources, expectedSemanticEdits, expectedDeclarationError, expectedDiagnostics) End Sub End Module End Namespace
diryboy/roslyn
src/EditorFeatures/VisualBasicTest/EditAndContinue/Helpers/Extensions.vb
Visual Basic
mit
6,023
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("2016030701vb Stop Watch")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("2016030701vb Stop Watch")> <Assembly: AssemblyCopyright("Copyright © 2016")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("06407597-142b-4d91-9601-10ff4be05fde")> ' 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")>
Hadesxz/VB-codes
2016030701vb Stop Watch/2016030701vb Stop Watch/My Project/AssemblyInfo.vb
Visual Basic
mit
1,164
'//////////////////////////////////////////////////////////////////////// ' Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved. ' ' This file is part of Aspose.Words. The source code in this file ' is only intended as a supplement to the documentation, and is provided ' "as is", without warranty of any kind, either expressed or implied. '//////////////////////////////////////////////////////////////////////// Imports Microsoft.VisualBasic Imports System Imports System.Text.RegularExpressions Imports System.Collections Imports System.Drawing Imports System.IO Imports System.Reflection Imports Aspose.Words Public Class FindAndHighlight Public Shared Sub Run() ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir_FindAndReplace() Dim doc As New Document(dataDir & "TestFile.doc") ' We want the "your document" phrase to be highlighted. Dim regex As New Regex("your document", RegexOptions.IgnoreCase) doc.Range.Replace(regex, New ReplaceEvaluatorFindAndHighlight(), False) ' Save the output document. doc.Save(dataDir & "TestFile Out.doc") Console.WriteLine(vbNewLine & "Text highlighted successfully." & vbNewLine & "File saved at " + dataDir + "TestFile Out.doc") End Sub Private Class ReplaceEvaluatorFindAndHighlight Implements IReplacingCallback ''' <summary> ''' This method is called by the Aspose.Words find and replace engine for each match. ''' This method highlights the match string, even if it spans multiple runs. ''' </summary> Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing ' This is a Run node that contains either the beginning or the complete match. Dim currentNode As Node = e.MatchNode ' The first (and may be the only) run can contain text before the match, ' in this case it is necessary to split the run. If e.MatchOffset > 0 Then currentNode = SplitRun(CType(currentNode, Run), e.MatchOffset) End If ' This array is used to store all nodes of the match for further highlighting. Dim runs As New ArrayList() ' Find all runs that contain parts of the match string. Dim remainingLength As Integer = e.Match.Value.Length Do While (remainingLength > 0) AndAlso (currentNode IsNot Nothing) AndAlso (currentNode.GetText().Length <= remainingLength) runs.Add(currentNode) remainingLength = remainingLength - currentNode.GetText().Length ' Select the next Run node. ' Have to loop because there could be other nodes such as BookmarkStart etc. Do currentNode = currentNode.NextSibling Loop While (currentNode IsNot Nothing) AndAlso (currentNode.NodeType <> NodeType.Run) Loop ' Split the last run that contains the match if there is any text left. If (currentNode IsNot Nothing) AndAlso (remainingLength > 0) Then SplitRun(CType(currentNode, Run), remainingLength) runs.Add(currentNode) End If ' Now highlight all runs in the sequence. For Each run As Run In runs run.Font.HighlightColor = Color.Yellow Next run ' Signal to the replace engine to do nothing because we have already done all what we wanted. Return ReplaceAction.Skip End Function End Class ''' <summary> ''' Splits text of the specified run into two runs. ''' Inserts the new run just after the specified run. ''' </summary> Private Shared Function SplitRun(ByVal run As Run, ByVal position As Integer) As Run Dim afterRun As Run = CType(run.Clone(True), Run) afterRun.Text = run.Text.Substring(position) run.Text = run.Text.Substring(0, position) run.ParentNode.InsertAfter(afterRun, run) Return afterRun End Function End Class
dtscal/Aspose_Words_NET
Examples/VisualBasic/Programming-Documents/Find-Replace/FindAndHighlight.vb
Visual Basic
mit
4,184
 Public Module readCommand Public chunk As Object Public data As Object Public Function Parse(ByVal text As String, ByVal header As String, ByVal closer As String) As String Dim inner As String = text.Substring(text.IndexOf(header) + header.Length, text.LastIndexOf(closer) - (text.IndexOf(header) + header.Length)) Return inner End Function Public Function ParseOuter(ByVal text As String, ByVal header As String, ByVal closer As String) As String Dim inner As String = text.Substring(text.IndexOf(header) + header.Length, text.IndexOf(closer) - (text.IndexOf(header) + header.Length)) Return header & inner & closer End Function End Module
willowslaboratory/WLABV3
library.willowslab.net/Library_v3/Modules/readCommand.vb
Visual Basic
mit
702
Imports SistFoncreagro.BussinessEntities Public Interface IMarcaRepository Sub SaveMarca(ByVal marca As Marca) Sub DeleteMarca(ByVal IdMarca As Int32) Function GetAllFromMarca() As List(Of Marca) Function GetAllFromByIdMarca(ByVal idMarca As Int32) As Marca End Interface
crackper/SistFoncreagro
SistFoncreagro.DataAccess/IMarcaRepository.vb
Visual Basic
mit
291
' Copyright 2016 Esri. ' ' Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. ' You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 ' ' Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ' "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific ' language governing permissions and limitations under the License. Imports Esri.ArcGISRuntime.Data Imports Esri.ArcGISRuntime.Geometry Imports Esri.ArcGISRuntime.Mapping Imports Esri.ArcGISRuntime.Symbology Imports System.Windows Imports System.Windows.Media Namespace FeatureLayerQuery Public Class FeatureLayerQueryVB ' Create reference to service of US States Private _statesUrl As String = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/2" ' Create globally available feature table for easy referencing Private _featureTable As ServiceFeatureTable ' Create globally available feature layer for easy referencing Private _featureLayer As FeatureLayer Public Sub New() InitializeComponent() ' Create the UI, setup the control references and execute initialization Initialize() End Sub Private Sub Initialize() ' Create new Map with basemap Dim myMap As New Map(Basemap.CreateTopographic()) ' Create and set initial map location Dim initialLocation As New MapPoint(-11000000, 5000000, SpatialReferences.WebMercator) myMap.InitialViewpoint = New Viewpoint(initialLocation, 100000000) ' Create feature table using a url _featureTable = New ServiceFeatureTable(New Uri(_statesUrl)) ' Create feature layer using this feature table _featureLayer = New FeatureLayer(_featureTable) ' Set the Opacity of the Feature Layer _featureLayer.Opacity = 0.6 ' Create a new renderer for the States Feature Layer Dim lineSymbol As New SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Black, 1) Dim fillSymbol As New SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Colors.Yellow, lineSymbol) ' Set States feature layer renderer _featureLayer.Renderer = New SimpleRenderer(fillSymbol) ' Add feature layer to the map myMap.OperationalLayers.Add(_featureLayer) ' Assign the map to the MapView myMapView.Map = myMap End Sub Private Async Sub OnQueryClicked(sender As Object, e As System.Windows.RoutedEventArgs) ' Remove any previous feature selections that may have been made _featureLayer.ClearSelection() ' Begin query process Await QueryStateFeature(queryEntry.Text) End Sub Private Async Function QueryStateFeature(ByVal stateName As String) As Task Try ' Create a query parameters that will be used to Query the feature table Dim queryParams As New QueryParameters() ' Construct and assign the where clause that will be used to query the feature table queryParams.WhereClause = "upper(STATE_NAME) LIKE '%" & (stateName.ToUpper()) & "%'" ' Query the feature table Dim queryResult As FeatureQueryResult = Await _featureTable.QueryFeaturesAsync(queryParams) ' Cast the QueryResult to a List so the results can be interrogated Dim features = queryResult.ToList() If features.Any() Then ' Get the first feature returned in the Query result Dim feature As Feature = features(0) ' Add the returned feature to the collection of currently selected features _featureLayer.SelectFeature(feature) ' Zoom to the extent of the newly selected feature Await myMapView.SetViewpointGeometryAsync(feature.Geometry.Extent) Else MessageBox.Show("State Not Found!", "Add a valid state name.") End If Catch ex As Exception MessageBox.Show("Sample error", "An error occurred" & ex.ToString()) End Try End Function End Class End Namespace
Arc3D/arcgis-runtime-samples-dotnet
src/WPF/ArcGISRuntime.WPF.Samples/Samples/Data/FeatureLayerQuery/FeatureLayerQueryVB.xaml.vb
Visual Basic
apache-2.0
4,587
Imports Microsoft.SPOT Imports Microsoft.SPOT.Hardware Imports SecretLabs.NETMF.Hardware Imports SecretLabs.NETMF.Hardware.Netduino Imports Toolbox.NETMF.Hardware ' Copyright 2012-2014 Stefan Thoolen (http://www.netmftoolbox.com/) ' ' 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. Module Module1 Sub Main() ' The Adafruit LCD Shield uses a MCP23017 IC as multiplex chip Dim Mux As Mcp23017 = New Mcp23017(32, 100) ' Pins 0 to 4 on the Mux-chip are connected to the buttons Dim ButtonSelect As IGPIPort = Mux.Pins(0) Dim ButtonRight As IGPIPort = Mux.Pins(1) Dim ButtonDown As IGPIPort = Mux.Pins(2) Dim ButtonUp As IGPIPort = Mux.Pins(3) Dim ButtonLeft As IGPIPort = Mux.Pins(4) ' Enables pull-ups for all the buttons For i As Integer = 0 To 4 Mux.EnablePullup(i, True) Mux.Pins(i).InvertReadings = True Next ' Pins 6 to 8 on the Mux-chip are for the backlight Dim Red As IGPOPort = Mux.Pins(6) ' Red backlight Dim Green As IGPOPort = Mux.Pins(7) ' Green backlight Dim Blue As IGPOPort = Mux.Pins(8) ' Blue backlight ' Pins 9 to 15 are connected to the HD44780 LCD Dim Display As Hd44780Lcd = New Hd44780Lcd( Data:=Mux.CreateParallelOut(9, 4), ClockEnablePin:=Mux.Pins(13), ReadWritePin:=Mux.Pins(14), RegisterSelectPin:=Mux.Pins(15) ) ' Initializes the game Games.HD44780_Snake.Init(Display, ButtonSelect, ButtonLeft, ButtonRight, ButtonUp, ButtonDown) ' Turn on blue backlight Blue.Write(False) : Red.Write(True) : Green.Write(True) ' Display splash Games.HD44780_Snake.Splash() ' Wait 5 sec. Thread.Sleep(5000) ' Turn on green backlight Blue.Write(True) : Red.Write(True) : Green.Write(False) ' Starts the game Try Games.HD44780_Snake.Start() Catch ex As Exception Display.ClearDisplay() Display.Write(ex.Message) End Try ' Turn on red backlight Blue.Write(True) : Red.Write(False) : Green.Write(True) End Sub End Module
JakeLardinois/NetMF.Toolbox
Samples/Visual Basic/Hd44780LcdSnake/Module1.vb
Visual Basic
apache-2.0
2,738
Public Class AheuiStreamCollection Implements IAheuiStorageCollection(Of Stream) Public Sub Add(token As FinalNames) Implements ICollection(Of FinalNames).Add collection.Add(token, Stream.Null) End Sub Public Sub Add(ParamArray tokens As FinalNames()) Implements IAheuiStorageCollection(Of Stream).Add For Each token In tokens collection.Add(token, Stream.Null) Next End Sub Public Sub Clear() Implements ICollection(Of FinalNames).Clear collection.Clear() End Sub Public Function Contains(token As FinalNames) As Boolean Implements ICollection(Of FinalNames).Contains Return collection.Contains(token) End Function Public Sub CopyTo(array() As FinalNames, arrayIndex As Integer) Implements ICollection(Of FinalNames).CopyTo collection.Keys.CopyTo(array, arrayIndex) End Sub Public ReadOnly Property Count As Integer Implements ICollection(Of FinalNames).Count Get Return collection.Count End Get End Property Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of FinalNames).IsReadOnly Get Return collection.IsReadOnly End Get End Property Default Public ReadOnly Property Item(token As FinalNames) As Stream Implements IAheuiStorageCollection(Of Stream).Item Get Return collection.Item(token) End Get End Property Public Function Remove(token As FinalNames) As Boolean Implements ICollection(Of FinalNames).Remove If IsReadOnly Then Throw New NotSupportedException Try collection.Remove(token) Catch Return False End Try Return True End Function Public Function Remove(ParamArray tokens As FinalNames()) As Boolean Implements IAheuiStorageCollection(Of Stream).Remove If IsReadOnly Then Throw New NotSupportedException Try For Each token In tokens collection.Remove(token) Next Catch Return False End Try Return True End Function Public Shadows Iterator Function GetEnumerator() As IEnumerator(Of FinalNames) Implements IEnumerable(Of FinalNames).GetEnumerator For Each i In collection.Keys Yield i Next End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function Private collection As New Hashtable End Class
minacle/Minacle.Aheui
Minacle.Aheui/AheuiStreamCollection.vb
Visual Basic
bsd-2-clause
2,353
' 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.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class IteratorRewriter Inherits StateMachineRewriter(Of FieldSymbol) Private ReadOnly _elementType As TypeSymbol Private ReadOnly _isEnumerable As Boolean Private _currentField As FieldSymbol Private _initialThreadIdField As FieldSymbol Public Sub New(body As BoundStatement, method As MethodSymbol, isEnumerable As Boolean, stateMachineType As IteratorStateMachine, slotAllocatorOpt As VariableSlotAllocator, compilationState As TypeCompilationState, diagnostics As DiagnosticBag) MyBase.New(body, method, stateMachineType, slotAllocatorOpt, compilationState, diagnostics) Me._isEnumerable = isEnumerable Dim methodReturnType = method.ReturnType If methodReturnType.GetArity = 0 Then Me._elementType = method.ContainingAssembly.GetSpecialType(SpecialType.System_Object) Else ' the element type may contain method type parameters, which are now alpha-renamed into type parameters of the generated class Me._elementType = DirectCast(methodReturnType, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics().Single().InternalSubstituteTypeParameters(Me.TypeMap) End If End Sub ''' <summary> ''' Rewrite an iterator method into a state machine class. ''' </summary> Friend Overloads Shared Function Rewrite(body As BoundBlock, method As MethodSymbol, methodOrdinal As Integer, slotAllocatorOpt As VariableSlotAllocator, compilationState As TypeCompilationState, diagnostics As DiagnosticBag, <Out> ByRef stateMachineType As IteratorStateMachine) As BoundBlock If body.HasErrors Or Not method.IsIterator Then Return body End If Dim methodReturnType As TypeSymbol = method.ReturnType Dim retSpecialType = method.ReturnType.OriginalDefinition.SpecialType Dim isEnumerable As Boolean = retSpecialType = SpecialType.System_Collections_Generic_IEnumerable_T OrElse retSpecialType = SpecialType.System_Collections_IEnumerable Dim elementType As TypeSymbol If method.ReturnType.IsDefinition Then elementType = method.ContainingAssembly.GetSpecialType(SpecialType.System_Object) Else elementType = DirectCast(methodReturnType, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(0) End If stateMachineType = New IteratorStateMachine(slotAllocatorOpt, compilationState, method, methodOrdinal, elementType, isEnumerable) compilationState.ModuleBuilderOpt.CompilationState.SetStateMachineType(method, stateMachineType) Dim rewriter As New IteratorRewriter(body, method, isEnumerable, stateMachineType, slotAllocatorOpt, compilationState, diagnostics) ' check if we have all the types we need If rewriter.EnsureAllSymbolsAndSignature() Then Return body End If Return rewriter.Rewrite() End Function Friend Overrides Function EnsureAllSymbolsAndSignature() As Boolean Dim hasErrors As Boolean = MyBase.EnsureAllSymbolsAndSignature If Me.Method.IsSub OrElse Me._elementType.IsErrorType Then hasErrors = True End If ' NOTE: in current implementation these attributes must exist ' TODO: change to "don't use if not found" EnsureWellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, hasErrors) EnsureWellKnownMember(Of MethodSymbol)(WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor, hasErrors) ' NOTE: We don't ensure DebuggerStepThroughAttribute, it is just not emitted if not found ' EnsureWellKnownMember(Of MethodSymbol)(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor, hasErrors) ' TODO: do we need these here? They are used on the actual iterator method. ' EnsureWellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachine__ctor, hasErrors) EnsureSpecialType(SpecialType.System_Object, hasErrors) EnsureSpecialType(SpecialType.System_Boolean, hasErrors) EnsureSpecialType(SpecialType.System_Int32, hasErrors) If Me.Method.ReturnType.IsDefinition Then If Me._isEnumerable Then EnsureSpecialType(SpecialType.System_Collections_IEnumerator, hasErrors) End If Else If Me._isEnumerable Then EnsureSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T, hasErrors) EnsureSpecialType(SpecialType.System_Collections_IEnumerable, hasErrors) End If EnsureSpecialType(SpecialType.System_Collections_IEnumerator, hasErrors) End If EnsureSpecialType(SpecialType.System_IDisposable, hasErrors) Return hasErrors End Function Protected Overrides Sub GenerateControlFields() ' Add a field: int _state Me.StateField = Me.F.StateMachineField(Me.F.SpecialType(SpecialType.System_Int32), Me.Method, GeneratedNames.MakeStateMachineStateFieldName(), Accessibility.Public) ' Add a field: T current _currentField = F.StateMachineField(_elementType, Me.Method, GeneratedNames.MakeIteratorCurrentFieldName(), Accessibility.Public) ' if it is an Enumerable, add a field: initialThreadId As Integer _initialThreadIdField = If(_isEnumerable, F.StateMachineField(F.SpecialType(SpecialType.System_Int32), Me.Method, GeneratedNames.MakeIteratorInitialThreadIdName(), Accessibility.Public), Nothing) End Sub Protected Overrides Sub GenerateMethodImplementations() Dim managedThreadId As BoundExpression = Nothing ' Thread.CurrentThread.ManagedThreadId ' Add bool IEnumerator.MoveNext() and void IDisposable.Dispose() Dim disposeMethod = Me.OpenMethodImplementation(SpecialMember.System_IDisposable__Dispose, "Dispose", DebugAttributes.DebuggerNonUserCodeAttribute, Accessibility.Private, generateDebugInfo:=False, hasMethodBodyDependency:=True) Dim debuggerHidden = IsDebuggerHidden(Me.Method) Dim moveNextAttrs As DebugAttributes = DebugAttributes.CompilerGeneratedAttribute If debuggerHidden Then moveNextAttrs = moveNextAttrs Or DebugAttributes.DebuggerHiddenAttribute Dim moveNextMethod = Me.OpenMethodImplementation(SpecialMember.System_Collections_IEnumerator__MoveNext, "MoveNext", moveNextAttrs, Accessibility.Private, generateDebugInfo:=True, hasMethodBodyDependency:=True) GenerateMoveNextAndDispose(moveNextMethod, disposeMethod) F.CurrentMethod = moveNextMethod If _isEnumerable Then ' generate the code for GetEnumerator() ' IEnumerable<elementType> result; ' if (this.initialThreadId == Thread.CurrentThread.ManagedThreadId && this.state == -2) ' { ' this.state = 0; ' result = this; ' } ' else ' { ' result = new Ints0_Impl(0); ' } ' result.parameter = this.parameterProxy; ' copy all of the parameter proxies ' Add IEnumerator<int> IEnumerable<int>.GetEnumerator() Dim getEnumeratorGeneric = Me.OpenMethodImplementation(F.SpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).Construct(_elementType), SpecialMember.System_Collections_Generic_IEnumerable_T__GetEnumerator, "GetEnumerator", DebugAttributes.DebuggerNonUserCodeAttribute, Accessibility.Private, generateDebugInfo:=False, hasMethodBodyDependency:=False) Dim bodyBuilder = ArrayBuilder(Of BoundStatement).GetInstance() Dim resultVariable = F.SynthesizedLocal(StateMachineType) ' iteratorClass result; Dim currentManagedThreadIdMethod As MethodSymbol = Nothing Dim currentManagedThreadIdProperty As PropertySymbol = F.WellKnownMember(Of PropertySymbol)(WellKnownMember.System_Environment__CurrentManagedThreadId, isOptional:=True) If (currentManagedThreadIdProperty IsNot Nothing) Then currentManagedThreadIdMethod = currentManagedThreadIdProperty.GetMethod() End If If (currentManagedThreadIdMethod IsNot Nothing) Then managedThreadId = F.Call(Nothing, currentManagedThreadIdMethod) Else managedThreadId = F.Property(F.Property(WellKnownMember.System_Threading_Thread__CurrentThread), WellKnownMember.System_Threading_Thread__ManagedThreadId) End If ' if (this.state == -2 && this.initialThreadId == Thread.CurrentThread.ManagedThreadId) ' this.state = 0; ' result = this; ' goto thisInitialized ' else ' result = new IteratorClass(0) ' ' initialize [Me] if needed ' thisInitialized: ' ' initialize other fields Dim thisInitialized = F.GenerateLabel("thisInitialized") bodyBuilder.Add( F.If( condition:= F.LogicalAndAlso( F.IntEqual(F.Field(F.Me, StateField, False), F.Literal(StateMachineStates.FinishedStateMachine)), F.IntEqual(F.Field(F.Me, _initialThreadIdField, False), managedThreadId)), thenClause:= F.Block( F.Assignment(F.Field(F.Me, StateField, True), F.Literal(StateMachineStates.FirstUnusedState)), F.Assignment(F.Local(resultVariable, True), F.Me), If(Method.IsShared OrElse Method.MeParameter.Type.IsReferenceType, F.Goto(thisInitialized), DirectCast(F.Block(), BoundStatement)) ), elseClause:= F.Assignment(F.Local(resultVariable, True), F.[New](StateMachineType.Constructor, F.Literal(0))) )) ' Initialize all the parameter copies Dim copySrc = InitialParameters Dim copyDest = nonReusableLocalProxies If Not Method.IsShared Then ' starting with "this" Dim proxy As FieldSymbol = Nothing If (copyDest.TryGetValue(Method.MeParameter, proxy)) Then bodyBuilder.Add( F.Assignment( F.Field(F.Local(resultVariable, True), proxy.AsMember(StateMachineType), True), F.Field(F.Me, copySrc(Method.MeParameter).AsMember(F.CurrentType), False))) End If End If bodyBuilder.Add(F.Label(thisInitialized)) For Each parameter In Method.Parameters Dim proxy As FieldSymbol = Nothing If (copyDest.TryGetValue(parameter, proxy)) Then bodyBuilder.Add( F.Assignment( F.Field(F.Local(resultVariable, True), proxy.AsMember(StateMachineType), True), F.Field(F.Me, copySrc(parameter).AsMember(F.CurrentType), False))) End If Next bodyBuilder.Add(F.Return(F.Local(resultVariable, False))) F.CloseMethod(F.Block(ImmutableArray.Create(resultVariable), bodyBuilder.ToImmutableAndFree())) ' Generate IEnumerable.GetEnumerator ' NOTE: this is a private implementing method. Its name is irrelevant ' but must be different from another GetEnumerator. Dev11 uses GetEnumerator0 here. ' IEnumerable.GetEnumerator seems better - ' it is clear why we have the property, and "Current" suffix will be shared in metadata with another Current. ' It is also consistent with the naming of IEnumerable.Current (see below). Me.OpenMethodImplementation(SpecialMember.System_Collections_IEnumerable__GetEnumerator, "IEnumerable.GetEnumerator", DebugAttributes.DebuggerNonUserCodeAttribute, Accessibility.Private, generateDebugInfo:=False, hasMethodBodyDependency:=False) F.CloseMethod(F.Return(F.Call(F.Me, getEnumeratorGeneric))) End If ' Add T IEnumerator<T>.Current Me.OpenPropertyImplementation(F.SpecialType(SpecialType.System_Collections_Generic_IEnumerator_T).Construct(_elementType), SpecialMember.System_Collections_Generic_IEnumerator_T__Current, "Current", DebugAttributes.DebuggerNonUserCodeAttribute, Accessibility.Private, False) F.CloseMethod(F.Return(F.Field(F.Me, _currentField, False))) ' Add void IEnumerator.Reset() Me.OpenMethodImplementation(SpecialMember.System_Collections_IEnumerator__Reset, "Reset", DebugAttributes.DebuggerNonUserCodeAttribute, Accessibility.Private, generateDebugInfo:=False, hasMethodBodyDependency:=False) F.CloseMethod(F.Throw(F.[New](F.WellKnownType(WellKnownType.System_NotSupportedException)))) ' Add object IEnumerator.Current ' NOTE: this is a private implementing property. Its name is irrelevant ' but must be different from another Current. ' Dev11 uses fully qualified and substituted name here (System.Collections.Generic.IEnumerator(Of Object).Current), ' It may be an overkill and may lead to metadata bloat. ' IEnumerable.Current seems better - ' it is clear why we have the property, and "Current" suffix will be shared in metadata with another Current. Me.OpenPropertyImplementation(SpecialMember.System_Collections_IEnumerator__Current, "IEnumerator.Current", DebugAttributes.DebuggerNonUserCodeAttribute, Accessibility.Private, False) F.CloseMethod(F.Return(F.Field(F.Me, _currentField, False))) ' Add a body for the constructor If True Then F.CurrentMethod = StateMachineType.Constructor Dim bodyBuilder = ArrayBuilder(Of BoundStatement).GetInstance() bodyBuilder.Add(F.BaseInitialization()) bodyBuilder.Add(F.Assignment(F.Field(F.Me, StateField, True), F.Parameter(F.CurrentMethod.Parameters(0)).MakeRValue)) ' this.state = state If _isEnumerable Then ' this.initialThreadId = Thread.CurrentThread.ManagedThreadId; bodyBuilder.Add(F.Assignment(F.Field(F.Me, _initialThreadIdField, True), managedThreadId)) End If bodyBuilder.Add(F.Return()) F.CloseMethod(F.Block(bodyBuilder.ToImmutableAndFree())) bodyBuilder = Nothing End If End Sub Protected Overrides Function GenerateStateMachineCreation(stateMachineVariable As LocalSymbol, frameType As NamedTypeSymbol) As BoundStatement Return F.Return(F.Local(stateMachineVariable, False)) End Function Protected Overrides Sub InitializeStateMachine(bodyBuilder As ArrayBuilder(Of BoundStatement), frameType As NamedTypeSymbol, stateMachineLocal As LocalSymbol) ' Dim stateMachineLocal As new IteratorImplementationClass(N) ' where N is either 0 (if we're producing an enumerator) or -2 (if we're producing an enumerable) Dim initialState = If(_isEnumerable, StateMachineStates.FinishedStateMachine, StateMachineStates.FirstUnusedState) bodyBuilder.Add( F.Assignment( F.Local(stateMachineLocal, True), F.[New](StateMachineType.Constructor.AsMember(frameType), F.Literal(initialState)))) End Sub Protected Overrides ReadOnly Property PreserveInitialParameterValues As Boolean Get Return Me._isEnumerable End Get End Property Friend Overrides ReadOnly Property TypeMap As TypeSubstitution Get Return StateMachineType.TypeSubstitution End Get End Property Private Sub GenerateMoveNextAndDispose(moveNextMethod As SynthesizedStateMachineMethod, disposeMethod As SynthesizedStateMachineMethod) Dim rewriter = New IteratorMethodToClassRewriter(method:=Me.Method, F:=Me.F, state:=Me.StateField, current:=Me._currentField, HoistedVariables:=Me.hoistedVariables, localProxies:=Me.nonReusableLocalProxies, SynthesizedLocalOrdinals:=Me.SynthesizedLocalOrdinals, slotAllocatorOpt:=Me.SlotAllocatorOpt, nextFreeHoistedLocalSlot:=Me.nextFreeHoistedLocalSlot, diagnostics:=Diagnostics) rewriter.GenerateMoveNextAndDispose(Body, moveNextMethod, disposeMethod) End Sub Protected Overrides Function CreateByValLocalCapture(field As FieldSymbol, local As LocalSymbol) As FieldSymbol Return field End Function Protected Overrides Function CreateParameterCapture(field As FieldSymbol, parameter As ParameterSymbol) As FieldSymbol Return field End Function Protected Overrides Sub InitializeParameterWithProxy(parameter As ParameterSymbol, proxy As FieldSymbol, stateMachineVariable As LocalSymbol, initializers As ArrayBuilder(Of BoundExpression)) Debug.Assert(proxy IsNot Nothing) Dim frameType As NamedTypeSymbol = If(Me.Method.IsGenericMethod, Me.StateMachineType.Construct(Me.Method.TypeArguments), Me.StateMachineType) Dim expression As BoundExpression = If(parameter.IsMe, DirectCast(Me.F.Me, BoundExpression), Me.F.Parameter(parameter).MakeRValue()) initializers.Add( Me.F.AssignmentExpression( Me.F.Field( Me.F.Local(stateMachineVariable, True), proxy.AsMember(frameType), True), expression)) End Sub End Class End Namespace
akoeplinger/roslyn
src/Compilers/VisualBasic/Portable/Lowering/IteratorRewriter/IteratorRewriter.vb
Visual Basic
apache-2.0
22,127
' 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.ExceptionServices Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ObjectBrowser.Mocks Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ObjectBrowser <[UseExportProvider]> Public MustInherit Class AbstractObjectBrowserTests Protected MustOverride ReadOnly Property LanguageName As String Protected Function GetWorkspaceDefinition(code As XElement) As XElement Return <Workspace> <Project Language=<%= LanguageName %> CommonReferences="true"> <Document><%= code.Value.Trim() %></Document> </Project> </Workspace> End Function Protected Function GetWorkspaceDefinition(code As XElement, metaDataCode As XElement, commonReferences As Boolean) As XElement Return <Workspace> <Project Language=<%= LanguageName %> CommonReferences=<%= commonReferences %>> <Document><%= code.Value.Trim() %></Document> <MetadataReferenceFromSource Language=<%= LanguageName %> CommonReferences="true"> <Document><%= metaDataCode.Value.Trim() %></Document> </MetadataReferenceFromSource> </Project> </Workspace> End Function <HandleProcessCorruptedStateExceptions()> Friend Function CreateLibraryManager(definition As XElement) As TestState Dim workspace = TestWorkspace.Create(definition, exportProvider:=VisualStudioTestExportProvider.Factory.CreateExportProvider()) Dim result As TestState = Nothing Try Dim mockComponentModel = New MockComponentModel(workspace.ExportProvider) mockComponentModel.ProvideService(Of VisualStudioWorkspace)(New MockVisualStudioWorkspace(workspace)) Dim mockServiceProvider = New MockServiceProvider(mockComponentModel) Dim libraryManager = CreateLibraryManager(mockServiceProvider) result = New TestState(workspace, libraryManager) Finally If result Is Nothing Then workspace.Dispose() End If End Try Return result End Function Friend MustOverride Function CreateLibraryManager(serviceProvider As IServiceProvider) As AbstractObjectBrowserLibraryManager Friend Function ProjectNode(name As String) As NavInfoNodeDescriptor Return New NavInfoNodeDescriptor With {.Kind = ObjectListKind.Projects, .Name = name} End Function Friend Function NamespaceNode(name As String) As NavInfoNodeDescriptor Return New NavInfoNodeDescriptor With {.Kind = ObjectListKind.Namespaces, .Name = name} End Function Friend Function TypeNode(name As String) As NavInfoNodeDescriptor Return New NavInfoNodeDescriptor With {.Kind = ObjectListKind.Types, .Name = name} End Function End Class End Namespace
OmarTawfik/roslyn
src/VisualStudio/Core/Test/ObjectBrowser/AbstractObjectBrowserTests.vb
Visual Basic
apache-2.0
3,514
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics ' Unit tests for local type inference Public Class VariableTypeInference Inherits BasicTestBase #Region "InferenceErrors" <Fact> Public Sub TestSelfInferenceCycleError() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Imports System Module Program Sub Main(args As String()) dim i = i End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> BC30980: Type of 'i' cannot be inferred from an expression containing 'i'. dim i = i ~ BC42104: Variable 'i' is used before it has been assigned a value. A null reference exception could result at runtime. dim i = i ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TestMultiVariableInferenceCycleError() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Imports System Module Program Sub Main(args As String()) dim i = j dim j = i End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> BC32000: Local variable 'j' cannot be referred to before it is declared. dim i = j ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TestArrayInferenceRankError() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Imports System Module Program Sub Main(args As String()) dim i(,) = new integer() {} End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> BC36909: Cannot infer a data type for 'i' because the array dimensions do not match. dim i(,) = new integer() {} ~~~~ BC30414: Value of type 'Integer()' cannot be converted to 'Object(*,*)' because the array types have different numbers of dimensions. dim i(,) = new integer() {} ~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TestArrayInferenceNonNullableElementError() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Imports System Module Program Sub Main(args As String()) dim i?() = new integer() {} End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> BC36628: A nullable type cannot be inferred for variable 'i'. dim i?() = new integer() {} ~ BC30333: Value of type 'Integer()' cannot be converted to 'Object()' because 'Integer' is not a reference type. dim i?() = new integer() {} ~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TestNullableIdentifierWithArrayExpression() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Imports System Module Program Sub Main(args As String()) Dim x? = New Integer() {} End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> BC36628: A nullable type cannot be inferred for variable 'x'. Dim x? = New Integer() {} ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TestArrayIdentifierWithScalarExpression() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Imports System Module Program Sub Main(args As String()) Dim x() = 1 End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> BC36536: Variable cannot be initialized with non-array type 'Integer'. Dim x() = 1 ~ BC30311: Value of type 'Integer' cannot be converted to 'Object()'. Dim x() = 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TestNullableIdentifierWithScalarReferenceType() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Imports System Module Program Sub Main(args As String()) Dim x? = "hello" End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> BC36628: A nullable type cannot be inferred for variable 'x'. Dim x? = "hello" ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub #End Region <Fact> Public Sub TestInferOffPrimitiveTypes() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOff.vb"> Option Infer Off Module m2 Sub Main() 'Test:a dim a = 1 'Test:b dim b = "a" 'Test:c dim c = 1.0 End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> </errors> Dim tree = CompilationUtils.GetTree(compilation, "inferOff.vb") Dim model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Object") CheckVariableType(tree, model, "Test:b", "System.Object") CheckVariableType(tree, model, "Test:c", "System.Object") CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TestInferOnPrimitiveTypes() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Module m1 Sub Main() 'Test:a dim a = 1 'Test:b dim b = "a" 'Test:c dim c = 1.0 End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> </errors> Dim tree = CompilationUtils.GetTree(compilation, "inferOn.vb") Dim model = compilation.GetSemanticModel(tree) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.String") CheckVariableType(tree, model, "Test:c", "System.Double") End Sub <Fact> Public Sub TestDontInferStaticLocal() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Module m1 Sub Main() 'Test:a static a = 1 ' a is object not integer because static locals do not infer a type. End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> </errors> Dim tree = CompilationUtils.GetTree(compilation, "inferOn.vb") Dim model = compilation.GetSemanticModel(tree) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) CheckVariableType(tree, model, "Test:a", "System.Object") End Sub <Fact> Public Sub TestInferNullableArrayOfInteger() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Module m1 Sub Main() 'Test:t Dim t?() = New Integer?() {} End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> </errors> Dim tree = CompilationUtils.GetTree(compilation, "inferOn.vb") Dim model = compilation.GetSemanticModel(tree) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) CheckVariableType(tree, model, "Test:t", "System.Nullable(Of System.Int32)()") End Sub <Fact> Public Sub TestArrayInference() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Module m1 Sub Main() 'Test:t Dim t() = New Integer() {} 'Test:u Dim u() = new Integer()() {} 'Test:v Dim v() = new Integer()()() {} End Sub End Module </file> </compilation>, options) Dim expectedErrors = <errors> </errors> Dim tree = CompilationUtils.GetTree(compilation, "inferOn.vb") Dim model = compilation.GetSemanticModel(tree) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) CheckVariableType(tree, model, "Test:t", "System.Int32()") CheckVariableType(tree, model, "Test:u", "System.Int32()()") CheckVariableType(tree, model, "Test:v", "System.Int32()()()") End Sub <WorkItem(542371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542371")> <Fact> Public Sub TestOptionInferWithOptionStrict() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Module m1 Sub m1() Dim t = New Integer() Dim u = 1 Dim x$ = "test" Dim v() = new Integer()()() {} End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.On)) compilation.VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(False).WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim t = New Integer() ~ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim u = 1 ~ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim v() = new Integer()()() {} ~ </errors>) compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(False).WithOptionStrict(OptionStrict.Off)) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> </errors>) End Sub <Fact> Public Sub TestErrorsForLocalsWithoutAsClause() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="TestInferredTypes.vb"> Module m1 Sub m1() 'Test:a const a = 1 'Test:b dim b = 1 b = a End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.On)) compilation.VerifyDiagnostics() Dim tree = CompilationUtils.GetTree(compilation, "TestInferredTypes.vb") Dim model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Int32") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.Off)) compilation.VerifyDiagnostics() model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Int32") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(False).WithOptionStrict(OptionStrict.On)) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StrictDisallowImplicitObject, "a"), Diagnostic(ERRID.ERR_StrictDisallowImplicitObject, "b")) model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(False).WithOptionStrict(OptionStrict.Off)) compilation.VerifyDiagnostics() model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.Custom)) compilation.VerifyDiagnostics() model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Int32") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(False).WithOptionStrict(OptionStrict.Custom)) compilation.VerifyDiagnostics( Diagnostic(ERRID.WRN_ObjectAssumedVar1, "a").WithArguments("Variable declaration without an 'As' clause; type of Object assumed."), Diagnostic(ERRID.WRN_ObjectAssumedVar1, "b").WithArguments("Variable declaration without an 'As' clause; type of Object assumed.")) model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestErrorsForLocalsWithoutAsClauseStaticLocals() 'Static Locals do not type infer Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="TestInferredTypes.vb"> Module m1 Sub m1() 'Test:a const a = 1 'Test:b Static b = 1 b = a End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.On)) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StrictDisallowImplicitObject, "b")) Dim tree = CompilationUtils.GetTree(compilation, "TestInferredTypes.vb") Dim model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.Off)) compilation.VerifyDiagnostics() model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(False).WithOptionStrict(OptionStrict.On)) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StrictDisallowImplicitObject, "a"), Diagnostic(ERRID.ERR_StrictDisallowImplicitObject, "b")) model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(False).WithOptionStrict(OptionStrict.Off)) compilation.VerifyDiagnostics() model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.Custom)) compilation.VerifyDiagnostics(Diagnostic(ERRID.WRN_ObjectAssumedVar1, "b").WithArguments("Static variable declared without an 'As' clause; type of Object assumed.")) model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOptionInfer(False).WithOptionStrict(OptionStrict.Custom)) compilation.VerifyDiagnostics( Diagnostic(ERRID.WRN_ObjectAssumedVar1, "a").WithArguments("Variable declaration without an 'As' clause; type of Object assumed."), Diagnostic(ERRID.WRN_ObjectAssumedVar1, "b").WithArguments("Static variable declared without an 'As' clause; type of Object assumed.")) model = compilation.GetSemanticModel(tree) CheckVariableType(tree, model, "Test:a", "System.Int32") CheckVariableType(tree, model, "Test:b", "System.Object") End Sub <WorkItem(542402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542402")> <Fact> Public Sub TestCircularDeclarationReference() Dim options = TestOptions.ReleaseDll.WithRootNamespace("Goo.Bar") Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="inferOn.vb"> Option Infer On Option Explicit Off Option Strict Off Class TestClass Sub New(ByVal x As TestClass) End Sub Shared Function GetSomething(ByVal x As TestClass) As TestClass Return Nothing End Function End Class Friend Module TypeInfCircularTest Sub TypeInfCircular() Dim x = y.GetSomething(x), y = New TestClass(x) End Sub End Module </file> </compilation>) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "y").WithArguments("y"), Diagnostic(ERRID.ERR_CircularInference1, "x").WithArguments("x"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "x").WithArguments("x")) End Sub <WorkItem(545427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545427")> <Fact()> Public Sub TestNothingConversionLocalConst1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation name="TestSByteLocalConst"> <file name="a.vb"> Class C End Class Module Module1 Sub Main() Const bar1 = DirectCast(Nothing, Integer()) Const bar2 = TryCast(Nothing, String()) Const bar3 = CType(Nothing, C()) End Sub End Module </file> </compilation>) compilation.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocalConst, "bar1").WithArguments("bar1"), Diagnostic(ERRID.WRN_UnusedLocalConst, "bar2").WithArguments("bar2"), Diagnostic(ERRID.WRN_UnusedLocalConst, "bar3").WithArguments("bar3") ) End Sub <WorkItem(545427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545427")> <Fact()> Public Sub TestNothingConversionLocalConst2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation name="TestSByteLocalConst"> <file name="a.vb"> Class C End Class Module Module1 Sub Main() Const bar1 = DirectCast(Nothing, Integer) Const bar2 = DirectCast(Nothing, Object) Const bar3 = DirectCast(Nothing, String) Const bar4 = DirectCast(Nothing, Decimal) Const bar5 = DirectCast(Nothing, Date) const bar6 as string End Sub End Module </file> </compilation>) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_ConstantWithNoValue, "bar6"), Diagnostic(ERRID.WRN_UnusedLocalConst, "bar1").WithArguments("bar1"), Diagnostic(ERRID.WRN_UnusedLocalConst, "bar2").WithArguments("bar2"), Diagnostic(ERRID.WRN_UnusedLocalConst, "bar3").WithArguments("bar3"), Diagnostic(ERRID.WRN_UnusedLocalConst, "bar4").WithArguments("bar4"), Diagnostic(ERRID.WRN_UnusedLocalConst, "bar5").WithArguments("bar5")) End Sub <WorkItem(545763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545763")> <Fact()> Public Sub TestInferNullableType() Dim source = <compilation name="TestSByteLocalConst"> <file name="a.vb"> Imports System Structure S1 Dim x As Integer End Structure Module Module1 Public Sub Main() Dim y? = New S1?(New S1) Console.WriteLine(y.GetType()) End Sub End Module </file> </compilation> CompileAndVerify(source, options:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), expectedOutput:=<![CDATA[ S1 ]]>) End Sub Private Sub CheckVariableType(tree As SyntaxTree, model As SemanticModel, textToFind As String, typeName As String) Dim node = CompilationUtils.FindTokenFromText(tree, textToFind).Parent Dim varName = textToFind.Substring(textToFind.IndexOf(":"c) + 1) Dim vardecl = node.DescendantNodes().OfType(Of ModifiedIdentifierSyntax)().First() Dim varSymbol = model.GetDeclaredSymbol(vardecl) Assert.NotNull(varSymbol) Assert.Equal(varName, varSymbol.Name) Assert.Equal(SymbolKind.Local, varSymbol.Kind) Assert.Equal(typeName, DirectCast(varSymbol, LocalSymbol).Type.ToTestDisplayString()) End Sub End Class End Namespace
jkotas/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/VariableTypeInference.vb
Visual Basic
apache-2.0
25,778
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Collections Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a .NET assembly. An assembly consists of one or more modules. ''' </summary> Friend MustInherit Class AssemblySymbol Inherits Symbol Implements IAssemblySymbol ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version of Symbol. ' Do not make any changes to the public interface without making the corresponding change ' to the C# version. ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' The system assembly, which provides primitive types like Object, String, etc., e.g. mscorlib.dll. ''' The value is provided by ReferenceManager and must not be modified. For SourceAssemblySymbol, non-missing ''' coreLibrary must match one of the referenced assemblies returned by GetReferencedAssemblySymbols() method of ''' the main module. If there is no existing assembly that can be used as a source for the primitive types, ''' the value is a Compilation.MissingCorLibrary. ''' </summary> Private _corLibrary As AssemblySymbol ''' <summary> ''' The system assembly, which provides primitive types like Object, String, etc., e.g. mscorlib.dll. ''' The value is a MissingAssemblySymbol if none of the referenced assemblies can be used as a source for the ''' primitive types and the owning assembly cannot be used as the source too. Otherwise, it is one of ''' the referenced assemblies returned by GetReferencedAssemblySymbols() method or the owning assembly. ''' </summary> Friend ReadOnly Property CorLibrary As AssemblySymbol Get Return _corLibrary End Get End Property ''' <summary> ''' A helper method for ReferenceManager to set the system assembly, which provides primitive ''' types like Object, String, etc., e.g. mscorlib.dll. ''' </summary> ''' <param name="corLibrary"></param> Friend Sub SetCorLibrary(corLibrary As AssemblySymbol) Debug.Assert(_corLibrary Is Nothing) _corLibrary = corLibrary End Sub ''' <summary> ''' Simple name of the assembly. ''' </summary> ''' <remarks> ''' This is equivalent to <see cref="Identity"/>.<see cref="AssemblyIdentity.Name"/>, but may be ''' much faster to retrieve for source code assemblies, since it does not require binding the assembly-level ''' attributes that contain the version number and other assembly information. ''' </remarks> Public Overrides ReadOnly Property Name As String Get Return Identity.Name End Get End Property ''' <summary> ''' True if the assembly contains interactive code. ''' </summary> Public Overridable ReadOnly Property IsInteractive As Boolean Implements IAssemblySymbol.IsInteractive Get Return False End Get End Property ''' <summary> ''' Get the name of this assembly. ''' </summary> Public MustOverride ReadOnly Property Identity As AssemblyIdentity Implements IAssemblySymbol.Identity ''' <summary> ''' Target architecture of the machine. ''' </summary> Friend ReadOnly Property Machine As System.Reflection.PortableExecutable.Machine Get Return Modules(0).Machine End Get End Property ''' <summary> ''' Indicates that this PE file makes Win32 calls. See CorPEKind.pe32BitRequired for more information (http://msdn.microsoft.com/en-us/library/ms230275.aspx). ''' </summary> Friend ReadOnly Property Bit32Required As Boolean Get Return Modules(0).Bit32Required End Get End Property ''' <summary> ''' Gets a read-only list of all the modules in this assembly. (There must be at least one.) The first one is the main module ''' that holds the assembly manifest. ''' </summary> Public MustOverride ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol) ''' <summary> ''' Gets the merged root namespace that contains all namespaces and types defined in the modules ''' of this assembly. If there is just one module in this assembly, this property just returns the ''' GlobalNamespace of that module. ''' </summary> Public MustOverride ReadOnly Property GlobalNamespace As NamespaceSymbol ''' <summary> ''' Given a namespace symbol, returns the corresponding assembly specific namespace symbol ''' </summary> Friend Function GetAssemblyNamespace(namespaceSymbol As NamespaceSymbol) As NamespaceSymbol If namespaceSymbol.IsGlobalNamespace Then Return Me.GlobalNamespace End If Dim container As NamespaceSymbol = namespaceSymbol.ContainingNamespace If container Is Nothing Then Return Me.GlobalNamespace End If If namespaceSymbol.Extent.Kind = NamespaceKind.Assembly AndAlso namespaceSymbol.ContainingAssembly = Me Then Return namespaceSymbol End If Dim assemblyContainer As NamespaceSymbol = GetAssemblyNamespace(container) If assemblyContainer Is container Then ' Trivial case, container isn't merged. Return namespaceSymbol End If If assemblyContainer Is Nothing Then Return Nothing End If Return assemblyContainer.GetNestedNamespace(namespaceSymbol.Name) End Function Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Assembly End Get End Property Public NotOverridable Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return Nothing End Get End Property Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitAssembly(Me, arg) End Function Friend Sub New() ' Only the compiler can create AssemblySymbols. End Sub ''' <summary> ''' Does this symbol represent a missing assembly. ''' </summary> Friend MustOverride ReadOnly Property IsMissing As Boolean Public NotOverridable Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Nothing End Get End Property ''' <summary> ''' Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. ''' This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. ''' </summary> Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property ''' <summary> ''' Lookup a top level type referenced from metadata, names should be ''' compared case-sensitively. ''' </summary> ''' <param name="emittedName"> ''' Full type name with generic name mangling. ''' </param> ''' <param name="digThroughForwardedTypes"> ''' Take forwarded types into account. ''' </param> ''' <remarks></remarks> Friend Function LookupTopLevelMetadataType(ByRef emittedName As MetadataTypeName, digThroughForwardedTypes As Boolean) As NamedTypeSymbol Return LookupTopLevelMetadataTypeWithCycleDetection(emittedName, visitedAssemblies:=Nothing, digThroughForwardedTypes:=digThroughForwardedTypes) End Function ''' <summary> ''' Lookup a top level type referenced from metadata, names should be ''' compared case-sensitively. Detect cycles during lookup. ''' </summary> ''' <param name="emittedName"> ''' Full type name, possibly with generic name mangling. ''' </param> ''' <param name="visitedAssemblies"> ''' List of assemblies lookup has already visited (since type forwarding can introduce cycles). ''' </param> ''' <param name="digThroughForwardedTypes"> ''' Take forwarded types into account. ''' </param> Friend MustOverride Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol ''' <summary> ''' Returns the type symbol for a forwarded type based its canonical CLR metadata name. ''' The name should refer to a non-nested type. If type with this name Is Not forwarded, ''' null Is returned. ''' </summary> Public Function ResolveForwardedType(fullyQualifiedMetadataName As String) As NamedTypeSymbol If fullyQualifiedMetadataName Is Nothing Then Throw New ArgumentNullException(NameOf(fullyQualifiedMetadataName)) End If Dim emittedName = MetadataTypeName.FromFullName(fullyQualifiedMetadataName) Return TryLookupForwardedMetadataType(emittedName, ignoreCase:=False) End Function ''' <summary> ''' Look up the given metadata type, if it Is forwarded. ''' </summary> Friend Function TryLookupForwardedMetadataType(ByRef emittedName As MetadataTypeName, ignoreCase As Boolean) As NamedTypeSymbol Return TryLookupForwardedMetadataTypeWithCycleDetection(emittedName, visitedAssemblies:=Nothing, ignoreCase:=ignoreCase) End Function ''' <summary> ''' Look up the given metadata type, if it is forwarded. ''' </summary> Friend Overridable Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol Return Nothing End Function Friend Function CreateCycleInTypeForwarderErrorTypeSymbol(ByRef emittedName As MetadataTypeName) As ErrorTypeSymbol Dim diagInfo As DiagnosticInfo = New DiagnosticInfo(MessageProvider.Instance, ERRID.ERR_TypeFwdCycle2, emittedName.FullName, Me) Return New MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo(Me.Modules(0), emittedName, diagInfo) End Function ''' <summary> ''' Lookup declaration for predefined CorLib type in this Assembly. Only valid if this ''' assembly is the Cor Library ''' </summary> ''' <param name="type"></param> ''' <returns></returns> ''' <remarks></remarks> Friend MustOverride Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol ''' <summary> ''' Register declaration of predefined CorLib type in this Assembly. ''' </summary> ''' <param name="corType"></param> Friend Overridable Sub RegisterDeclaredSpecialType(corType As NamedTypeSymbol) Throw ExceptionUtilities.Unreachable End Sub ''' <summary> ''' Continue looking for declaration of predefined CorLib type in this Assembly ''' while symbols for new type declarations are constructed. ''' </summary> Friend Overridable ReadOnly Property KeepLookingForDeclaredSpecialTypes As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property ''' <summary> ''' Return an array of assemblies involved in canonical type resolution of ''' NoPia local types defined within this assembly. In other words, all ''' references used by previous compilation referencing this assembly. ''' </summary> ''' <returns></returns> Friend MustOverride Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol) Friend MustOverride Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol)) ''' <summary> ''' Return an array of assemblies referenced by this assembly, which are linked (/l-ed) by ''' each compilation that is using this AssemblySymbol as a reference. ''' If this AssemblySymbol is linked too, it will be in this array too. ''' </summary> Friend MustOverride Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol) Friend MustOverride Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol)) ''' <summary> ''' Assembly is /l-ed by compilation that is using it as a reference. ''' </summary> Friend MustOverride ReadOnly Property IsLinked As Boolean ''' <summary> ''' Returns true and a string from the first GuidAttribute on the assembly, ''' the string might be null or an invalid guid representation. False, ''' if there is no GuidAttribute with string argument. ''' </summary> Friend Overridable Function GetGuidString(ByRef guidString As String) As Boolean Return GetGuidStringDefaultImplementation(guidString) End Function Public MustOverride ReadOnly Property TypeNames As ICollection(Of String) Implements IAssemblySymbol.TypeNames Public MustOverride ReadOnly Property NamespaceNames As ICollection(Of String) Implements IAssemblySymbol.NamespaceNames ''' <summary> ''' An empty list means there was no IVT attribute with matching <paramref name="simpleName"/>. ''' An IVT attribute without a public key setting is represented by an entry that is empty in the returned list ''' </summary> ''' <param name="simpleName"></param> ''' <returns></returns> ''' <remarks></remarks> Friend MustOverride Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte)) Friend MustOverride Function AreInternalsVisibleToThisAssembly(other As AssemblySymbol) As Boolean ''' <summary> ''' Get symbol for predefined type from Cor Library used by this assembly. ''' </summary> ''' <param name="type"></param> ''' <returns>The symbol for the pre-defined type or Nothing if the type is not defined in the core library</returns> ''' <remarks></remarks> Friend Function GetSpecialType(type As SpecialType) As NamedTypeSymbol If type <= SpecialType.None OrElse type > SpecialType.Count Then Throw New ArgumentOutOfRangeException() End If Return CorLibrary.GetDeclaredSpecialType(type) End Function ''' <summary> ''' The NamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of ''' Error if there was no COR Library in a compilation using the assembly. '''</summary> Friend ReadOnly Property ObjectType As NamedTypeSymbol Get Return GetSpecialType(SpecialType.System_Object) End Get End Property ''' <summary> ''' Get symbol for predefined type from Cor Library used by this assembly. ''' </summary> ''' <param name="type"></param> ''' <returns></returns> ''' <remarks></remarks> Friend Function GetPrimitiveType(type As Microsoft.Cci.PrimitiveTypeCode) As NamedTypeSymbol Return GetSpecialType(SpecialTypes.GetTypeFromMetadataName(type)) End Function ''' <summary> ''' Lookup a type within the assembly using its canonical CLR metadata name (names are compared case-sensitively). ''' </summary> ''' <param name="fullyQualifiedMetadataName"> ''' </param> ''' <returns> ''' Symbol for the type or null if type cannot be found or is ambiguous. ''' </returns> Public Function GetTypeByMetadataName(fullyQualifiedMetadataName As String) As NamedTypeSymbol Return GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences:=False, isWellKnownType:=False) End Function Private Shared ReadOnly s_nestedTypeNameSeparators As Char() = {"+"c} ''' <summary> ''' Lookup a type within the assembly using its canonical CLR metadata name (names are compared case-sensitively). ''' </summary> ''' <param name="metadataName"></param> ''' <param name="includeReferences"> ''' If search within assembly fails, lookup in assemblies referenced by the primary module. ''' For source assembly, this is equivalent to all assembly references given to compilation. ''' </param> ''' <param name="isWellKnownType"> ''' Extra restrictions apply when searching for a well-known type. In particular, the type must be public. ''' </param> ''' <param name="useCLSCompliantNameArityEncoding"> ''' While resolving the name, consider only types following CLS-compliant generic type names and arity encoding (ECMA-335, section 10.7.2). ''' I.e. arity is inferred from the name and matching type must have the same emitted name and arity. ''' </param> ''' <returns></returns> Friend Function GetTypeByMetadataName(metadataName As String, includeReferences As Boolean, isWellKnownType As Boolean, Optional useCLSCompliantNameArityEncoding As Boolean = False) As NamedTypeSymbol If metadataName Is Nothing Then Throw New ArgumentNullException(NameOf(metadataName)) End If Dim type As NamedTypeSymbol = Nothing Dim mdName As MetadataTypeName If metadataName.Contains("+"c) Then Dim parts() As String = metadataName.Split(s_nestedTypeNameSeparators) If parts.Length > 0 Then mdName = MetadataTypeName.FromFullName(parts(0), useCLSCompliantNameArityEncoding) type = GetTopLevelTypeByMetadataName(mdName, includeReferences, isWellKnownType) Dim i As Integer = 1 While type IsNot Nothing AndAlso Not type.IsErrorType() AndAlso i < parts.Length mdName = MetadataTypeName.FromTypeName(parts(i)) Dim temp = type.LookupMetadataType(mdName) type = If(Not isWellKnownType OrElse IsValidWellKnownType(temp), temp, Nothing) i += 1 End While End If Else mdName = MetadataTypeName.FromFullName(metadataName, useCLSCompliantNameArityEncoding) type = GetTopLevelTypeByMetadataName(mdName, includeReferences, isWellKnownType) End If Return If(type Is Nothing OrElse type.IsErrorType(), Nothing, type) End Function ''' <summary> ''' Lookup a top level type within the assembly or one of the assemblies referenced by the primary module, ''' names are compared case-sensitively. In case of ambiguity, type from this assembly wins, ''' otherwise Nothing is returned. ''' </summary> ''' <returns> ''' Symbol for the type or Nothing if type cannot be found or ambiguous. ''' </returns> Friend Function GetTopLevelTypeByMetadataName(ByRef metadataName As MetadataTypeName, includeReferences As Boolean, isWellKnownType As Boolean) As NamedTypeSymbol Dim result As NamedTypeSymbol ' First try this assembly result = Me.LookupTopLevelMetadataType(metadataName, digThroughForwardedTypes:=False) If isWellKnownType AndAlso Not IsValidWellKnownType(result) Then result = Nothing End If If (IsAcceptableMatchForGetTypeByNameAndArity(result)) Then Return result End If result = Nothing If includeReferences Then ' Lookup in references Dim references As ImmutableArray(Of AssemblySymbol) = Me.Modules(0).GetReferencedAssemblySymbols() For i As Integer = 0 To references.Length - 1 Step 1 Debug.Assert(Not (TypeOf Me Is SourceAssemblySymbol AndAlso references(i).IsMissing)) ' Non-source assemblies can have missing references Dim candidate As NamedTypeSymbol = references(i).LookupTopLevelMetadataType(metadataName, digThroughForwardedTypes:=False) If isWellKnownType AndAlso Not IsValidWellKnownType(candidate) Then candidate = Nothing End If If IsAcceptableMatchForGetTypeByNameAndArity(candidate) AndAlso Not candidate.IsHiddenByEmbeddedAttribute() AndAlso candidate <> result Then If (result IsNot Nothing) Then ' Ambiguity Return Nothing End If result = candidate End If Next End If Return result End Function Friend Shared Function IsAcceptableMatchForGetTypeByNameAndArity(candidate As NamedTypeSymbol) As Boolean Return candidate IsNot Nothing AndAlso (candidate.Kind <> SymbolKind.ErrorType OrElse Not (TypeOf candidate Is MissingMetadataTypeSymbol)) End Function ''' <summary> ''' If this property returns false, it is certain that there are no extension ''' methods (from language perspective) inside this assembly. If this property returns true, ''' it is highly likely (but not certain) that this type contains extension methods. ''' This property allows the search for extension methods to be narrowed much more quickly. ''' ''' !!! Note that this property can mutate during lifetime of the symbol !!! ''' !!! from True to False, as we learn more about the assembly. !!! ''' </summary> Public MustOverride ReadOnly Property MightContainExtensionMethods As Boolean Implements IAssemblySymbol.MightContainExtensionMethods Friend MustOverride ReadOnly Property PublicKey As ImmutableArray(Of Byte) Protected Enum IVTConclusion Match OneSignedOneNot PublicKeyDoesntMatch NoRelationshipClaimed End Enum Protected Function PerformIVTCheck(key As ImmutableArray(Of Byte), otherIdentity As AssemblyIdentity) As IVTConclusion ' Implementation of this function in C# compiler is somewhat different, but we believe ' that the difference doesn't affect any real world scenarios that we know/care about. ' At the moment we don't feel it is worth porting the logic, but we might reconsider in the future. ' We also have an easy out here. Suppose Smith names Jones as a friend, And Jones Is ' being compiled as a module, Not as an assembly. You can only strong-name an assembly. So if this module ' Is named Jones, And Smith Is extending friend access to Jones, then we are going to optimistically ' assume that Jones Is going to be compiled into an assembly with a matching strong name, if necessary. Dim compilation As Compilation = Me.DeclaringCompilation If compilation IsNot Nothing AndAlso compilation.Options.OutputKind.IsNetModule() Then Return IVTConclusion.Match End If Dim result As IVTConclusion If Me.PublicKey.IsDefaultOrEmpty OrElse key.IsDefaultOrEmpty Then If Me.PublicKey.IsDefaultOrEmpty AndAlso key.IsDefaultOrEmpty Then 'we are not signed, therefore the other assembly shouldn't be signed result = If(otherIdentity.IsStrongName, IVTConclusion.OneSignedOneNot, IVTConclusion.Match) ElseIf Me.PublicKey.IsDefaultOrEmpty Then result = IVTConclusion.PublicKeyDoesntMatch Else ' key is NullOrEmpty, Me.PublicKey is not. result = IVTConclusion.NoRelationshipClaimed End If ElseIf ByteSequenceComparer.Equals(key, Me.PublicKey) Then result = If(otherIdentity.IsStrongName, IVTConclusion.Match, IVTConclusion.OneSignedOneNot) Else result = IVTConclusion.PublicKeyDoesntMatch End If Return result End Function Friend Function IsValidWellKnownType(result As NamedTypeSymbol) As Boolean If result Is Nothing OrElse result.TypeKind = TypeKind.Error Then Return False End If Debug.Assert(result.ContainingType Is Nothing OrElse IsValidWellKnownType(result.ContainingType), "Checking the containing type is the caller's responsibility.") Return result.DeclaredAccessibility = Accessibility.Public OrElse IsSymbolAccessible(result, Me) End Function #Region "IAssemblySymbol" Private ReadOnly Property IAssemblySymbol_GlobalNamespace As INamespaceSymbol Implements IAssemblySymbol.GlobalNamespace Get Return Me.GlobalNamespace End Get End Property Private Function IAssemblySymbol_GivesAccessTo(toAssembly As IAssemblySymbol) As Boolean Implements IAssemblySymbol.GivesAccessTo If Equals(Me, toAssembly) Then Return True End If Dim assembly = TryCast(toAssembly, AssemblySymbol) If assembly Is Nothing Then Return False End If Dim myKeys = Me.GetInternalsVisibleToPublicKeys(assembly.Identity.Name) For Each key In myKeys If assembly.PerformIVTCheck(key, Me.Identity) = IVTConclusion.Match Then Return True End If Next Return False End Function Private ReadOnly Property IAssemblySymbol_Modules As IEnumerable(Of IModuleSymbol) Implements IAssemblySymbol.Modules Get Return Me.Modules End Get End Property Private Function IAssemblySymbol_ResolveForwardedType(metadataName As String) As INamedTypeSymbol Implements IAssemblySymbol.ResolveForwardedType Return Me.ResolveForwardedType(metadataName) End Function Private Function IAssemblySymbol_GetTypeByMetadataName(metadataName As String) As INamedTypeSymbol Implements IAssemblySymbol.GetTypeByMetadataName Return Me.GetTypeByMetadataName(metadataName) End Function Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitAssembly(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitAssembly(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitAssembly(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitAssembly(Me) End Function #End Region End Class End Namespace
droyad/roslyn
src/Compilers/VisualBasic/Portable/Symbols/AssemblySymbol.vb
Visual Basic
apache-2.0
29,764
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenOverridingAndHiding Inherits BasicTestBase <WorkItem(540852, "DevDiv")> <Fact> Public Sub TestSimpleMustOverride() Dim source = <compilation> <file name="a.vb"> Imports System MustInherit Class A Public MustOverride Function F As Integer() Protected MustOverride Sub Meth() Protected Friend MustOverride Property Prop As Integer() End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32[] F() cil managed"), Signature("A", "Meth", ".method family newslot strict abstract virtual instance System.Void Meth() cil managed"), Signature("A", "get_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Int32[] get_Prop() cil managed"), Signature("A", "set_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32[] Value) cil managed"), Signature("A", "Prop", ".property readwrite System.Int32[] Prop") }) End Sub <WorkItem(528311, "DevDiv")> <WorkItem(540865, "DevDiv")> <Fact> Public Sub TestSimpleOverrides() Dim source = <compilation> <file name="a.vb"> MustInherit Class A Public MustOverride Sub F() End Class Class B Inherits A Public Overrides Sub F() End Sub End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("B", "F", ".method public hidebysig strict virtual instance System.Void F() cil managed"), Signature("A", "F", ".method public newslot strict abstract virtual instance System.Void F() cil managed") }) verifier.VerifyDiagnostics() End Sub <WorkItem(540884, "DevDiv")> <Fact> Public Sub TestMustOverrideOverrides() Dim source = <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub G() Console.WriteLine("A.G") End Sub End Class MustInherit Class B Inherits A Public MustOverride Overrides Sub G() End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("B", "G", ".method public hidebysig strict abstract virtual instance System.Void G() cil managed"), Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed") }) verifier.VerifyDiagnostics() End Sub <WorkItem(542576, "DevDiv")> <Fact> Public Sub TestDontMergePartials() Dim source = <compilation> <file name="a.vb"> MustInherit Class A MustOverride Function F() As Integer Overridable Sub G() End Sub End Class Partial Class B Inherits A 'This would normally be an error if this partial part for class B 'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable 'can't be combined). Strangely Dev10 doesn't report the same error 'when the NotInheritable modifier appears on a different partial part. NotOverridable Overrides Function F() As Integer Return 1 End Function 'This would normally be an error if this partial part for class B 'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable 'can't be combined). Strangely Dev10 doesn't report the same error 'when the NotInheritable modifier appears on a different partial part. NotOverridable Overrides Sub G() End Sub End Class</file> <file name="b.vb"> NotInheritable Class B Inherits A End Class </file> </compilation> CompileAndVerify(source, expectedSignatures:= { Signature("B", "F", ".method public hidebysig strict virtual final instance System.Int32 F() cil managed"), Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32 F() cil managed"), Signature("B", "G", ".method public hidebysig strict virtual final instance System.Void G() cil managed"), Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed") }). VerifyDiagnostics() End Sub <WorkItem(543751, "DevDiv")> <Fact(), WorkItem(543751, "DevDiv")> Public Sub TestMustOverloadWithOptional() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Const str As String = "" Sub Main(args As String()) End Sub Function fun() test(temp:=Nothing, x:=1) Return Nothing End Function Function test(ByRef x As Integer, temp As Object, Optional y As String = str, Optional z As Object = Nothing) Return Nothing End Function Function test(ByRef x As Integer, Optional temp As Object = Nothing) Return Nothing End Function End Module </file> </compilation>). VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase1() 'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this 'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub foo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[using System; public abstract class C2 : C1 { new internal virtual void foo() { Console.WriteLine("C2"); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Imports System Public Class C3 : Inherits C2 Public Overrides Sub foo Console.WriteLine("C3") End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() 'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors. 'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): 'C1 : Public MustOverride Sub foo(). 'Public Class C4 : Inherits C3 ' ~~ Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[ Imports System Public Class C4 : Inherits C3 End Class Public Class C5 : Inherits C2 ' Corresponding case in C# results in PEVerify errors - See test 'CrossLanguageCase1' in CodeGenOverridingAndHiding.cs Public Overrides Sub foo() Console.WriteLine("C5") End Sub End Class Public Module Program Sub Main() Dim x As C1 = New C4 x.foo() Dim y As C2 = New C5 y.Foo() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) Dim vb3Verifier = CompileAndVerify(vb3Compilation, expectedOutput:=<![CDATA[C3 C5]]>) vb3Verifier.VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase2() 'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this 'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub foo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[using System; [assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")] public abstract class C2 : C1 { new internal virtual void foo() { Console.WriteLine("C2"); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Imports System Public Class C3 : Inherits C2 Public Overrides Sub foo Console.WriteLine("C3") End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() 'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors. 'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): 'C1 : Public MustOverride Sub foo(). 'Public Class C4 : Inherits C3 ' ~~ Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[Imports System Public Class C4 : Inherits C3 Public Overrides Sub foo Console.WriteLine("C4") End Sub End Class Public Module Program Sub Main() Dim x As C1 = New C4 x.foo Dim y As C2 = New C4 y.foo End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) Dim vb3Verifier = CompileAndVerify(vb3Compilation, expectedOutput:=<![CDATA[C4 C2]]>) vb3Verifier.VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase3() 'Note: Dev10 and Roslyn produce identical errors for this case. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub foo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")] public abstract class C2 : C1 { new internal virtual void foo() { } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Public Class C3 : Inherits C2 Public Overrides Sub foo End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[MustInherit Public Class C4 : Inherits C3 Public Overrides Sub foo End Sub End Class Public Class C5 : Inherits C2 Public Overrides Sub foo() End Sub End Class Public Class C6 : Inherits C2 Friend Overrides Sub foo() End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) vb3Compilation.AssertTheseDiagnostics(<expected> BC30610: Class 'C5' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C1: Public MustOverride Sub foo(). Public Class C5 : Inherits C2 ~~ BC30266: 'Public Overrides Sub foo()' cannot override 'Friend Overridable Overloads Sub foo()' because they have different access levels. Public Overrides Sub foo() ~~~ BC30610: Class 'C6' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C1: Public MustOverride Sub foo(). Public Class C6 : Inherits C2 ~~ </expected>) End Sub <WorkItem(543794, "DevDiv")> <Fact()> Public Sub CrossLanguageTest4() Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub foo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VB2")] public abstract class C2 : C1 { new internal virtual void foo() { } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[MustInherit Public Class C3 : Inherits C2 Friend Overrides Sub foo() End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) CompileAndVerify(vb2Compilation).VerifyDiagnostics() End Sub <Fact(), WorkItem(544536, "DevDiv")> Public Sub VBOverrideCsharpOptional() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[ public abstract class Trivia { public abstract void Format(int i, int j = 2); } public class Whitespace : Trivia { public override void Format(int i, int j) {} } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[ MustInherit Class AbstractLineBreakTrivia Inherits Whitespace Public Overrides Sub Format(i As Integer, j As Integer) End Sub End Class Class AfterStatementTerminatorTokenTrivia Inherits AbstractLineBreakTrivia End Class ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={cs1Compilation}) CompileAndVerify(vb2Compilation).VerifyDiagnostics() End Sub <Fact()> Public Sub VBOverrideCsharpOptional2() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[ public abstract class Trivia { public abstract void Format(int i, int j = 2); } public class Whitespace : Trivia { public override void Format(int i, int j) {} } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[ MustInherit Class AbstractLineBreakTrivia Inherits Trivia Public Overrides Sub Format(i As Integer, j As Integer) End Sub End Class Class AfterStatementTerminatorTokenTrivia Inherits AbstractLineBreakTrivia End Class ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={cs1Compilation}) CompilationUtils.AssertTheseDiagnostics(vb2Compilation, <expected> BC30308: 'Public Overrides Sub Format(i As Integer, j As Integer)' cannot override 'Public MustOverride Overloads Sub Format(i As Integer, [j As Integer = 2])' because they differ by optional parameters. Public Overrides Sub Format(i As Integer, j As Integer) ~~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadingBasedOnOptionalParameters() ' NOTE: this matches Dev11 implementation, not Dev10 Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Class C ' allowed Shared Sub f(ByVal x As Integer) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 0) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal s As String = "") End Sub End Class Class C2 ' allowed Shared Sub f(ByVal x As Integer, Optional ByVal y As Short = 1) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 1) End Sub End Class Class C3 ' allowed Shared Sub f() End Sub Shared Sub f(Optional ByVal x As Integer = 0) End Sub End Class Class C4 ' allowed` Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByVal ParamArray xx As Integer()) End Sub End Class Class C5 ' disallowed Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByVal x As Integer) End Sub End Class Class C6 ' disallowed Shared Sub f(Optional ByVal x As Integer() = Nothing) End Sub Shared Sub f(ByVal ParamArray xx As Integer()) End Sub End Class Class C7 ' disallowed Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByRef x As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(x As Integer)' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer = 0) ~ BC30300: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer() = Nothing) ~ BC30368: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by parameters declared 'ParamArray'. Shared Sub f(Optional ByVal x As Integer() = Nothing) ~ BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer = 0) ~ BC30345: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. Shared Sub f(Optional ByVal x As Integer = 0) ~ </errors>) End Sub <Fact()> Public Sub HidingBySignatureWithOptionalParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub f(Optional x As String = "") Console.WriteLine("A::f(Optional x As String = """")") End Sub End Class Class B Inherits A Public Overridable Overloads Sub f() Console.WriteLine("B::f()") End Sub End Class Class C Inherits B Public Sub f(Optional x As String = "") Console.WriteLine("C::f(Optional x As String = """")") End Sub Public Shared Sub Main() Dim c As B = New C c.f() c.f(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC40005: sub 'f' shadows an overridable method in the base class 'B'. To override the base method, this method must be declared 'Overrides'. Public Sub f(Optional x As String = "") ~ </errors>) End Sub <Fact()> Public Sub BC31404ForOverloadingBasedOnOptionalParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> MustInherit Class A Public MustOverride Sub f(Optional x As String = "") End Class MustInherit Class B1 Inherits A Public MustOverride Overloads Sub f(Optional x As String = "") End Class MustInherit Class B2 Inherits A Public MustOverride Overloads Sub f(x As String) End Class MustInherit Class B3 Inherits A Public MustOverride Overloads Sub f(x As Integer, Optional y As String = "") End Class MustInherit Class B4 Inherits A Public MustOverride Overloads Sub f() End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31404: 'Public MustOverride Overloads Sub f([x As String = ""])' cannot shadow a method declared 'MustOverride'. Public MustOverride Overloads Sub f(Optional x As String = "") ~ BC31404: 'Public MustOverride Overloads Sub f(x As String)' cannot shadow a method declared 'MustOverride'. Public MustOverride Overloads Sub f(x As String) ~ </errors>) End Sub <Fact()> Public Sub OverloadingWithNotAccessibleMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub f(Optional x As String = "") End Sub End Class Class B Inherits A Public Overridable Overloads Sub f() End Sub End Class Class BB Inherits A Private Overloads Sub f() End Sub Private Overloads Sub f(Optional x As String = "") End Sub End Class Class C Inherits BB Public Overloads Overrides Sub f(Optional x As String = "") Console.Write("f(Optional x As String = "");") End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> </errors>) End Sub <Fact()> Public Sub AddressOfWithFunctionOrSub1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class Clazz Public Shared Sub S(Optional x As Integer = 0) Console.WriteLine("Sub S") End Sub Public Shared Function S() As Boolean Console.WriteLine("Function S") Return True End Function Public Shared Sub Main() Dim a As action = AddressOf S a() End Sub End Class </file> </compilation>, expectedOutput:="Function S") End Sub <Fact, WorkItem(546816, "DevDiv")> Public Sub OverrideFinalizeWithoutNewslot() CompileAndVerify( <compilation> <file name="a.vb"> Class SelfDestruct Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class </file> </compilation>, {MscorlibRef_v20}).VerifyDiagnostics() End Sub End Class End Namespace
droyad/roslyn
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenOverridingAndHiding.vb
Visual Basic
apache-2.0
25,720
' 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.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Friend Class AfterCommitCaretMoveUndoPrimitive Inherits AbstractCommitCaretMoveUndoPrimitive Private ReadOnly _newPosition As Integer Private ReadOnly _newVirtualSpaces As Integer Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, position As CaretPosition) MyBase.New(textBuffer, textBufferAssociatedViewService) ' Grab the old position and virtual spaces. This is cheaper than holding onto ' a VirtualSnapshotPoint as it won't hold old snapshots alive _newPosition = position.VirtualBufferPosition.Position _newVirtualSpaces = position.VirtualBufferPosition.VirtualSpaces End Sub Public Overrides Sub [Do]() Dim view = TryGetView() If view IsNot Nothing Then view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _newPosition), _newVirtualSpaces)) view.Caret.EnsureVisible() End If End Sub Public Overrides Sub Undo() ' When we are going forward, we do nothing here since the BeforeCommitCaretMoveUndoPrimitive ' will take care of it End Sub End Class End Namespace
jhendrixMSFT/roslyn
src/EditorFeatures/VisualBasic/LineCommit/AfterCommitCaretMoveUndoPrimitive.vb
Visual Basic
apache-2.0
1,596
Module Module1 Sub Main() For Each e In System.Web.Helpers.Json.Decode(DirectCast((New System.Net.WebClient()).DownloadString("http://sw.cs.wwu.edu/~fugiera/matches"), String)) 'worldcup.sfg.io Console.Write(If((e.status = "completed"), " {0} {1} vs {2} {3}" & vbLf, ""), e.home_team.country, e.home_team.goals, e.away_team.country, e.away_team.goals) Next End Sub End Module
reillysiemens/jogos
visualBasic/jogos/jogos/Module1.vb
Visual Basic
mit
415
Imports CheatGenerator.ARDS Public Class BlueStoredMoney Implements CodeDefinition Public ReadOnly Property Author As String Implements CodeDefinition.Author Get Return "Demonic722" End Get End Property Public ReadOnly Property Category As String Implements CodeDefinition.Category Get Return "Money" End Get End Property Public ReadOnly Property Name As String Implements CodeDefinition.Name Get Return "Stored Money" End Get End Property Public ReadOnly Property SupportedGames As String() Implements CodeDefinition.SupportedGames Get Return {} 'SaveEditor.GameStrings.BlueGame} End Get End Property Public ReadOnly Property SupportedRegions As UShort Implements CodeDefinition.SupportedRegions Get Return Region.US End Get End Property Public Overrides Function ToString() As String Implements CodeDefinition.ToString Return Name End Function Public Function GenerateCode(Save As Object, TargetRegion As Region, ButtonActivator As UShort, CodeType As CheatFormat) As String Implements CodeDefinition.GenerateCode 'Dim s = DirectCast(Save, RBSave) 'Dim moneyHex As String = Conversion.Hex(s.StoredMoney) 'Dim code As New SkyEditorBase.ARDS.CodeGeneratorHelper.Code 'code.Add(CodeGeneratorHelper.Line.IfButtonDown(ButtonActivator)) 'code.Add(New CodeGeneratorHelper.Line(String.Format("0213C130 {0}", moneyHex.PadLeft(8, "0")))) 'code.Add(CodeGeneratorHelper.Line.MasterEnd) 'Return code.ToString Return "" End Function Public ReadOnly Property SupportedCheatFormats As CheatFormat() Implements CodeDefinition.SupportedCheatFormats Get Return {CheatFormat.ARDS} End Get End Property End Class
evandixon/Sky-Editor
CheatGenerator/Library/ARDS/Blue Stored Money.vb
Visual Basic
mit
1,970
Option Strict Off Option Explicit On Imports VB = Microsoft.VisualBasic Friend Class frmZeroiseED Inherits System.Windows.Forms.Form Public Event ExportStarted(ByVal ExportingFormat As DatabaseExport.DatabaseExportEnum) Public Event ExportError(ByRef myError As ErrObject, ByVal ExportingFormat As DatabaseExport.DatabaseExportEnum) Public Event ExportComplete(ByVal Success As Boolean, ByVal ExportingFormat As DatabaseExport.DatabaseExportEnum) Private Declare Function GetQueueStatus Lib "user32" (ByVal qsFlags As Integer) As Integer Dim rs As ADODB.Recordset ' As ADODB.Recordset Dim sql As String Dim gSection As Short Const sec_Payment As Short = 0 Const sec_Debit As Short = 1 Const sec_Credit As Short = 2 'Public Enum DatabaseExportEnum ' [CSV] = 0 ' [HTML] = 1 ' [Excel] = 2 'End Enum Private Sub loadLanguage() rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 2499 'Export Customer Details|Checked If rsLang.RecordCount Then Me.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Me.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 2501 'Please click start to export customer details|Checked If rsLang.RecordCount Then Label1.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Label1.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1004 'Exit|Checked If rsLang.RecordCount Then cmdExit.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdExit.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 2490 'Password|Checked If rsLang.RecordCount Then Label2.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Label2.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 2496 'Start|Checked If rsLang.RecordCount Then cmdstart.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdstart.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsHelp.filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'" 'UPGRADE_ISSUE: Form property frmZeroiseED.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp.Fields("Help_ContextID").Value End Sub Private Sub cmdExit_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdExit.Click Me.Close() End Sub Private Sub frmZeroiseED_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load loadLanguage() 'If App.PrevInstance = True Then End 'If openConnection() = True Then 'ExportToCSV 'Else: MsgBox "Connection to database was not successful" 'End If End Sub Private Sub cmdStart_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdStart.Click 'If mdbFile.Text <> "" Then Dim dtDate As String Dim dtMonth As String Dim stPass As String 'Construct password........... If Len(VB.Day(Today)) = 1 Then dtDate = "0" & Str(VB.Day(Today)) Else dtDate = Trim(Str(VB.Day(Today))) If Len(Month(Today)) = 1 Then dtMonth = "0" & Str(Month(Today)) Else dtMonth = Trim(Str(Month(Today))) 'Create password stPass = dtDate & "##" & dtMonth stPass = Replace(stPass, " ", "") If Trim(txtPassword.Text) = stPass Then ' ZeroiseStock If openConnection() = True Then 'Trim(mdbFile.Text) ExportToCSV() Else : MsgBox("Connection to database was not successful") End If Else MsgBox("Incorrect password was entered!!!", MsgBoxStyle.Exclamation, "Incorrect Passwords") End If 'Else 'MsgBox "Upload your database before you continue", vbOKOnly, "Customers" 'End If End Sub Function ShowOpen1() As Boolean Dim strPath_DB1 As String Dim Extention As String On Error GoTo Extracter With cmdDlgOpen '.CancelError = True .Title = "Upload Database" .FileName = "" .Filter = "Access File (*.mdb)|*.mdb|Access (*.mdb)|*.mdb|" .FilterIndex = 0 .ShowDialog() strPath_DB1 = .FileName End With If strPath_DB1 <> "" Then mdbFile.Text = strPath_DB1 ShowOpen1 = True Else ShowOpen1 = False End If Exit Function Extracter: If MsgBoxResult.Cancel Then Exit Function End If MsgBox(Err.Description) End Function Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click Dim fso As New Scripting.FileSystemObject If ShowOpen1 = True Then Else Exit Sub End If End Sub Public Property FilePath() As String Get Dim x As Short Dim temp As String Dim strPath_DB1 As String strPath_DB1 = (Trim(mdbFile.Text)) FilePath = mdbFile.Text temp = FilePath x = InStrRev(temp, "\") FilePath = Mid(temp, 1, x - 1) FilePath = FilePath & "\" End Get Set(ByVal Value As String) Dim x As Short Dim temp As String FilePath = mdbFile.Text temp = FilePath x = InStrRev(temp, "\") FilePath = Mid(temp, 1, x - 1) FilePath = FilePath & "\" End Set End Property Private Function DoEventsEx() As Integer On Error Resume Next DoEventsEx = GetQueueStatus(&H80 Or &H1 Or &H4 Or &H20 Or &H10) If DoEventsEx <> 0 Then System.Windows.Forms.Application.DoEvents() End If End Function Public Sub ExportToCSV(Optional ByVal PrintHeader As Boolean = True) Dim ExportFilePath As String Dim rs As ADODB.Recordset Dim i As Integer Dim TotalRecords As Integer Dim ErrorOccured As Boolean Dim NumberOfFields As Short Const quote As String = """" 'Faster then Chr$(34) Dim sql As String Dim fso As New Scripting.FileSystemObject cmdstart.Enabled = False cmdExit.Enabled = False txtPassword.Enabled = False Dim ptbl As String Dim t_day As String Dim t_Mon As String If Len(Trim(Str(VB.Day(Today)))) = 1 Then t_day = "0" & Trim(CStr(VB.Day(Today))) Else t_day = CStr(VB.Day(Today)) If Len(Trim(Str(Month(Today)))) = 1 Then t_Mon = "0" & Trim(CStr(Month(Today))) Else t_Mon = Str(Month(Today)) ExportFilePath = serverPath & "4POSDebtor" & Trim(CStr(Year(Today))) & Trim(t_Mon) & Trim(t_day) If fso.FileExists(ExportFilePath & ".csv") Then fso.DeleteFile((ExportFilePath & ".csv")) rs = getRS("SELECT CustomerID, Customer_InvoiceName, Customer_DepartmentName, Customer_FirstName, Customer_Surname, Customer_PhysicalAddress, Customer_PostalAddress, Customer_Telephone, Customer_Current as CurrentBalance,Customer_30Days as 30Days, Customer_60Days as 60days, Customer_90Days as 90Days, Customer_120Days as 120Days,Customer_150Days as 150Days FROM Customer") prgBar.Maximum = rs.RecordCount If rs.RecordCount > 0 Then FileOpen(1, ExportFilePath & ".csv", OpenMode.Output) With getRS("SELECT CustomerID, Customer_InvoiceName, Customer_DepartmentName, Customer_FirstName, Customer_Surname, Customer_PhysicalAddress, Customer_PostalAddress, Customer_Telephone, Customer_Current as CurrentBalance,Customer_30Days as 30Days, Customer_60Days as 60days, Customer_90Days as 90Days, Customer_120Days as 120Days,Customer_150Days as 150Days FROM Customer") rs.MoveFirst() NumberOfFields = rs.Fields.Count - 1 If PrintHeader Then For i = 0 To NumberOfFields - 1 'Now add the field names Print(1, rs.Fields(i).name & ",") 'similar to the ones below Next i PrintLine(1, rs.Fields(NumberOfFields).name) End If Do While Not rs.EOF prgBar.Value = prgBar.Value + 1 On Error Resume Next TotalRecords = TotalRecords + 1 For i = 0 To NumberOfFields 'If there is an emty field, If (IsDbNull(rs.Fields(i).Value)) Then 'add a , to indicate it is Print(1, ",") 'empty Else If i = NumberOfFields Then Print(1, quote & Trim(CStr(rs.Fields(i).Value)) & quote) Else Print(1, quote & Trim(CStr(rs.Fields(i).Value)) & quote & ",") End If End If 'Putting data under "" will not Next i 'confuse the reader of the file DoEventsEx() 'between Dhaka, Bangladesh as two PrintLine(1) 'fields or as one field. rs.moveNext() Loop End With FileClose(1) MsgBox("Customer details were successfully exported to : " & FilePath & "" & "4POSProd" & Trim(CStr(Year(Today))) & Trim(t_Mon) & Trim(t_day) & ".csv", MsgBoxStyle.OKOnly, "Customers") ' DoEvents ' DoEvents ' MsgBox "Now Zeroising...", vbOKOnly, "Customers" ' cmdStart.Enabled = False ' cmdExit.Enabled = False ' Set rsZ = getRS("SELECT CustomerID FROM Customer") ' Do While Not rsZ.EOF ' DoEvents ' cmdProcess_Click (rsZ("CustomerID")) ' DoEvents ' rsZ.moveNext ' Loop 'MsgBox "Completed", vbOKOnly, "Customers" 'cmdStart.Enabled = True 'cmdExit.Enabled = True Me.Close() End If System.Windows.Forms.Cursor.Current = Cursors.Default rs.Close() 'cnnDB.Close 'Set cnnDB = Nothing 'closeConnection End Sub Private Sub frmZeroiseED_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress Dim KeyAscii As Short = Asc(eventArgs.KeyChar) If KeyAscii = 27 Then KeyAscii = 0 Me.Close() End If eventArgs.KeyChar = Chr(KeyAscii) If KeyAscii = 0 Then eventArgs.Handled = True End If End Sub Private Sub cmdProcess_Click(ByRef cID As Integer) Dim amount As Decimal Dim txtAmountText As String Dim txtNarrativeText As String Dim txtNotesText As String Dim rsCus As ADODB.Recordset Dim cSQL As String Dim sql As String Dim sql1 As String Dim rs As ADODB.Recordset Dim id As String Dim days120, days60, current, lAmount, days30, days90, days150 As Decimal System.Windows.Forms.Application.DoEvents() 'If txtNarrative.Text = "" Then ' MsgBox "Narrative is a mandarory field", vbExclamation, Me.Caption ' txtNarrative.SetFocus ' Exit Sub 'End If 'If CCur(txtAmount.Text) = 0 Then ' MsgBox "Amount is a mandarory field", vbExclamation, Me.Caption ' txtAmount.SetFocus ' Exit Sub 'End If cSQL = "SELECT CustomerTransaction.*, TransactionType.TransactionType_Name, IIf([CustomerTransaction_Amount]>0,[CustomerTransaction_Amount],Null) AS debit, IIf([CustomerTransaction_Amount]<0,[CustomerTransaction_Amount],Null) AS credit" cSQL = cSQL & " FROM CustomerTransaction INNER JOIN TransactionType ON CustomerTransaction.CustomerTransaction_TransactionTypeID = TransactionType.TransactionTypeID" cSQL = cSQL & " WHERE (((CustomerTransaction.CustomerTransaction_CustomerID)=" & cID & "))" cSQL = cSQL & " ORDER BY CustomerTransaction.CustomerTransaction_Date DESC;" rsCus = getRS(cSQL) If CDec(rsCus("CustomerTransaction_Amount").Value) < 0 Then 'rsCus("credit") <> "" gSection = 1 txtNotesText = "Zeroise Creditors Accounts" txtNarrativeText = "Zeroise Creditors Accounts" txtAmountText = (rsCus("CustomerTransaction_Amount").Value / -1) End If If CDec(rsCus("CustomerTransaction_Amount").Value) > 0 Then 'rsCus("debit") <> "" gSection = 2 txtNotesText = "Zeroise Debitors Accounts" txtNarrativeText = "Zeroise Debitors Accounts" txtAmountText = (rsCus("CustomerTransaction_Amount")) End If sql = "INSERT INTO CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName )" Select Case gSection Case sec_Payment sql = sql & "SELECT " & cID & " AS Customer, 3 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" & Replace(txtNotesText, "'", "''") & "' AS description, " & CDec(0 - CDec(txtAmountText)) & " AS amount, '" & Replace(txtNarrativeText, "'", "''") & "' AS reference, 'System' AS person FROM Company;" Case sec_Debit sql = sql & "SELECT " & cID & " AS Customer, 4 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" & Replace(txtNotesText, "'", "''") & "' AS description, " & CDec(txtAmountText) & " AS amount, '" & Replace(txtNarrativeText, "'", "''") & "' AS reference, 'System' AS person FROM Company;" Case sec_Credit sql = sql & "SELECT " & cID & " AS Customer, 5 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" & Replace(txtNotesText, "'", "''") & "' AS description, " & CDec(0 - CDec(txtAmountText)) & " AS amount, '" & Replace(txtNarrativeText, "'", "''") & "' AS reference, 'System' AS person FROM Company;" End Select cnnDB.Execute(sql) rs = getRS("SELECT MAX(CustomerTransactionID) AS id From CustomerTransaction") If rs.BOF Or rs.EOF Then Else id = rs.Fields("id").Value cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_Current = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_Current) Is Null));") cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_30Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_30Days) Is Null));") cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_60Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_60Days) Is Null));") cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_90Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_90Days) Is Null));") cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_120Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_120Days) Is Null));") cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_150Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_150Days) Is Null));") rs = getRS("SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_Amount, Customer.Customer_Current, Customer.Customer_30Days, Customer.Customer_60Days, Customer.Customer_90Days, Customer.Customer_120Days, Customer.Customer_150Days FROM Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID Where (((CustomerTransaction.CustomerTransactionID) = " & id & "));") amount = rs.Fields("CustomerTransaction_Amount").Value current = rs.Fields("Customer_Current").Value days30 = rs.Fields("Customer_30Days").Value days60 = rs.Fields("Customer_60Days").Value days90 = rs.Fields("Customer_90Days").Value days120 = rs.Fields("Customer_120Days").Value days150 = rs.Fields("Customer_150Days").Value If amount < 0 Then days150 = days150 + amount If (days150 < 0) Then amount = days150 days150 = 0 Else amount = 0 End If days120 = days120 + amount If (days120 < 0) Then amount = days120 days120 = 0 Else amount = 0 End If days90 = days90 + amount If (days90 < 0) Then amount = days90 days90 = 0 Else amount = 0 End If days60 = days60 + amount If (days60 < 0) Then amount = days60 days60 = 0 Else amount = 0 End If days30 = days30 + amount If (days30 < 0) Then amount = days30 days30 = 0 Else amount = 0 End If End If current = current + amount 'cnnDB.Execute "UPDATE Customer SET Customer.Customer_Current = " & current & ", Customer.Customer_30Days = " & days30 & ", Customer.Customer_60Days = " & days60 & ", Customer.Customer_90Days = " & days90 & ", Customer.Customer_120Days = " & days120 & ", Customer.Customer_150Days = 0" & days150 & " WHERE (((Customer.CustomerID)=" & rs("CustomerTransaction_CustomerID") & "));" cnnDB.Execute("UPDATE Customer SET Customer.Customer_Current = " & 0 & ", Customer.Customer_30Days = " & 0 & ", Customer.Customer_60Days = " & 0 & ", Customer.Customer_90Days = " & 0 & ", Customer.Customer_120Days = " & 0 & ", Customer.Customer_150Days = " & 0 & " WHERE (((Customer.CustomerID)=" & rs.Fields("CustomerTransaction_CustomerID").Value & "));") End If End Sub End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmZeroiseED.vb
Visual Basic
mit
18,676
Imports System.IO Imports Microsoft Public Class frmScreenshotCapture Dim OriginalHeight As Int32 Dim originalWidth As Int32 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim bounds As Rectangle Dim screenshot As System.Drawing.Bitmap Dim graph As Graphics bounds = Screen.PrimaryScreen.Bounds screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb) graph = Graphics.FromImage(screenshot) graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy) PictureBox1.Image = screenshot Me.ToolStripStatus2.Text = "Capture Taken" Me.ListEvents.Items.Add("Action:Capture Taken") End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim savefiledialog1 As New SaveFileDialog savefiledialog1.Title = "Save File" savefiledialog1.FileName = "*.png" savefiledialog1.Filter = "PNG |*.png" If savefiledialog1.ShowDialog() = DialogResult.OK Then PictureBox1.Image.Save(savefiledialog1.FileName, System.Drawing.Imaging.ImageFormat.Png) End If Me.ToolStripStatus2.Text = "Saved Capture" Me.ListEvents.Items.Add("Action: Saved Capture") End Sub Private Sub ToolStripStatusLabel2_Click(sender As Object, e As EventArgs) Handles ToolStripStatus2.Click Me.ToolStripStatus2.Name = "" Me.ToolStripStatus2.Text = "Screenshot Capture started. No action yet." Me.ToolStripStatus2.ToolTipText = "Last Activity" Me.ToolStripStatus2.Width = 100 End Sub Private Sub frmScreenshotCapture_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress Dim bounds As Rectangle Dim screenshot As System.Drawing.Bitmap Dim graph As Graphics bounds = Screen.PrimaryScreen.Bounds screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb) graph = Graphics.FromImage(screenshot) graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy) PictureBox1.Image = screenshot Me.ToolStripStatus2.Text = "Capture Taken Using Enter (Keystroke)" Me.ListEvents.Items.Add("Action: Capture Taken Using Enter (Keystroke)") End Sub Private Sub frmScreenshotCapture_Load(sender As Object, e As EventArgs) Handles MyBase.Load Me.KeyPreview = True 'Panel Settings Panel1.AutoScroll = True 'Picture Box Settings PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize Me.ToolStripStatus2.Text = "Ready..." Me.ListEvents.Items.Add("Screenshot Capture initiated successfully...") Me.ToolStripStatus3.ToolTipText = "Started: " & System.DateTime.Now.ToShortTimeString() Me.ToolStripStatus3.Text = System.DateTime.Today.ToLongDateString() Dim xf As DialogResult xf = MessageBox.Show("Capture your Desktop. Default resolution is set to your Computer Display Resolution. Click OK to continue. ", "Welcome to Screenshot Capture", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) If xf = DialogResult.Cancel Then Me.Close() End If End Sub Private Sub TrackBar1_ValueChanged(sender As Object, e As EventArgs) Handles TrackBar1.ValueChanged Dim OriginalHeight As Int32 Dim originalWidth As Int32 OriginalHeight = Me.PictureBox1.Height originalWidth = Me.PictureBox1.Width Dim NewWidth As Integer = originalWidth + TrackBar1.Value * 20 Dim s As New Size(NewWidth, NewWidth * OriginalHeight / originalWidth) PictureBox1.Size = s PictureBox1.Refresh() ToolStripStatus1.Text = TrackBar1.Value Dim betafix As DialogResult betafix = MessageBox.Show("Picture-box can be re-sized only before loading the image, there after it is read only and has no effect !", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error) If betafix = DialogResult.Cancel Then Me.Close() End If PictureBox1.Image = Nothing PictureBox1.BackColor = Color.Empty PictureBox1.Invalidate() Me.ToolStripStatus2.Text = "Zoom In & Out" Me.ListEvents.Items.Add("Action: Zoom In & Out") End Sub 'Pan Image Private m_PanStartPoint As New Point Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) m_PanStartPoint = New Point(e.X, e.Y) Me.ToolStripStatus2.Text = "Pan on Mouse Down" Me.ListEvents.Items.Add("Action: Pan on Mouse Down") End Sub Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) 'Verify Left Button is pressed while the mouse is moving If e.Button = Windows.Forms.MouseButtons.Left Then 'Here we get the change in coordinates. Dim DeltaX As Integer = (m_PanStartPoint.X - e.X) Dim DeltaY As Integer = (m_PanStartPoint.Y - e.Y) 'Then we set the new autoscroll position. 'ALWAYS pass positive integers to the panels autoScrollPosition method Panel1.AutoScrollPosition = _ New Drawing.Point((DeltaX - Panel1.AutoScrollPosition.X), _ (DeltaY - Panel1.AutoScrollPosition.Y)) End If Me.ToolStripStatus2.Text = "Pan on Mouse Move" Me.ListEvents.Items.Add("Action: Pan on Mouse Move") End Sub 'This prints to the default printer and the image is printed in the top left corner at its native size Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage e.Graphics.DrawImage(PictureBox1.Image, e.MarginBounds.Left, e.MarginBounds.Top) End Sub 'Prints the document Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click Try PrintDocument1.Print() Me.ToolStripStatus2.Text = "Printing..." Me.ListEvents.Items.Add("Printing Picture...") Catch ex As Exception MessageBox.Show("No Capture or Image in PictureBox Area. Please Try Again!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.ListEvents.Items.Add("Fatal Error: Cannot Print. No Capture or Image in PictureBox Area!") Me.ToolStripStatus2.Text = "No Capture or Image in PictureBox Area" Finally End Try End Sub 'RotateFlip Image using buttons Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click 'Calls RotateFlip method of class Image Try PictureBox1.Image.RotateFlip(RotateFlipType.Rotate270FlipNone) PictureBox1.Invalidate() Dim tmp As Integer tmp = PictureBox1.Width PictureBox1.Width = PictureBox1.Height PictureBox1.Height = tmp Me.ToolStripStatus2.Text = "Picture Rotated Left" Me.ListEvents.Items.Add("Action: Picture Rotated Left") Catch ex As Exception MessageBox.Show("No Capture or Image in PictureBox Area. Please Try Again!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.ListEvents.Items.Add("Fatal Error:Cannot RotateFlip Left. No Capture or Image in PictureBox Area!") Me.ToolStripStatus2.Text = "No Capture or Image in PictureBox Area" Finally End Try End Sub Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click Try 'Calls RotateFlip method of class Image PictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipNone) 'Forces to repaint image PictureBox1.Invalidate() 'Swaps width * Height Dim tmp As Integer tmp = PictureBox1.Width PictureBox1.Width = PictureBox1.Height PictureBox1.Height = tmp Me.ToolStripStatus2.Text = "Picture Rotated Right" Me.ListEvents.Items.Add("Action: Picture Rotated Right") Catch ex As Exception MessageBox.Show("No Capture or Image in PictureBox Area. Please Try Again!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.ToolStripStatus2.Text = "No Capture or Image in PictureBox Area" Me.ListEvents.Items.Add("Fatal Error:Cannot RotateFlip Right. No Capture or Image in PictureBox Area!") Finally End Try End Sub 'Flip tool do not need to change dimensions of Image Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click Try PictureBox1.Image.RotateFlip(RotateFlipType.RotateNoneFlipX) PictureBox1.Invalidate() Me.ToolStripStatus2.Text = "Picture Flipped Horizontally" Me.ListEvents.Items.Add("Action: Picture Flipped Horizontally") Catch ex As Exception MessageBox.Show("No Capture or Image in PictureBox Area. Please Try Again!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.ToolStripStatus2.Text = "No Capture or Image in PictureBox Area" Me.ListEvents.Items.Add("Fatal Error:Cannot RotateFlip Horizontally. No Capture or Image in PictureBox Area!") Finally End Try End Sub Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click Try PictureBox1.Image.RotateFlip(RotateFlipType.RotateNoneFlipY) PictureBox1.Invalidate() Me.ToolStripStatus2.Text = "Picture Flipped Vertically" Me.ListEvents.Items.Add("Action: Picture Flipped Vertically") Catch ex As Exception MessageBox.Show("No Capture or Image in PictureBox Area. Please Try Again!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.ToolStripStatus2.Text = "No Capture or Image in PictureBox Area" Me.ListEvents.Items.Add("Fatal Error:Cannot RotateFlip Vertically. No Capture or Image in PictureBox Area!") Finally End Try End Sub Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click PictureBox1.Image = Nothing PictureBox1.BackColor = Color.Empty PictureBox1.Invalidate() Me.ToolStripStatus2.Text = "Picture Area reset" Me.ListEvents.Items.Add("Caution: Reset Picture Area!") End Sub End Class
Gochojr/Garam-Editor
frmScreenshotCapture.vb
Visual Basic
mit
10,680
Imports System.Data Partial Class CGS_fEntrada_Almacen 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 loComandoSeleccionar1 As New StringBuilder() loComandoSeleccionar1.AppendLine(" SELECT Recepciones.Usu_Cre ") loComandoSeleccionar1.AppendLine("FROM Recepciones") loComandoSeleccionar1.AppendLine(" JOIN Renglones_Recepciones") loComandoSeleccionar1.AppendLine(" ON Recepciones.Documento = Renglones_Recepciones.Documento") loComandoSeleccionar1.AppendLine(" JOIN Proveedores") loComandoSeleccionar1.AppendLine(" ON Recepciones.Cod_Pro = Proveedores.Cod_Pro") loComandoSeleccionar1.AppendLine(" JOIN Articulos ") loComandoSeleccionar1.AppendLine(" ON Articulos.Cod_Art = Renglones_Recepciones.Cod_Art") loComandoSeleccionar1.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) Dim loServicios1 As New cusDatos.goDatos Dim laDatosReporte1 As DataSet = loServicios1.mObtenerTodosSinEsquema(loComandoSeleccionar1.ToString, "usuario") Dim aString As String = laDatosReporte1.Tables(0).Rows(0).Item(0) aString = Trim(aString) Dim loComandoSeleccionar2 As New StringBuilder() loComandoSeleccionar2.AppendLine(" SELECT Nom_Usu ") loComandoSeleccionar2.AppendLine(" FROM Usuarios ") loComandoSeleccionar2.AppendLine(" WHERE Cod_Usu = '" & aString & "'") loComandoSeleccionar2.AppendLine(" AND Cod_Cli = " & goServicios.mObtenerCampoFormatoSQL(goCliente.pcCodigo)) Dim loServicios2 As New cusDatos.goDatos goDatos.pcNombreAplicativoExterno = "Framework" Dim laDatosReporte2 As DataSet = loServicios2.mObtenerTodosSinEsquema(loComandoSeleccionar2.ToString, "nombreUsuario") Dim aString2 As String = laDatosReporte2.Tables("nombreUsuario").Rows(0).Item(0) aString2 = RTrim(aString2) Dim loComandoSeleccionar3 As New StringBuilder() loComandoSeleccionar3.AppendLine("SELECT ROW_NUMBER() OVER (ORDER BY Registros.Fec_Ini) AS Num,*") loComandoSeleccionar3.AppendLine("FROM(SELECT Recepciones.Cod_Pro As Cod_Cli, ") loComandoSeleccionar3.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Recepciones.Nom_Pro = '') THEN Proveedores.Nom_Pro ELSE ") loComandoSeleccionar3.AppendLine(" (CASE WHEN (Recepciones.Nom_Pro = '') THEN Proveedores.Nom_Pro ELSE Recepciones.Nom_Pro END) END) AS Nom_Cli, ") loComandoSeleccionar3.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Recepciones.Nom_Pro = '') THEN Proveedores.Rif ELSE ") loComandoSeleccionar3.AppendLine(" (CASE WHEN (Recepciones.Rif = '') THEN Proveedores.Rif ELSE Recepciones.Rif END) END) AS Rif, ") loComandoSeleccionar3.AppendLine(" Proveedores.Nit, ") loComandoSeleccionar3.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Recepciones.Nom_Pro = '') THEN SUBSTRING(Proveedores.Dir_Fis,1, 200) ELSE ") loComandoSeleccionar3.AppendLine(" (CASE WHEN (SUBSTRING(Recepciones.Dir_Fis,1, 200) = '') THEN SUBSTRING(Proveedores.Dir_Fis,1, 200) ELSE SUBSTRING(Recepciones.Dir_Fis,1, 200) END) END) AS Dir_Fis, ") loComandoSeleccionar3.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Recepciones.Nom_Pro = '') THEN Proveedores.Telefonos ELSE ") loComandoSeleccionar3.AppendLine(" (CASE WHEN (Recepciones.Telefonos = '') THEN Proveedores.Telefonos ELSE Recepciones.Telefonos END) END) AS Telefonos, ") loComandoSeleccionar3.AppendLine(" Proveedores.Fax AS Fax, ") loComandoSeleccionar3.AppendLine(" Recepciones.Documento AS Documento,") loComandoSeleccionar3.AppendLine(" Recepciones.Fec_Ini AS Fec_Ini,") loComandoSeleccionar3.AppendLine(" Recepciones.Cod_Ven AS Cod_Ven, ") loComandoSeleccionar3.AppendLine(" Recepciones.Comentario AS Comentario,") loComandoSeleccionar3.AppendLine(" SUBSTRING(Vendedores.Nom_Ven,1,25) AS Nom_Ven, ") loComandoSeleccionar3.AppendLine(" RR.Cod_Art AS Cod_Art,") loComandoSeleccionar3.AppendLine(" Articulos.Nom_Art AS Nom_Art,") loComandoSeleccionar3.AppendLine(" Articulos.Generico AS Generico,") loComandoSeleccionar3.AppendLine(" RR.Notas AS Notas, ") loComandoSeleccionar3.AppendLine(" RR.Can_Art1 AS Cantidad,") loComandoSeleccionar3.AppendLine(" RR.Cod_Uni AS Cod_Uni,") loComandoSeleccionar3.AppendLine(" RR.Doc_Ori AS OC_Origen,") loComandoSeleccionar3.AppendLine(" CASE WHEN ((SELECT Renglones_OCompras.Can_Art1") loComandoSeleccionar3.AppendLine(" FROM Renglones_OCompras") loComandoSeleccionar3.AppendLine(" JOIN Renglones_Recepciones ON Renglones_OCompras.Documento = Renglones_Recepciones.Doc_Ori") loComandoSeleccionar3.AppendLine(" AND Renglones_OCompras.Renglon = Renglones_Recepciones.Ren_Ori") loComandoSeleccionar3.AppendLine(" WHERE Renglones_OCompras.Documento = RR.Doc_Ori") loComandoSeleccionar3.AppendLine(" AND Renglones_OCompras.Renglon = RR.Ren_Ori") loComandoSeleccionar3.AppendLine(" ) = RR.Can_Art1) THEN 'TOTAL' ELSE 'PARCIAL' END AS Entrega,") loComandoSeleccionar3.AppendLine(" '" & aString2 & "' AS Almacenista,") loComandoSeleccionar3.AppendLine(" Recepciones.Fec_Reg AS Fec_Rec") loComandoSeleccionar3.AppendLine("FROM Recepciones") loComandoSeleccionar3.AppendLine(" JOIN Renglones_Recepciones AS RR") loComandoSeleccionar3.AppendLine(" ON Recepciones.Documento = RR.Documento") loComandoSeleccionar3.AppendLine(" JOIN Proveedores") loComandoSeleccionar3.AppendLine(" ON Recepciones.Cod_Pro = Proveedores.Cod_Pro") loComandoSeleccionar3.AppendLine(" JOIN Formas_Pagos") loComandoSeleccionar3.AppendLine(" ON Recepciones.Cod_For = Formas_Pagos.Cod_For") loComandoSeleccionar3.AppendLine(" JOIN Vendedores") loComandoSeleccionar3.AppendLine(" ON Recepciones.Cod_Ven = Vendedores.Cod_Ven") loComandoSeleccionar3.AppendLine(" JOIN Articulos") loComandoSeleccionar3.AppendLine(" ON Articulos.Cod_Art = RR.Cod_Art ") loComandoSeleccionar3.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal & ") Registros ") 'Me.mEscribirConsulta(loComandoSeleccionar3.ToString) Dim loServicios3 As New cusDatos.goDatos Dim laDatosReporte3 As DataSet = loServicios3.mObtenerTodosSinEsquema(loComandoSeleccionar3.ToString, "curReportes") '------------------------------------------------------------------------------------------------------- ' Verificando si el select (tabla nº0) trae registros '------------------------------------------------------------------------------------------------------- If (laDatosReporte3.Tables(0).Rows.Count <= 0) Then Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _ "No se Encontraron Registros para los Parámetros Especificados. ", _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _ "350px", _ "200px") End If '--------------------------------------------------' ' Carga la imagen del logo en cusReportes ' '--------------------------------------------------' Me.mCargarLogoEmpresa(laDatosReporte3.Tables(0), "LogoEmpresa") loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("CGS_fEntrada_Almacen", laDatosReporte3) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvCGS_fRecepciones_Proveedores.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: 27/12/08: Codigo inicial '-------------------------------------------------------------------------------------------' ' CMS: 10/09/09: Se ajusto el nombre del articulo para los casos de aquellos articulos genericos '-------------------------------------------------------------------------------------------' ' CMS: 16/09/09: Se Agrego la distribucion de impuesto '-------------------------------------------------------------------------------------------' ' MAT: 01/03/11: Ajuste de la vista de diseño ' '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
CGS_fEntrada_Almacen.aspx.vb
Visual Basic
mit
10,284
Imports System.Net Imports System.IO Namespace IO Public Class FTP ''' <summary> ''' Shared method which will return a list of files from a ''' FTP Location ''' </summary> ''' <param name="ftpAddress"></param> ''' <param name="ftpUser"></param> ''' <param name="ftpPassword"></param> ''' <param name="ExceptionInfo"></param> ''' <returns>List(of string)</returns> ''' <remarks>ExceptionInfo will return any exception messages should a failure occur</remarks> Public Shared Function ListRemoteFiles(ftpAddress As String, ftpUser As String, ftpPassword As String, ExceptionInfo As Exception) As List(Of String) Dim ListOfFilesOnFTPSite As New List(Of String) Dim ftpRequest As FtpWebRequest = Nothing Dim ftpResponse As FtpWebResponse = Nothing Dim strReader As StreamReader = Nothing Dim sline As String = "" Try ftpRequest = CType(WebRequest.Create(ftpAddress), FtpWebRequest) With ftpRequest .Credentials = New NetworkCredential(ftpUser, ftpPassword) .Method = WebRequestMethods.Ftp.ListDirectory End With ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse) strReader = New StreamReader(ftpResponse.GetResponseStream) If strReader IsNot Nothing Then sline = strReader.ReadLine While sline IsNot Nothing ListOfFilesOnFTPSite.Add(sline) sline = strReader.ReadLine End While Catch ex As Exception ExceptionInfo = ex Finally If ftpResponse IsNot Nothing Then ftpResponse.Close() ftpResponse = Nothing End If If strReader IsNot Nothing Then strReader.Close() strReader = Nothing End If End Try ListRemoteFiles = ListOfFilesOnFTPSite ListOfFilesOnFTPSite = Nothing End Function ''' <summary> ''' Shared method which will download a single file to a target location ''' </summary> ''' <param name="ftpAddress"></param> ''' <param name="ftpUser"></param> ''' <param name="ftpPassword"></param> ''' <param name="fileToDownload"></param> ''' <param name="downloadTargetFolder"></param> ''' <param name="deleteAfterDownload"></param> ''' <param name="ExceptionInfo"></param> ''' <returns></returns> ''' <remarks>ExceptionInfo will return any exception messages should a failure occur</remarks> Public Shared Function DownloadSingleFile(ftpAddress As String, ftpUser As String, ftpPassword As String, fileToDownload As String, _ downloadTargetFolder As String, deleteAfterDownload As Boolean, ExceptionInfo As Exception) As Boolean Dim FileDownloaded As Boolean = False Try Dim sFtpFile As String = ftpAddress & fileToDownload Dim sTargetFileName = System.IO.Path.GetFileName(sFtpFile) sTargetFileName = sTargetFileName.Replace("/", "\") sTargetFileName = downloadTargetFolder & sTargetFileName My.Computer.Network.DownloadFile(sFtpFile, sTargetFileName, ftpUser, ftpPassword) If deleteAfterDownload Then Dim ftpRequest As FtpWebRequest = Nothing ftpRequest = CType(WebRequest.Create(sFtpFile), FtpWebRequest) With ftpRequest .Credentials = New NetworkCredential(ftpUser, ftpPassword) .Method = WebRequestMethods.Ftp.DeleteFile End With Dim response As FtpWebResponse = CType(ftpRequest.GetResponse(), FtpWebResponse) response.Close() ftpRequest = Nothing FileDownloaded = True End If Catch ex As Exception ExceptionInfo = ex End Try Return FileDownloaded End Function Public Shared Function UploadFTPFiles(ftpAddress As String, ftpUser As String, ftpPassword As String, fileToUpload As String, _ targetFileName As String, deleteAfterUpload As Boolean, ExceptionInfo As Exception) As Boolean Dim credential As NetworkCredential Try Dim s As String credential = New NetworkCredential(ftpUser, ftpPassword) If ftpAddress.EndsWith("/") = False Then ftpAddress = ftpAddress & "/" Dim request As FtpWebRequest = DirectCast(WebRequest.Create(d), FtpWebRequest) request.KeepAlive = False request.Method = WebRequestMethods.Ftp.UploadFile request.Credentials = credential request.UsePassive = False request.Timeout = (60 * 1000) * 3 '3 mins Using reader As New FileStream(SourceFile.Get(context), FileMode.Open) Dim buffer(Convert.ToInt32(reader.Length - 1)) As Byte reader.Read(buffer, 0, buffer.Length) reader.Close() request.ContentLength = buffer.Length Dim stream As Stream = request.GetRequestStream stream.Write(buffer, 0, buffer.Length) stream.Close() Using response As FtpWebResponse = DirectCast(request.GetResponse, FtpWebResponse) If deleteAfterUpload.Get(context) = True Then My.Computer.FileSystem.DeleteFile(SourceFile.Get(context)) End If response.Close() End Using End Using Catch ex As Exception Exceptions.HandleException(ex, Me.DisplayName) Finally End Try End Function End Class End Namespace
jpodon/CodeExplained
CExp.Core/CExp.Core/IO/FTP.vb
Visual Basic
mit
6,320
Public Class pdfedit End Class
MJGC-Jonathan/ComputerHelper
Computer Helper/Computer Helper/pdfedit.vb
Visual Basic
mit
34
Imports System.Windows.Forms Public Class ConfigurationProperties Public Property SelectedObject As Object Get Return PropertyGrid1.SelectedObject End Get Set(value As Object) PropertyGrid1.SelectedObject = value End Set End Property Private Sub OK_Button_Click(ByVal sender As Object, ByVal e As EventArgs) Handles OK_Button.Click Me.DialogResult = System.Windows.Forms.DialogResult.OK Me.Close() End Sub Private Sub Cancel_Button_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Cancel_Button.Click Me.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.Close() End Sub End Class
bofabcd/DevToolbar
ConfigurationProperties.vb
Visual Basic
mit
744
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("Domashno_1___Problem_1")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Microsoft")> <Assembly: AssemblyProduct("Domashno_1___Problem_1")> <Assembly: AssemblyCopyright("Copyright © Microsoft 2015")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("2a196a13-d94a-4608-9cc9-2d9458f27452")> ' 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")>
fr0wsTyl/TelerikAcademy-2015
Telerik - HTML/Homework evaluation/01. 2/Domashno 1 - Problem 1/Domashno 1 - Problem 1/My Project/AssemblyInfo.vb
Visual Basic
mit
1,179
Imports System.Runtime.InteropServices Imports System.Data Imports Extensibility Imports Microsoft.Office.Core Imports Excel = Microsoft.Office.Interop.Excel Imports Word = Microsoft.Office.Interop.Word Imports PowerPoint = Microsoft.Office.Interop.PowerPoint Imports System.Reflection Imports System.Drawing Imports System.IO #Region " Read me for Add-in installation and setup information. " ' When run, the Add-in wizard prepared the registry for the Add-in. ' At a later time, if the Add-in becomes unavailable for reasons such as: ' 1) You moved this project to a computer other than which is was originally created on. ' 2) You chose 'Yes' when presented with a message asking if you wish to remove the Add-in. ' 3) Registry corruption. ' you will need to re-register the Add-in by building the ColorBrewerAddinSetup project, ' right click the project in the Solution Explorer, then choose install. #End Region <GuidAttribute("017F85B5-99D0-4630-8371-80CD3F1D0324"), ProgIdAttribute("ColorBrewerAddin.Connect")> _ Public Class Addin Implements Extensibility.IDTExtensibility2, IRibbonExtensibility Private applicationObject As Object Private addInInstance As Object Private appExcel As Excel.Application Private appWord As Word.Application Private appPowerPoint As PowerPoint.Application Dim PalettesDataSet As New DataSet Dim PalettesDataTable As System.Data.DataTable Dim objShell As Object Public Sub OnBeginShutdown(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnBeginShutdown End Sub Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnAddInsUpdate End Sub Public Sub OnStartupComplete(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnStartupComplete End Sub Public Sub OnDisconnection(ByVal RemoveMode As Extensibility.ext_DisconnectMode, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnDisconnection End Sub Public Sub OnConnection(ByVal application As Object, ByVal connectMode As Extensibility.ext_ConnectMode, ByVal addInInst As Object, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnConnection applicationObject = application addInInstance = addInInst ''Load Palettes XML to datatable Dim thisAssembly As Assembly = GetType(Addin).Assembly Dim reader As New System.IO.StreamReader(thisAssembly.GetManifestResourceStream(thisAssembly.GetName.Name + ".Palettes.xml")) Try PalettesDataSet.ReadXml(reader) reader.Close() PalettesDataTable = PalettesDataSet.Tables(0) Catch e As Exception MsgBox("Unspecified Error.") End Try End Sub #Region "IRibbonExtensibility Members" Public Function GetCustomUI(ByVal RibbonID As String) As String Implements IRibbonExtensibility.GetCustomUI Return ReadString("RibbonUI.xml") End Function Public Sub OnAction(ByVal control As IRibbonControl, Optional ByVal PalId As Integer = 0) Try Select Case control.Id Case "About" MsgBox("Thanks for trying out the ColorBrewer Office Add-in!" _ & vbNewLine & vbNewLine & "Originally designed for use in cartography and GIS, the ColorBrewer project was developed by Cynthia Brewer, Professor of Geography at Penn State University. R users may recognize these palettes, as they are employed by Hadley Wickham's popular ggplot2 (via the RColorBrewer package created by Erich Neuwirth)." _ & vbNewLine & vbNewLine & "The goal of developing this add-in was to provide an easy way of using these palettes in Office charts, thereby enabling users to quickly venture beyond the default options." _ & vbNewLine & vbNewLine & "For more information, please visit the GitHub repository or the ColorBrewer website via the provided links." _ & vbNewLine & vbNewLine & vbNewLine & "v6.0 ColorBrewer Office Add-in developed by Scott Nicholson.") Case "Palettes" Select Case applicationObject.Name.ToString Case "Microsoft Excel" appExcel = applicationObject Call Excel_Sub(PalId, False) Case "Microsoft Word" appWord = applicationObject Call Word_Sub(PalId, False) Case "Microsoft PowerPoint" appPowerPoint = applicationObject Call PowerPoint_Sub(PalId, False) Case Else MsgBox("Error: This Office application is not supported.") End Select Case "Reverse_color_order" Select Case applicationObject.Name.ToString Case "Microsoft Excel" appExcel = applicationObject Call Excel_Sub(PalId, True) Case "Microsoft Word" appWord = applicationObject Call Word_Sub(PalId, True) Case "Microsoft PowerPoint" appPowerPoint = applicationObject Call PowerPoint_Sub(PalId, True) Case Else MsgBox("Error: This Office application is not supported.") End Select Case "Help" MsgBox("Thanks for trying out the ColorBrewer Office Add-in!" _ & vbNewLine & vbNewLine & vbNewLine & "To get started, select a chart and then choose either:" _ & vbNewLine & vbNewLine & "•""Choose a Palette"" to change the chart's color scheme, or" _ & vbNewLine & vbNewLine & "•""Reverse Color Order"" to reverse the chart's existing color scheme." _ & vbNewLine & vbNewLine & vbNewLine & "For more help, check out the GitHub page by clicking the ""GitHub"" button.") Case "GitHub" objShell = CreateObject("Wscript.Shell") objShell.Run("https://github.com/srnicholson/ColorBrewer-Office-Addin/") Case "ColorBrewerWebsite" objShell = CreateObject("Wscript.Shell") objShell.Run("http://colorbrewer2.org/") Case Else MsgBox("Unkown Control Id: " + control.Id, , "ColorBrewer Office Addin") End Select Catch throwedException As Exception MsgBox("Error: Unexpected state in ColorBrewer OnAction" + vbNewLine + "Error details: " + throwedException.Message) End Try End Sub #End Region #Region "ColorBrewer Methods" Public Sub Excel_Sub(ByVal PalId As Integer, ByVal reverse As Boolean) Dim chart As Excel.Chart Dim color_name As String color_name = PaletteID2Name(PalId) If appExcel.ActiveChart Is Nothing Then MsgBox("Error: No chart selected.") Exit Sub End If Try chart = appExcel.ActiveChart Call ColorBrewerFill(chart, color_name, reverse) Catch MsgBox("Unspecified Error.") End Try End Sub Public Sub Word_Sub(ByVal PalId As Integer, ByVal reverse As Boolean) Dim inline As Word.InlineShape Dim shape As Word.Shape Dim chart As Word.Chart Dim color_name As String Try color_name = PaletteID2Name(PalId) With appWord.ActiveWindow.Selection 'Determine if the selection is a regular shape or an inline shape (or not a chart) If .Type = 7 Then inline = .InlineShapes(1) shape = inline.ConvertToShape() ElseIf .Type = 8 Then shape = .ShapeRange(1) Else MsgBox("Error: No chart selected.") Exit Sub End If End With chart = shape.ConvertToInlineShape().Chart Call ColorBrewerFill(chart, color_name, reverse) Catch e As Exception MsgBox("Unknown Error.") End Try End Sub Public Sub PowerPoint_Sub(ByVal PalId As Integer, ByVal reverse As Boolean) Dim chart As PowerPoint.Chart Dim color_name As String color_name = PaletteID2Name(PalId) Try chart = appPowerPoint.ActiveWindow.Selection.ShapeRange(1).Chart Catch MsgBox("Error: No chart selected.") Exit Sub End Try Try Call ColorBrewerFill(chart, color_name, reverse) Catch MsgBox("Unspecified Error.") End Try End Sub Sub ColorBrewerFill(ByRef chart As Object, ByVal pal As String, ByVal reverse As Boolean) Dim palette As Array Dim series_count As Integer Dim rgb_color As Long Dim i As Integer Dim old_colors As New ArrayList With chart series_count = .SeriesCollection.Count Select Case CType(.ChartType, XlChartType) 'Chart types enumerated here: https://msdn.microsoft.com/en-us/library/office/ff838409.aspx Case XlChartType.xlXYScatter, XlChartType.xlXYScatterLines, XlChartType.xlXYScatterSmooth, XlChartType.xlLineMarkers, XlChartType.xlLineMarkersStacked, XlChartType.xlLineMarkersStacked100, XlChartType.xlRadarMarkers 'Points, Lines optional Case If Not reverse Then palette = GetPaletteData(pal, series_count) If BlankPalette(palette) Then Exit Sub End If old_colors = GetChartRGBs(chart, XlChartType.xlXYScatter) For i = 1 To series_count If reverse Then rgb_color = CType(old_colors(series_count - i), Long) Else rgb_color = RGB(palette(i - 1)(2), palette(i - 1)(3), palette(i - 1)(4)) End If With .SeriesCollection(i) 'MsgBox("Changing color: " & old_colors(i - 1) & " in series " & i & ".") .MarkerForegroundColor = rgb_color .MarkerBackgroundColor = rgb_color If .Format.Line.Visible = True Then .Format.Line.ForeColor.RGB = rgb_color End If End With Next Case XlChartType.xlLine, XlChartType.xlLineStacked, XlChartType.xlRadar, XlChartType.xlXYScatterLinesNoMarkers, XlChartType.xlXYScatterSmoothNoMarkers, XlChartType.xlLineStacked100 'Line Only Case If Not reverse Then palette = GetPaletteData(pal, series_count) If BlankPalette(palette) Then Exit Sub Else old_colors = GetChartRGBs(chart, XlChartType.xlLine) End If For i = 1 To series_count 'MsgBox("Changing color: " & old_colors(i - 1) & " in series " & i & ".") If reverse Then rgb_color = old_colors(series_count - i) Else rgb_color = RGB(palette(i - 1)(2), palette(i - 1)(3), palette(i - 1)(4)) End If With .SeriesCollection(i) .Format.Line.Visible = False .Format.Line.Visible = True .Format.Line.ForeColor.RGB = rgb_color End With Next Case XlChartType.xl3DArea, XlChartType.xl3DAreaStacked, XlChartType.xl3DAreaStacked100, _ XlChartType.xl3DBarClustered, XlChartType.xl3DBarStacked, XlChartType.xl3DBarStacked100, _ XlChartType.xlBubble, XlChartType.xlBubble3DEffect, XlChartType.xl3DColumn, _ XlChartType.xl3DLine, XlChartType.xl3DColumnClustered, XlChartType.xl3DColumnStacked, _ XlChartType.xl3DColumnStacked100, XlChartType.xlArea, XlChartType.xlAreaStacked, _ XlChartType.xlAreaStacked100, XlChartType.xlBarClustered, XlChartType.xlBarStacked, _ XlChartType.xlBarStacked100, XlChartType.xlColumnClustered, XlChartType.xlColumnStacked, _ XlChartType.xlColumnStacked100, XlChartType.xlConeBarClustered, XlChartType.xlConeBarStacked, _ XlChartType.xlConeBarStacked100, XlChartType.xlConeCol, XlChartType.xlConeColClustered, _ XlChartType.xlConeColStacked, XlChartType.xlConeColStacked100, XlChartType.xlCylinderBarClustered, _ XlChartType.xlCylinderBarStacked, XlChartType.xlCylinderBarStacked100, XlChartType.xlCylinderCol, _ XlChartType.xlCylinderColClustered, XlChartType.xlCylinderColStacked, XlChartType.xlCylinderColStacked100, _ XlChartType.xlPyramidBarClustered, XlChartType.xlPyramidBarStacked, XlChartType.xlPyramidBarStacked100, _ XlChartType.xlPyramidCol, XlChartType.xlPyramidColClustered, XlChartType.xlPyramidColStacked, _ XlChartType.xlPyramidColStacked100, XlChartType.xlRadarFilled 'Area Case Dim old_spacing As String 'prevent column spacing from changing during color change old_spacing = .ChartGroups(1).Overlap If Not reverse Then palette = GetPaletteData(pal, series_count) If BlankPalette(palette) Then Exit Sub Else old_colors = GetChartRGBs(chart, XlChartType.xlColumnClustered) End If For i = 1 To series_count 'MsgBox("Changing color: " & old_colors(i - 1) & " in series " & i & ".") If reverse Then rgb_color = old_colors(series_count - i) Else rgb_color = RGB(palette(i - 1)(2), palette(i - 1)(3), palette(i - 1)(4)) End If With .SeriesCollection(i) .Interior.Color = rgb_color '.Border.Color = rgb_color End With Next 'prevent column spacing from changing during color change .ChartGroups(1).Overlap = old_spacing Case XlChartType.xl3DPie, XlChartType.xl3DPieExploded, XlChartType.xlDoughnut, XlChartType.xlDoughnutExploded, XlChartType.xlPie 'Pie Case Dim j As Integer Dim counter As Integer = 0 If reverse Then old_colors = GetChartRGBs(chart, XlChartType.xlPie) End If For i = 1 To series_count With .SeriesCollection(i) If Not reverse Then palette = GetPaletteData(pal, .Points.Count) If BlankPalette(palette) Then Exit Sub End If For j = 1 To .Points.Count If reverse Then rgb_color = old_colors(.Points.Count * series_count - counter - 1) counter = counter + 1 Else rgb_color = RGB(palette(j - 1)(2), palette(j - 1)(3), palette(j - 1)(4)) End If With .Points(j) .Interior.Color = rgb_color '.Border.Color = rgb_color End With Next End With Next Case Else MsgBox("Error: Graph type not supported.", vbOKOnly) End Select End With End Sub Private Function GetPaletteData(pal As String, NumColors As Integer) As Array Dim filter As String filter = "[C] = '" + pal + "' AND [N] = '" + NumColors.ToString + "'" Try Return PalettesDataTable.Select(filter) Catch e As Exception MsgBox("Error: Invalid GetPaletteData function query") Return Nothing End Try End Function Private Function BlankPalette(palette As Array) As Boolean If palette.Length = 0 Then MsgBox("Error: The chart's series count is outside the range for this palette." & vbNewLine & _ "Try a different palette or change the number of series in the chart." & vbNewLine & vbNewLine & _ "Tip: Valid ranges for each palette are listed in the 'Choose a Palette' drop-down menu.") Return True Else Return False End If End Function Private Function GetChartRGBs(ByVal chart As Object, ByVal type As XlChartType) As ArrayList 'Returns ArrayList of RGB (BGR?) values corresponding to each series in the chart 'Workaround for getting automatic colors for non-column charts is based on the 'clever solution by David Zemens on Stack Overflow here: http://stackoverflow.com/a/25826428 Dim chtType As Long Dim colors As New ArrayList Dim fill_value As Long Dim counter As Integer chtType = chart.ChartType 'Select correct SeriesCollection fill value based on xlChartType Select Case type Case XlChartType.xlXYScatter fill_value = chart.SeriesCollection(1).MarkerForegroundColor Case XlChartType.xlColumnClustered fill_value = chart.SeriesCollection(1).Format.Fill.ForeColor.RGB Case XlChartType.xlLine If chart.SeriesCollection(1).Format.Line.ForeColor.RGB = 16777215 Then '16777215 appears to be what automatic line color is in Office 2007 fill_value = -1 Else fill_value = chart.SeriesCollection(1).Format.Line.ForeColor.RGB End If Case XlChartType.xlPie fill_value = chart.SeriesCollection(1).Points(1).Interior.Color Case Else fill_value = 9999 'Throw error End Select 'ONLY changes to column plot IF the series fill type is automatic 'Otherwise, custom colors (such as from a previous ColorBrewer run) will be lost. If fill_value <= 0 Then 'Temporarily change chart type to "column" in order to extract automatic RGB values chart.ChartType = 51 For Each srs In chart.SeriesCollection colors.Add(srs.Format.Fill.ForeColor.RGB) Next Else Select Case type Case XlChartType.xlXYScatter For Each srs In chart.SeriesCollection colors.Add(srs.MarkerForegroundColor) Next Case XlChartType.xlColumnClustered For Each srs In chart.SeriesCollection colors.Add(srs.Format.Fill.ForeColor.RGB) Next Case XlChartType.xlLine For Each srs In chart.SeriesCollection colors.Add(srs.Format.Line.ForeColor.RGB) Next Case XlChartType.xlPie For Each srs In chart.SeriesCollection For Each point In srs.Points colors.Add(point.Interior.Color) Next Next Case Else MsgBox("Error: unable to extract original series colors") End Select End If chart.ChartType = chtType Return colors End Function #End Region #Region "XML Methods" ' Modified from https://github.com/NetOfficeFw/NetOffice/blob/master/Examples/Misc/VB/COMAddin%20Examples/SuperAddin/Addin.vb#L192 Private Shared Function ReadString(ByVal fileName As String) As String Dim thisAssembly As Assembly = GetType(Addin).Assembly Dim resourceStream As Stream = thisAssembly.GetManifestResourceStream(thisAssembly.GetName().Name + "." + fileName) If (IsNothing(resourceStream)) Then Throw (New IOException("Error accessing resource Stream.")) End If Dim textStreamReader As StreamReader = New StreamReader(resourceStream) If (IsNothing(textStreamReader)) Then Throw (New IOException("Error accessing resource File.")) End If Dim text As String = textStreamReader.ReadToEnd() resourceStream.Close() textStreamReader.Close() Return text End Function #End Region #Region "Gallery Callbacks" Private itemCount As Integer = 35 ' Used with GetItemCount. Private itemHeight As Integer = 22 ' Used with GetItemHeight. Private itemWidth As Integer = 182 ' Used with GetItemWidth. Public Function LoadImage(ByVal imageName As String) As Bitmap Dim thisAssembly As Assembly = GetType(Addin).Assembly Dim stream As Stream = thisAssembly.GetManifestResourceStream(thisAssembly.GetName().Name + "." + imageName) Return New Bitmap(stream) End Function Public Function GetLabel(ByVal control As IRibbonControl) As String Dim strText As String Select Case control.Id Case "Palettes" : strText = "Choose a Palette:" End Select Return strText End Function Public Function GetShowImage(ByVal control As IRibbonControl) As Boolean Return True End Function Public Function GetShowLabel(ByVal control As IRibbonControl) As Boolean Return True End Function Public Function GetItemImage(ByVal control As IRibbonControl, ByVal itemIndex As Integer) As Bitmap Dim imageName As String imageName = PaletteID2Name(itemIndex) & ".png" Dim thisAssembly As Assembly = GetType(Addin).Assembly Dim stream As Stream = thisAssembly.GetManifestResourceStream(thisAssembly.GetName().Name + "." + imageName) Return New Bitmap(stream) End Function Public Function GetSize(ByVal control As IRibbonControl) As RibbonControlSize Select Case control.Id Case "Palettes" : Return RibbonControlSize.RibbonControlSizeLarge End Select End Function Public Function GetEnabled(ByVal control As IRibbonControl) As Boolean Select Case control.Id Case "Palettes" Return True Case Else Return True End Select End Function Public Function GetItemCount(ByVal control As IRibbonControl) As Integer Return itemCount End Function Public Function getItemHeight(ByVal control As IRibbonControl) As Integer Return itemHeight End Function Public Function getItemWidth(ByVal control As IRibbonControl) As Integer Return itemWidth End Function Public Function getItemLabel(ByVal control As IRibbonControl, ByVal id As String) As String Select Case id Case 0 : Return "Accent (3 - 8)" Case 1 : Return "Blues (3 - 9)" Case 2 : Return "BrBG (3 - 11)" Case 3 : Return "BuGn (3 - 9)" Case 4 : Return "BuPu (3 - 9)" Case 5 : Return "Dark2 (3 - 8)" Case 6 : Return "GnBu (3 - 9)" Case 7 : Return "Greens (3 - 9)" Case 8 : Return "Greys (3 - 9)" Case 9 : Return "Oranges (3 - 9)" Case 10 : Return "OrRd (3 - 9)" Case 11 : Return "Paired (3 - 12)" Case 12 : Return "Pastel1 (3 - 9)" Case 13 : Return "Pastel2 (3 - 8)" Case 14 : Return "PiYG (3 - 11)" Case 15 : Return "PRGn (3 - 11)" Case 16 : Return "PuBu (3 - 9)" Case 17 : Return "PuBuGn (3 - 9)" Case 18 : Return "PuOr (3 - 11)" Case 19 : Return "PuRd (3 - 9)" Case 20 : Return "Purples (3 - 9)" Case 21 : Return "RdBu (3 - 11)" Case 22 : Return "RdGy (3 - 11)" Case 23 : Return "RdPu (3 - 9)" Case 24 : Return "Reds (3 - 9)" Case 25 : Return "RdYlBu (3 - 11)" Case 26 : Return "RdYlGn (3 - 11)" Case 27 : Return "Set1 (3 - 9)" Case 28 : Return "Set2 (3 - 8)" Case 29 : Return "Set3 (3 - 12)" Case 30 : Return "Spectral (3 - 11)" Case 31 : Return "YlGn (3 - 9)" Case 32 : Return "YlGnBu (3 - 9)" Case 33 : Return "YlOrBr (3 - 9)" Case 34 : Return "YlOrRd (3 - 9)" End Select End Function Function PaletteID2Name(index As Integer) As String Select Case index Case 0 : Return "Accent" Case 1 : Return "Blues" Case 2 : Return "BrBG" Case 3 : Return "BuGn" Case 4 : Return "BuPu" Case 5 : Return "Dark2" Case 6 : Return "GnBu" Case 7 : Return "Greens" Case 8 : Return "Greys" Case 9 : Return "Oranges" Case 10 : Return "OrRd" Case 11 : Return "Paired" Case 12 : Return "Pastel1" Case 13 : Return "Pastel2" Case 14 : Return "PiYG" Case 15 : Return "PRGn" Case 16 : Return "PuBu" Case 17 : Return "PuBuGn" Case 18 : Return "PuOr" Case 19 : Return "PuRd" Case 20 : Return "Purples" Case 21 : Return "RdBu" Case 22 : Return "RdGy" Case 23 : Return "RdPu" Case 24 : Return "Reds" Case 25 : Return "RdYlBu" Case 26 : Return "RdYlGn" Case 27 : Return "Set1" Case 28 : Return "Set2" Case 29 : Return "Set3" Case 30 : Return "Spectral" Case 31 : Return "YlGn" Case 32 : Return "YlGnBu" Case 33 : Return "YlOrBr" Case 34 : Return "YlOrRd" End Select End Function Public Function GetItemScreenTip(ByVal control As IRibbonControl, ByVal index As Integer) As String End Function Public Function GetItemSuperTip(ByVal control As IRibbonControl, ByVal index As Integer) As String End Function Public Function GetKeyTip(ByVal control As IRibbonControl) As String End Function Public Function GetSuperTip(ByVal control As IRibbonControl) As String Select Case control.Id Case "About" : Return "Click to learn more about the ColorBrewer Add-in." Case "Palettes" : Return "Click to open the palette gallery." Case "Reverse_color_order" : Return "Click to reverse the color order of the selected chart." Case "Help" : Return "Click for help using the ColorBrewer Add-in." Case "GitHub" : Return "Click to go to the ColorBrewer Add-in code repository on GitHub." + vbCrLf + vbCrLf + "https://github.com/srnicholson/ColorBrewer-Office-Addin/" Case "ColorBrewerWebsite" : Return "Click to go to the ColorBrewer website." + vbCrLf + vbCrLf + "http://colorbrewer2.org/" End Select End Function Public Sub galleryOnAction(ByVal control As IRibbonControl, ByVal selectedId As String, _ ByVal selectedIndex As Integer) OnAction(control, selectedIndex) End Sub #End Region End Class
srnicholson/ColorBrewer-Office-Addin
ColorBrewerAddin/Addin.vb
Visual Basic
apache-2.0
28,442
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.DocumentationComments Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.DocumentationComments Public Class DocumentationCommentTests Inherits AbstractDocumentationCommentTests <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_Class() Const code = " ''$$ Class C End Class " Const expected = " ''' <summary> ''' $$ ''' </summary> Class C End Class " VerifyTypingCharacter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_Method() Const code = " Class C ''$$ Function M(Of T)(foo As Integer, i() As Integer) As Integer Return 0 End Function End Class " Const expected = " Class C ''' <summary> ''' $$ ''' </summary> ''' <typeparam name=""T""></typeparam> ''' <param name=""foo""></param> ''' <param name=""i""></param> ''' <returns></returns> Function M(Of T)(foo As Integer, i() As Integer) As Integer Return 0 End Function End Class " VerifyTypingCharacter(code, expected) End Sub <WorkItem(538715)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NoReturnType() Const code = " Class C ''$$ Function F() End Function End Class " Const expected = " Class C ''' <summary> ''' $$ ''' </summary> ''' <returns></returns> Function F() End Function End Class " VerifyTypingCharacter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NotWhenDocCommentExists1() Const code = " ''$$ ''' <summary></summary> Class C End Class " Const expected = " '''$$ ''' <summary></summary> Class C End Class " VerifyTypingCharacter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NotWhenDocCommentExists2() Const code = " Class C ''$$ ''' <summary></summary> Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " Const expected = " Class C '''$$ ''' <summary></summary> Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " VerifyTypingCharacter(code, expected) End Sub <WorkItem(537506)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NotAfterClassName() Const code = " Class C''$$ End Class " Const expected = " Class C'''$$ End Class " VerifyTypingCharacter(code, expected) End Sub <WorkItem(537508)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NotInsideClass() Const code = " Class C ''$$ End Class " Const expected = " Class C '''$$ End Class " VerifyTypingCharacter(code, expected) End Sub <WorkItem(537510)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NotAfterConstructorName() Const code = " Class C Sub New() ''$$ End Class " Const expected = " Class C Sub New() '''$$ End Class " VerifyTypingCharacter(code, expected) End Sub <WorkItem(537511)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NotInsideConstructor() Const code = " Class C Sub New() ''$$ End Sub End Class " Const expected = " Class C Sub New() '''$$ End Sub End Class " VerifyTypingCharacter(code, expected) End Sub <WorkItem(537512)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NotInsideMethodBody() Const code = " Class C Sub Foo() ''$$ End Sub End Class " Const expected = " Class C Sub Foo() '''$$ End Sub End Class " VerifyTypingCharacter(code, expected) End Sub <WorkItem(540004)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TypingCharacter_NoReturnsOnWriteOnlyProperty() Const code = " Class C ''$$ WriteOnly Property Prop As Integer Set(ByVal value As Integer End Set End Property End Class " Const expected = " Class C ''' <summary> ''' $$ ''' </summary> WriteOnly Property Prop As Integer Set(ByVal value As Integer End Set End Property End Class " VerifyTypingCharacter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Class1() Const code = " '''$$ Class C End Class " Const expected = " ''' <summary> ''' $$ ''' </summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Class2() Const code = " '''$$Class C End Class " Const expected = " ''' <summary> ''' $$ ''' </summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Class3() Const code = " '''$$<Foo()> Class C End Class " Const expected = " ''' <summary> ''' $$ ''' </summary> <Foo()> Class C End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(538717)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Module() Const code = " '''$$Module M Dim x As Integer End Module " Const expected = " ''' <summary> ''' $$ ''' </summary> Module M Dim x As Integer End Module " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Method1() Const code = " Class C '''$$ Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " Const expected = " Class C ''' <summary> ''' $$ ''' </summary> ''' <typeparam name=""T""></typeparam> ''' <param name=""foo""></param> ''' <returns></returns> Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Method2() Const code = " Class C '''$$Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " Const expected = " Class C ''' <summary> ''' $$ ''' </summary> ''' <typeparam name=""T""></typeparam> ''' <param name=""foo""></param> ''' <returns></returns> Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InsertApostrophes1() Const code = " '''$$ ''' <summary></summary> Class C End Class " Const expected = " ''' ''' $$ ''' <summary></summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InsertApostrophes2() Const code = " ''' <summary> ''' $$ ''' </summary> Class C End Class " Const expected = " ''' <summary> ''' ''' $$ ''' </summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InsertApostrophes3() Const code = " ''' <summary>$$</summary> Class C End Class " Const expected = " ''' <summary> ''' $$</summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InsertApostrophes4() Const code = " '''$$ ''' <summary></summary> Class C End Class " Const expected = " ''' ''' $$ ''' <summary></summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InsertApostrophes5() Const code = " ''' <summary> ''' $$ ''' </summary> Class C End Class " Const expected = " ''' <summary> ''' ''' $$ ''' </summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InsertApostrophes6() Const code = " ''' <summary>$$</summary> Class C End Class " Const expected = " ''' <summary> ''' $$</summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InsertApostrophes7() Const code = " Class C '''$$ ''' <summary></summary> Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " Const expected = " Class C ''' ''' $$ ''' <summary></summary> Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(540017)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InsertApostrophes8() Const code = " ''' <summary></summary>$$ Class C End Class " Const expected = " ''' <summary></summary> ''' $$ Class C End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(540017)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_DontInsertApostrophes1() Const code = " ''' <summary></summary> ''' $$ Class C End Class " Const expected = " ''' <summary></summary> ''' $$ Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_NotInsideConstructor() Const code = " Class C Sub New() '''$$ End Sub End Class " Const expected = " Class C Sub New() ''' $$ End Sub End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(537534)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_NotInsideMethodBody() Const code = " Class C Sub Foo() '''$$ End Sub End Class " Const expected = " Class C Sub Foo() ''' $$ End Sub End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(537550)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_NotBeforeDocComment() Const code = " Class c1 $$''' <summary> ''' ''' </summary> ''' <returns></returns> Public Sub Foo() Dim x = 1 End Sub End Class " Const expected = " Class c1 $$''' <summary> ''' ''' </summary> ''' <returns></returns> Public Sub Foo() Dim x = 1 End Sub End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(2091, "https://github.com/dotnet/roslyn/issues/2091")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_InTextBeforeSpace() Const code = " Class C ''' <summary> ''' hello$$ world ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' hello ''' $$world ''' </summary> Sub M() End Sub End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Indentation1() Const code = " Class C ''' <summary> ''' hello world$$ ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' hello world ''' $$ ''' </summary> Sub M() End Sub End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Indentation2() Const code = " Class C ''' <summary> ''' hello $$world ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' hello ''' $$world ''' </summary> Sub M() End Sub End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Indentation3() Const code = " Class C ''' <summary> ''' hello$$ world ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' hello ''' $$world ''' </summary> Sub M() End Sub End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Indentation4() Const code = " Class C ''' <summary> ''' $$hello world ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' ''' $$hello world ''' </summary> Sub M() End Sub End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Indentation5_UseTabs() Const code = " Class C ''' <summary> ''' hello world$$ ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' hello world ''' $$ ''' </summary> Sub M() End Sub End Class " VerifyPressingEnter(code, expected, useTabs:=True) End Sub <WorkItem(5486, "https://github.com/dotnet/roslyn/issues/5486")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Selection1() Const code = " ''' <summary> ''' Hello [|World|]$$! ''' </summary> Class C End Class " Const expected = " ''' <summary> ''' Hello ''' $$! ''' </summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <WorkItem(5486, "https://github.com/dotnet/roslyn/issues/5486")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub PressingEnter_Selection2() Const code = " ''' <summary> ''' Hello $$[|World|]! ''' </summary> Class C End Class " Const expected = " ''' <summary> ''' Hello ''' $$! ''' </summary> Class C End Class " VerifyPressingEnter(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub Command_Class() Const code = " Class C $$ End Class " Const expected = " ''' <summary> ''' $$ ''' </summary> Class C End Class " VerifyInsertCommentCommand(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub Command_Class_NotIfCommentExists() Const code = " ''' <summary></summary> Class C $$ End Class " Const expected = " ''' <summary></summary> Class C $$ End Class " VerifyInsertCommentCommand(code, expected) End Sub <WorkItem(538715)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub Command_Method1() Const code = " Class C Function F()$$ End Function End Class " Const expected = " Class C ''' <summary> ''' $$ ''' </summary> ''' <returns></returns> Function F() End Function End Class " VerifyInsertCommentCommand(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub Command_Method2() Const code = " Class C Function M(Of T)(foo As Integer) As Integer $$Return 0 End Function End Class " Const expected = " Class C ''' <summary> ''' $$ ''' </summary> ''' <typeparam name=""T""></typeparam> ''' <param name=""foo""></param> ''' <returns></returns> Function M(Of T)(foo As Integer) As Integer Return 0 End Function End Class " VerifyInsertCommentCommand(code, expected) End Sub <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub Command_Method_NotIfCommentExists() Const code = " Class C ''' <summary></summary> Function M(Of T)(foo As Integer) As Integer $$Return 0 End Function End Class " Const expected = " Class C ''' <summary></summary> Function M(Of T)(foo As Integer) As Integer $$Return 0 End Function End Class " VerifyInsertCommentCommand(code, expected) End Sub <WorkItem(538482)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub Command_FirstModuleOnLine() Const code = " $$Module M : End Module : Module N : End Module " Const expected = " ''' <summary> ''' $$ ''' </summary> Module M : End Module : Module N : End Module " VerifyInsertCommentCommand(code, expected) End Sub <WorkItem(538482)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub Command_NotOnSecondModuleOnLine() Const code = "Module M : End Module : $$Module N : End Module" Const expected = "Module M : End Module : $$Module N : End Module" VerifyInsertCommentCommand(code, expected) End Sub <WorkItem(538482)> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub Command_FirstPropertyOnLine() Const code = " Module M Property $$i As Integer : Property j As Integer End Module " Const expected = " Module M ''' <summary> ''' $$ ''' </summary> ''' <returns></returns> Property i As Integer : Property j As Integer End Module " VerifyInsertCommentCommand(code, expected) End Sub <WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TestOpenLineAbove1() Const code = " Class C ''' <summary> ''' stuff$$ ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' $$ ''' stuff ''' </summary> Sub M() End Sub End Class " VerifyOpenLineAbove(code, expected) End Sub <WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TestOpenLineAbove2() Const code = " Class C ''' <summary> ''' $$stuff ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' $$ ''' stuff ''' </summary> Sub M() End Sub End Class " VerifyOpenLineAbove(code, expected) End Sub <WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TestOpenLineAbove3() Const code = " Class C ''' $$<summary> ''' stuff ''' </summary> Sub M() End Sub End Class " ' Note that the caret position specified below does Not look correct because ' it Is in virtual space in this case. Const expected = " Class C $$ ''' <summary> ''' stuff ''' </summary> Sub M() End Sub End Class " VerifyOpenLineAbove(code, expected) End Sub <WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TestOpenLineAbove4_Tabs() Const code = " Class C ''' <summary> ''' $$stuff ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' $$ ''' stuff ''' </summary> Sub M() End Sub End Class " VerifyOpenLineAbove(code, expected, useTabs:=True) End Sub <WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TestOpenLineBelow1() Const code = " Class C ''' <summary> ''' stuff$$ ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' stuff ''' $$ ''' </summary> Sub M() End Sub End Class " VerifyOpenLineBelow(code, expected) End Sub <WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TestOpenLineBelow2() Const code = " Class C ''' <summary> ''' $$stuff ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' stuff ''' $$ ''' </summary> Sub M() End Sub End Class " VerifyOpenLineBelow(code, expected) End Sub <WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TestOpenLineBelow3() Const code = " ''' <summary> ''' stuff ''' $$</summary>" Const expected = " ''' <summary> ''' stuff ''' </summary> ''' $$" VerifyOpenLineBelow(code, expected) End Sub <WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")> <Fact, Trait(Traits.Feature, Traits.Features.DocumentationComments)> Public Sub TestOpenLineBelow4_Tabs() Const code = " Class C ''' <summary> ''' $$stuff ''' </summary> Sub M() End Sub End Class " Const expected = " Class C ''' <summary> ''' stuff ''' $$ ''' </summary> Sub M() End Sub End Class " VerifyOpenLineBelow(code, expected, useTabs:=True) End Sub Friend Overrides Function CreateCommandHandler( waitIndicator As IWaitIndicator, undoHistoryRegistry As ITextUndoHistoryRegistry, editorOperationsFactoryService As IEditorOperationsFactoryService, completionService As IAsyncCompletionService) As ICommandHandler Return New DocumentationCommentCommandHandler(waitIndicator, undoHistoryRegistry, editorOperationsFactoryService, completionService) End Function Protected Overrides Function CreateTestWorkspace(code As String) As TestWorkspace Return VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code) End Function Protected Overrides ReadOnly Property DocumentationCommentCharacter As Char Get Return "'"c End Get End Property End Class End Namespace
grianggrai/roslyn
src/EditorFeatures/VisualBasicTest/DocumentationComments/DocumentationCommentTests.vb
Visual Basic
apache-2.0
25,881
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.17626 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System '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()> _ Public Class AppResources Private Shared resourceMan As Global.System.Resources.ResourceManager Private Shared resourceCulture As Global.System.Globalization.CultureInfo <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend Sub New() MyBase.New End Sub '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Public Shared 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("ParsePhoneStarterProject.AppResources", GetType(AppResources).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)> _ Public Shared Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property '''<summary> ''' Looks up a localized string similar to LeftToRight. '''</summary> Public Shared ReadOnly Property ResourceFlowDirection() As String Get Return ResourceManager.GetString("ResourceFlowDirection", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to us-EN. '''</summary> Public Shared ReadOnly Property ResourceLanguage() As String Get Return ResourceManager.GetString("ResourceLanguage", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to MY APPLICATION. '''</summary> Public Shared ReadOnly Property ApplicationTitle() As String Get Return ResourceManager.GetString("ApplicationTitle", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to button. '''</summary> Public Shared ReadOnly Property AppBarButtonText() As String Get Return ResourceManager.GetString("AppBarButtonText", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to Menu Item. '''</summary> Public Shared ReadOnly Property AppBarMenuItemText() As String Get Return ResourceManager.GetString("AppBarMenuItemText", resourceCulture) End Get End Property End Class
AmeliaMesdag/Parse-SDK-dotNET
Parse.StarterProjects/VB/ParsePhoneStarterProject/ParsePhoneStarterProject/Resources/AppResources.Designer.vb
Visual Basic
bsd-3-clause
4,096
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Backstop that forms the end of the binder chain. Does nothing, and should never actually get hit. Provides ''' asserts that methods never get called. ''' </summary> Friend NotInheritable Class BackstopBinder Inherits Binder Public Sub New() MyBase.New(Nothing) End Sub Public Overrides Function CheckAccessibility(sym As Symbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo), Optional accessThroughType As TypeSymbol = Nothing, Optional basesBeingResolved As ConsList(Of Symbol) = Nothing) As AccessCheckResult Throw ExceptionUtilities.Unreachable End Function Public Overrides Function GetBinder(node As SyntaxNode) As Binder Throw ExceptionUtilities.Unreachable End Function Public Overrides Function GetBinder(stmtList As SyntaxList(Of StatementSyntax)) As Binder Throw ExceptionUtilities.Unreachable End Function Public Overrides ReadOnly Property ImplicitlyTypedLocalsBeingBound As ConsList(Of LocalSymbol) Get Return ConsList(Of LocalSymbol).Empty End Get End Property ''' <summary> ''' Returns true if the node is in a position where an unbound type ''' such as (C(of)) is allowed. ''' </summary> Public Overrides Function IsUnboundTypeAllowed(syntax As GenericNameSyntax) As Boolean Return False End Function Public Overrides ReadOnly Property ContainingMember As Symbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsInQuery As Boolean Get ' we should stop at the method or type binder. Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property ContainingNamespaceOrType As NamespaceOrTypeSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides Function GetSyntaxReference(node As VisualBasicSyntaxNode) As SyntaxReference Throw ExceptionUtilities.Unreachable End Function Protected Overrides Function CreateBoundWithBlock(node As WithBlockSyntax, boundBlockBinder As Binder, diagnostics As DiagnosticBag) As BoundStatement Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function BindInsideCrefAttributeValue(name As TypeSyntax, preserveAliases As Boolean, diagnosticBag As DiagnosticBag, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Friend Overrides Function BindInsideCrefAttributeValue(reference As CrefReferenceSyntax, preserveAliases As Boolean, diagnosticBag As DiagnosticBag, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Friend Overrides Function BindXmlNameAttributeValue(identifier As IdentifierNameSyntax, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Protected Friend Overrides Function TryBindOmittedLeftForMemberAccess(node As MemberAccessExpressionSyntax, diagnostics As DiagnosticBag, accessingBinder As Binder, <Out> ByRef wholeMemberAccessExpressionBound As Boolean) As BoundExpression Return Nothing End Function Protected Overrides Function TryBindOmittedLeftForDictionaryAccess(node As MemberAccessExpressionSyntax, accessingBinder As Binder, diagnostics As DiagnosticBag) As BoundExpression Return Nothing End Function Protected Overrides Function TryBindOmittedLeftForConditionalAccess(node As ConditionalAccessExpressionSyntax, accessingBinder As Binder, diagnostics As DiagnosticBag) As BoundExpression Return Nothing End Function Protected Friend Overrides Function TryBindOmittedLeftForXmlMemberAccess(node As XmlMemberAccessExpressionSyntax, diagnostics As DiagnosticBag, accessingBinder As Binder) As BoundExpression Return Nothing End Function Protected Overrides Function TryGetConditionalAccessReceiver(node As ConditionalAccessExpressionSyntax) As BoundExpression Return Nothing End Function Friend Overrides ReadOnly Property ConstantFieldsInProgress As SymbolsInProgress(Of FieldSymbol) Get Return SymbolsInProgress(Of FieldSymbol).Empty End Get End Property Friend Overrides ReadOnly Property DefaultParametersInProgress As SymbolsInProgress(Of ParameterSymbol) Get Return SymbolsInProgress(Of ParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property OptionStrict As OptionStrict Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property OptionInfer As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property OptionExplicit As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property OptionCompareText As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property CheckOverflow As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property AllImplicitVariableDeclarationsAreHandled As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ImplicitVariableDeclarationAllowed As Boolean Get Return False End Get End Property Public Overrides Function DeclareImplicitLocalVariable(nameSyntax As IdentifierNameSyntax, diagnostics As DiagnosticBag) As LocalSymbol Throw ExceptionUtilities.Unreachable End Function Public Overrides ReadOnly Property ImplicitlyDeclaredVariables As ImmutableArray(Of LocalSymbol) Get Return ImmutableArray(Of LocalSymbol).Empty End Get End Property Public Overrides Sub DisallowFurtherImplicitVariableDeclaration(diagnostics As DiagnosticBag) ' No action needed. End Sub Public Overrides Function GetContinueLabel(continueSyntaxKind As SyntaxKind) As LabelSymbol Return Nothing End Function Public Overrides Function GetExitLabel(exitSyntaxKind As SyntaxKind) As LabelSymbol Return Nothing End Function Public Overrides Function GetReturnLabel() As LabelSymbol Return Nothing End Function Public Overrides Function GetLocalForFunctionValue() As LocalSymbol Return Nothing End Function Protected Overrides ReadOnly Property IsInsideChainedConstructorCallArguments As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property BindingLocation As BindingLocation Get Return BindingLocation.None End Get End Property Private Shared ReadOnly s_defaultXmlNamespaces As New Dictionary(Of String, String) From { {StringConstants.DefaultXmlnsPrefix, StringConstants.DefaultXmlNamespace}, {StringConstants.XmlPrefix, StringConstants.XmlNamespace}, {StringConstants.XmlnsPrefix, StringConstants.XmlnsNamespace} } Friend Overrides Function LookupXmlNamespace(prefix As String, ignoreXmlNodes As Boolean, <Out()> ByRef [namespace] As String, <Out()> ByRef fromImports As Boolean) As Boolean fromImports = False Return s_defaultXmlNamespaces.TryGetValue(prefix, [namespace]) End Function Friend Overrides ReadOnly Property HasImportedXmlNamespaces As Boolean Get Return False End Get End Property Friend Overrides Sub GetInScopeXmlNamespaces(builder As ArrayBuilder(Of KeyValuePair(Of String, String))) ' Method shouldn't be called outside of XmlElement. Throw ExceptionUtilities.Unreachable End Sub Friend Overrides Function LookupLabelByNameToken(labelName As SyntaxToken) As LabelSymbol Return Nothing End Function #If DEBUG Then Public Overrides Sub CheckSimpleNameBindingOrder(node As SimpleNameSyntax) ' do nothing End Sub Public Overrides Sub EnableSimpleNameBindingOrderChecks(enable As Boolean) ' do nothing End Sub #End If Friend Overrides Function GetWithStatementPlaceholderSubstitute(placeholder As BoundValuePlaceholderBase) As BoundExpression Return Nothing End Function Public Overrides ReadOnly Property QuickAttributeChecker As QuickAttributeChecker Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property IsDefaultInstancePropertyAllowed As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property SuppressCallerInfo As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property SuppressObsoleteDiagnostics As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSemanticModelBinder As Boolean Get Return False End Get End Property Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions Return options End Function End Class End Namespace
jkotas/roslyn
src/Compilers/VisualBasic/Portable/Binding/BackstopBinder.vb
Visual Basic
apache-2.0
12,165
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.ArrayStatements Public Class ReDimKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function ReDimInMethodBodyTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>|</MethodBody>, "ReDim") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function ReDimAfterStatementTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody> Dim x |</MethodBody>, "ReDim") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function ReDimMissingInClassBlockTest() As Task Await VerifyRecommendationsMissingAsync(<ClassDeclaration>|</ClassDeclaration>, "ReDim") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function ReDimInSingleLineLambdaTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = Sub() |</MethodBody>, "ReDim") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function ReDimNotInSingleLineFunctionLambdaTest() As Task Await VerifyRecommendationsMissingAsync(<MethodBody>Dim x = Function() |</MethodBody>, "ReDim") End Function End Class End Namespace
ericfe-ms/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/ArrayStatements/ReDimKeywordRecommenderTests.vb
Visual Basic
apache-2.0
1,923
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotInheritable Partial Class BoundWithStatement Inherits BoundStatement ''' <summary> Returns the placeholder used in this With statement to ''' substitute the expression in initial binding </summary> Friend ReadOnly Property ExpressionPlaceholder As BoundValuePlaceholderBase Get Return Binder.ExpressionPlaceholder End Get End Property ''' <summary> ''' A draft version of initializers which will be used in this With statement. ''' Initializers are expressinos which are used to capture expression in the current ''' With statement; they can be empty in some cases like if the expression is a local ''' variable of value type. ''' ''' Note, the initializers returned by this property are 'draft' because they are ''' generated based on initial bound tree, the real initializers will be generated ''' in lowering based on lowered expression form. ''' </summary> Friend ReadOnly Property DraftInitializers As ImmutableArray(Of BoundExpression) Get Return Binder.DraftInitializers End Get End Property ''' <summary> ''' A draft version of placeholder substitute which will be used in this With statement. ''' ''' Note, the placeholder substitute returned by this property is 'draft' because it is ''' generated based on initial bound tree, the real substitute will be generated in lowering ''' based on lowered expression form. ''' </summary> Friend ReadOnly Property DraftPlaceholderSubstitute As BoundExpression Get Return Binder.DraftPlaceholderSubstitute End Get End Property End Class End Namespace
paladique/roslyn
src/Compilers/VisualBasic/Portable/BoundTree/BoundWithStatement.vb
Visual Basic
apache-2.0
2,245
' 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Iterator Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.Iterator Public Class ConvertToIteratorTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicConvertToIteratorCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToIterator)> Public Async Function TestConvertToIteratorFunction() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Module Module1 Function M() As IEnumerable(Of Integer) [|Yield|] 1 End Function End Module", "Imports System Imports System.Collections.Generic Module Module1 Iterator Function M() As IEnumerable(Of Integer) Yield 1 End Function End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToIterator)> Public Async Function TestConvertToIteratorSub() As Task Await TestMissingInRegularAndScriptAsync( "Module Module1 Sub M() As [|Yield|] 1 End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToIterator)> Public Async Function TestConvertToIteratorFunctionLambda() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Module Module1 Sub M() Dim a As Func(Of IEnumerable(Of Integer)) = Function() [|Yield|] 0 End Function End Sub End Module", "Imports System Imports System.Collections.Generic Module Module1 Sub M() Dim a As Func(Of IEnumerable(Of Integer)) = Iterator Function() Yield 0 End Function End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToIterator)> Public Async Function TestConvertToIteratorSubLambda() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Module Module1 Sub M() Dim a As Func(Of IEnumerable(Of Integer)) = Sub() [|Yield|] 0 End Sub End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToIterator)> Public Async Function TestConvertToIteratorSingleLineFunctionLambda() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Module Module1 Sub M() Dim a As Func(Of IEnumerable(Of Integer)) = Function() [|Yield|] 0 End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToIterator)> Public Async Function TestConvertToIteratorSingleLineSubLambda() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Module Module1 Sub M() Dim a As Func(Of IEnumerable(Of Integer)) = Sub() [|Yield|] 0 End Sub End Module") End Function End Class Public Class ChangeToYieldTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicChangeToYieldCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)> Public Async Function TestChangeToYieldCodeFixProviderFunction() As Task Await TestInRegularAndScriptAsync( "Module Module1 Iterator Function M() As IEnumerable(Of Integer) [|Return|] 1 End Function End Module", "Module Module1 Iterator Function M() As IEnumerable(Of Integer) Yield 1 End Function End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)> Public Async Function TestChangeToYieldCodeFixProviderSub() As Task Await TestInRegularAndScriptAsync( "Module Module1 Iterator Sub M() [|Return|] 1 End Sub End Module", "Module Module1 Iterator Sub M() Yield 1 End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)> Public Async Function TestChangeToYieldCodeFixProviderFunctionLambda() As Task Await TestInRegularAndScriptAsync( "Module Module1 Sub M() Dim a = Iterator Function() [|Return|] 0 End Function End Sub End Module", "Module Module1 Sub M() Dim a = Iterator Function() Yield 0 End Function End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)> Public Async Function TestChangeToYieldCodeFixProviderSubLambda() As Task Await TestInRegularAndScriptAsync( "Module Module1 Sub M() Dim a = Iterator Sub() [|Return|] 0 End Sub End Sub End Module", "Module Module1 Sub M() Dim a = Iterator Sub() Yield 0 End Sub End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)> Public Async Function TestChangeToYieldCodeFixProviderSingleLineFunctionLambda() As Task Await TestMissingInRegularAndScriptAsync("Module Module1 Sub M() Dim a = Iterator Function() [|Return|] 0 End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToYield)> Public Async Function TestChangeToYieldCodeFixProviderSingleLineSubLambda() As Task Await TestInRegularAndScriptAsync( "Module Module1 Sub M() Dim a = Iterator Sub() [|Return|] 0 End Sub End Module", "Module Module1 Sub M() Dim a = Iterator Sub() Yield 0 End Sub End Module") End Function End Class End Namespace
AlekseyTs/roslyn
src/EditorFeatures/VisualBasicTest/Diagnostics/Iterator/IteratorTests.vb
Visual Basic
mit
6,804
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Public Class CallsGraphQueryTests <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Public Async Function CallsSimpleTests() As Task Using testState = Await ProgressionTestState.CreateAsync( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> class A { public A() { } public void Run() { } static void $$Main(string[] args) { new A().Run(); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New CallsGraphQuery(), GraphContextDirection.Source) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=A Member=(Name=Main OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPrivate="True" CodeSchemaProperty_IsStatic="True" CommonLabel="Main" Icon="Microsoft.VisualStudio.Method.Private" Label="Main"/> <Node Id="(@1 Type=A Member=.ctor)" Category="CodeSchema_Method" CodeSchemaProperty_IsConstructor="True" CodeSchemaProperty_IsPublic="True" CommonLabel="A" Icon="Microsoft.VisualStudio.Method.Public" Label="A"/> <Node Id="(@1 Type=A Member=Run)" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="Run" Icon="Microsoft.VisualStudio.Method.Public" Label="Run"/> </Nodes> <Links> <Link Source="(@1 Type=A Member=(Name=Main OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Target="(@1 Type=A Member=.ctor)" Category="CodeSchema_Calls"/> <Link Source="(@1 Type=A Member=(Name=Main OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Target="(@1 Type=A Member=Run)" Category="CodeSchema_Calls"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Public Async Function CallsLambdaTests() As Task Using testState = Await ProgressionTestState.CreateAsync( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class A { static void $$Foo(String[] args) { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int oddNumbers = numbers.Count(n => n % 2 == 1); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New CallsGraphQuery(), GraphContextDirection.Source) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=A Member=(Name=Foo OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPrivate="True" CodeSchemaProperty_IsStatic="True" CommonLabel="Foo" Icon="Microsoft.VisualStudio.Method.Private" Label="Foo"/> <Node Id="(Namespace=System.Linq Type=Enumerable Member=(Name=Count GenericParameterCount=1 OverloadingParameters=[(@2 Namespace=System Type=(Name=Func GenericParameterCount=2 GenericArguments=[(@2 Namespace=System Type=Int32),(@2 Namespace=System Type=Boolean)]))]))" Category="CodeSchema_Method" CodeSchemaProperty_IsExtension="True" CodeSchemaProperty_IsPublic="True" CommonLabel="Count" Icon="Microsoft.VisualStudio.Method.Public" Label="Count"/> </Nodes> <Links> <Link Source="(@1 Type=A Member=(Name=Foo OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Target="(Namespace=System.Linq Type=Enumerable Member=(Name=Count GenericParameterCount=1 OverloadingParameters=[(@2 Namespace=System Type=(Name=Func GenericParameterCount=2 GenericArguments=[(@2 Namespace=System Type=Int32),(@2 Namespace=System Type=Boolean)]))]))" Category="CodeSchema_Calls"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Public Async Function CallsPropertiesTests() As Task Using testState = Await ProgressionTestState.CreateAsync( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> class A { static public int Get() { return 1; } public int $$PropertyA = A.Get(); } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New CallsGraphQuery(), GraphContextDirection.Source) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=A Member=Get)" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CodeSchemaProperty_IsStatic="True" CommonLabel="Get" Icon="Microsoft.VisualStudio.Method.Public" Label="Get"/> <Node Id="(@1 Type=A Member=PropertyA)" Category="CodeSchema_Field" CodeSchemaProperty_IsPublic="True" CommonLabel="PropertyA" Icon="Microsoft.VisualStudio.Field.Public" Label="PropertyA"/> </Nodes> <Links> <Link Source="(@1 Type=A Member=PropertyA)" Target="(@1 Type=A Member=Get)" Category="CodeSchema_Calls"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Public Async Function CallsDelegatesTests() As Task Using testState = Await ProgressionTestState.CreateAsync( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; delegate void MyDelegate1(int x, float y); class C { public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); } static void $$Main(string[] args) { C mc = new C(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod; md1(1, 5); md1 -= mc.DelegatedMethod; } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New CallsGraphQuery(), GraphContextDirection.Source) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=C Member=(Name=DelegatedMethod OverloadingParameters=[(@2 Namespace=System Type=Int32),(@2 Namespace=System Type=Single)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="DelegatedMethod" Icon="Microsoft.VisualStudio.Method.Public" Label="DelegatedMethod"/> <Node Id="(@1 Type=C Member=(Name=Main OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPrivate="True" CodeSchemaProperty_IsStatic="True" CommonLabel="Main" Icon="Microsoft.VisualStudio.Method.Private" Label="Main"/> <Node Id="(@1 Type=C Member=.ctor)" Category="CodeSchema_Method" CodeSchemaProperty_IsConstructor="True" CodeSchemaProperty_IsPublic="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Method.Public" Label="C"/> <Node Id="(@1 Type=MyDelegate1 Member=(Name=Invoke OverloadingParameters=[(@2 Namespace=System Type=Int32),(@2 Namespace=System Type=Single)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CodeSchemaProperty_IsVirtual="True" CommonLabel="Invoke" Icon="Microsoft.VisualStudio.Method.Public" Label="Invoke"/> </Nodes> <Links> <Link Source="(@1 Type=C Member=(Name=Main OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Target="(@1 Type=C Member=(Name=DelegatedMethod OverloadingParameters=[(@2 Namespace=System Type=Int32),(@2 Namespace=System Type=Single)]))" Category="CodeSchema_Calls"/> <Link Source="(@1 Type=C Member=(Name=Main OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Target="(@1 Type=C Member=.ctor)" Category="CodeSchema_Calls"/> <Link Source="(@1 Type=C Member=(Name=Main OverloadingParameters=[(@2 Namespace=System Type=(Name=String ArrayRank=1 ParentType=String))]))" Target="(@1 Type=MyDelegate1 Member=(Name=Invoke OverloadingParameters=[(@2 Namespace=System Type=Int32),(@2 Namespace=System Type=Single)]))" Category="CodeSchema_Calls"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Public Async Function CallsDelegateCreationExpressionTests() As Task Using testState = Await ProgressionTestState.CreateAsync( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; delegate void MyEvent(); class Test { event MyEvent Clicked; void Handler() { } public void $$Run() { Test t = new Test(); t.Clicked += new MyEvent(Handler); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New CallsGraphQuery(), GraphContextDirection.Source) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=Test Member=.ctor)" Category="CodeSchema_Method" CodeSchemaProperty_IsConstructor="True" CodeSchemaProperty_IsPublic="True" CommonLabel="Test" Icon="Microsoft.VisualStudio.Method.Public" Label="Test"/> <Node Id="(@1 Type=Test Member=Handler)" Category="CodeSchema_Method" CodeSchemaProperty_IsPrivate="True" CommonLabel="Handler" Icon="Microsoft.VisualStudio.Method.Private" Label="Handler"/> <Node Id="(@1 Type=Test Member=Run)" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="Run" Icon="Microsoft.VisualStudio.Method.Public" Label="Run"/> </Nodes> <Links> <Link Source="(@1 Type=Test Member=Run)" Target="(@1 Type=Test Member=.ctor)" Category="CodeSchema_Calls"/> <Link Source="(@1 Type=Test Member=Run)" Target="(@1 Type=Test Member=Handler)" Category="CodeSchema_Calls"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
bbarry/roslyn
src/VisualStudio/Core/Test/Progression/CallsGraphQueryTests.vb
Visual Basic
apache-2.0
14,779
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.IO Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.Win32 Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests Public Class AnalyzerDependencyCheckerTests Inherits TestBase Private Shared s_msbuildDirectory As String Private Shared ReadOnly Property MSBuildDirectory As String Get If s_msbuildDirectory Is Nothing Then Dim key = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0", False) If key IsNot Nothing Then Dim toolsPath = key.GetValue("MSBuildToolsPath") If toolsPath IsNot Nothing Then s_msbuildDirectory = toolsPath.ToString() End If End If End If Return s_msbuildDirectory End Get End Property Private Shared s_CSharpCompilerExecutable As String = Path.Combine(MSBuildDirectory, "csc.exe") Private Shared s_mscorlibDisplayName As String = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Private Shared Function GetIgnorableAssemblyLists() As IEnumerable(Of IIgnorableAssemblyList) Dim mscorlib As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName(s_mscorlibDisplayName, mscorlib) Return {New IgnorableAssemblyIdentityList({mscorlib})} End Function <Fact, WorkItem(1064914)> Public Sub ConflictsTest1() ' Dependency Graph: ' A Using directory = New DisposableDirectory(Temp) Dim library = BuildLibrary(directory, "public class A { }", "A") Dim dependencyChecker = New AnalyzerDependencyChecker({library}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Empty(results.Conflicts) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest2() ' Dependency graph: ' A --> B Dim sourceA = " public class A { void M() { B b = new B(); } }" Dim sourceB = "public class B { }" Using directory = New DisposableDirectory(Temp) Dim libraryB = BuildLibrary(directory, sourceB, "B") Dim libraryA = BuildLibrary(directory, sourceA, "A", "B") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Empty(results.Conflicts) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest3() ' Dependency graph: ' A --> B ' \ ' -> C Dim sourceA = " public class A { void M() { B b = new B(); C c = new C(); } }" Dim sourceB = "public class B { }" Dim sourceC = "public class C { }" Using directory = New DisposableDirectory(Temp) Dim libraryC = BuildLibrary(directory, sourceC, "C") Dim libraryB = BuildLibrary(directory, sourceB, "B") Dim libraryA = BuildLibrary(directory, sourceA, "A", "B", "C") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Empty(results.Conflicts) Assert.Empty(results.MissingDependencies) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest4() ' Dependency graph: ' A --> B ' C --> D Dim sourceA = " public class A { void M() { B b = new B(); } }" Dim sourceB = "public class B { }" Dim sourceC = " public class C { void M() { C c = new C(); } }" Dim sourceD = "public class D { }" Using directory = New DisposableDirectory(Temp) Dim libraryB = BuildLibrary(directory, sourceB, "B") Dim libraryA = BuildLibrary(directory, sourceA, "A", "B") Dim libraryD = BuildLibrary(directory, sourceD, "D") Dim libraryC = BuildLibrary(directory, sourceC, "C", "D") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC, libraryD}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Empty(results.Conflicts) Assert.Empty(results.MissingDependencies) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest5() ' Dependency graph: ' Directory 1: ' A --> B ' Directory 2: ' C --> D Dim sourceA = " public class A { void M() { B b = new B(); } }" Dim sourceB = "public class B { }" Dim sourceC = " public class C { void M() { C c = new C(); } }" Dim sourceD = "public class D { }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp) Dim libraryB = BuildLibrary(directory1, sourceB, "B") Dim libraryA = BuildLibrary(directory1, sourceA, "A", "B") Dim libraryD = BuildLibrary(directory2, sourceD, "D") Dim libraryC = BuildLibrary(directory2, sourceC, "C", "D") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC, libraryD}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Empty(results.Conflicts) Assert.Empty(results.MissingDependencies) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest6() ' Dependency graph: ' A - ' \ ' -> C ' / ' B - Dim sourceA = " public class A { void M() { C c = new C(); } }" Dim sourceB = " public class B { void M() { C c = new C(); } }" Dim sourceC = "public class C { }" Using directory = New DisposableDirectory(Temp) Dim libraryC = BuildLibrary(directory, sourceC, "C") Dim libraryA = BuildLibrary(directory, sourceA, "A", "C") Dim libraryB = BuildLibrary(directory, sourceB, "B", "C") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Empty(results.Conflicts) Assert.Empty(results.MissingDependencies) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest7() ' Dependency graph: ' Directory 1: ' A --> C ' Directory 2: ' B --> C Dim sourceA = " public class A { void M() { C c = new C(); } }" Dim sourceB = " public class B { void M() { C c = new C(); } }" Dim sourceC = "public class C { }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp) Dim libraryC1 = BuildLibrary(directory1, sourceC, "C") Dim libraryA = BuildLibrary(directory1, sourceA, "A", "C") Dim libraryC2 = directory2.CreateFile("C.dll").CopyContentFrom(libraryC1).Path Dim libraryB = BuildLibrary(directory2, sourceB, "B", "C") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC1, libraryC2}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Empty(results.Conflicts) Assert.Empty(results.MissingDependencies) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest8() ' Dependency graph: ' Directory 1: ' A --> C ' Directory 2: ' B --> C' Dim sourceA = " public class A { void M() { C c = new C(); } }" Dim sourceB = " public class B { void M() { C c = new C(); } }" Dim sourceC = " public class C { public static string Field = ""Assembly C""; }" Dim sourceCPrime = " public class C { public static string Field = ""Assembly C Prime""; }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp) Dim libraryC = BuildLibrary(directory1, sourceC, "C") Dim libraryA = BuildLibrary(directory1, sourceA, "A", "C") Dim libraryCPrime = BuildLibrary(directory2, sourceCPrime, "C") Dim libraryB = BuildLibrary(directory2, sourceB, "B", "C") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC, libraryCPrime}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Dim conflicts = results.Conflicts Assert.Equal(expected:=1, actual:=conflicts.Length) Dim analyzer1FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath1) Dim analyzer2FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath2) Assert.Equal(expected:="C.dll", actual:=analyzer1FileName) Assert.Equal(expected:="C.dll", actual:=analyzer2FileName) Assert.Equal(expected:=New AssemblyIdentity("C"), actual:=conflicts(0).Identity) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest9() ' Dependency graph: ' Directory 1: ' A --> C --> D ' Directory 2: ' B --> C --> D' Dim sourceA = " public class A { void M() { C c = new C(); } }" Dim sourceB = " public class B { void M() { C c = new C(); } }" Dim sourceC = " public class C { void M() { D d = new D(); } }" Dim sourceD = " public class D { public static string Field = ""Assembly D""; }" Dim sourceDPrime = " public class D { public static string Field = ""Assembly D Prime""; }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp) Dim libraryD = BuildLibrary(directory1, sourceD, "D") Dim libraryDPrime = BuildLibrary(directory2, sourceDPrime, "D") Dim libraryC1 = BuildLibrary(directory1, sourceC, "C", "D") Dim libraryC2 = directory2.CreateFile("C.dll").CopyContentFrom(libraryC1).Path Dim libraryA = BuildLibrary(directory1, sourceA, "A", "C") Dim libraryB = BuildLibrary(directory2, sourceB, "B", "C") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC1, libraryC2, libraryD, libraryDPrime}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Dim conflicts = results.Conflicts Assert.Equal(expected:=1, actual:=conflicts.Length) Dim analyzer1FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath1) Dim analyzer2FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath2) Assert.Equal(expected:="D.dll", actual:=analyzer1FileName) Assert.Equal(expected:="D.dll", actual:=analyzer2FileName) Assert.Equal(expected:=New AssemblyIdentity("D"), actual:=conflicts(0).Identity) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest10() ' Dependency graph: ' Directory 1: ' A --> C --> E ' Directory 2: ' B --> D --> E' Dim sourceA = " public class A { void M() { C c = new C(); } }" Dim sourceB = " public class B { void M() { D d = new D(); } }" Dim sourceC = " public class C { void M() { E e = new E(); } }" Dim sourceD = " public class D { void M() { E e = new E(); } }" Dim sourceE = " public class E { public static string Field = ""Assembly E""; }" Dim sourceEPrime = " public class E { public static string Field = ""Assembly D Prime""; }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp) Dim libraryE = BuildLibrary(directory1, sourceE, "E") Dim libraryEPrime = BuildLibrary(directory2, sourceEPrime, "E") Dim libraryC = BuildLibrary(directory1, sourceC, "C", "E") Dim libraryD = BuildLibrary(directory2, sourceD, "D", "E") Dim libraryA = BuildLibrary(directory1, sourceA, "A", "C") Dim libraryB = BuildLibrary(directory2, sourceB, "B", "D") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC, libraryD, libraryE, libraryEPrime}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Dim conflicts = results.Conflicts Assert.Equal(expected:=1, actual:=conflicts.Length) Dim analyzer1FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath1) Dim analyzer2FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath2) Assert.Equal(expected:="E.dll", actual:=analyzer1FileName) Assert.Equal(expected:="E.dll", actual:=analyzer2FileName) Assert.Equal(expected:=New AssemblyIdentity("E"), actual:=conflicts(0).Identity) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest11() ' Dependency graph: ' Directory 1: ' A --> B ' Directory 2: ' A --> B' Dim sourceA = " public class A { void M() { B b = new B(); } }" Dim sourceB = " public class B { public static string Field = ""Assembly B""; }" Dim sourceBPrime = " public class B { public static string Field = ""Assembly B Prime""; }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp) Dim libraryB = BuildLibrary(directory1, sourceB, "B") Dim libraryA1 = BuildLibrary(directory1, sourceA, "A", "B") Dim libraryBPrime = BuildLibrary(directory2, sourceBPrime, "B") Dim libraryA2 = directory2.CreateFile("A.dll").CopyContentFrom(libraryA1).Path Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA1, libraryA2, libraryB, libraryBPrime}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Dim conflicts = results.Conflicts Assert.Equal(expected:=1, actual:=conflicts.Length) Dim analyzer1FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath1) Dim analyzer2FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath2) Assert.Equal(expected:="B.dll", actual:=analyzer1FileName) Assert.Equal(expected:="B.dll", actual:=analyzer2FileName) Assert.Equal(expected:=New AssemblyIdentity("B"), actual:=conflicts(0).Identity) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest12() ' Dependency graph: ' Directory 1: ' A --> B ' Directory 2: ' A' --> B' Dim sourceA = " public class A { public static string Field = ""Assembly A""; void M() { B b = new B(); } }" Dim sourceAPrime = " public class A { public static string Field = ""Assembly A Prime""; void M() { B b = new B(); } }" Dim sourceB = " public class B { public static string Field = ""Assembly B""; }" Dim sourceBPrime = " public class B { public static string Field = ""Assembly B Prime""; }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp) Dim libraryB = BuildLibrary(directory1, sourceB, "B") Dim libraryA = BuildLibrary(directory1, sourceA, "A", "B") Dim libraryBPrime = BuildLibrary(directory2, sourceBPrime, "B") Dim libraryAPrime = BuildLibrary(directory2, sourceAPrime, "A", "B") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryAPrime, libraryB, libraryBPrime}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Dim conflicts = results.Conflicts Assert.Equal(expected:=2, actual:=conflicts.Length) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest13() ' Dependency graph: ' Directory 1: ' A --> B ' Directory 2: ' A' --> B Dim sourceA = " public class A { public static string Field = ""Assembly A""; void M() { B b = new B(); } }" Dim sourceAPrime = " public class A { public static string Field = ""Assembly A Prime""; void M() { B b = new B(); } }" Dim sourceB = " public class B { public static string Field = ""Assembly B""; }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp) Dim libraryB1 = BuildLibrary(directory1, sourceB, "B") Dim libraryA = BuildLibrary(directory1, sourceA, "A", "B") Dim libraryB2 = directory2.CreateFile("B.dll").CopyContentFrom(libraryB1).Path Dim libraryAPrime = BuildLibrary(directory2, sourceAPrime, "A", "B") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryAPrime, libraryB1, libraryB2}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Dim conflicts = results.Conflicts Assert.Equal(expected:=1, actual:=conflicts.Length) Dim analyzer1FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath1) Dim analyzer2FileName As String = Path.GetFileName(conflicts(0).AnalyzerFilePath2) Assert.Equal(expected:="A.dll", actual:=analyzer1FileName) Assert.Equal(expected:="A.dll", actual:=analyzer2FileName) Assert.Equal(expected:=New AssemblyIdentity("A"), actual:=conflicts(0).Identity) End Using End Sub <Fact, WorkItem(1064914)> Public Sub ConflictsTest14() ' Dependency graph: ' Directory 1: ' A --> D ' Directory 2: ' B --> D' ' Directory 3: ' C --> D'' Dim sourceA = " public class A { void M() { D d = new D(); } }" Dim sourceB = " public class B { void M() { D d = new D(); } }" Dim sourceC = " public class C { void M() { D d = new D(); } }" Dim sourceD = " public class D { public static string Field = ""Assembly D""; }" Dim sourceDPrime = " public class D { public static string Field = ""Assembly D Prime""; }" Dim sourceDPrimePrime = " public class D { public static string Field = ""Assembly D Prime Prime""; }" Using directory1 = New DisposableDirectory(Temp), directory2 = New DisposableDirectory(Temp), directory3 = New DisposableDirectory(Temp) Dim libraryD = BuildLibrary(directory1, sourceD, "D") Dim libraryA = BuildLibrary(directory1, sourceA, "A", "D") Dim libraryDPrime = BuildLibrary(directory2, sourceDPrime, "D") Dim libraryB = BuildLibrary(directory2, sourceB, "B", "D") Dim libraryDPrimePrime = BuildLibrary(directory3, sourceDPrimePrime, "D") Dim libraryC = BuildLibrary(directory3, sourceC, "C", "D") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA, libraryB, libraryC, libraryD, libraryDPrime, libraryDPrimePrime}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Equal(expected:=3, actual:=results.Conflicts.Length) End Using End Sub <Fact> Public Sub MissingTest1() ' Dependency Graph: ' A Using directory = New DisposableDirectory(Temp) Dim library = BuildLibrary(directory, "public class A { }", "A") Dim dependencyChecker = New AnalyzerDependencyChecker({library}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Assert.Empty(results.MissingDependencies) End Using End Sub <Fact> Public Sub MissingTest2() ' Dependency graph: ' A --> B* Dim sourceA = " public class A { void M() { B b = new B(); } }" Dim sourceB = "public class B { }" Using directory = New DisposableDirectory(Temp) Dim libraryB = BuildLibrary(directory, sourceB, "B") Dim libraryA = BuildLibrary(directory, sourceA, "A", "B") Dim dependencyChecker = New AnalyzerDependencyChecker({libraryA}, GetIgnorableAssemblyLists()) Dim results = dependencyChecker.Run() Dim missingDependencies = results.MissingDependencies Assert.Equal(expected:=1, actual:=missingDependencies.Count) Dim analyzerFileName As String = Path.GetFileName(missingDependencies(0).AnalyzerPath) Assert.Equal(expected:="A.dll", actual:=analyzerFileName) Assert.Equal(expected:=New AssemblyIdentity("B"), actual:=missingDependencies(0).DependencyIdentity) End Using End Sub <Fact, WorkItem(3020, "https://github.com/dotnet/roslyn/issues/3020")> Public Sub IgnorableAssemblyIdentityList_IncludesItem() Dim mscorlib1 As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName(s_mscorlibDisplayName, mscorlib1) Dim ignorableAssemblyList = New IgnorableAssemblyIdentityList({mscorlib1}) Dim mscorlib2 As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName(s_mscorlibDisplayName, mscorlib2) Assert.True(ignorableAssemblyList.Includes(mscorlib2)) End Sub <Fact, WorkItem(3020, "https://github.com/dotnet/roslyn/issues/3020")> Public Sub IgnorableAssemblyIdentityList_DoesNotIncludeItem() Dim mscorlib As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName(s_mscorlibDisplayName, mscorlib) Dim ignorableAssemblyList = New IgnorableAssemblyIdentityList({mscorlib}) Dim alpha As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName("Alpha, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", alpha) Assert.False(ignorableAssemblyList.Includes(alpha)) End Sub <Fact, WorkItem(3020, "https://github.com/dotnet/roslyn/issues/3020")> Public Sub IgnorableAssemblyNamePrefixList_IncludesItem_Prefix() Dim ignorableAssemblyList = New IgnorableAssemblyNamePrefixList("Alpha") Dim alphaBeta As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName("Alpha.Beta, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", alphaBeta) Assert.True(ignorableAssemblyList.Includes(alphaBeta)) End Sub <Fact, WorkItem(3020, "https://github.com/dotnet/roslyn/issues/3020")> Public Sub IgnorableAssemblyNamePrefixList_IncludesItem_WholeName() Dim ignorableAssemblyList = New IgnorableAssemblyNamePrefixList("Alpha") Dim alpha As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName("Alpha, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", alpha) Assert.True(ignorableAssemblyList.Includes(alpha)) End Sub <Fact, WorkItem(3020, "https://github.com/dotnet/roslyn/issues/3020")> Public Sub IgnorableAssemblyNamePrefixList_DoesNotIncludeItem() Dim ignorableAssemblyList = New IgnorableAssemblyNamePrefixList("Beta") Dim alpha As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName("Alpha, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", alpha) Assert.False(ignorableAssemblyList.Includes(alpha)) End Sub Private Function BuildLibrary(directory As DisposableDirectory, fileContents As String, libraryName As String, ParamArray referenceNames As String()) As String Dim sourceFile = directory.CreateFile(libraryName + ".cs").WriteAllText(fileContents).Path Dim tempOut = Path.Combine(directory.Path, libraryName + ".out") Dim libraryOut = Path.Combine(directory.Path, libraryName + ".dll") Dim sb = New StringBuilder For Each name In referenceNames sb.Append(" /r:") sb.Append(Path.Combine(directory.Path, name + ".dll")) Next Dim references = sb.ToString() Dim arguments = $"/C ""{s_CSharpCompilerExecutable}"" /nologo /t:library /out:{libraryOut} {references} {sourceFile} > {tempOut}" Dim output = ProcessUtilities.RunAndGetOutput("cmd", arguments, expectedRetCode:=0) Return libraryOut End Function End Class End Namespace
KevinRansom/roslyn
src/VisualStudio/Core/Test/AnalyzerSupport/AnalyzerDependencyCheckerTests.vb
Visual Basic
apache-2.0
27,209
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser <ExportLanguageService(GetType(ILibraryService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicLibraryService Inherits AbstractLibraryService Private Shared ReadOnly s_typeDisplayFormat As New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance) Private Shared ReadOnly s_memberDisplayFormat As SymbolDisplayFormat = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, parameterOptions:=SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Public Sub New() MyBase.New(Guids.VisualBasicLibraryId, __SymbolToolLanguage.SymbolToolLanguage_VB, s_typeDisplayFormat, s_memberDisplayFormat) End Sub End Class End Namespace
robinsedlaczek/roslyn
src/VisualStudio/VisualBasic/Impl/ObjectBrowser/VisualBasicLibraryService.vb
Visual Basic
apache-2.0
1,847
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents global namespace. Namespace's name is always empty ''' </summary> ''' <remarks></remarks> Friend Class GlobalNamespaceDeclaration Inherits SingleNamespaceDeclaration Public Sub New(hasImports As Boolean, syntaxReference As SyntaxReference, nameLocation As Location, children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) MyBase.New(String.Empty, hasImports, syntaxReference, nameLocation, children) End Sub Public Overrides ReadOnly Property IsGlobalNamespace As Boolean Get Return True End Get End Property End Class End Namespace
v-codeel/roslyn
src/Compilers/VisualBasic/Portable/Declarations/GlobalNamespaceDeclaration.vb
Visual Basic
apache-2.0
1,336
'------------------------------------------------------------------------------ ' <auto-generated> ' 這段程式碼是由工具產生的。 ' 執行階段版本:4.0.30319.34014 ' ' 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, ' 變更將會遺失。 ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources '這個類別是自動產生的,是利用 StronglyTypedResourceBuilder '類別透過 ResGen 或 Visual Studio 這類工具。 '若要加入或移除成員,請編輯您的 .ResX 檔,然後重新執行 ResGen '(利用 /str 選項),或重建您的 VS 專案。 '''<summary> ''' 用於查詢當地語系化字串等的強類型資源類別。 '''</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> ''' 傳回這個類別使用的快取的 ResourceManager 執行個體。 '''</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("Xiaomi_Auto_Buy.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' 覆寫目前執行緒的 CurrentUICulture 屬性,對象是所有 ''' 使用這個強類型資源類別的資源查閱。 '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property '''<summary> ''' 查詢類型 System.Drawing.Bitmap 的當地語系化資源。 '''</summary> Friend ReadOnly Property cancel1() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("cancel1", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' 查詢類型 System.Drawing.Bitmap 的當地語系化資源。 '''</summary> Friend ReadOnly Property cancel2() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("cancel2", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property End Module End Namespace
hearsilent/Xiaomi-Auto-Buy
Xiaomi Auto Buy/My Project/Resources.Designer.vb
Visual Basic
mit
3,579
Imports System.Collections.ObjectModel Imports Business.Business Imports Entities.Entities Imports MaterialDesignThemes.Wpf Public Class ucLoaiBenh Private listLoaiBenh As ObservableCollection(Of LoaiBenhDTO) Private Sub CancelButton_Click(sender As Object, e As RoutedEventArgs) dgLoaiBenh.SelectedIndex = -1 End Sub Private Async Sub DeleteButton_Click(sender As Object, e As RoutedEventArgs) 'Kiểm tra người dùng có muốn xóa hay không Dim dialog As New Domain.YesNoDialog dialog.Message.Text = "Bạn có chắc chắn xóa " + dgLoaiBenh.SelectedItems.Count.ToString() + " loại bệnh được chọn" Await DialogHost.Show(dialog) If (dialog.DialogResult = MessageBoxResult.No) Then Exit Sub End If 'Tiến hành xóa Dim result As Boolean For Each loaiBenh As LoaiBenhDTO In dgLoaiBenh.SelectedItems result = LoaiBenhBUS.DeleteLoaiBenhByMa(loaiBenh.MaLoaiBenh) Next If (result = True) Then Domain.Dialog.Show("Xóa thành công") Else Domain.Dialog.Show("Xóa thất bại") End If ReloadData() End Sub Private Sub UpdateButton_Click(sender As Object, e As RoutedEventArgs) 'Kiểm tra người dùng đã chọn trong danh sách chưa If dgLoaiBenh.SelectedIndex = -1 Then Domain.Dialog.Show("Chưa có đối tượng được chọn") Return End If 'Lấy thông tin từ người dùng nhập vào Dim loaiBenh As New LoaiBenhDTO() loaiBenh.MaLoaiBenh = tbMaLoaiBenh.Text If tbTenLoaiBenh.Text.Trim() = "" Then Domain.Dialog.Show("Bạn chưa nhập tên loại bệnh") Exit Sub End If loaiBenh.TenLoaiBenh = tbTenLoaiBenh.Text 'Tiến hành cập nhật Dim result As Boolean = LoaiBenhBUS.InsertOrUpdateLoaiBenh(loaiBenh) If (result = True) Then Domain.Dialog.Show("Cập nhật thành công") Else Domain.Dialog.Show("Cập nhật thất bại") End If ReloadData() End Sub Private Sub NewButton_Click(sender As Object, e As RoutedEventArgs) 'Kiểm tra danh sách loại bệnh có trống không If Not listLoaiBenh.Count = 0 Then 'Kiểm tra người dùng đã cập nhật loại bệnh thêm vào trước đó hay chưa If Not listLoaiBenh.Last.MaLoaiBenh = LoaiBenhBUS.GetMaLoaiBenh() Then 'Thêm loại bệnh trống mới vào danh sách Dim loaiBenh As New LoaiBenhDTO(LoaiBenhBUS.GetMaLoaiBenh(), Nothing) listLoaiBenh.Add(loaiBenh) dgLoaiBenh.SelectedIndex = dgLoaiBenh.Items.Count - 1 Else Domain.Dialog.Show("Bạn chưa cập nhật loại bệnh bạn mới thêm vào trước đó") Exit Sub End If Else 'Thêm loại bệnh trống mới vào danh sách Dim loaiBenh As New LoaiBenhDTO(LoaiBenhBUS.GetMaLoaiBenh(), Nothing) listLoaiBenh.Add(loaiBenh) dgLoaiBenh.SelectedIndex = dgLoaiBenh.Items.Count - 1 End If End Sub Private Sub ReloadData() 'Khi người dùng vào màn hình thì cập nhật lại danh sách loại bệnh If dgLoaiBenh IsNot Nothing And Me.IsVisible Then listLoaiBenh = LoaiBenhBUS.GetAllLoaiBenh() dgLoaiBenh.DataContext = listLoaiBenh End If End Sub End Class
trumpsilver/ScrapTest
Presentation/ucLoaiBenh.xaml.vb
Visual Basic
mit
3,618
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 Dim sweptProtrusions As SolidEdgePart.SweptProtrusions = Nothing Dim sweptProtrusion As SolidEdgePart.SweptProtrusion = 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) sweptProtrusions = model.SweptProtrusions For i As Integer = 1 To sweptProtrusions.Count sweptProtrusion = sweptProtrusions.Item(i) Dim FaceType = SolidEdgeGeometry.FeatureTopologyQueryTypeConstants.igQueryAll Dim faces = CType(sweptProtrusion.Faces(FaceType), SolidEdgeGeometry.Edges) Next i End If Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgePart.SweptProtrusion.Faces.vb
Visual Basic
mit
1,886
Imports System Imports System.IO Imports Microsoft.Win32 Public Class MainForm Dim ShownPro As Boolean = False Dim NeedsDKP As Boolean = False Dim CacheHasTinternet As Boolean = True Function ScriptArgumentStringToType(ByVal Type As String) As Byte If Type = "Integer" Then Return 0 If Type = "Boolean" Then Return 1 If Type = "Float" Then Return 2 If Type = "Signed Byte" Then Return 3 If Type = "Unsigned Byte" Then Return 4 If Type = "String" Then Return 5 Return 0 End Function Sub PatchSetting(ByVal SettingName As String, ByVal SettingValue As String) Dim DoTheAdd As Boolean = True Dim FS As String = String.Empty For Each SettingLine As String In File.ReadAllLines(SettingsPath) 'If SettingLine.Length = 0 Then Continue For If SettingLine.StartsWith(SettingName + " ") Then DoTheAdd = False FS += SettingLine + vbcrlf Next If DoTheAdd Then FS += SettingName + " " + SettingValue File.WriteAllText(SettingsPath, FS) End If End Sub Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'If Not System.IO.Directory.Exists(System.IO.Path.GetTempPath + "DSGameMaker") Then 'My.Computer.FileSystem.CreateDirectory(System.IO.Path.GetTempPath + "DSGameMaker") 'End If 'Load plugins 'For Each X As String In File.ReadAllLines(AppPath + "pluginList.dat") 'PluginsToolStripMenuItem.DropDownItems.Add(X, Nothing, New EventHandler(AddressOf RunPlugin)) 'PluginsToolStripMenuItem.DropDownItems.Add(X) 'PluginsToolStripMenuItem.DropDownItems.Item(PluginsToolStripMenuItem.DropDownItems.Count - 1) 'Next 'Initialize Apply Finders With ApplyFinders .Add("[X]") .Add("[Y]") .Add("[VX]") .Add("[VY]") .Add("[OriginalX]") .Add("[OriginalY]") .Add("[Screen]") .Add("[Width]") .Add("[Height]") End With 'Initialize Variable Types With VariableTypes .Add("Integer") .Add("Boolean") .Add("Float") .Add("Signed Byte") .Add("Unsigned Byte") .Add("String") End With AppPath = Application.StartupPath If AppPath.EndsWith("\bin\Debug") Then AppPath = My.Computer.FileSystem.SpecialDirectories.ProgramFiles + "\" + Application.ProductName AppPath += "\" 'Set Up Action icons ActionBG = If(File.Exists(AppPath + "ActionBG.png"), PathToImage(AppPath + "ActionBG.png"), My.Resources.ActionBG) ActionConditionalBG = If(File.Exists(AppPath + "ActionConditionalBG.png"), PathToImage(AppPath + "ActionConditionalBG.png"), My.Resources.ActionConditionalBG) CDrive = AppPath.Substring(0, 3) For Each ctl As Control In Me.Controls If TypeOf ctl Is MdiClient Then ctl.BackgroundImage = My.Resources.MDIBG Next ctl Dim System32Path As String = Environment.GetFolderPath(Environment.SpecialFolder.System) CacheHasTinternet = HasInternetConnection("http://google.com") If Not File.Exists(System32Path + "\SciLexer.dll") Then File.Copy(AppPath + "SciLexer.dll", System32Path + "\SciLexer.dll") End If If Not File.Exists(System32Path + "\ScintillaNet.dll") Then File.Copy(AppPath + "ScintillaNet.dll", System32Path + "\ScintillaNet.dll") End If 'Also into Windows... nasty, rare suggested fix Dim WindowsPath As String = System32Path.Substring(0, System32Path.LastIndexOf("\")) If Not File.Exists(WindowsPath + "\SciLexer.dll") Then File.Copy(AppPath + "SciLexer.dll", WindowsPath + "\SciLexer.dll") End If If Not File.Exists(WindowsPath + "\ScintillaNet.dll") Then File.Copy(AppPath + "ScintillaNet.dll", WindowsPath + "\ScintillaNet.dll") End If Try SetFileType(".dsgm", "DSGMFile") SetFileDescription("DSGMFile", Application.ProductName + " Project") AddAction("DSGMFile", "open", "Open") SetExtensionCommandLine("open", "DSGMFile", """" + AppPath + Application.ProductName + ".exe"" ""%1""") SetDefaultIcon("DSGMFile", """" + AppPath + "Icon.ico""") Catch ex As Exception MsgWarn("You should run " + Application.ProductName + " as an Administrator." + vbCrLf + vbCrLf + "(" + ex.Message + ")") End Try Dim VitalFiles As New Collection With VitalFiles .Add(AppPath + "Resources\NoSprite.png") .Add(AppPath + "ActionIcons\Empty.png") .Add(AppPath + "DefaultResources\Sprite.png") .Add(AppPath + "DefaultResources\Background.png") .Add(AppPath + "DefaultResources\Sound.wav") End With Dim VitalBuggered As Byte = 0 For Each X As String In VitalFiles If Not File.Exists(X) Then VitalBuggered += 1 Next If VitalBuggered = 1 Then MsgError("A vital file is missing. You must reinstall " + Application.ProductName + ".") : Exit Sub If VitalBuggered > 1 Then MsgError("Some vital files are missing. You must reinstall " + Application.ProductName + ".") : Exit Sub RebuildFontCache() 'Toolstrip Renderers MainToolStrip.Renderer = New clsToolstripRenderer DMainMenuStrip.Renderer = New clsMenuRenderer ResRightClickMenu.Renderer = New clsMenuRenderer 'Resources Setup ResourceTypes(0) = "Sprites" MainImageList.Images.Add("SpriteIcon", My.Resources.SpriteIcon) ResourceTypes(1) = "Objects" MainImageList.Images.Add("ObjectIcon", My.Resources.ObjectIcon) ResourceTypes(2) = "Backgrounds" MainImageList.Images.Add("BackgroundIcon", My.Resources.BackgroundIcon) ResourceTypes(3) = "Sounds" MainImageList.Images.Add("SoundIcon", My.Resources.SoundIcon) ResourceTypes(4) = "Rooms" MainImageList.Images.Add("RoomIcon", My.Resources.RoomIcon) ResourceTypes(5) = "Paths" MainImageList.Images.Add("PathIcon", My.Resources.PathIcon) ResourceTypes(6) = "Scripts" MainImageList.Images.Add("ScriptIcon", My.Resources.ScriptIcon) 'Imagelist Setup 'MainImageList.Images.Add("ScriptIcon", My.Resources.ScriptIcon) MainImageList.Images.Add("FolderIcon", My.Resources.FolderIcon) 'Resources Setup For Resource As Byte = 0 To ResourceTypes.Length - 1 ResourcesTreeView.Nodes.Add(String.Empty, ResourceTypes(Resource), 7, 7) Next 'Settings If Not File.Exists(AppPath + "data.dat") Then IO.File.Copy(AppPath + "restore.dat", AppPath + "data.dat") End If SettingsPath = AppPath + "data.dat" PatchSetting("USE_EXTERNAL_SCRIPT_EDITOR", "0") PatchSetting("RIGHT_CLICK", "1") PatchSetting("HIDE_OLD_ACTIONS", "1") PatchSetting("SHRINK_ACTIONS_LIST", "0") LoadSettings() 'Fonts Setup For Each FontFile As String In Directory.GetFiles(AppPath + "Fonts") Dim FontName As String = FontFile.Substring(FontFile.LastIndexOf("\") + 1) FontName = FontName.Substring(0, FontName.IndexOf(".")) FontNames.Add(FontName) Next Text = TitleDataWorks() End Sub Sub GenerateShite(ByVal DisplayResult As String) Dim DW As Int16 = Convert.ToInt16(GetSetting("DEFAULT_ROOM_WIDTH")) Dim DH As Int16 = Convert.ToInt16(GetSetting("DEFAULT_ROOM_HEIGHT")) ' FIX: If DW < 256 Then DW = 256 If DW > 4096 Then DW = 4096 If DW < 192 Then DW = 192 If DH > 4096 Then DH = 4096 CurrentXDS = "ROOM Room_1," + DW.ToString + "," + DH.ToString + ",1,," + DW.ToString + "," + DH.ToString + ",1," + vbCrLf CurrentXDS += "BOOTROOM Room_1" + vbCrLf CurrentXDS += "SCORE 0" + vbCrLf CurrentXDS += "LIVES 3" + vbCrLf CurrentXDS += "HEALTH 100" + vbCrLf CurrentXDS += "PROJECTNAME " + DisplayResult + vbCrLf CurrentXDS += "TEXT2 " + vbCrLf CurrentXDS += "TEXT3 " + vbCrLf CurrentXDS += "FAT_CALL 0" + vbCrLf CurrentXDS += "NITROFS_CALL 1" + vbCrLf CurrentXDS += "MIDPOINT_COLLISIONS 0" + vbCrLf CurrentXDS += "INCLUDE_WIFI_LIB 0" + vbCrLf End Sub Private Sub NewProject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewProjectButton.Click, NewProjectButtonTool.Click Shell(AppPath + ProductName + ".exe /skipauto") End Sub Private Sub MainForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing If BeingUsed Then Dim WillExit As Boolean = False Dim TheText As String = "Your new project" If Not IsNewProject Then TheText = "'" + CacheProjectName + "'" End If Dim Result As Integer = MessageBox.Show(TheText + " may have unsaved changes." + vbCrLf + vbCrLf + "Do you want to save just in case?", Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) If Result = MsgBoxResult.Yes Then : SaveButton_Click(New Object, New System.EventArgs) : WillExit = True ElseIf Result = MsgBoxResult.No Then : e.Cancel = False : WillExit = True ElseIf Result = MsgBoxResult.Cancel Then : e.Cancel = True End If Try If WillExit Then Directory.Delete(SessionPath, True) Directory.Delete(CompilePath, True) If IsNewProject Then IO.File.Delete(AppPath + "NewProjects\" + Session + ".dsgm") End If Catch : End Try End If End Sub Public Sub InternalSave() CleanInternalXDS() SaveButton.Enabled = False SaveButtonTool.Enabled = False IO.File.WriteAllText(SessionPath + "XDS.xds", CurrentXDS) Dim MyBAT As String = "zip.exe a save.zip Sprites Backgrounds Sounds Scripts IncludeFiles NitroFSFiles XDS.xds" + vbCrLf + "exit" RunBatchString(MyBAT, SessionPath, True) 'File.Delete(ProjectPath) File.Copy(SessionPath + "save.zip", ProjectPath, True) File.Delete(SessionPath + "save.bat") File.Delete(SessionPath + "save.zip") SaveButton.Enabled = True SaveButtonTool.Enabled = True End Sub Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click, SaveButtonTool.Click 'If it's a new project, call Save As instead. If IsNewProject Then SaveAsButton_Click(New Object, New System.EventArgs) Exit Sub End If InternalSave() IsNewProject = False End Sub Private Sub AddSpriteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddSpriteButton.Click, AddSpriteButtonTool.Click Dim NewName As String = MakeResourceName("Sprite", "SPRITE") File.Copy(AppPath + "DefaultResources\Sprite.png", SessionPath + "Sprites\0_" + NewName + ".png") XDSAddLine("SPRITE " + NewName + ",32,32") AddResourceNode(ResourceIDs.Sprite, NewName, "SpriteNode", True) For Each X As Form In MdiChildren If Not IsObject(X.Text) Then Continue For DirectCast(X, DObject).AddSprite(NewName) Next RedoSprites = True End Sub Private Sub AddObjectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddObjectButton.Click, AddObjectButtonTool.Click Dim ObjectCount As Byte = GetXDSFilter("OBJECT ").Length Dim NewName As String = MakeResourceName("Object", "OBJECT") XDSAddLine("OBJECT " + NewName + ",None,0") AddResourceNode(ResourceIDs.DObject, NewName, "ObjectNode", True) For Each X As Form In MdiChildren If Not X.Name = "Room" Then Continue For DirectCast(X, Room).AddObjectToDropper(NewName) Next End Sub Private Sub AddBackgroundButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddBackgroundButton.Click, AddBackgroundButtonTool.Click Dim NewName As String = MakeResourceName("Background", "BACKGROUND") File.Copy(AppPath + "DefaultResources\Background.png", SessionPath + "Backgrounds\" + NewName + ".png") XDSAddLine("BACKGROUND " + NewName) AddResourceNode(ResourceIDs.Background, NewName, "BackgroundNode", True) For Each X As Form In MdiChildren If Not IsRoom(X.Text) Then Continue For For Each Y As Control In X.Controls If Not Y.Name = "ObjectsTabControl" Then Continue For For Each Z As Control In DirectCast(Y, TabControl).TabPages(0).Controls If Z.Name = "TopScreenGroupBox" Or Z.Name = "BottomScreenGroupBox" Then For Each I As Control In Z.Controls If I.Name.EndsWith("BGDropper") Then DirectCast(I, ComboBox).Items.Add(NewName) End If Next End If Next Next Next BGsToRedo.Add(NewName) End Sub Private Sub AddSoundButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddSoundButton.Click, AddSoundButtonTool.Click Dim NewName As String = MakeResourceName("Sound", "SOUND") SoundType.ShowDialog() Dim SB As Boolean = SoundType.IsSoundEffect File.Copy(AppPath + "DefaultResources\Sound." + If(SB, "wav", "mp3"), SessionPath + "Sounds\" + NewName + "." + If(SB, "wav", "mp3")) XDSAddLine("SOUND " + NewName + "," + If(SB, "0", "1")) AddResourceNode(ResourceIDs.Sound, NewName, "SoundNode", True) SoundsToRedo.Add(NewName) End Sub Private Sub AddRoomButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddRoomButton.Click, AddRoomButtonTool.Click Dim RoomCount As Byte = GetXDSFilter("ROOM ").Length Dim NewName As String = MakeResourceName("Room", "ROOM") Dim DW As Int16 = Convert.ToInt16(GetSetting("DEFAULT_ROOM_WIDTH")) Dim DH As Int16 = Convert.ToInt16(GetSetting("DEFAULT_ROOM_HEIGHT")) If DW < 256 Then DW = 256 If DW > 4096 Then DW = 4096 If DW < 192 Then DW = 192 If DH > 4096 Then DH = 4096 XDSAddLine("ROOM " + NewName + "," + DW.ToString + "," + DH.ToString + ",1,," + DW.ToString + "," + DH.ToString + ",1,") AddResourceNode(ResourceIDs.Room, NewName, "RoomNode", True) End Sub Private Sub AddPathButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddPathButton.Click, AddPathButtonTool.Click Dim NewName As String = MakeResourceName("Path", "PATH") XDSAddLine("PATH " + NewName) AddResourceNode(ResourceIDs.Path, NewName, "PathNode", True) End Sub Private Sub AddScriptButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddScriptButton.Click, AddScriptButtonTool.Click Dim NewName As String = MakeResourceName("Script", "SCRIPT") File.CreateText(SessionPath + "Scripts\" + NewName + ".dbas").Dispose() XDSAddLine("SCRIPT " + NewName + ",1") AddResourceNode(ResourceIDs.Script, NewName, "ScriptNode", True) End Sub Public Function OpenWarn() As Boolean Dim TheText As String = "'" + CacheProjectName + "'" If IsNewProject Then TheText = "your new Project" Dim Answer As Byte = MessageBox.Show("Are you sure you want to open another Project?" + vbCrLf + vbCrLf + "You will lose any changes you have made to " + TheText + ".", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) If Answer = MsgBoxResult.Yes Then Return True Else Return False End Function Private Sub OpenProjectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenProjectButton.Click, OpenProjectButtonTool.Click If BeingUsed Then : If Not OpenWarn() Then : Exit Sub : End If : End If Dim Result As String = OpenFile(String.Empty, Application.ProductName + " Projects|*.dsgm") If Result.Length = 0 Then Exit Sub OpenProject(Result) End Sub Sub LoadLastProject(ByVal Automatic As Boolean) 'IsNewProject = False Dim LastPath As String = GetSetting("LAST_PROJECT") If Automatic Then If File.Exists(LastPath) Then OpenProject(LastPath) End If Exit Sub End If If BeingUsed Then If LastPath = ProjectPath Then 'Same Project - Reload job Dim Result As Byte = MessageBox.Show("Do you want to reload the current Project?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) If Result = MsgBoxResult.Yes Then CleanFresh(False) : OpenProject(ProjectPath) : Exit Sub Else 'Loading a different project If Not OpenWarn() Then Exit Sub 'Yes load a new file If File.Exists(LastPath) Then OpenProject(LastPath) Exit Sub Else OpenProjectButton_Click(New Object, New System.EventArgs) End If End If Else 'Fresh session If File.Exists(LastPath) Then OpenProject(LastPath) Else OpenProjectButton_Click(New Object, New System.EventArgs) End If End If End Sub Private Sub OpenLastProjectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenLastProjectButton.Click, OpenLastProjectButtonTool.Click LoadLastProject(False) End Sub Private Sub SaveAsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsButton.Click, SaveAsButtonTool.Click Dim Directory As String = ProjectPath Directory = Directory.Substring(0, Directory.IndexOf("\")) Dim Result As String = String.Empty If IsNewProject Then Result = SaveFile(Directory, Application.ProductName + " Projects|*.dsgm", "New Project.dsgm") Else Result = SaveFile(Directory, Application.ProductName + " Projects|*.dsgm", CacheProjectName + ".dsgm") End If If Result.Length = 0 Then Exit Sub CleanInternalXDS() SaveButton.Enabled = False SaveButtonTool.Enabled = False IO.File.WriteAllText(SessionPath + "XDS.xds", CurrentXDS) Dim MyBAT As String = "zip.exe a save.zip Sprites Backgrounds Sounds Scripts IncludeFiles NitroFSFiles XDS.xds" + vbCrLf + "exit" RunBatchString(MyBAT, SessionPath, True) 'File.Delete(ProjectPath) ProjectPath = Result File.Copy(SessionPath + "save.zip", ProjectPath, True) File.Delete(SessionPath + "save.bat") File.Delete(SessionPath + "save.zip") SaveButton.Enabled = True SaveButtonTool.Enabled = True IsNewProject = False Me.Text = TitleDataWorks() End Sub Private Sub OptionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OptionsButton.Click, OptionsButtonTool.Click Options.ShowDialog() End Sub Private Sub ResourcesTreeView_NodeMouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles ResourcesTreeView.NodeMouseDoubleClick If Not e.Node.Parent Is Nothing Then OpenResource(e.Node.Text, e.Node.Parent.Index, False) End If End Sub Private Sub GameSettingsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GameSettingsButton.Click, GameSettingsButtonTool.Click GameSettings.ShowDialog() End Sub Private Sub TestGameButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestGameButton.Click, TestGameButtonTool.Click If Not CompileWrapper() Then Exit Sub Compile.HasDoneIt = False Compile.ShowDialog() If Compile.Success Then NOGBAShizzle() Else CompileFail() End If End Sub Private Sub CompileGameButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompileGameButton.Click, CompileGameButtonTool.Click If Not CompileWrapper() Then Exit Sub Compile.HasDoneIt = False Compile.ShowDialog() If Compile.Success Then With Compiled .Text = CacheProjectName .MainLabel.Text = CacheProjectName .SubLabel.Text = "Compiled by " + Environment.UserName + " at " + GetTime() .ShowDialog() End With Else CompileFail() End If End Sub Private Sub ActionEditorButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ActionEditorButton.Click For Each X As Form In MdiChildren If X.Text = "Action Editor" Then X.Focus() : Exit Sub Next 'Dim ActionForm As New ActionEditor ShowInternalForm(ActionEditor) End Sub Private Sub VariableManagerButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GlobalVariablesButton.Click, GlobalVariablesButtonTool.Click GlobalVariables.ShowDialog() End Sub Sub ActuallyCleanUp() For Each X As String In Directory.GetDirectories(CDrive) If X = CompilePath.Substring(0, CompilePath.Length - 1) Then Continue For Try If X.StartsWith(CDrive + "DSGMTemp") Then Directory.Delete(X, True) Catch : End Try Next For Each X As String In Directory.GetDirectories(AppPath + "ProjectTemp") If X = SessionPath.Substring(0, SessionPath.Length - 1) Then Continue For Try Directory.Delete(X, True) Catch : End Try Next 'For Each X As String In Directory.GetFiles(AppPath + "NewProjects") ' If X.EndsWith(CacheProjectName + ".dsgm") Then Continue For ' File.Delete(X) 'Next End Sub Private Sub CleanUpButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CleanUpButton.Click 'If ProjectPath.Length > 0 Then MsgError("You have a project loaded, so temporary data may not be cleared.") : Exit Sub MsgWarn("This will clean up all unused data created by the sessions system." + vbCrLf + vbCrLf + "Ensure you do not have other instances of the application open.") ActuallyCleanUp() MsgInfo("The process completed successfully.") End Sub Private Sub ProjectStatisticsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Statistics.ShowDialog() End Sub Private Sub OpenCompileTempButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenCompileTempButton.Click System.Diagnostics.Process.Start("explorer", CompilePath) End Sub Private Sub OpenProjectTempButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenProjectTempButton.Click System.Diagnostics.Process.Start("explorer", SessionPath) End Sub Private Sub WebsiteButton_Click() Handles WebsiteButton.Click URL(Domain) End Sub Private Sub ForumButton_Click() Handles ForumButton.Click URL(Domain + "dsgmforum") End Sub Private Sub EditInternalXDSButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditInternalXDSButton.Click If MdiChildren.Count > 0 Then MsgWarn("You must close all open windows to continue.") : Exit Sub Dim Thing As New EditCode With Thing .CodeMode = CodeMode.XDS .ImportExport = False .ReturnableCode = CurrentXDS .StartPosition = FormStartPosition.CenterParent .Text = "Edit Internal XDS" .ShowDialog() CurrentXDS = .MainTextBox.Text End With End Sub Private Sub FontViewerButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FontViewerButton.Click For Each X As Form In MdiChildren If X.Text = "Font Viewer" Then X.Focus() : Exit Sub Next 'Dim ActionForm As New ActionEditor ShowInternalForm(FontViewer) 'FontEditor.ShowDialog() End Sub Private Sub GlobalArraysButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GlobalArraysButton.Click, GlobalArraysButtonTool.Click GlobalArrays.ShowDialog() End Sub Private Sub AboutDSGMButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutDSGMButton.Click AboutDSGM.ShowDialog() End Sub Private Sub MainForm_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown Dim BlankNew As Boolean = True If UpdateVersion > IDVersion Then DUpdate.ShowDialog() End If If Not Directory.Exists(CDrive + "devkitPro") Then MsgInfo("Thank you for installing " + Application.ProductName + "." + vbCrLf + vbCrLf + "The toolchain will now be installed to compile your games.") RundevkitProUpdater() End If Dim SkipAuto As Boolean = False Dim Args As New List(Of String) For Each X As String In My.Application.CommandLineArgs If X = "/skipauto" Then SkipAuto = True : Continue For Args.Add(X) Next If Args.Count > 1 Then MsgWarn("You can only open one Project with " + Application.ProductName + " at once.") ElseIf Args.Count = 1 Then If File.Exists(Args(0)) Then OpenProject(Args(0)) BlankNew = False Else If Not SkipAuto Then If Convert.ToByte(GetSetting("OPEN_LAST_PROJECT_STARTUP")) = 1 Then LoadLastProject(True) BlankNew = False End If End If End If If BlankNew Then BeingUsed = True Dim SessionName As String = String.Empty For Looper As Byte = 0 To 10 SessionName = "NewProject" + MakeSessionName() If Not IO.Directory.Exists(AppPath + "ProjectTemp\" + SessionName) Then Exit For Next FormSession(SessionName) FormSessionFS() IsNewProject = True ProjectPath = AppPath + "NewProjects\" + SessionName + ".dsgm" Me.Text = TitleDataWorks() GenerateShite("<New Project>") RedoAllGraphics = True RedoSprites = True BGsToRedo.Clear() AddResourceNode(ResourceIDs.Room, "Room_1", "RoomNode", False) InternalSave() End If End Sub Private Sub DeleteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteButton.Click DeleteResource(ActiveMdiChild.Text, ActiveMdiChild.Name) End Sub Private Sub CompilesToNitroFSButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompilesToNitroFSButton.Click RedoAllGraphics = True RedoSprites = True BGsToRedo.Clear() Dim ResourceName As String = ResourcesTreeView.SelectedNode.Text If File.Exists(CompilePath + "nitrofiles\" + ResourceName + ".c") Then File.Delete(CompilePath + "nitrofiles\" + ResourceName + ".c") End If If File.Exists(CompilePath + "nitrofiles\" + ResourceName + "_Map.bin") Then File.Delete(CompilePath + "nitrofiles\" + ResourceName + "_Map.bin") End If If File.Exists(CompilePath + "nitrofiles\" + ResourceName + "_Tiles.bin") Then File.Delete(CompilePath + "nitrofiles\" + ResourceName + "_Tiles.bin") End If If File.Exists(CompilePath + "nitrofiles\" + ResourceName + "_Pal.bin") Then File.Delete(CompilePath + "nitrofiles\" + ResourceName + "_Pal.bin") End If Dim OldLine As String = GetXDSLine(ResourcesTreeView.SelectedNode.Parent.Text.ToUpper.Substring(0, ResourcesTreeView.SelectedNode.Parent.Text.Length - 1) + " " + ResourcesTreeView.SelectedNode.Text) Dim NewLine As String = GetXDSLine(ResourcesTreeView.SelectedNode.Parent.Text.ToUpper.Substring(0, ResourcesTreeView.SelectedNode.Parent.Text.Length - 1) + " " + ResourcesTreeView.SelectedNode.Text) If ResourcesTreeView.SelectedNode.Parent.Text = "Sprites" Then If iGet(NewLine, 3, ",") = "NoNitro" Then NewLine = NewLine.Replace(",NoNitro", ",Nitro") Else NewLine = NewLine.Replace(",Nitro", ",NoNitro") End If If iGet(NewLine, 3, ",") = String.Empty Then NewLine += ",Nitro" End If End If If ResourcesTreeView.SelectedNode.Parent.Text = "Backgrounds" Then If iGet(NewLine, 1, ",") = "NoNitro" Then NewLine = NewLine.Replace(",NoNitro", ",Nitro") Else NewLine = NewLine.Replace(",Nitro", ",NoNitro") End If If iGet(NewLine, 1, ",") = String.Empty Then NewLine += ",Nitro" End If End If XDSChangeLine(OldLine, NewLine) 'MsgBox(ResourcesTreeView.SelectedNode.Parent.Text.ToUpper.Substring(0, ResourcesTreeView.SelectedNode.Parent.Text.Length - 1) + " " + ResourcesTreeView.SelectedNode.Text) End Sub Private Sub ManualButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelpContentsButton.Click HelpViewer.ShowDialog() End Sub Private Sub TutorialsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OnlineTutorialsButton.Click URL(Domain + "dsgmforum/viewforum.php?f=6") End Sub Private Sub GlobalStructuresButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GlobalStructuresButton.Click, GlobalStructuresButtonTool.Click GlobalStructures.ShowDialog() End Sub Private Sub RunDevkitProUpdaterButton(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReinstallToolchainButton.Click RundevkitProUpdater() End Sub Private Sub EditMenu_DropDownOpening(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditMenu.DropDownOpening GoToLastFoundButton.Enabled = False If LastResourceFound.Length > 0 Then GoToLastFoundButton.Enabled = True Dim OuiOui As Boolean = Not (ActiveMdiChild Is Nothing) DeleteButton.Enabled = OuiOui DuplicateButton.Enabled = OuiOui End Sub Private Sub CompileChangeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GraphicsChangeButton.Click, SoundChangeButton.Click Select Case DirectCast(sender, ToolStripMenuItem).Name Case "GraphicsChangeButton" RedoAllGraphics = True RedoSprites = True BGsToRedo.Clear() Case "SoundChangeButton" BuildSoundsRedoFromFile() End Select End Sub Private Sub RunNOGBAButton_Click() Handles RunNOGBAButton.Click Diagnostics.Process.Start(FormNOGBAPath() + "\NO$GBA.exe") End Sub Private Sub ResRightClickMenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ResRightClickMenu.Opening Dim ToWorkFrom As TreeNode Try ToWorkFrom = ResourcesTreeView.SelectedNode.Parent DeleteResourceRightClickButton.Enabled = True OpenResourceRightClickButton.Enabled = True DuplicateResourceRightClickButton.Enabled = True CompilesToNitroFSButton.Enabled = True CompilesToNitroFSButton.Image = DS_Game_Maker.My.Resources.Resources.DeleteIcon If ToWorkFrom.Text = String.Empty Then Exit Try Catch ex As Exception ToWorkFrom = ResourcesTreeView.SelectedNode DeleteResourceRightClickButton.Enabled = False OpenResourceRightClickButton.Enabled = False DuplicateResourceRightClickButton.Enabled = False CompilesToNitroFSButton.Enabled = False CompilesToNitroFSButton.Image = DS_Game_Maker.My.Resources.Resources.DeleteIcon End Try With AddResourceRightClickButton .Image = My.Resources.PlusIcon Select Case ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) Case "Sprite" : .Image = AddSpriteButton.Image Case "Background" : .Image = AddBackgroundButton.Image Case "Script" : .Image = AddScriptButton.Image Case "Room" : .Image = AddRoomButton.Image Case "Path" : .Image = AddPathButton.Image Case "Object" : .Image = AddObjectButton.Image Case "Sound" : .Image = AddSoundButton.Image End Select .Text = "Add " + ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) End With With CompilesToNitroFSButton If Not ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Sprite" And Not ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Background" Then .Enabled = False If Not ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Sound" Then .Image = DS_Game_Maker.My.Resources.Resources.DeleteIcon Else .Image = DS_Game_Maker.My.Resources.Resources.AcceptIcon End If Else If ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Sprite" Then If iGet(GetXDSLine("SPRITE " + ResourcesTreeView.SelectedNode.Text), 3, ",") = "Nitro" Then .Image = DS_Game_Maker.My.Resources.Resources.AcceptIcon End If End If If ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Background" Then If iGet(GetXDSLine("BACKGROUND " + ResourcesTreeView.SelectedNode.Text), 1, ",") = "Nitro" Then .Image = DS_Game_Maker.My.Resources.Resources.AcceptIcon End If End If End If End With End Sub Private Sub ResourcesTreeView_NodeMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles ResourcesTreeView.NodeMouseClick ResourcesTreeView.SelectedNode = e.Node End Sub Private Sub DeleteResourceRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteResourceRightClickButton.Click Dim Type As String = ResourcesTreeView.SelectedNode.Parent.Text.Substring(0, ResourcesTreeView.SelectedNode.Parent.Text.Length - 1) If Type = "Object" Then Type = "DObject" Type = Type.Replace(" ", String.Empty) DeleteResource(ResourcesTreeView.SelectedNode.Text, Type) End Sub Private Sub OpenResourceRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenResourceRightClickButton.Click OpenResource(ResourcesTreeView.SelectedNode.Text, ResourcesTreeView.SelectedNode.Parent.Index, False) End Sub Private Sub AddResourceRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddResourceRightClickButton.Click Dim TheText As String = AddResourceRightClickButton.Text.Substring(4) Select Case TheText Case "Sprite" : AddSpriteButton_Click(New Object, New System.EventArgs) Case "Background" : AddBackgroundButton_Click(New Object, New System.EventArgs) Case "Object" : AddObjectButton_Click(New Object, New System.EventArgs) Case "Sound" : AddSoundButton_Click(New Object, New System.EventArgs) Case "Room" : AddRoomButton_Click(New Object, New System.EventArgs) Case "Path" : AddPathButton_Click(New Object, New System.EventArgs) Case "Script" : AddScriptButton_Click(New Object, New System.EventArgs) End Select End Sub Private Sub DuplicateResourceRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DuplicateResourceRightClickButton.Click Dim TheName As String = ResourcesTreeView.SelectedNode.Text CopyResource(TheName, GenerateDuplicateResourceName(TheName), ResourcesTreeView.SelectedNode.Parent.Index) End Sub Private Sub FindResourceButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindResourceButton.Click Dim Result As String = GetInput("Which resource are you looking for?", LastResourceFound, ValidateLevel.None) FindResource(Result) End Sub Private Sub GoToLastFoundButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GoToLastFoundButton.Click FindResource(LastResourceFound) End Sub Private Sub FindInScriptsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindInScriptsButton.Click Dim Result As String = GetInput("Search term:", LastScriptTermFound, ValidateLevel.None) Dim Shower As New FoundInScripts With Shower .Term = Result .Text = "Searching Scripts for '" + Result + "'" End With ShowInternalForm(Shower) End Sub Private Sub DuplicateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DuplicateButton.Click If ActiveMdiChild Is Nothing Then Exit Sub Dim TheName As String = ActiveMdiChild.Text Dim ResT As Byte = 0 Select Case ActiveMdiChild.Name Case "Sprite" ResT = ResourceIDs.Sprite Case "Background" ResT = ResourceIDs.Background Case "DObject" ResT = ResourceIDs.DObject Case "Room" ResT = ResourceIDs.Room Case "Path" ResT = ResourceIDs.Path Case "Script" ResT = ResourceIDs.Script Case "Sound" ResT = ResourceIDs.Sound End Select CopyResource(TheName, GenerateDuplicateResourceName(TheName), ResT) End Sub 'Private Sub InstallPluginButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InstallPluginButton.Click, InstallPluginToolStripMenuItem.Click ' Dim FilePath As String = OpenFile(String.Empty, "DS Game Maker Plugins|*.dsgmp") ' If FilePath.Length = 0 Then Exit Sub 'Dim P As String = AppPath + "PluginInstall\" ' Directory.CreateDirectory(P) ' File.Copy(FilePath, P + "Plugin.zip") 'Dim MyBAT As String = "zip.exe x Plugin.zip -y" + vbCrLf + "exit" ' RunBatchString(MyBAT, P, True) 'Dim PName As String = String.Empty 'Dim PAuthor As String = String.Empty 'Dim PLink As String = String.Empty 'Dim Files As New List(Of String) 'Dim MakeLines As New List(Of String) ' For Each X As String In File.ReadAllLines(P + "data.txt") ' If X.StartsWith("NAME ") Then PName = X.Substring(5) ' If X.StartsWith("AUTHOR ") Then PAuthor = X.Substring(7) ' If X.StartsWith("LINK ") Then PLink = X.Substring(5) ' Next ' File.Copy(P + "Executable.exe", AppPath + "Plugins\" + PName + ".exe") ' File.WriteAllText(AppPath + "pluginList.dat", File.ReadAllText(AppPath + "pluginList.dat") + PName + vbCrLf) ' My.Computer.FileSystem.DeleteDirectory(P, FileIO.DeleteDirectoryOption.DeleteAllContents) ' End Sub 'Private Sub RunPlugin(ByVal sender As Object, ByVal e As System.EventArgs) 'DirectCast(sender, ToolStripMenuItem).Name ' Dim Plugins As Integer 'Dim SelectedPlugin As Integer ' For Each X As String In File.ReadAllLines(AppPath + "pluginList.dat") ' Plugins += 1 ' Next 'If PluginsToolStripMenuItem.DropDownItems.Item(3).Pressed Then ' MsgBox("fdm") 'End If 'MsgBox(PluginsToolStripMenuItem.DropDownItems.Item(3).Text) 'For LoopVar As Integer = 2 To Plugins + 2 ' If PluginsToolStripMenuItem.DropDownItems.Item(LoopVar).Pressed Then ' SelectedPlugin = LoopVar ' End If ' Next ' MsgInfo("Running Plugin " + PluginsToolStripMenuItem.DropDownItems.Item(SelectedPlugin).Text) 'End Sub End Class
jadaradix/dsgamemaker
MainForm.vb
Visual Basic
mit
42,169
Option Strict Off Option Explicit On Imports VB = Microsoft.VisualBasic Friend Class frmStockTakeCSV Inherits System.Windows.Forms.Form Dim rs As ADODB.Recordset Dim Te_Name As String Dim MyFTypes As String Dim sql1 As String Dim fso As New Scripting.FileSystemObject ' picture loading Dim lMWNo As Integer ' to select W/H for stock take Private Sub loadLanguage() 'NOTE: Caption has a spelling mistake, DB Entry 1213 is correct! rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1213 'Stock Take If rsLang.RecordCount Then Me.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Me.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 2506 'Show Differendce|Checked If rsLang.RecordCount Then cmdDiff.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdDiff.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value 'NOTE: DB Entry 2507 requires "&" for accelerator key rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 2507 'Save and Exit|Checked If rsLang.RecordCount Then cmdClose.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdClose.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1838 'Barcode|Checked If rsLang.RecordCount Then Label1.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Label1.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1674 'Description|Checked If rsLang.RecordCount Then Label2.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Label2.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1676 'Qty|Checked If rsLang.RecordCount Then Label3.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Label3.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1080 'Search|Checked If rsLang.RecordCount Then cmdSearch.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdSearch.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 2512 'Show Pictures|Checked If rsLang.RecordCount Then chkPic.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : chkPic.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsHelp.filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'" 'UPGRADE_ISSUE: Form property frmStockTakeCSV.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp.Fields("Help_ContextID").Value End Sub 'UPGRADE_WARNING: Event chkPic.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' Private Sub chkPic_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkPic.CheckStateChanged If chkPic.CheckState Then Me.Width = twipsToPixels(12675, True) picBC.Visible = True imgBC.Visible = True Me.Left = twipsToPixels(400, True) Else Me.Width = twipsToPixels(8640, True) picBC.Visible = False imgBC.Visible = False End If End Sub Private Sub cmdClose_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdClose.Click Dim MStockNew As Integer On Error GoTo MyErH Dim rsB As ADODB.Recordset Dim rsk As ADODB.Recordset rsB = New ADODB.Recordset rsk = New ADODB.Recordset rsk = getRS("SELECT * FROM " & Te_Name & "") If rsk.RecordCount > 0 Then 'UPGRADE_WARNING: Couldn't resolve default property of object MStockNew. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' MStockNew = 2 rsB = getRS("INSERT INTO StockGroup(StockGroup_Name,StockGroup_Disabled)VALUES('" & Te_Name & "',0)") UpdateCatalogID((Te_Name)) End If MyErH: Me.Close() End Sub Private Sub report_WHTransfer(ByRef tblName As String) Dim rs As ADODB.Recordset Dim sql As String Dim Report As CrystalDecisions.CrystalReports.Engine.ReportDocument Report.Load("cryWHRecVerify.rpt") System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor rs = getRS("SELECT Company.Company_Name FROM Company;") Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name")) rs.Close() sql = "SELECT Handheld777_0.HandHeldID, StockItem.StockItem_Name, Handheld777_0.Quantity" sql = sql & " FROM Handheld777_0 INNER JOIN StockItem ON Handheld777_0.HandHeldID = StockItem.StockItemID;" rs = getRS(sql) Dim ReportNone As CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone.Load("cryNoRecords.rpt") If rs.BOF Or rs.EOF Then ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString) ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString) frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString frmReportShow.CRViewer1.ReportSource = ReportNone frmReportShow.mReport = ReportNone : frmReportShow.sMode = "0" frmReportShow.CRViewer1.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default frmReportShow.ShowDialog() Exit Sub End If Report.Database.Tables(1).SetDataSource(rs) 'Report.VerifyOnEveryPrint = True frmReportShow.Text = Report.ParameterFields("txtTitle").ToString frmReportShow.CRViewer1.ReportSource = Report frmReportShow.mReport = Report : frmReportShow.sMode = "0" frmReportShow.CRViewer1.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default frmReportShow.ShowDialog() End Sub Private Sub cmdDiff_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdDiff.Click Dim strIn As String Dim strFldName As String 'Te_Name Dim rs As ADODB.Recordset Dim rj As ADODB.Recordset On Error Resume Next 'Set rs = getRS("SELECT * FROM Te_Name") cnnDB.Execute("DELETE * FROM Handheld777_0;") cnnDB.Execute("DROP TABLE Handheld777_0;") strFldName = "HandHeldID Number,Handheld_Barcode Text(50), Quantity Currency" cnnDB.Execute("CREATE TABLE " & "Handheld777_0" & " (" & strFldName & ")") System.Windows.Forms.Application.DoEvents() rj = getRS("SELECT WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID, WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID, WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity From WarehouseStockItemLnk WHERE (((WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID)=" & lMWNo & ") AND ((WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity)>0))") Do While rj.EOF = False rs = getRS("SELECT * FROM " & Te_Name & " WHERE HandHeldID=" & rj.Fields("WarehouseStockItemLnk_StockItemID").Value & ";") If rs.RecordCount > 0 Then Else strIn = "INSERT INTO Handheld777_0 (HandHeldID,Handheld_Barcode,Quantity) VALUES (" & rj.Fields("WarehouseStockItemLnk_StockItemID").Value & ", '" & rj.Fields("WarehouseStockItemLnk_Quantity").Value & "', " & rj.Fields("WarehouseStockItemLnk_Quantity").Value & ")" cnnDB.Execute(strIn) End If rj.moveNext() Loop report_WHTransfer("Handheld777_0") cnnDB.Execute("DELETE * FROM Handheld777_0;") cnnDB.Execute("DROP TABLE Handheld777_0;") Exit Sub diff_Error: MsgBox(Err.Number & " " & Err.Description) End Sub Private Sub cmdsearch_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdsearch.Click Dim eroor As String On Error Resume Next 'openConnection Dim rsP As ADODB.Recordset Dim rsk As ADODB.Recordset Dim rsTest As ADODB.Recordset Dim rsNew As ADODB.Recordset rs = New ADODB.Recordset rsP = New ADODB.Recordset rsk = New ADODB.Recordset rsk = New ADODB.Recordset rsTest = New ADODB.Recordset rsNew = New ADODB.Recordset If Me.txtcode.Text = "" Then Exit Sub 'If Me.txtCode.Text <> "" Then 'creating table name 'Te_Name = "HandHeld" & Trim(Year(Date)) & Trim(Month(Date)) & Trim(Day(Date)) & Trim(Hour(Now)) & Trim(Minute(Now)) & Trim(Second(Now)) & "_" & frmMenu.lblUser.Tag rsTest = getRS("SELECT Barcodes,Description,Quantity FROM " & Te_Name & "") 'If rsTest.RecordCount And MStockNew = 0 Then rs = getRS("SELECT * FROM Catalogue WHERE Catalogue_Barcode='" & Me.txtcode.Text & "'") 'check if the barcode exists If rs.RecordCount > 0 Then rsP = getRS("SELECT StockItem_Name FROM StockItem WHERE StockItemID=" & rs.Fields("Catalogue_StockItemID").Value & "") Me.txtdesc.Text = rsP.Fields("StockItem_Name").Value Me.txtQty.Focus() 'show pic If Me.cmdSearch.Text <> "&Add" Then If chkPic.CheckState And picBC.Visible = True Then If fso.FileExists(serverPath & "\images\" & Me.txtcode.Text & ".jpg") Then picBC.Image = System.Drawing.Image.FromFile(serverPath & "\images\" & Me.txtcode.Text & ".jpg") imgBC.Image = picBC.Image Else MsgBox("No picture found for " & Me.txtcode.Text) End If End If End If 'show pic Me.cmdSearch.Text = "&Add" 'if the barcode does not exist display a message ElseIf rs.RecordCount < 1 Then MsgBox("The Item does not exist,Please add it in Stock Create/Edit, New Stock Item", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OKOnly, "4POS") Me.txtcode.Text = "" Me.txtcode.Focus() Exit Sub End If 'Checking if the barcode was found and if the quantity textbox has a value Dim NewQty As Double If Me.cmdSearch.Text = "&Add" And Me.txtQty.Text <> "" Then 'creating fields with their data types MyFTypes = "HandHeldID Number,Barcodes Text(50),Description Text(50),Quantity Currency" rsk = getRS("SELECT * FROM " & Te_Name & "") 'if the table has not been created yet create it Select Case eroor Case Is < 0 Error(5) Case 1 GoTo erh End Select erh: cnnDB.Execute("CREATE TABLE " & Te_Name & " (" & MyFTypes & ")") 'selecting from the new table created rsNew = getRS("SELECT * FROM " & Te_Name & " WHERE Barcodes='" & Me.txtcode.Text & "'") 'if the item is already in the newly created table then add the previous quantity to the new one then update it If rsNew.RecordCount > 0 Then NewQty = CDbl(Me.txtQty.Text) NewQty = NewQty + rsNew.Fields("Quantity").Value 'update the quantity rsk = getRS("UPDATE " & Te_Name & " SET Quantity=" & NewQty & " WHERE Barcodes='" & Me.txtcode.Text & "'") ElseIf rsNew.RecordCount < 1 Then 'inserting into the newly created table rsk = getRS("INSERT INTO " & Te_Name & "(HandHeldID,Barcodes,Description,Quantity)VALUES(" & rs.Fields("Catalogue_StockItemID").Value & ",'" & Me.txtcode.Text & "','" & Me.txtdesc.Text & "'," & Me.txtQty.Text & " )") End If 'selecting from the newly created table rsk = getRS("SELECT Barcodes,Description,Quantity FROM " & Te_Name & "") 'filling the datagrid with the record consisting of barcode,description,quantity if the barcode exist Me.DataGrid1.DataSource = rsk Me.txtcode.Text = "" Me.txtdesc.Text = "" Me.txtQty.Text = "" Me.cmdSearch.Text = "&Search" Me.txtcode.Focus() End If 'ElseIf rsTest.RecordCount > 0 And MStockNew = 2 Then 'MsgBox "A Table with the Same Name Already Exist", vbApplicationModal + vbOKOnly, "4POS" 'Me.txtCode.Text = "" 'Me.cmdClose.SetFocus 'End If End Sub Private Sub frmStockTakeCSV_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress Dim KeyAscii As Short = Asc(eventArgs.KeyChar) If KeyAscii = 13 And Me.cmdSearch.Text = "&Search" And Me.txtcode.Text <> "" Then cmdsearch_Click(cmdsearch, New System.EventArgs()) ElseIf KeyAscii = 13 And Me.cmdSearch.Text = "&Add" And Me.txtdesc.Text <> "" Then cmdsearch_Click(cmdsearch, New System.EventArgs()) ElseIf KeyAscii = 27 Then cmdClose_Click(cmdClose, New System.EventArgs()) End If eventArgs.KeyChar = Chr(KeyAscii) If KeyAscii = 0 Then eventArgs.Handled = True End If End Sub Sub UpdateCatalogID(ByRef st_Name As String) Dim strFldName As String Dim strIn As String Dim rj As ADODB.Recordset Dim rs As ADODB.Recordset Dim rID As ADODB.Recordset 'Set rID = getRS("SELECT * FROM " & st_Name) 'Do While rID.EOF = False ' If prgUpdate.value = prgUpdate.Max Then ' prgUpdate.value = 0 ' Else ' prgUpdate.value = prgUpdate.value + 1 ' End If ' 'rID("Handheld_Barcode") = 0 ' rID("HandHeldID") = 0 ' rID.update '"HandHeldID", 0 ' rID.moveNext 'Loop strIn = "UPDATE " & st_Name & " SET HandHeldID = 0 WHERE Quantity > 0;" cnnDB.Execute(strIn) rj = getRS("SELECT * FROM " & st_Name) Do While rj.EOF = False 'If prgUpdate.value = prgUpdate.Max Then ' prgUpdate.value = 0 'Else ' prgUpdate.value = prgUpdate.value + 1 'End If 'Set rs = getRS("SELECT * FROM Catalogue WHERE Catalogue_Barcode = '" & rj("Handheld_Barcode") & "'") rs = getRS("SELECT StockItem.StockItem_Disabled, StockItem.StockItem_Discontinued, * FROM Catalogue INNER JOIN StockItem ON Catalogue.Catalogue_StockItemID = StockItem.StockItemID WHERE (((Catalogue.Catalogue_Barcode)='" & rj.Fields("Barcodes").Value & "') AND ((StockItem.StockItem_Disabled)=False) AND ((StockItem.StockItem_Discontinued)=False));") If rs.RecordCount > 0 Then cnnDB.Execute("UPDATE " & st_Name & " SET HandHeldID = " & rs.Fields("Catalogue_StockItemID").Value & ", Quantity = " & (rj.Fields("Quantity").Value * rs.Fields("Catalogue_Quantity").Value) & " WHERE Barcodes = '" & rj.Fields("Barcodes").Value & "'") rj.moveNext() Loop 'chkDuplicate: strFldName = "HandHeldID Number,Barcodes Text(50),Description Text(50),Quantity Currency" cnnDB.Execute("CREATE TABLE " & "Handheld777" & " (" & strFldName & ")") System.Windows.Forms.Application.DoEvents() rj = getRS("SELECT * FROM " & st_Name) Do While rj.EOF = False rs = getRS("SELECT * FROM Handheld777 WHERE HandHeldID=" & rj.Fields("HandHeldID").Value & ";") If rs.RecordCount > 0 Then strIn = "UPDATE Handheld777 SET Quantity = " & (rs.Fields("Quantity").Value + rj.Fields("Quantity").Value) & " WHERE HandHeldID=" & rj.Fields("HandHeldID").Value & ";" Else strIn = "INSERT INTO Handheld777 (HandHeldID,Barcodes,Quantity) VALUES (" & rj.Fields("HandHeldID").Value & ", '" & rj.Fields("Barcodes").Value & "', " & rj.Fields("Quantity").Value & ")" End If cnnDB.Execute(strIn) rj.moveNext() Loop cnnDB.Execute("DELETE * FROM " & st_Name & ";") 'strIn = "SELECT Handheld777.* INTO " & st_Name & " FROM Handheld777" '& ResolveTable(cmbTables.Text) cnnDB.Execute("INSERT INTO " & st_Name & " SELECT * FROM Handheld777;") cnnDB.Execute("DROP TABLE Handheld777;") 'chkDuplicate: 'DeleteBlankID 'MsgBox "File was extracted and exported succesfully", vbApplicationModal + vbInformation + vbOKOnly, App.title 'prgUpdate.value = 300 End Sub Private Sub frmStockTakeCSV_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load On Error Resume Next If cnnDB Is Nothing Then If openConnection = True Then End If End If 'creating table name Te_Name = "HandHeld" & Trim(CStr(Year(Today))) & Trim(CStr(Month(Today))) & Trim(CStr(VB.Day(Today))) & Trim(CStr(Hour(Now))) & Trim(CStr(Minute(Now))) & Trim(CStr(Second(Now))) & "_" & frmMenu.lblUser.Tag loadLanguage() lMWNo = frmMWSelect.getMWNo If lMWNo > 1 Then 'Set rsWH = getRS("SELECT * FROM Warehouse WHERE WarehouseID=" & lMWNo & ";") 'Report.txtWH.SetText rsWH("Warehouse_Name") End If End Sub End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmStockTakeCSV.vb
Visual Basic
mit
16,508
Option Strict Off Option Explicit On Friend Class frmBlockTestFilterSelect Inherits System.Windows.Forms.Form Dim gID As Integer Dim dataArray(,) As Integer Dim cmdClick As New List(Of Button) Private Sub loadLanguage() 'frmPricelistFilterItem = No Code [Allocate Stock Items to Pricelist] 'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 'If rsLang.RecordCount Then frmPricelistFilterItem.Caption = rsLang("LanguageLayoutLnk_Description"): frmPricelistFilterItem.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") 'lblHeading = No Code/Dynamic! 'TOOLBAR CODE NOT DONE!!! rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1080 'Search|Checked If rsLang.RecordCount Then _lbl_2.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _lbl_2.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1004 'Exit|Checked If rsLang.RecordCount Then cmdExit.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdExit.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsHelp.filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'" 'UPGRADE_ISSUE: Form property frmBlockTestFilterSelect.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp.Fields("Help_ContextID").Value End Sub Private Sub cmdClick_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Dim Index As Integer Dim btn As New Button btn = DirectCast(eventSender, Button) Index = GetIndexer(btn, cmdClick) tbStockItem_ButtonClick(Me.tbStockItem.Items.Item(Index), New System.EventArgs()) lstStockItem.Focus() End Sub Private Sub cmdExit_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdExit.Click Me.Close() End Sub Public Sub loadItem(ByRef id As Integer, ByRef selectTestLoad As Integer, ByRef tempTestID As Integer) Dim x As Short Dim rs As ADODB.Recordset gID = id 'Set rs = getRS("SELECT StockItem.StockItem_Name, * FROM BlockTest INNER JOIN StockItem ON BlockTest.BlockTest_MainItemID = StockItem.StockItemID WHERE (((BlockTest.BlockTest_MainItemID)=" & gID & "));") rs = getRS("SELECT StockItem.StockItem_Name, * FROM BlockTest INNER JOIN StockItem ON BlockTest.BlockTest_MainItemID = StockItem.StockItemID WHERE (((BlockTest.BlockTest_MainItemID)=" & gID & ") AND ((BlockTest.BlockTestID)<>" & tempTestID & "));") If rs.BOF Or rs.EOF Then Else lblHeading.Text = rs.Fields("StockItem_Name").Value 'Set rs = getRS("SELECT TOP 100 PERCENT StockItem.StockItemID, StockItem.StockItem_Name FROM StockItem ORDER BY StockItem_Name;") ReDim dataArray(rs.RecordCount, 3) x = -1 Do Until rs.EOF x = x + 1 dataArray(x, 0) = rs.Fields("BlockTestID").Value dataArray(x, 1) = rs.Fields("BlockTest_Desc").Value dataArray(x, 2) = False dataArray(x, 3) = rs.Fields("BlockTest_WeightCarcass").Value rs.MoveNext() Loop 'Set rs = getRS("SELECT PricelistFilterStockItemLnk.PricelistStockItemLnk_StockItemID From PricelistFilterStockItemLnk WHERE (((PricelistFilterStockItemLnk.PricelistStockItemLnk_PricelistID)=" & gID & "));") 'Do Until rs.EOF ' For x = LBound(dataArray) To UBound(dataArray) ' If dataArray(x, 0) = rs("PricelistStockItemLnk_StockItemID") Then ' dataArray(x, 2) = True ' End If ' Next x ' rs.moveNext 'Loop doLoad() loadLanguage() ShowDialog() selectTestLoad = dataArray.Clone() End If End Sub Private Sub doLoad() Dim x As Short Dim loading As Boolean Dim tmp As String loading = True lstStockItem.Visible = False Me.lstStockItem.Items.Clear() Dim m As Integer Select Case Me.tbStockItem.Tag Case CStr(1) For x = 0 To UBound(dataArray) - 1 If dataArray(x, 2) Then If InStr(UCase(dataArray(x, 1)), UCase(Me.txtSearch.Text)) Then tmp = dataArray(x, 1) & ", " & x.ToString m = lstStockItem.Items.Add(tmp) lstStockItem.SetItemChecked(m, dataArray(x, 2)) End If End If Next Case CStr(2) For x = 0 To UBound(dataArray) - 1 If dataArray(x, 2) Then Else If InStr(UCase(dataArray(x, 1)), UCase(Me.txtSearch.Text)) Then tmp = dataArray(x, 1) & ", " & x.ToString m = lstStockItem.Items.Add(tmp) lstStockItem.SetItemChecked(m, dataArray(x, 2)) End If End If Next Case Else For x = 0 To UBound(dataArray) - 1 If InStr(UCase(dataArray(x, 1)), UCase(Me.txtSearch.Text)) Then tmp = dataArray(x, 1) & ", " & x.ToString m = lstStockItem.Items.Add(tmp) lstStockItem.SetItemChecked(m, dataArray(x, 2)) End If Next End Select If lstStockItem.SelectedIndex Then lstStockItem.SelectedIndex = 0 lstStockItem.Visible = True loading = False End Sub Private Sub frmBlockTestFilterSelect_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress Dim KeyAscii As Short = Asc(eventArgs.KeyChar) Select Case KeyAscii Case System.Windows.Forms.Keys.Escape KeyAscii = 0 cmdExit_Click(cmdExit, New System.EventArgs()) End Select eventArgs.KeyChar = Chr(KeyAscii) If KeyAscii = 0 Then eventArgs.Handled = True End If End Sub 'UPGRADE_WARNING: Event lstStockItem.SelectedIndexChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' Private Sub lstStockItem_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles lstStockItem.SelectedIndexChanged Dim loading As Boolean Dim sql As String If loading Then Exit Sub Dim x As Short x = CShort(lstStockItem.SelectedIndex) If lstStockItem.SelectedIndex <> -1 Then dataArray(x, 2) = CShort(lstStockItem.GetItemChecked(lstStockItem.SelectedIndex)) 'sql = "DELETE PricelistFilterStockItemLnk.* From PricelistFilterStockItemLnk WHERE (((PricelistFilterStockItemLnk.PricelistStockitemLnk_PricelistID)=" & gID & ") AND ((PricelistFilterStockItemLnk.PricelistStockitemLnk_StockitemID)=" & dataArray(x, 0) & "));" 'cnnDB.Execute sql 'If dataArray(x, 2) Then ' sql = "INSERT INTO PricelistFilterStockItemLnk ( PricelistStockitemLnk_PricelistID, PricelistStockitemLnk_StockitemID ) SELECT " & gID & " AS pricelist, " & dataArray(x, 0) & " AS stock;" ' cnnDB.Execute sql 'End If End If End Sub Private Sub tbStockItem_ButtonClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles _tbStockItem_Button1.Click, _tbStockItem_Button2.Click, _tbStockItem_Button3.Click Dim Button As System.Windows.Forms.ToolStripItem = CType(eventSender, System.Windows.Forms.ToolStripItem) Dim x As Short For x = 0 To tbStockItem.Items.Count CType(tbStockItem.Items.Item(x), ToolStripButton).Checked = False Next tbStockItem.Tag = Button.Owner.Items.IndexOf(Button) - 1 ' buildDepartment 'Button.Checked = True doLoad() End Sub Private Sub txtSearch_KeyDown(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown Dim KeyCode As Short = eventArgs.KeyCode Dim Shift As Short = eventArgs.KeyData \ &H10000 If KeyCode = 40 Then Me.lstStockItem.Focus() KeyCode = 0 End If End Sub Private Sub txtSearch_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtSearch.KeyPress Dim KeyAscii As Short = Asc(eventArgs.KeyChar) Select Case KeyAscii Case 13 doLoad() KeyAscii = 0 End Select eventArgs.KeyChar = Chr(KeyAscii) If KeyAscii = 0 Then eventArgs.Handled = True End If End Sub Private Sub frmBlockTestFilterSelect_Load(sender As Object, e As System.EventArgs) Handles Me.Load cmdClick.AddRange(New Button() {_cmdClick_1, _cmdClick_2, _cmdClick_3}) Dim btn As New Button For Each btn In cmdClick AddHandler btn.Click, AddressOf cmdClick_Click Next End Sub End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmBlockTestFilterSelect.vb
Visual Basic
mit
9,519
Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Aspose.Email.Outlook.Pst Imports Aspose.Email Imports Aspose.Email.Outlook Imports Aspose.Email.Recurrences ' This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET ' API reference when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq ' for more information. If you do not wish to use NuGet, you can manually download ' Aspose.Email for .NET API from http://www.aspose.com/downloads, ' install it and then add its reference to this project. For any issues, questions or suggestions ' please feel free to contact us using http://www.aspose.com/community/forums/default.aspx ' Namespace Aspose.Email.Examples.VisualBasic.Email.Outlook Class WeeklyEndAfterNoccurrences Public Shared Sub Run() ' ExStart:WeeklyEndAfterNoccurrences ' The path to the File directory. Dim dataDir As String = RunExamples.GetDataDir_Outlook() Dim localZone As TimeZone = TimeZone.CurrentTimeZone Dim ts As TimeSpan = localZone.GetUtcOffset(DateTime.Now) Dim StartDate As New DateTime(2015, 7, 16) StartDate = StartDate.Add(ts) Dim DueDate As New DateTime(2015, 7, 16) Dim endByDate As New DateTime(2015, 9, 1) DueDate = DueDate.Add(ts) endByDate = endByDate.Add(ts) Dim task As New MapiTask("This is test task", "Sample Body", StartDate, DueDate) task.State = MapiTaskState.NotAssigned ' Set the weekly recurrence Dim rec = New MapiCalendarWeeklyRecurrencePattern() With { _ .EndType = MapiCalendarRecurrenceEndType.EndAfterNOccurrences, _ .PatternType = MapiCalendarRecurrencePatternType.Week, _ .Period = 1, _ .WeekStartDay = DayOfWeek.Sunday, _ .DayOfWeek = MapiCalendarDayOfWeek.Friday, _ .OccurrenceCount = GetOccurrenceCount(StartDate, endByDate, "FREQ=WEEKLY;BYDAY=FR") _ } If rec.OccurrenceCount = 0 Then rec.OccurrenceCount = 1 End If task.Recurrence = rec task.Save(dataDir & "Weekly_out.msg", TaskSaveFormat.Msg) ' ExEnd:WeeklyEndAfterNoccurrences End Sub Private Shared Function GetOccurrenceCount(start As DateTime, endBy As DateTime, rrule As String) As UInteger ' ExStart:GetOccurrenceCount Dim pattern As New CalendarRecurrence(String.Format("DTSTART:{0}" & vbCr & vbLf & "RRULE:{1}", start.ToString("yyyyMMdd"), rrule)) Dim dates As DateCollection = pattern.GenerateOccurrences(start, endBy) Return CUInt(dates.Count) ' ExEnd:GetOccurrenceCount End Function End Class End Namespace
maria-shahid-aspose/Aspose.Email-for-.NET
Examples/VisualBasic/Outlook/WeeklyEndAfterNoccurrences.vb
Visual Basic
mit
2,925
Option Strict On Imports Xeora.Web.Shared Namespace Xeora.Web.Controller.Directive.Control Public Class VariableBlock Inherits ControlBase Implements IInstanceRequires Public Event InstanceRequested(ByRef Instance As IDomain) Implements IInstanceRequires.InstanceRequested Public Sub New(ByVal DraftStartIndex As Integer, ByVal DraftValue As String, ByVal ContentArguments As [Global].ArgumentInfoCollection) MyBase.New(DraftStartIndex, DraftValue, ContentArguments) End Sub Public Overrides Sub Render(ByRef SenderController As ControllerBase) ' UpdateBlock can be located under a variable block because of this ' Variable block should be rendered with its current settings all the time If Not String.IsNullOrEmpty(Me.BoundControlID) Then If Me.IsRendered Then Exit Sub If Not Me.BoundControlRenderWaiting Then Dim Controller As ControllerBase = Me Do Until Controller.Parent Is Nothing If TypeOf Controller.Parent Is ControllerBase AndAlso TypeOf Controller.Parent Is INamable Then If String.Compare( CType(Controller.Parent, INamable).ControlID, Me.BoundControlID, True) = 0 Then Throw New Exception.InternalParentException(Exception.InternalParentException.ChildDirectiveTypes.Control) End If End If Controller = Controller.Parent Loop Me.RegisterToRenderCompletedOf(Me.BoundControlID) End If If TypeOf SenderController Is ControlBase AndAlso TypeOf SenderController Is INamable Then If String.Compare( CType(SenderController, INamable).ControlID, Me.BoundControlID, True) <> 0 Then Exit Sub Else Me.RenderInternal() End If End If Else Me.RenderInternal() End If End Sub Private Sub RenderInternal() Dim ContentDescription As [Global].ContentDescription = New [Global].ContentDescription(Me.InsideValue) Dim BlockContent As String = ContentDescription.Parts.Item(0) ' Call Related Function and Exam It Dim ControllerLevel As ControllerBase = Me Dim Leveling As Integer = Me.Level Do If Leveling > 0 Then ControllerLevel = ControllerLevel.Parent If TypeOf ControllerLevel Is RenderlessController Then _ ControllerLevel = ControllerLevel.Parent Leveling -= 1 End If Loop Until ControllerLevel Is Nothing OrElse Leveling = 0 ' Execution preparation should be done at the same level with it's parent. Because of that, send parent as parameters Me.BindInfo.PrepareProcedureParameters( New [Shared].Execution.BindInfo.ProcedureParser( Sub(ByRef ProcedureParameter As [Shared].Execution.BindInfo.ProcedureParameter) ProcedureParameter.Value = PropertyController.ParseProperty( ProcedureParameter.Query, ControllerLevel.Parent, CType(IIf(ControllerLevel.Parent Is Nothing, Nothing, ControllerLevel.Parent.ContentArguments), [Global].ArgumentInfoCollection), New IInstanceRequires.InstanceRequestedEventHandler( Sub(ByRef Instance As IDomain) RaiseEvent InstanceRequested(Instance) End Sub) ) End Sub) ) Dim BindInvokeResult As [Shared].Execution.BindInvokeResult = Manager.Assembly.InvokeBind(Me.BindInfo, Manager.Assembly.ExecuterTypes.Control) Dim VariableBlockResult As ControlResult.VariableBlock = Nothing If BindInvokeResult.ReloadRequired Then Throw New Exception.ReloadRequiredException(BindInvokeResult.ApplicationPath) Else If Not BindInvokeResult.InvokeResult Is Nothing AndAlso TypeOf BindInvokeResult.InvokeResult Is System.Exception Then Throw New Exception.ExecutionException( CType(BindInvokeResult.InvokeResult, System.Exception).Message, CType(BindInvokeResult.InvokeResult, System.Exception).InnerException ) Else VariableBlockResult = CType(BindInvokeResult.InvokeResult, ControlResult.VariableBlock) End If End If ' ---- If Not VariableBlockResult Is Nothing Then For Each Key As String In VariableBlockResult.Keys Me.ContentArguments.AppendKeyWithValue(Key, VariableBlockResult.Item(Key)) Next End If Me.RequestParse(BlockContent, Me) Me.DefineRenderedValue(Me.Create()) Me.UnRegisterFromRenderCompletedOf(Me.BoundControlID) End Sub End Class End Namespace
xeora/v6
Framework/Xeora.Web/Controller/Directive/Control/VariableBlock.vb
Visual Basic
mit
5,818
' 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.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlDeclarationHighlighter Inherits AbstractKeywordHighlighter(Of XmlDeclarationSyntax) <ImportingConstructor> Public Sub New() End Sub Protected Overloads Overrides Function GetHighlights(xmlDocumentPrologue As XmlDeclarationSyntax, cancellationToken As CancellationToken) As IEnumerable(Of TextSpan) Dim highlights As New List(Of TextSpan) With xmlDocumentPrologue If Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then highlights.Add(.LessThanQuestionToken.Span) highlights.Add(.QuestionGreaterThanToken.Span) End If End With Return highlights End Function End Class End Namespace
nguerrera/roslyn
src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/XmlProcessingInstructionHighlighter.vb
Visual Basic
apache-2.0
1,344
' 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.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class BaseClassTests Inherits BasicTestBase <Fact> Public Sub DirectCircularInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits A End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'A' cannot reference itself in Inherits clause. Inherits A ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B End Class Class B Inherits A End Class </file> </compilation>) Dim expectedErrors = <errors> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritance1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B End Class Class B Inherits A End Class Class C Inherits B End Class </file> </compilation>) Dim expectedErrors = <errors> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class B End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31446: Class 'A' cannot reference its nested type 'A.B' in Inherits clause. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C End Class End Class Class B Inherits A.C End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits F Class C class D end class End Class End Class Class F Inherits A.C.D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'F'. 'F' inherits from 'A.C.D'. 'A.C.D' is nested in 'A.C'. 'A.C' is nested in 'A'.'. Inherits F ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C Inherits F class D end class End Class End Class Class B Inherits E End Class Class E Inherits A.C End Class Class F End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C Inherits F class D end class End Class End Class Class B Inherits E End Class Class E Inherits A.C End Class Class F Inherits A.C.D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ BC30907: This inheritance causes circular dependencies between class 'A.C' and its nested or base type ' 'A.C' inherits from 'F'. 'F' inherits from 'A.C.D'. 'A.C.D' is nested in 'A.C'.'. Inherits F ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InheritanceDependencyGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> namespace n1 Class Program Class A(of T) Inherits A(of Integer) End Class End Class end namespace </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'Program.A(Of T)' cannot reference itself in Inherits clause. Inherits A(of Integer) ~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependencyGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits C(Of String) Class C(Of T) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31446: Class 'A' cannot reference its nested type 'A.C(Of String)' in Inherits clause. Inherits C(Of String) ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependencyGeneric1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A(of T) Inherits B Class C(of U) class D end class End Class End Class Class B Inherits E(of B) End Class Class E(of L) Inherits A(of Integer).C(of Long).D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A(Of T)' and its nested or base type ' 'A(Of T)' inherits from 'B'. 'B' inherits from 'E(Of B)'. 'E(Of B)' inherits from 'A(Of Integer).C(Of Long).D'. 'A(Of Integer).C(Of Long).D' is nested in 'A(Of T).C(Of U)'. 'A(Of T).C(Of U)' is nested in 'A(Of T)'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub DirectCircularInheritanceInInterface1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits A, A End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'A' cannot inherit from itself: 'A' inherits from 'A'. Inherits A, A ~ BC30584: 'A' cannot be inherited more than once. Inherits A, A ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritanceInInterface1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface x1 End interface Interface x2 End interface Interface A Inherits B End interface Interface B Inherits x1, B, x2 End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'B' cannot inherit from itself: 'B' inherits from 'B'. Inherits x1, B, x2 ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B Interface B End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30908: interface 'A' cannot inherit from a type nested within it. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B Interface C End Interface End Interface Interface B Inherits A.C End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between interface 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B class C Interface D Inherits F interface E end interface End Interface end class End Interface Interface B Inherits E End Interface Interface E Inherits A.C.D.E End Interface Interface F End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between interface 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C.D.E'. 'A.C.D.E' is nested in 'A.C.D'. 'A.C.D' is nested in 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceImplementingDependency5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1 inherits s1.cls2 implements s1.cls2.i2 interface i1 end interface End Class structure s1 implements cls1.i1 Class cls2 Interface i2 End Interface End Class end structure </file> </compilation>) ' ' this would be an error if implementing was a dependency ' Dim expectedErrors = <errors> 'BC30907: This inheritance causes circular dependencies between structure 's1' and its nested or base type ' ' 's1' implements 'cls1.i1'. ' 'cls1.i1' is nested in 'cls1'. ' 'cls1' inherits from 's1.cls2'. ' 's1.cls2' is nested in 's1'.'. ' implements cls1.i1 ' ~~~~~~~ ' </errors> CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U)). End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.' is not defined. Inherits B(Of C(Of C(Of U)). ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140_a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U)).C(Of U) End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.C' is not defined. Inherits B(Of C(Of C(Of U)).C(Of U) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140_b() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U))).C(Of U) End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'B(Of S).C(Of U)' cannot inherit from itself: 'B(Of S).C(Of U)' inherits from 'B(Of S).C(Of U)'. Inherits B(Of C(Of C(Of U))).C(Of U) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U)). End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.' is not defined. Inherits B(Of C(Of C(Of U)). ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140_a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U)).C(Of U) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.C' is not defined. Inherits B(Of C(Of C(Of U)).C(Of U) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140_b() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U))).C(Of U) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'B(Of S).C(Of U)' cannot reference itself in Inherits clause. Inherits B(Of C(Of C(Of U))).C(Of U) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceClassMutualContainment() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1 Inherits i1.cls2 Interface i2 End Interface End Class Interface i1 Inherits cls1.i2 Class cls2 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'cls1' and its nested or base type ' 'cls1' inherits from 'i1.cls2'. 'i1.cls2' is nested in 'i1'. 'i1' inherits from 'cls1.i2'. 'cls1.i2' is nested in 'cls1'.'. Inherits i1.cls2 ~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceClassMutualContainmentGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1(of T) Inherits i1(of Integer).cls2 Interface i2 End Interface End Class Interface i1(of T) Inherits cls1(of T).i2 Class cls2 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'cls1(Of T)' and its nested or base type ' 'cls1(Of T)' inherits from 'i1(Of Integer).cls2'. 'i1(Of Integer).cls2' is nested in 'i1(Of T)'. 'i1(Of T)' inherits from 'cls1(Of T).i2'. 'cls1(Of T).i2' is nested in 'cls1(Of T)'.'. Inherits i1(of Integer).cls2 ~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ImportedCycle1() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C3 Inherits C1 End Class </file> </compilation>, {TestReferences.NetFx.v4_0_30319.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ImportedCycle2() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim C3 = TestReferences.SymbolsTests.CyclicInheritance.Class3 Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C3 Inherits C1 End Class </file> </compilation>, {TestReferences.NetFx.v4_0_30319.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C4 Inherits C3 End Class </file> </compilation>, {TestReferences.NetFx.v4_0_30319.mscorlib, C1, C2, C3}) expectedErrors = <errors> BC30916: Type 'C3' is not supported because it either directly or indirectly inherits from itself. Inherits C3 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub CyclicInterfaces3() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Interface I4 Inherits I1 End Interface </file> </compilation>, {TestReferences.NetFx.v4_0_30319.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself. Inherits I1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) End Sub #If Retargeting Then <Fact(skip:=SkipReason.AlreadyTestingRetargeting)> Public Sub CyclicRetargeted4() #Else <Fact> Public Sub CyclicRetargeted4() #End If Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv1}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B_base) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A_base) Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv2, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsType(Of Retargeting.RetargetingNamedTypeSymbol)(B2) Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Dim expectedErrors = <errors> BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself. Inherits ClassB ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp2, expectedErrors) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim errorBase1 = TryCast(A2.BaseType, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) End Sub <Fact> Public Sub CyclicRetargeted5() Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> 'hi </file> </compilation>, { TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv1, ClassBv1 }) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).[Distinct]().Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B1) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B_base) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A_base) Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv2, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B2) Assert.NotEqual(B1, B2) Assert.Same((DirectCast(B1.ContainingModule, PEModuleSymbol)).Module, DirectCast(B2.ContainingModule, PEModuleSymbol).Module) Assert.Equal(DirectCast(B1, PENamedTypeSymbol).Handle, DirectCast(B2, PENamedTypeSymbol).Handle) Assert.Same(C.BaseType, B2) Dim expectedErrors = <errors> BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself. Inherits ClassB ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp2, expectedErrors) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim errorBase1 = TryCast(A2.BaseType, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted6() #Else <Fact> Public Sub CyclicRetargeted6() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv2}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Dim expectedErrors = <errors> BC30257: Class 'ClassB' cannot inherit from itself: 'ClassB' inherits from 'ClassA'. 'ClassA' inherits from 'ClassB'. Inherits ClassA ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Assert.Same(B2.BaseType, A2) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted7() #Else <Fact> Public Sub CyclicRetargeted7() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> 'hi </file> </compilation>, { TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv2, ClassBv1 }) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).[Distinct]().Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsType(Of PENamedTypeSymbol)(B1) Dim errorBase = TryCast(B_base, ErrorTypeSymbol) Dim er = errorBase.ErrorInfo Assert.Equal("error BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, { TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp) }) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsType(Of PENamedTypeSymbol)(B2) Assert.NotEqual(B1, B2) Assert.Same(DirectCast(B1.ContainingModule, PEModuleSymbol).Module, DirectCast(B2.ContainingModule, PEModuleSymbol).Module) Assert.Equal(DirectCast(B1, PENamedTypeSymbol).Handle, DirectCast(B2, PENamedTypeSymbol).Handle) Assert.Same(C.BaseType, B2) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A2.BaseType) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B2.BaseType) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted8() #Else <Fact> Public Sub CyclicRetargeted8() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv2}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Dim expectedErrors = <errors> BC30257: Class 'ClassB' cannot inherit from itself: 'ClassB' inherits from 'ClassA'. 'ClassA' inherits from 'ClassB'. Inherits ClassA ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {TestReferences.NetFx.v4_0_30319.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Assert.Same(B2.BaseType, A2) End Sub <WorkItem(538503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538503")> <Fact> Public Sub TypeFromBaseInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class B End Class End Interface Interface IC Inherits IA Class D Inherits B End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538500")> <Fact> Public Sub TypeThroughBaseInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IB Inherits IA End Interface Class D Inherits IB.C End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' | / ' . / ' \ / ' . ' | ' . <Fact> Public Sub TypeFromBaseInterfaceAmbiguous() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IADerived Inherits IA End Interface Interface IA1Base Class C End Class End Interface Interface IA1 inherits IA1Base, IADerived End Interface Interface IB Inherits IA1 Class D Inherits C End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C' is ambiguous across the inherited interfaces 'IA1Base' and 'IA'. Inherits C ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceDiamondInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IA1 Inherits IA End Interface Interface IA2 inherits IA, IA1 End Interface Interface IA3 inherits IA, IA1, IA2 End Interface Interface IA4 inherits IA, IA1, IA2, IA3 End Interface Interface IB Inherits IA4, IA3, IA2, IA1, IA Class D Inherits C End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . {C1} ' | ' . ' <Fact> Public Sub TypeFromInterfaceYInheritanceShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface IA Shadows Class C1 End Class End Interface Interface IA1 Inherits IA, I0 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . ' | ' . ' <Fact> Public Sub TypeFromInterfaceYInheritanceNoShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface IA Shadows Class C1 End Class End Interface Interface IA1 Inherits IA, I0 End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C1' is ambiguous across the inherited interfaces 'IA' and 'I0'. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub ' ' .{C1} . ' \ / ' . <- .{C1} ' \ / ' . ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . <- .{C1} ' \ / ' . ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / \ ' . <- .{C1} . ' \ / / ' . _ _ _ / ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IA2 Inherits I1 End Interface Interface IB Inherits IA, IA1, IA2 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / \ ' . <- . . ' \ / / ' . _ _ _ / ' <Fact> Public Sub TypeFromInterfaceAInheritanceNoShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 End Interface Interface IA2 Inherits I1 End Interface Interface IB Inherits IA, IA1, IA2 Class D Inherits C1 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C1' is ambiguous across the inherited interfaces 'I0' and 'I1'. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCycles() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> interface ii1 : inherits ii1,ii2 interface ii2 : inherits ii1 end interface end interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'ii1' cannot inherit from itself: 'ii1' inherits from 'ii1'. interface ii1 : inherits ii1,ii2 ~~~ BC30908: interface 'ii1' cannot inherit from a type nested within it. interface ii1 : inherits ii1,ii2 ~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCantShadowAmbiguity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface DerivedWithoutAmbiguity Inherits Base1 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity End Interface Class Test Dim x as Goo.c1 = Nothing End Class </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'c1' is ambiguous across the inherited interfaces 'Base1' and 'Base2'. Dim x as Goo.c1 = Nothing ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCantShadowAmbiguity1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface Base3 Inherits Base1, Base2 Shadows Class c1 End Class End Interface Interface DerivedWithoutAmbiguity Inherits Base3 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity End Interface Class Test Inherits Goo.c1 End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub TypeFromInterfaceUnreachableAmbiguityIsOk() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface DerivedWithoutAmbiguity Inherits Base1 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity Shadows Class c1 End Class End Interface Class Test Dim x as Goo.c1 = Nothing End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub AccessibilityCheckInInherits1() Dim compilationDef = <compilation name="AccessibilityCheckInInherits1"> <file name="a.vb"> Public Class C(Of T) Protected Class A End Class End Class Public Class E Protected Class D Inherits C(Of D) Public Class B Inherits A End Class End Class End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30509: 'B' cannot inherit from class 'C(Of E.D).A' because it expands the access of the base class to class 'E'. Inherits A ~ </expected>) End Sub <Fact> Public Sub AccessibilityCheckInInherits2() Dim compilationDef = <compilation name="AccessibilityCheckInInherits2"> <file name="a.vb"> Public Class C(Of T) End Class Public Class E Inherits C(Of P) Private Class P End Class End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30921: 'E' cannot inherit from class 'C(Of E.P)' because it expands the access of type 'E.P' to namespace '&lt;Default&gt;'. Inherits C(Of P) ~~~~~~~ </expected>) End Sub <WorkItem(538878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538878")> <Fact> Public Sub ProtectedNestedBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Class B End Class End Class Class D Inherits A Protected Class B End Class End Class Class E Inherits D Protected Class F Inherits B End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(537949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537949")> <Fact> Public Sub ImplementingNestedInherited() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I(Of T) End Interface Class A(Of T) Class B Inherits A(Of B) Implements I(Of B.B) End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538509")> <Fact> Public Sub ImplementingNestedInherited1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B Class C End Class End Class Class A(Of T) Inherits B Implements I(Of C) End Class Interface I(Of T) End Interface Class C Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538811")> <Fact> Public Sub OverloadedViaInterfaceInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Function Goo() As T End Interface Interface IB Inherits IA(Of Integer) Overloads Sub Goo(ByVal x As Integer) End Interface Interface IC Inherits IB, IA(Of String) End Interface Module M Sub Main() Dim x As IC = Nothing Dim s As Integer = x.Goo() End Sub End Module </file> </compilation>) Dim expectedErrors = <errors> BC30521: Overload resolution failed because no accessible 'Goo' is most specific for these arguments: 'Function IA(Of String).Goo() As String': Not most specific. 'Function IA(Of Integer).Goo() As Integer': Not most specific. Dim s As Integer = x.Goo() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub OverloadedViaInterfaceInheritance1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Function Goo() As T End Interface Interface IB Class Goo End Class End Interface Interface IC Inherits IB, IA(Of String) End Interface Class M Sub Main() Dim x As IC Dim s As String = x.Goo().ToLower() End Sub End Class </file> </compilation>) Dim expectedErrors = <errors> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Dim s As String = x.Goo().ToLower() ~ BC30685: 'Goo' is ambiguous across the inherited interfaces 'IB' and 'IA(Of String)'. Dim s As String = x.Goo().ToLower() ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <WorkItem(539775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539775")> <Fact> Public Sub AmbiguousNestedInterfaceInheritedFromMultipleGenericInstantiations() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A(Of T) Interface B Inherits A(Of B), A(Of B()) Interface C Inherits B End Interface End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'B' is ambiguous across the inherited interfaces 'A(Of A(Of T).B)' and 'A(Of A(Of T).B())'. Inherits B ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <WorkItem(538809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538809")> <Fact> Public Sub Bug4532() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Overloads Sub Goo(ByVal x As T) End Interface Interface IC Inherits IA(Of Date), IA(Of Integer) Overloads Sub Goo() End Interface Class M Sub Main() Dim c As IC = Nothing c.Goo() End Sub End Class </file> </compilation>) Dim expectedErrors = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub CircularInheritanceThroughSubstitution() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Class B Inherits A(Of E) End Class Class E Inherits B.E.B End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'A(Of T).E' cannot reference itself in Inherits clause. Inherits B.E.B ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub ''' <summary> ''' The base type of a nested type should not change depending on ''' whether or not the base type of the containing type has been ''' evaluated. ''' </summary> <WorkItem(539744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539744")> <Fact> Public Sub BaseTypeEvaluationOrder() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Public Class X End Class End Class Class B Inherits A(Of B.Y.Error) Public Class Y Inherits X End Class End Class </file> </compilation> If True Then Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim classB = CType(compilation.GlobalNamespace.GetMembers("B").Single(), NamedTypeSymbol) Dim classY = CType(classB.GetMembers("Y").Single(), NamedTypeSymbol) Dim baseB = classB.BaseType Assert.Equal("?", baseB.ToDisplayString()) Assert.True(baseB.IsErrorType()) Dim baseY = classY.BaseType Assert.Equal("X", baseY.ToDisplayString()) Assert.True(baseY.IsErrorType()) End If If True Then Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim classB = CType(compilation.GlobalNamespace.GetMembers("B").Single(), NamedTypeSymbol) Dim classY = CType(classB.GetMembers("Y").Single(), NamedTypeSymbol) Dim baseY = classY.BaseType Assert.Equal("X", baseY.ToDisplayString()) Assert.True(baseY.IsErrorType()) Dim baseB = classB.BaseType Assert.Equal("?", baseB.ToDisplayString()) Assert.True(baseB.IsErrorType()) End If End Sub <Fact> Public Sub CyclicBases2() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class X Inherits Y.N End Class Class Y Inherits X.N End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim g = compilation.GlobalNamespace Dim x = g.GetTypeMembers("X").Single() Dim y = g.GetTypeMembers("Y").Single() Assert.NotEqual(y, x.BaseType) Assert.NotEqual(x, y.BaseType) Assert.Equal(SymbolKind.ErrorType, x.BaseType.Kind) Assert.Equal(SymbolKind.ErrorType, y.BaseType.Kind) Assert.Equal("", x.BaseType.Name) Assert.Equal("X.N", y.BaseType.Name) End Sub <Fact> Public Sub CyclicBases4() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Inherits B(Of A(Of T)) End Class Class B(Of T) Inherits A(Of B(Of T)) Public Function F() As A(Of T) Return Nothing End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Assert.Equal(1, compilation.GetDeclarationDiagnostics().Length) End Sub <Fact> Public Sub CyclicBases5() ' bases are cyclic, but you can still find members when binding bases Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Public Class X End Class End Class Class B Inherits A Public Class Y End Class End Class Class Z Inherits A.Y End Class Class W Inherits B.X End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim g = compilation.GlobalNamespace Dim z = g.GetTypeMembers("Z").Single() Dim w = g.GetTypeMembers("W").Single() Dim zBase = z.BaseType Assert.Equal("Y", zBase.Name) Dim wBase = w.BaseType Assert.Equal("X", wBase.Name) End Sub <Fact> Public Sub EricLiCase1() Dim text = <compilation name="Compilation"> <file name="a.vb"> Interface I(Of T) End Interface Class A Public Class B End Class End Class Class C Inherits A Implements I(Of C.B) End Class </file> </compilation> Dim compilation0 = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertNoErrors(compilation0) ' same as in Dev10 End Sub <WorkItem(544454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544454")> <Fact()> Public Sub InterfaceImplementedWithPrivateType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Imports System Imports System.Collections Imports System.Collections.Generic Public Class A Implements IEnumerable(Of A.MyPrivateType) Private Class MyPrivateType End Class Private Function GetEnumerator() As IEnumerator(Of MyPrivateType) Implements IEnumerable(Of MyPrivateType).GetEnumerator Throw New NotImplementedException() End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class </file> </compilation>) Dim c2Source = <compilation name="C2"> <file name="b.vb"> Imports System.Collections.Generic Class Z Public Function goo(a As A) As IEnumerable(Of Object) Return a End Function End Class </file> </compilation> Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(c2Source, {New VisualBasicCompilationReference(compilation)}) 'Works this way, but doesn't when compilation is supplied as metadata compilation.VerifyDiagnostics() c2.VerifyDiagnostics() Dim compilationImage = compilation.EmitToArray(options:=New EmitOptions(metadataOnly:=True)) CompilationUtils.CreateCompilationWithMscorlib40AndReferences(c2Source, {MetadataReference.CreateFromImage(compilationImage)}).VerifyDiagnostics() End Sub <WorkItem(792711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792711")> <Fact> Public Sub Repro792711() Dim source = <compilation> <file name="a.vb"> Public Class Base(Of T) End Class Public Class Derived(Of T) : Inherits Base(Of Derived(Of T)) End Class </file> </compilation> Dim metadataRef = CreateCompilationWithMscorlib40(source).EmitToImageReference(embedInteropTypes:=True) Dim comp = CreateCompilationWithMscorlib40AndReferences(<compilation/>, {metadataRef}) Dim derived = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Assert.Equal(TypeKind.Class, derived.TypeKind) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub Repro862536() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Interface B(Of S) : Inherits A(Of B(Of S).B(Of S)) Interface B(Of U) : Inherits B(Of B(Of U)) End Interface End Interface End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'B.B' is not defined. Interface B(Of S) : Inherits A(Of B(Of S).B(Of S)) ~~~~~~~~~~~~~~~ BC40004: interface 'B' conflicts with interface 'B' in the base interface 'A' and should be declared 'Shadows'. Interface B(Of U) : Inherits B(Of B(Of U)) ~ BC30296: Interface 'A(Of T).B(Of S).B(Of U)' cannot inherit from itself: 'A(Of T).B(Of S).B(Of U)' inherits from 'A(Of T).B(Of S).B(Of U)'. Interface B(Of U) : Inherits B(Of B(Of U)) ~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseInterface() Dim source = <compilation> <file name="a.vb"> Interface C(Of T) : Inherits C(Of C(Of T)) End Interface Interface B : Inherits C(Of Integer).NotFound End Interface </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type C(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'C(Of T)' cannot inherit from itself: 'C(Of T)' inherits from 'C(Of T)'. Interface C(Of T) : Inherits C(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Interface B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseInterfaceChain() Dim source = <compilation> <file name="a.vb"> Interface C(Of T) : Inherits D(Of C(Of T)) End Interface Interface D(Of T) : Inherits C(Of D(Of T)) End Interface Interface B : Inherits C(Of Integer).NotFound End Interface </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type D(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'C(Of T)' cannot inherit from itself: 'C(Of T)' inherits from 'D(Of C(Of T))'. 'D(Of C(Of T))' inherits from 'C(Of T)'. Interface C(Of T) : Inherits D(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Interface B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseClass() Dim source = <compilation> <file name="a.vb"> Class C(Of T) : Inherits C(Of C(Of T)) End Class Class B : Inherits C(Of Integer).NotFound End Class </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type C(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC31447: Class 'C(Of T)' cannot reference itself in Inherits clause. Class C(Of T) : Inherits C(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Class B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(1036374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036374")> <Fact()> Public Sub InterfaceCircularInheritance_01() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Inherits A(Of A(Of T)) Interface B Inherits A(Of B) End Interface End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim a = comp.GetTypeByMetadataName("A`1") Dim interfaces = a.AllInterfaces Assert.True(interfaces.Single.IsErrorType()) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'A(Of T)' cannot inherit from itself: 'A(Of T)' inherits from 'A(Of T)'. Inherits A(Of A(Of T)) ~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(1036374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036374")> <Fact()> Public Sub InterfaceCircularInheritance_02() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Inherits C(Of T) Interface B Inherits A(Of B) End Interface End Interface Interface C(Of T) Inherits A(Of A(Of T)) End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim a = comp.GetTypeByMetadataName("A`1") Dim interfaces = a.AllInterfaces Assert.True(interfaces.Single.IsErrorType()) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'A(Of T)' cannot inherit from itself: 'A(Of T)' inherits from 'C(Of T)'. 'C(Of T)' inherits from 'A(Of T)'. Inherits C(Of T) ~~~~~~~ ]]></errors>) End Sub End Class End Namespace
abock/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BaseClassTests.vb
Visual Basic
mit
69,199
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports CS = Microsoft.CodeAnalysis.CSharp Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CompilationAPITests Inherits BasicTestBase <WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")> <WorkItem(9153, "https://github.com/dotnet/roslyn/issues/9153")> <Fact> Public Sub PublicSignWithRelativeKeyPath() Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithPublicSign(True).WithCryptoKeyFile("test.snk") AssertTheseDiagnostics(VisualBasicCompilation.Create("test", options:=options), <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified BC37257: Option 'CryptoKeyFile' must be an absolute path. </errors>) End Sub <Fact> Public Sub LocalizableErrorArgumentToStringDoesntStackOverflow() ' Error ID is arbitrary Dim arg = New LocalizableErrorArgument(ERRID.IDS_ProjectSettingsLocationName) Assert.NotNull(arg.ToString()) End Sub <WorkItem(538778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538778")> <WorkItem(537623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537623")> <Fact> Public Sub CompilationName() ' report an error, rather then silently ignoring the directory ' (see cli partition II 22.30) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("C:/foo/Test.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("C:\foo\Test.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("\foo/Test.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("C:Test.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("Te" & ChrW(0) & "st.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create(" " & vbTab & " ")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create(ChrW(&HD800))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create(" a")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("\u2000a")) ' // U+2000 is whitespace ' other characters than directory separators are ok: VisualBasicCompilation.Create(";,*?<>#!@&") VisualBasicCompilation.Create("foo") VisualBasicCompilation.Create(".foo") VisualBasicCompilation.Create("foo ") ' can end with whitespace VisualBasicCompilation.Create("....") VisualBasicCompilation.Create(Nothing) End Sub <Fact> Public Sub CreateAPITest() Dim listSyntaxTree = New List(Of SyntaxTree) Dim listRef = New List(Of MetadataReference) Dim s1 = "using Foo" Dim t1 As SyntaxTree = VisualBasicSyntaxTree.ParseText(s1) listSyntaxTree.Add(t1) ' System.dll listRef.Add(TestReferences.NetFx.v4_0_30319.System) Dim ops = TestOptions.ReleaseExe ' Create Compilation with Option is not Nothing Dim comp = VisualBasicCompilation.Create("Compilation", listSyntaxTree, listRef, ops) Assert.Equal(ops, comp.Options) Assert.NotNull(comp.SyntaxTrees) Assert.NotNull(comp.References) Assert.Equal(1, comp.SyntaxTrees.Count) Assert.Equal(1, comp.References.Count) ' Create Compilation with PreProcessorSymbols of Option is empty Dim ops1 = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"System", "Microsoft.VisualBasic"})).WithRootNamespace("") ' Create Compilation with Assembly name contains invalid char Dim asmname = "楽聖いち にÅÅ€" comp = VisualBasicCompilation.Create(asmname, listSyntaxTree, listRef, ops1) Assert.Equal(asmname, comp.Assembly.Name) Assert.Equal(asmname + ".exe", comp.SourceModule.Name) Dim compOpt = VisualBasicCompilation.Create("Compilation", Nothing, Nothing, Nothing) Assert.NotNull(compOpt.Options) ' Not Implemented code ' comp = comp.ChangeOptions(options:=null) ' Assert.Equal(CompilationOptions.Default, comp.Options) ' comp = comp.ChangeOptions(ops1) ' Assert.Equal(ops1, comp.Options) ' comp = comp.ChangeOptions(comp1.Options) ' ssert.Equal(comp1.Options, comp.Options) ' comp = comp.ChangeOptions(CompilationOptions.Default) ' Assert.Equal(CompilationOptions.Default, comp.Options) End Sub <Fact> Public Sub GetSpecialType() Dim comp = VisualBasicCompilation.Create("compilation", Nothing, Nothing, Nothing) ' Get Special Type by enum Dim ntSmb = comp.GetSpecialType(typeId:=SpecialType.Count) Assert.Equal(SpecialType.Count, ntSmb.SpecialType) ' Get Special Type by integer ntSmb = comp.GetSpecialType(CType(31, SpecialType)) Assert.Equal(31, CType(ntSmb.SpecialType, Integer)) End Sub <Fact> Public Sub GetTypeByMetadataName() Dim comp = VisualBasicCompilation.Create("compilation", Nothing, Nothing, Nothing) ' Get Type Name And Arity Assert.Null(comp.GetTypeByMetadataName("`1")) Assert.Null(comp.GetTypeByMetadataName("中文`1")) ' Throw exception when the parameter of GetTypeByNameAndArity is NULL 'Assert.Throws(Of Exception)( ' Sub() ' comp.GetTypeByNameAndArity(fullName:=Nothing, arity:=1) ' End Sub) ' Throw exception when the parameter of GetTypeByNameAndArity is less than 0 'Assert.Throws(Of Exception)( ' Sub() ' comp.GetTypeByNameAndArity(String.Empty, -4) ' End Sub) Dim compilationDef = <compilation name="compilation"> <file name="a.vb"> Namespace A.B Class C Class D Class E End Class End Class End Class Class G(Of T) Class Q(Of S1,S2) ENd Class End Class Class G(Of T1,T2) End Class End Namespace Class C Class D Class E End Class End Class End Class </file> </compilation> comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) 'IsCaseSensitive Assert.Equal(Of Boolean)(False, comp.IsCaseSensitive) Assert.Equal("D", comp.GetTypeByMetadataName("C+D").Name) Assert.Equal("E", comp.GetTypeByMetadataName("C+D+E").Name) Assert.Null(comp.GetTypeByMetadataName("")) Assert.Null(comp.GetTypeByMetadataName("+")) Assert.Null(comp.GetTypeByMetadataName("++")) Assert.Equal("C", comp.GetTypeByMetadataName("A.B.C").Name) Assert.Equal("D", comp.GetTypeByMetadataName("A.B.C+D").Name) Assert.Null(comp.GetTypeByMetadataName("A.B.C+F")) Assert.Equal("E", comp.GetTypeByMetadataName("A.B.C+D+E").Name) Assert.Null(comp.GetTypeByMetadataName("A.B.C+D+E+F")) Assert.Equal(1, comp.GetTypeByMetadataName("A.B.G`1").Arity) Assert.Equal(2, comp.GetTypeByMetadataName("A.B.G`1+Q`2").Arity) Assert.Equal(2, comp.GetTypeByMetadataName("A.B.G`2").Arity) Assert.Null(comp.GetTypeByMetadataName("c")) Assert.Null(comp.GetTypeByMetadataName("A.b.C")) Assert.Null(comp.GetTypeByMetadataName("C+d")) Assert.Equal(SpecialType.System_Array, comp.GetTypeByMetadataName("System.Array").SpecialType) Assert.Null(comp.Assembly.GetTypeByMetadataName("System.Array")) Assert.Equal("E", comp.Assembly.GetTypeByMetadataName("A.B.C+D+E").Name) End Sub <Fact> Public Sub EmitToMemoryStreams() Dim comp = VisualBasicCompilation.Create("Compilation", options:=TestOptions.ReleaseDll) Using output = New MemoryStream() Using outputPdb = New MemoryStream() Using outputxml = New MemoryStream() Dim result = comp.Emit(output, outputPdb, Nothing) Assert.True(result.Success) result = comp.Emit(output, outputPdb) Assert.True(result.Success) result = comp.Emit(peStream:=output, pdbStream:=outputPdb, xmlDocumentationStream:=Nothing, cancellationToken:=Nothing) Assert.True(result.Success) result = comp.Emit(peStream:=output, pdbStream:=outputPdb, cancellationToken:=Nothing) Assert.True(result.Success) result = comp.Emit(output, outputPdb) Assert.True(result.Success) result = comp.Emit(output, outputPdb) Assert.True(result.Success) result = comp.Emit(output, outputPdb, outputxml) Assert.True(result.Success) result = comp.Emit(output, Nothing, Nothing, Nothing) Assert.True(result.Success) result = comp.Emit(output) Assert.True(result.Success) result = comp.Emit(output, Nothing, outputxml) Assert.True(result.Success) result = comp.Emit(output, xmlDocumentationStream:=outputxml) Assert.True(result.Success) result = comp.Emit(output, Nothing, outputxml) Assert.True(result.Success) result = comp.Emit(output, xmlDocumentationStream:=outputxml) Assert.True(result.Success) End Using End Using End Using End Sub <Fact> Public Sub Emit_BadArgs() Dim comp = VisualBasicCompilation.Create("Compilation", options:=TestOptions.ReleaseDll) Assert.Throws(Of ArgumentNullException)("peStream", Sub() comp.Emit(peStream:=Nothing)) Assert.Throws(Of ArgumentException)("peStream", Sub() comp.Emit(peStream:=New TestStream(canRead:=True, canWrite:=False, canSeek:=True))) Assert.Throws(Of ArgumentException)("pdbStream", Sub() comp.Emit(peStream:=New MemoryStream(), pdbStream:=New TestStream(canRead:=True, canWrite:=False, canSeek:=True))) Assert.Throws(Of ArgumentException)("pdbStream", Sub() comp.Emit(peStream:=New MemoryStream(), pdbStream:=New MemoryStream(), options:=EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded))) Assert.Throws(Of ArgumentException)("sourceLinkStream", Sub() comp.Emit( peStream:=New MemoryStream(), pdbStream:=New MemoryStream(), options:=EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream:=New TestStream(canRead:=False, canWrite:=True, canSeek:=True))) Assert.Throws(Of ArgumentException)("sourceLinkStream", Sub() comp.Emit( peStream:=New MemoryStream(), pdbStream:=New MemoryStream(), options:=EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Pdb), sourceLinkStream:=New MemoryStream())) Assert.Throws(Of ArgumentException)("sourceLinkStream", Sub() comp.Emit( peStream:=New MemoryStream(), pdbStream:=Nothing, options:=EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream:=New MemoryStream())) Assert.Throws(Of ArgumentException)("embeddedTexts", Sub() comp.Emit( peStream:=New MemoryStream(), pdbStream:=New MemoryStream(), options:=EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Pdb), embeddedTexts:={EmbeddedText.FromStream("_", New MemoryStream())})) Assert.Throws(Of ArgumentException)("embeddedTexts", Sub() comp.Emit( peStream:=New MemoryStream(), pdbStream:=Nothing, options:=EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), embeddedTexts:={EmbeddedText.FromStream("_", New MemoryStream())})) Assert.Throws(Of ArgumentException)("win32Resources", Sub() comp.Emit( peStream:=New MemoryStream(), win32Resources:=New TestStream(canRead:=True, canWrite:=False, canSeek:=False))) Assert.Throws(Of ArgumentException)("win32Resources", Sub() comp.Emit( peStream:=New MemoryStream(), win32Resources:=New TestStream(canRead:=False, canWrite:=False, canSeek:=True))) ' we don't report an error when we can't write to the XML doc stream: Assert.True(comp.Emit( peStream:=New MemoryStream(), pdbStream:=New MemoryStream(), xmlDocumentationStream:=New TestStream(canRead:=True, canWrite:=False, canSeek:=True)).Success) End Sub <Fact> Public Sub EmitOptionsDiagnostics() Dim c = CreateCompilationWithMscorlib({"class C {}"}) Dim stream = New MemoryStream() Dim options = New EmitOptions( debugInformationFormat:=CType(-1, DebugInformationFormat), outputNameOverride:=" ", fileAlignment:=513, subsystemVersion:=SubsystemVersion.Create(1000000, -1000000)) Dim result = c.Emit(stream, options:=options) result.Diagnostics.Verify( Diagnostic(ERRID.ERR_InvalidDebugInformationFormat).WithArguments("-1"), Diagnostic(ERRID.ERR_InvalidOutputName).WithArguments(CodeAnalysisResources.NameCannotStartWithWhitespace), Diagnostic(ERRID.ERR_InvalidFileAlignment).WithArguments("513"), Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("1000000.-1000000")) Assert.False(result.Success) End Sub <Fact> Public Sub ReferenceAPITest() ' Create Compilation takes two args Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = TestReferences.NetFx.v4_0_30319.mscorlib Dim ref2 = TestReferences.NetFx.v4_0_30319.System Dim ref3 = New TestMetadataReference(fullPath:="c:\xml.bms") Dim ref4 = New TestMetadataReference(fullPath:="c:\aaa.dll") ' Add a new empty item comp = comp.AddReferences(Enumerable.Empty(Of MetadataReference)()) Assert.Equal(0, comp.References.Count) ' Add a new valid item comp = comp.AddReferences(ref1) Dim assemblySmb = comp.GetReferencedAssemblySymbol(ref1) Assert.NotNull(assemblySmb) Assert.Equal("mscorlib", assemblySmb.Name, StringComparer.OrdinalIgnoreCase) Assert.Equal(1, comp.References.Count) Assert.Equal(MetadataImageKind.Assembly, comp.References(0).Properties.Kind) Assert.Same(ref1, comp.References(0)) ' Replace an existing item with another valid item comp = comp.ReplaceReference(ref1, ref2) Assert.Equal(1, comp.References.Count) Assert.Equal(MetadataImageKind.Assembly, comp.References(0).Properties.Kind) Assert.Equal(ref2, comp.References(0)) ' Remove an existing item comp = comp.RemoveReferences(ref2) Assert.Equal(0, comp.References.Count) 'WithReferences Dim hs1 As New HashSet(Of MetadataReference) From {ref1, ref2, ref3} Dim compCollection1 = VisualBasicCompilation.Create("Compilation") Assert.Equal(Of Integer)(0, Enumerable.Count(Of MetadataReference)(compCollection1.References)) Dim c2 As Compilation = compCollection1.WithReferences(hs1) Assert.Equal(Of Integer)(3, Enumerable.Count(Of MetadataReference)(c2.References)) 'WithReferences Dim compCollection2 = VisualBasicCompilation.Create("Compilation") Assert.Equal(Of Integer)(0, Enumerable.Count(Of MetadataReference)(compCollection2.References)) Dim c3 As Compilation = compCollection1.WithReferences(ref1, ref2, ref3) Assert.Equal(Of Integer)(3, Enumerable.Count(Of MetadataReference)(c3.References)) 'ReferencedAssemblyNames Dim RefAsm_Names As IEnumerable(Of AssemblyIdentity) = c2.ReferencedAssemblyNames Assert.Equal(Of Integer)(2, Enumerable.Count(Of AssemblyIdentity)(RefAsm_Names)) Dim ListNames As New List(Of String) Dim I As AssemblyIdentity For Each I In RefAsm_Names ListNames.Add(I.Name) Next Assert.Contains(Of String)("mscorlib", ListNames) Assert.Contains(Of String)("System", ListNames) 'RemoveAllReferences c2 = c2.RemoveAllReferences Assert.Equal(Of Integer)(0, Enumerable.Count(Of MetadataReference)(c2.References)) ' Overload with Hashset Dim hs = New HashSet(Of MetadataReference)() From {ref1, ref2, ref3} Dim compCollection = VisualBasicCompilation.Create("Compilation", references:=hs) compCollection = compCollection.AddReferences(ref1, ref2, ref3, ref4).RemoveReferences(hs) Assert.Equal(1, compCollection.References.Count) compCollection = compCollection.AddReferences(hs).RemoveReferences(ref1, ref2, ref3, ref4) Assert.Equal(0, compCollection.References.Count) ' Overload with Collection Dim col = New ObjectModel.Collection(Of MetadataReference)() From {ref1, ref2, ref3} compCollection = VisualBasicCompilation.Create("Compilation", references:=col) compCollection = compCollection.AddReferences(col).RemoveReferences(ref1, ref2, ref3) Assert.Equal(0, compCollection.References.Count) compCollection = compCollection.AddReferences(ref1, ref2, ref3).RemoveReferences(col) Assert.Equal(0, comp.References.Count) ' Overload with ConcurrentStack Dim stack = New Concurrent.ConcurrentStack(Of MetadataReference) stack.Push(ref1) stack.Push(ref2) stack.Push(ref3) compCollection = VisualBasicCompilation.Create("Compilation", references:=stack) compCollection = compCollection.AddReferences(stack).RemoveReferences(ref1, ref3, ref2) Assert.Equal(0, compCollection.References.Count) compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(stack) Assert.Equal(0, compCollection.References.Count) ' Overload with ConcurrentQueue Dim queue = New Concurrent.ConcurrentQueue(Of MetadataReference) queue.Enqueue(ref1) queue.Enqueue(ref2) queue.Enqueue(ref3) compCollection = VisualBasicCompilation.Create("Compilation", references:=queue) compCollection = compCollection.AddReferences(queue).RemoveReferences(ref3, ref2, ref1) Assert.Equal(0, compCollection.References.Count) compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(queue) Assert.Equal(0, compCollection.References.Count) End Sub <WorkItem(537826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537826")> <Fact> Public Sub SyntreeAPITest() Dim s1 = "using System.Linq;" Dim s2 = <![CDATA[Class foo sub main Public Operator End Operator End Class ]]>.Value Dim s3 = "Imports s$ = System.Text" Dim s4 = <text> Module Module1 Sub Foo() for i = 0 to 100 next end sub End Module </text>.Value Dim t1 = VisualBasicSyntaxTree.ParseText(s4) Dim withErrorTree = VisualBasicSyntaxTree.ParseText(s2) Dim withErrorTree1 = VisualBasicSyntaxTree.ParseText(s3) Dim withErrorTreeCS = VisualBasicSyntaxTree.ParseText(s1) Dim withExpressionRootTree = SyntaxFactory.ParseExpression("0").SyntaxTree ' Create compilation takes three args Dim comp = VisualBasicCompilation.Create("Compilation", {t1}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseDll) Dim tree = comp.SyntaxTrees.AsEnumerable() comp.VerifyDiagnostics() ' Add syntaxtree with error comp = comp.AddSyntaxTrees(withErrorTreeCS) Assert.Equal(2, comp.GetDiagnostics().Length()) ' Remove syntaxtree without error comp = comp.RemoveSyntaxTrees(tree) Assert.Equal(2, comp.GetDiagnostics(cancellationToken:=CancellationToken.None).Length()) ' Remove syntaxtree with error comp = comp.RemoveSyntaxTrees(withErrorTreeCS) Assert.Equal(0, comp.GetDiagnostics().Length()) Assert.Equal(0, comp.GetDeclarationDiagnostics().Length()) ' Get valid binding Dim bind = comp.GetSemanticModel(syntaxTree:=t1) Assert.NotNull(bind) ' Get Binding with tree is not exist bind = comp.GetSemanticModel(withErrorTree) Assert.NotNull(bind) ' Add syntaxtree which is CS language comp = comp.AddSyntaxTrees(withErrorTreeCS) Assert.Equal(2, comp.GetDiagnostics().Length()) comp = comp.RemoveSyntaxTrees(withErrorTreeCS) Assert.Equal(0, comp.GetDiagnostics().Length()) comp = comp.AddSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeCS) comp = comp.RemoveSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeCS) ' Add a new empty item comp = comp.AddSyntaxTrees(Enumerable.Empty(Of SyntaxTree)) Assert.Equal(0, comp.SyntaxTrees.Length) ' Add a new valid item comp = comp.AddSyntaxTrees(t1) Assert.Equal(1, comp.SyntaxTrees.Length) comp = comp.AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(s4)) Assert.Equal(2, comp.SyntaxTrees.Length) ' Replace an existing item with another valid item comp = comp.ReplaceSyntaxTree(t1, VisualBasicSyntaxTree.ParseText(s4)) Assert.Equal(2, comp.SyntaxTrees.Length) ' Replace an existing item with same item comp = comp.AddSyntaxTrees(t1).ReplaceSyntaxTree(t1, t1) Assert.Equal(3, comp.SyntaxTrees.Length) ' Replace with existing and verify that it throws Assert.Throws(Of ArgumentException)(Sub() comp.ReplaceSyntaxTree(t1, comp.SyntaxTrees(0))) Assert.Throws(Of ArgumentException)(Sub() comp.AddSyntaxTrees(t1)) ' SyntaxTrees have reference equality. This removal should fail. Assert.Throws(Of ArgumentException)(Sub() comp = comp.RemoveSyntaxTrees(VisualBasicSyntaxTree.ParseText(s4))) Assert.Equal(3, comp.SyntaxTrees.Length) ' Remove non-existing item Assert.Throws(Of ArgumentException)(Sub() comp = comp.RemoveSyntaxTrees(withErrorTree)) Assert.Equal(3, comp.SyntaxTrees.Length) Dim t4 = VisualBasicSyntaxTree.ParseText("Using System;") Dim t5 = VisualBasicSyntaxTree.ParseText("Usingsssssssssssss System;") Dim t6 = VisualBasicSyntaxTree.ParseText("Import System") ' Overload with Hashset Dim hs = New HashSet(Of SyntaxTree) From {t4, t5, t6} Dim compCollection = VisualBasicCompilation.Create("Compilation", syntaxTrees:=hs) compCollection = compCollection.RemoveSyntaxTrees(hs) Assert.Equal(0, compCollection.SyntaxTrees.Length) compCollection = compCollection.AddSyntaxTrees(hs).RemoveSyntaxTrees(t4, t5, t6) Assert.Equal(0, compCollection.SyntaxTrees.Length) ' Overload with Collection Dim col = New ObjectModel.Collection(Of SyntaxTree) From {t4, t5, t6} compCollection = VisualBasicCompilation.Create("Compilation", syntaxTrees:=col) compCollection = compCollection.RemoveSyntaxTrees(t4, t5, t6) Assert.Equal(0, compCollection.SyntaxTrees.Length) Assert.Throws(Of ArgumentException)(Sub() compCollection = compCollection.AddSyntaxTrees(t4, t5).RemoveSyntaxTrees(col)) Assert.Equal(0, compCollection.SyntaxTrees.Length) ' Overload with ConcurrentStack Dim stack = New Concurrent.ConcurrentStack(Of SyntaxTree) stack.Push(t4) stack.Push(t5) stack.Push(t6) compCollection = VisualBasicCompilation.Create("Compilation", syntaxTrees:=stack) compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5) Assert.Equal(0, compCollection.SyntaxTrees.Length) Assert.Throws(Of ArgumentException)(Sub() compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(stack)) Assert.Equal(0, compCollection.SyntaxTrees.Length) ' Overload with ConcurrentQueue Dim queue = New Concurrent.ConcurrentQueue(Of SyntaxTree) queue.Enqueue(t4) queue.Enqueue(t5) queue.Enqueue(t6) compCollection = VisualBasicCompilation.Create("Compilation", syntaxTrees:=queue) compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5) Assert.Equal(0, compCollection.SyntaxTrees.Length) Assert.Throws(Of ArgumentException)(Sub() compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(queue)) Assert.Equal(0, compCollection.SyntaxTrees.Length) ' VisualBasicCompilation.Create with syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.False(withExpressionRootTree.HasCompilationUnitRoot, "how did we get a CompilationUnit root?") Assert.Throws(Of ArgumentException)(Sub() VisualBasicCompilation.Create("Compilation", syntaxTrees:={withExpressionRootTree})) ' AddSyntaxTrees with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws(Of ArgumentException)(Sub() comp.AddSyntaxTrees(withExpressionRootTree)) ' ReplaceSyntaxTrees syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws(Of ArgumentException)(Sub() comp.ReplaceSyntaxTree(comp.SyntaxTrees(0), withExpressionRootTree)) End Sub <Fact> Public Sub ChainedOperations() Dim s1 = "using System.Linq;" Dim s2 = "" Dim s3 = "Import System" Dim t1 = VisualBasicSyntaxTree.ParseText(s1) Dim t2 = VisualBasicSyntaxTree.ParseText(s2) Dim t3 = VisualBasicSyntaxTree.ParseText(s3) Dim listSyntaxTree = New List(Of SyntaxTree) listSyntaxTree.Add(t1) listSyntaxTree.Add(t2) ' Remove second SyntaxTree Dim comp = VisualBasicCompilation.Create("Compilation") comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2) Assert.Equal(1, comp.SyntaxTrees.Length) 'ContainsSyntaxTree Dim b1 As Boolean = comp.ContainsSyntaxTree(t2) Assert.Equal(Of Boolean)(False, b1) comp = comp.AddSyntaxTrees({t2}) b1 = comp.ContainsSyntaxTree(t2) Assert.Equal(Of Boolean)(True, b1) Dim xt As SyntaxTree = Nothing Assert.Throws(Of ArgumentNullException)(Sub() b1 = comp.ContainsSyntaxTree(xt) End Sub) comp = comp.RemoveSyntaxTrees({t2}) Assert.Equal(1, comp.SyntaxTrees.Length) comp = comp.AddSyntaxTrees({t2}) Assert.Equal(2, comp.SyntaxTrees.Length) 'RemoveAllSyntaxTrees comp = comp.RemoveAllSyntaxTrees Assert.Equal(0, comp.SyntaxTrees.Length) comp = VisualBasicCompilation.Create("Compilation").AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees({t2}) Assert.Equal(Of Integer)(1, comp.SyntaxTrees.Length) Assert.Equal(Of String)("Object", comp.ObjectType.Name) ' Remove mid SyntaxTree listSyntaxTree.Add(t3) comp = comp.RemoveSyntaxTrees(t1).AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2) Assert.Equal(2, comp.SyntaxTrees.Length) ' remove list listSyntaxTree.Remove(t2) comp = comp.AddSyntaxTrees().RemoveSyntaxTrees(listSyntaxTree) comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(listSyntaxTree) Assert.Equal(0, comp.SyntaxTrees.Length) listSyntaxTree.Clear() listSyntaxTree.Add(t1) ' Chained operation count > 2 comp = comp.AddSyntaxTrees(listSyntaxTree).AddReferences().ReplaceSyntaxTree(t1, t2) Assert.Equal(1, comp.SyntaxTrees.Length) Assert.Equal(0, comp.References.Count) ' Create compilation with args is disordered Dim comp1 = VisualBasicCompilation.Create("Compilation") Dim Err = "c:\file_that_does_not_exist" Dim ref1 = TestReferences.NetFx.v4_0_30319.mscorlib Dim listRef = New List(Of MetadataReference) ' this is NOT testing Roslyn listRef.Add(ref1) listRef.Add(ref1) ' Remove with no args comp1 = comp1.AddReferences(listRef).AddSyntaxTrees(listSyntaxTree).RemoveReferences().RemoveSyntaxTrees() 'should have only added one reference since ref1.Equals(ref1) and Equal references are added only once. Assert.Equal(1, comp1.References.Count) Assert.Equal(1, comp1.SyntaxTrees.Length) End Sub <WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")> <Fact()> Public Sub MissedModuleA() Dim netModule1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="missing1"> <file name="a.vb"> Class C1 End Class </file> </compilation>, options:=TestOptions.ReleaseModule) netModule1.VerifyDiagnostics() Dim netModule2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="missing2"> <file name="a.vb"> Class C2 Public Shared Sub M() Dim a As New C1() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference()}, options:=TestOptions.ReleaseModule) netModule2.VerifyDiagnostics() Dim assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="missing"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) Dim a As New C2() End Sub End Class </file> </compilation>, additionalRefs:={netModule2.EmitToImageReference()}) assembly.VerifyDiagnostics(Diagnostic(ERRID.ERR_MissingNetModuleReference).WithArguments("missing1.netmodule")) assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="MissedModuleA"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) Dim a As New C2() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference(), netModule2.EmitToImageReference()}) assembly.VerifyDiagnostics() CompileAndVerify(assembly) End Sub <WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")> <Fact()> Public Sub MissedModuleB_OneError() Dim netModule1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="a1"> <file name="a.vb"> Class C1 End Class </file> </compilation>, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule1) Dim netModule2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a2"> <file name="a.vb"> Class C2 Public Shared Sub M() Dim a As New C1() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference()}, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule2) Dim netModule3 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a3"> <file name="a.vb"> Class C22 Public Shared Sub M() Dim a As New C1() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference()}, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule3) Dim assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) Dim a As New C2() Dim b As New C22() End Sub End Class </file> </compilation>, additionalRefs:={netModule2.EmitToImageReference(), netModule3.EmitToImageReference()}) CompilationUtils.AssertTheseDiagnostics(assembly, <errors> BC37221: Reference to 'a1.netmodule' netmodule missing. </errors>) End Sub <WorkItem(718500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718500")> <WorkItem(716762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716762")> <Fact()> Public Sub MissedModuleB_NoErrorForUnmanagedModules() Dim netModule1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="a1"> <file name="a.vb"> Imports System.Runtime.InteropServices Public Class ClassDLLImports Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" ( ByVal lpBuffer As String, ByRef nSize As Integer) As Integer End Class </file> </compilation>, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule1) Dim assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference(expectedWarnings:={ Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Runtime.InteropServices")})}) assembly.AssertNoDiagnostics() End Sub <WorkItem(715872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715872")> <Fact()> Public Sub MissedModuleC() Dim netModule1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="a1"> <file name="a.vb"> Class C1 End Class </file> </compilation>, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule1) Dim netModule2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a1"> <file name="a.vb"> Class C2 Public Shared Sub M() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference()}, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule2) Dim assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) Dim a As New C2() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference(), netModule2.EmitToImageReference()}) CompilationUtils.AssertTheseDiagnostics(assembly, <errors> BC37224: Module 'a1.netmodule' is already defined in this assembly. Each module must have a unique filename. </errors>) End Sub <Fact> Public Sub MixedRefType() ' Create compilation takes three args Dim csComp = CS.CSharpCompilation.Create("CompilationVB") Dim comp = VisualBasicCompilation.Create("Compilation") ' this is NOT right path, ' please don't use VB dll (there is a change to the location in Dev11; you test will fail then) csComp = csComp.AddReferences(SystemRef) ' Add VB reference to C# compilation For Each item In csComp.References comp = comp.AddReferences(item) comp = comp.ReplaceReference(item, item) Next Assert.Equal(1, comp.References.Count) Dim text1 = "Imports System" Dim comp1 = VisualBasicCompilation.Create("Test1", {VisualBasicSyntaxTree.ParseText(text1)}) Dim comp2 = VisualBasicCompilation.Create("Test2", {VisualBasicSyntaxTree.ParseText(text1)}) Dim compRef1 = comp1.ToMetadataReference() Dim compRef2 = comp2.ToMetadataReference() Dim csCompRef = csComp.ToMetadataReference(embedInteropTypes:=True) Dim ref1 = TestReferences.NetFx.v4_0_30319.mscorlib Dim ref2 = TestReferences.NetFx.v4_0_30319.System ' Add VisualBasicCompilationReference comp = VisualBasicCompilation.Create("Test1", {VisualBasicSyntaxTree.ParseText(text1)}, {compRef1, compRef2}) Assert.Equal(2, comp.References.Count) Assert.Equal(MetadataImageKind.Assembly, comp.References(0).Properties.Kind) Assert.Contains(compRef1, comp.References) Assert.Contains(compRef2, comp.References) Dim smb = comp.GetReferencedAssemblySymbol(compRef1) Assert.Equal(smb.Kind, SymbolKind.Assembly) Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase) ' Mixed reference type comp = comp.AddReferences(ref1) Assert.Equal(3, comp.References.Count) Assert.Contains(ref1, comp.References) ' Replace Compilation reference with Assembly file reference comp = comp.ReplaceReference(compRef2, ref2) Assert.Equal(3, comp.References.Count) Assert.Contains(ref2, comp.References) ' Replace Assembly file reference with Compilation reference comp = comp.ReplaceReference(ref1, compRef2) Assert.Equal(3, comp.References.Count) Assert.Contains(compRef2, comp.References) Dim modRef1 = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00).GetReference() ' Add Module file reference comp = comp.AddReferences(modRef1) ' Not Implemented 'Dim modSmb = comp.GetReferencedModuleSymbol(modRef1) 'Assert.Equal("ModuleCS00.mod", modSmb.Name) 'Assert.Equal(4, comp.References.Count) 'Assert.True(comp.References.Contains(modRef1)) ' Get Referenced Assembly Symbol 'smb = comp.GetReferencedAssemblySymbol(reference:=modRef1) 'Assert.Equal(smb.Kind, SymbolKind.Assembly) 'Assert.True(String.Equals(smb.AssemblyName.Name, "Test1", StringComparison.OrdinalIgnoreCase)) ' Get Referenced Module Symbol 'Dim moduleSmb = comp.GetReferencedModuleSymbol(reference:=modRef1) 'Assert.Equal(moduleSmb.Kind, SymbolKind.NetModule) 'Assert.True(String.Equals(moduleSmb.Name, "ModuleCS00.mod", StringComparison.OrdinalIgnoreCase)) ' Not implemented ' Get Compilation Namespace 'Dim nsSmb = comp.GlobalNamespace 'Dim ns = comp.GetCompilationNamespace(ns:=nsSmb) 'Assert.Equal(ns.Kind, SymbolKind.Namespace) 'Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)) ' Not implemented ' GetCompilationNamespace (Derived Class MergedNamespaceSymbol) 'Dim merged As NamespaceSymbol = MergedNamespaceSymbol.Create(New NamespaceExtent(New MockAssemblySymbol("Merged")), Nothing, Nothing) 'ns = comp.GetCompilationNamespace(ns:=merged) 'Assert.Equal(ns.Kind, SymbolKind.Namespace) 'Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)) ' Not implemented ' GetCompilationNamespace (Derived Class PENamespaceSymbol) 'Dim pensSmb As Metadata.PE.PENamespaceSymbol = CType(nsSmb, Metadata.PE.PENamespaceSymbol) 'ns = comp.GetCompilationNamespace(ns:=pensSmb) 'Assert.Equal(ns.Kind, SymbolKind.Namespace) 'Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)) ' Replace Module file reference with compilation reference comp = comp.RemoveReferences(compRef1).ReplaceReference(modRef1, compRef1) Assert.Equal(3, comp.References.Count) ' Check the reference order after replace Assert.Equal(MetadataImageKind.Assembly, comp.References(2).Properties.Kind) Assert.Equal(compRef1, comp.References(2)) ' Replace compilation Module file reference with Module file reference comp = comp.ReplaceReference(compRef1, modRef1) ' Check the reference order after replace Assert.Equal(3, comp.References.Count) Assert.Equal(MetadataImageKind.Module, comp.References(2).Properties.Kind) Assert.Equal(modRef1, comp.References(2)) ' Add CS compilation ref Assert.Throws(Of ArgumentException)(Function() comp.AddReferences(csCompRef)) For Each item In comp.References comp = comp.RemoveReferences(item) Next Assert.Equal(0, comp.References.Count) ' Not Implemented ' Dim asmByteRef = MetadataReference.CreateFromImage(New Byte(4) {}, "AssemblyBytesRef1", embedInteropTypes:=True) 'Dim asmObjectRef = New AssemblyObjectReference(assembly:=System.Reflection.Assembly.GetAssembly(GetType(Object)), embedInteropTypes:=True) 'comp = comp.AddReferences(asmByteRef, asmObjectRef) 'Assert.Equal(2, comp.References.Count) 'Assert.Equal(ReferenceKind.AssemblyBytes, comp.References(0).Kind) 'Assert.Equal(ReferenceKind.AssemblyObject, comp.References(1).Kind) 'Assert.Equal(asmByteRef, comp.References(0)) 'Assert.Equal(asmObjectRef, comp.References(1)) 'Assert.True(comp.References(0).EmbedInteropTypes) 'Assert.True(comp.References(1).EmbedInteropTypes) End Sub <Fact> Public Sub ModuleSuppliedAsAssembly() Dim comp = VisualBasicCompilation.Create("Compilation", references:={AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleVB01).GetReference()}) Assert.Equal(comp.GetDiagnostics().First().Code, ERRID.ERR_MetaDataIsNotAssembly) End Sub <Fact> Public Sub AssemblySuppliedAsModule() Dim comp = VisualBasicCompilation.Create("Compilation", references:={ModuleMetadata.CreateFromImage(TestResources.NetFX.v4_0_30319.System).GetReference()}) Assert.Equal(comp.GetDiagnostics().First().Code, ERRID.ERR_MetaDataIsNotModule) End Sub '' Get nonexistent Referenced Assembly Symbol <WorkItem(537637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537637")> <Fact> Public Sub NegReference1() Dim comp = VisualBasicCompilation.Create("Compilation") Assert.Null(comp.GetReferencedAssemblySymbol(TestReferences.NetFx.v4_0_30319.System)) Dim modRef1 = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleVB01).GetReference() Assert.Null(comp.GetReferencedModuleSymbol(modRef1)) End Sub '' Add already existing item <WorkItem(537617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537617")> <Fact> Public Sub NegReference2() Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = TestReferences.NetFx.v4_0_30319.System Dim ref2 = New TestMetadataReference(fullPath:="c:\a\xml.bms") Dim ref3 = ref2 Dim ref4 = New TestMetadataReference(fullPath:="c:\aaa.dll") comp = comp.AddReferences(ref1, ref1) Assert.Equal(1, comp.References.Count) Assert.Equal(ref1, comp.References(0)) ' Remove non-existing item Assert.Throws(Of ArgumentException)(Function() comp.RemoveReferences(ref2)) Dim listRef = New List(Of MetadataReference) From {ref1, ref2, ref3, ref4} comp = comp.AddReferences(listRef).AddReferences(ref2).ReplaceReference(ref2, ref2) Assert.Equal(3, comp.References.Count) comp = comp.RemoveReferences(listRef).AddReferences(ref1) Assert.Equal(1, comp.References.Count) Assert.Equal(ref1, comp.References(0)) End Sub '' Add a new invalid item <WorkItem(537575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537575")> <Fact> Public Sub NegReference3() Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = New TestMetadataReference(fullPath:="c:\xml.bms") Dim ref2 = TestReferences.NetFx.v4_0_30319.System comp = comp.AddReferences(ref1) Assert.Equal(1, comp.References.Count) ' Replace an non-existing item with another invalid item Assert.Throws(Of ArgumentException)(Sub() comp = comp.ReplaceReference(ref2, ref1) End Sub) Assert.Equal(1, comp.References.Count) End Sub '' Replace an non-existing item with null <WorkItem(537567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537567")> <Fact> Public Sub NegReference4() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = New TestMetadataReference(fullPath:="c:\xml.bms") Assert.Throws(Of ArgumentException)( Sub() comp.ReplaceReference(ref1, Nothing) End Sub) ' Replace null and the arg order of replace is vise Assert.Throws(Of ArgumentNullException)( Sub() comp.ReplaceReference(newReference:=ref1, oldReference:=Nothing) End Sub) End Sub '' Replace an non-existing item with another valid item <WorkItem(537566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537566")> <Fact> Public Sub NegReference5() Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = TestReferences.NetFx.v4_0_30319.mscorlib Dim ref2 = TestReferences.NetFx.v4_0_30319.System Assert.Throws(Of ArgumentException)( Sub() comp = comp.ReplaceReference(ref1, ref2) End Sub) Dim s1 = "Imports System.Text" Dim t1 = Parse(s1) ' Replace an non-existing item with another valid item and disorder the args Assert.Throws(Of ArgumentException)(Sub() comp.ReplaceSyntaxTree(newTree:=VisualBasicSyntaxTree.ParseText("Imports System"), oldTree:=t1) End Sub) Assert.Equal(0, comp.References.Count) End Sub '' Throw exception when add Nothing references <WorkItem(537618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537618")> <Fact> Public Sub NegReference6() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Assert.Throws(Of ArgumentNullException)(Sub() comp = comp.AddReferences(Nothing)) End Sub '' Throw exception when remove Nothing references <WorkItem(537621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537621")> <Fact> Public Sub NegReference7() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Dim RemoveNothingRefEx = Assert.Throws(Of ArgumentNullException)(Sub() comp = comp.RemoveReferences(Nothing)) End Sub '' Add already existing item <WorkItem(537576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537576")> <Fact> Public Sub NegSyntaxTree1() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Dim t1 = VisualBasicSyntaxTree.ParseText("Using System;") Assert.Throws(Of ArgumentException)(Sub() comp.AddSyntaxTrees(t1, t1)) Assert.Equal(0, comp.SyntaxTrees.Length) End Sub ' Throw exception when the parameter of ContainsSyntaxTrees is null <WorkItem(527256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527256")> <Fact> Public Sub NegContainsSyntaxTrees() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Assert.False(comp.SyntaxTrees.Contains(Nothing)) End Sub ' Throw exception when the parameter of AddReferences is CSharpCompilationReference <WorkItem(537778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537778")> <Fact> Public Sub NegGetSymbol() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Dim csComp = CS.CSharpCompilation.Create("CompilationCS") Dim compRef = csComp.ToMetadataReference() Assert.Throws(Of ArgumentException)(Function() comp.AddReferences(compRef)) '' Throw exception when the parameter of GetReferencedAssemblySymbol is null 'Assert.Throws(Of ArgumentNullException)(Sub() comp.GetReferencedAssemblySymbol(Nothing)) '' Throw exception when the parameter of GetReferencedModuleSymbol is null 'Assert.Throws(Of ArgumentNullException)( ' Sub() ' comp.GetReferencedModuleSymbol(Nothing) ' End Sub) End Sub '' Throw exception when the parameter of GetSpecialType is 'SpecialType.None' <WorkItem(537784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537784")> <Fact> Public Sub NegGetSpecialType() Dim comp = VisualBasicCompilation.Create("Compilation") Assert.Throws(Of ArgumentOutOfRangeException)( Sub() comp.GetSpecialType((SpecialType.None)) End Sub) ' Throw exception when the parameter of GetSpecialType is '0' Assert.Throws(Of ArgumentOutOfRangeException)( Sub() comp.GetSpecialType(CType(0, SpecialType)) End Sub) ' Throw exception when the parameter of GetBinding is out of range Assert.Throws(Of ArgumentOutOfRangeException)( Sub() comp.GetSpecialType(CType(100, SpecialType)) End Sub) ' Throw exception when the parameter of GetCompilationNamespace is null Assert.Throws(Of ArgumentNullException)( Sub() comp.GetCompilationNamespace(namespaceSymbol:=Nothing) End Sub) Dim bind = comp.GetSemanticModel(Nothing) Assert.NotNull(bind) End Sub <Fact> Public Sub NegSynTree() Dim comp = VisualBasicCompilation.Create("Compilation") Dim s1 = "Imports System.Text" Dim tree = VisualBasicSyntaxTree.ParseText(s1) ' Throw exception when add Nothing SyntaxTree Assert.Throws(Of ArgumentNullException)(Sub() comp.AddSyntaxTrees(Nothing)) ' Throw exception when Remove Nothing SyntaxTree Assert.Throws(Of ArgumentNullException)(Sub() comp.RemoveSyntaxTrees(Nothing)) ' Replace a tree with nothing (aka removing it) comp = comp.AddSyntaxTrees(tree).ReplaceSyntaxTree(tree, Nothing) Assert.Equal(0, comp.SyntaxTrees.Count) ' Throw exception when remove Nothing SyntaxTree Assert.Throws(Of ArgumentNullException)(Sub() comp = comp.ReplaceSyntaxTree(Nothing, tree)) Dim t1 = CS.SyntaxFactory.ParseSyntaxTree(s1) Dim t2 As SyntaxTree = t1 Dim t3 = t2 Dim csComp = CS.CSharpCompilation.Create("CompilationVB") csComp = csComp.AddSyntaxTrees(t1, CS.SyntaxFactory.ParseSyntaxTree("Imports Foo")) ' Throw exception when cast SyntaxTree For Each item In csComp.SyntaxTrees t3 = item Dim invalidCastSynTreeEx = Assert.Throws(Of InvalidCastException)(Sub() comp = comp.AddSyntaxTrees(CType(t3, VisualBasicSyntaxTree))) invalidCastSynTreeEx = Assert.Throws(Of InvalidCastException)(Sub() comp = comp.RemoveSyntaxTrees(CType(t3, VisualBasicSyntaxTree))) invalidCastSynTreeEx = Assert.Throws(Of InvalidCastException)(Sub() comp = comp.ReplaceSyntaxTree(CType(t3, VisualBasicSyntaxTree), CType(t3, VisualBasicSyntaxTree))) Next End Sub <Fact> Public Sub RootNSIllegalIdentifiers() AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("[[Global]]").Errors, <expected> BC2014: the value '[[Global]]' is invalid for option 'RootNamespace' </expected>) AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("From()").Errors, <expected> BC2014: the value 'From()' is invalid for option 'RootNamespace' </expected>) AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("x$").Errors, <expected> BC2014: the value 'x$' is invalid for option 'RootNamespace' </expected>) AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("Foo.").Errors, <expected> BC2014: the value 'Foo.' is invalid for option 'RootNamespace' </expected>) AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("_").Errors, <expected> BC2014: the value '_' is invalid for option 'RootNamespace' </expected>) End Sub <Fact> Public Sub AmbiguousNestedTypeSymbolFromMetadata() Dim code = "Class A : Class B : End Class : End Class" Dim c1 = VisualBasicCompilation.Create("Asm1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(code)}) Dim c2 = VisualBasicCompilation.Create("Asm2", syntaxTrees:={VisualBasicSyntaxTree.ParseText(code)}) Dim c3 = VisualBasicCompilation.Create("Asm3", references:={c1.ToMetadataReference(), c2.ToMetadataReference()}) Assert.Null(c3.GetTypeByMetadataName("A+B")) End Sub <Fact> Public Sub DuplicateNestedTypeSymbol() Dim code = "Class A : Class B : End Class : Class B : End Class : End Class" Dim c1 = VisualBasicCompilation.Create("Asm1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(code)}) Assert.Equal("A.B", c1.GetTypeByMetadataName("A+B").ToDisplayString()) End Sub <Fact()> <WorkItem(543211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543211")> Public Sub TreeDiagnosticsShouldNotIncludeEntryPointDiagnostics() Dim code1 = "Module M : Sub Main : End Sub : End Module" Dim code2 = " " Dim tree1 = VisualBasicSyntaxTree.ParseText(code1) Dim tree2 = VisualBasicSyntaxTree.ParseText(code2) Dim comp = VisualBasicCompilation.Create( "Test", syntaxTrees:={tree1, tree2}) Dim semanticModel2 = comp.GetSemanticModel(tree2) Dim diagnostics2 = semanticModel2.GetDiagnostics() Assert.Equal(0, diagnostics2.Length()) End Sub <Fact()> <WorkItem(543292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543292")> Public Sub CompilationStackOverflow() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Assert.Throws(Of NotSupportedException)(Function() compilation.DynamicType) Assert.Throws(Of NotSupportedException)(Function() compilation.CreatePointerTypeSymbol(Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, Nothing) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(tupleWithoutNames.TupleElements.All(Function(e) e.IsImplicitlyDeclared)) Assert.Equal({"System.Int32", "System.String"}, tupleWithoutNames.TupleElements.Select(Function(t) t.Type.ToTestDisplayString())) Assert.Equal(CInt(SymbolKind.NamedType), CInt(tupleWithoutNames.Kind)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tupleWithNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Alice", "Bob")) Assert.True(tupleWithNames.IsTupleType) Assert.Equal("(Alice As System.Int32, Bob As System.String)", tupleWithNames.ToTestDisplayString()) Assert.Equal({"Alice", "Bob"}, tupleWithNames.TupleElements.SelectAsArray(Function(e) e.Name)) Assert.Equal({"System.Int32", "System.String"}, tupleWithNames.TupleElements.Select(Function(t) t.Type.ToTestDisplayString())) Assert.Equal(SymbolKind.NamedType, tupleWithNames.Kind) End Sub <Fact()> Public Sub CreateAnonymousType_IncorrectLengths() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Assert.Throws(Of ArgumentException)( Function() Return compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(DirectCast(Nothing, ITypeSymbol)), ImmutableArray.Create("m1", "m2")) End Function) End Sub <Fact> Public Sub CreateAnonymousType_IncorrectLengths_IsReadOnly() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Assert.Throws(Of ArgumentException)( Sub() compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(DirectCast(compilation.GetSpecialType(SpecialType.System_Int32), ITypeSymbol), DirectCast(compilation.GetSpecialType(SpecialType.System_Int32), ITypeSymbol)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(True)) End Sub) End Sub <Fact> Public sub CreateAnonymousType_IncorrectLengths_Locations() Dim Compilation = VisualBasicCompilation.Create("HelloWorld") Assert.Throws(Of ArgumentException)( Sub() Compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(DirectCast(Compilation.GetSpecialType(SpecialType.System_Int32), ITypeSymbol), DirectCast(Compilation.GetSpecialType(SpecialType.System_Int32), ITypeSymbol)), ImmutableArray.Create("m1", "m2"), memberLocations:=ImmutableArray.Create(Location.None)) End Sub) End Sub <Fact> Public Sub CreateAnonymousType_WritableProperty() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Dim type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(DirectCast(compilation.GetSpecialType(SpecialType.System_Int32), ITypeSymbol), DirectCast(compilation.GetSpecialType(SpecialType.System_Int32), ITypeSymbol)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(False, False)) Assert.True(type.IsAnonymousType) Assert.Equal(2, type.GetMembers().OfType(Of IPropertySymbol).Count()) Assert.Equal("<anonymous type: m1 As Integer, m2 As Integer>", type.ToDisplayString()) Assert.All(type.GetMembers().OfType(Of IPropertySymbol)().Select(Function(p) p.Locations.FirstOrDefault()), Sub(loc) Assert.Equal(loc, Location.None)) End Sub <Fact> Public Sub CreateAnonymousType_Locations() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Dim tree = VisualBasicSyntaxTree.ParseText("Class X") compilation = compilation.AddSyntaxTrees(tree) Dim loc1 = Location.Create(tree, New TextSpan(0, 1)) Dim loc2 = Location.Create(tree, New TextSpan(1, 1)) Dim type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(DirectCast(compilation.GetSpecialType(SpecialType.System_Int32), ITypeSymbol), DirectCast(compilation.GetSpecialType(SpecialType.System_Int32), ITypeSymbol)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(False, False), ImmutableArray.Create(loc1, loc2)) Assert.True(type.IsAnonymousType) Assert.Equal(2, type.GetMembers().OfType(Of IPropertySymbol).Count()) Assert.Equal(loc1, type.GetMembers("m1").Single().Locations.Single()) Assert.Equal(loc2, type.GetMembers("m2").Single().Locations.Single()) Assert.Equal("<anonymous type: m1 As Integer, m2 As Integer>", type.ToDisplayString()) End Sub <Fact()> Public Sub CreateAnonymousType_NothingArgument() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Assert.Throws(Of ArgumentNullException)( Function() Return compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(DirectCast(Nothing, ITypeSymbol)), ImmutableArray.Create("m1")) End Function) End Sub <Fact()> Public Sub CreateAnonymousType1() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Dim type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(Of ITypeSymbol)(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1")) Assert.True(type.IsAnonymousType) Assert.Equal(1, type.GetMembers().OfType(Of IPropertySymbol).Count()) Assert.Equal("<anonymous type: Key m1 As Integer>", type.ToDisplayString()) Assert.All(type.GetMembers().OfType(Of IPropertySymbol)().Select(Function(p) p.Locations.FirstOrDefault()), Sub(loc) Assert.Equal(loc, Location.None)) End Sub <Fact()> Public Sub CreateMutableAnonymousType1() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Dim type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(Of ITypeSymbol)(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1"), ImmutableArray.Create(False)) Assert.True(type.IsAnonymousType) Assert.Equal(1, type.GetMembers().OfType(Of IPropertySymbol).Count()) Assert.Equal("<anonymous type: m1 As Integer>", type.ToDisplayString()) Assert.All(type.GetMembers().OfType(Of IPropertySymbol)().Select(Function(p) p.Locations.FirstOrDefault()), Sub(loc) Assert.Equal(loc, Location.None)) End Sub <Fact()> Public Sub CreateAnonymousType2() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Dim type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create(Of ITypeSymbol)(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray.Create("m1", "m2")) Assert.True(type.IsAnonymousType) Assert.Equal(2, type.GetMembers().OfType(Of IPropertySymbol).Count()) Assert.Equal("<anonymous type: Key m1 As Integer, Key m2 As Boolean>", type.ToDisplayString()) Assert.All(type.GetMembers().OfType(Of IPropertySymbol)().Select(Function(p) p.Locations.FirstOrDefault()), Sub(loc) Assert.Equal(loc, Location.None)) End Sub <Fact()> Public Sub GetEntryPoint_Exe() Dim source = <compilation name="Name1"> <file name="a.vb"><![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, OutputKind.ConsoleApplication) compilation.VerifyDiagnostics() Dim mainMethod = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of MethodSymbol)("Main") Assert.Equal(mainMethod, compilation.GetEntryPoint(Nothing)) Dim entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol) entryPointAndDiagnostics.Diagnostics.Verify() End Sub <Fact()> Public Sub GetEntryPoint_Dll() Dim source = <compilation name="Name1"> <file name="a.vb"><![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary) compilation.VerifyDiagnostics() Assert.Null(compilation.GetEntryPoint(Nothing)) Assert.Null(compilation.GetEntryPointAndDiagnostics(Nothing)) End Sub <Fact()> Public Sub GetEntryPoint_Module() Dim source = <compilation name="Name1"> <file name="a.vb"><![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, OutputKind.NetModule) compilation.VerifyDiagnostics() Assert.Null(compilation.GetEntryPoint(Nothing)) Assert.Null(compilation.GetEntryPointAndDiagnostics(Nothing)) End Sub <Fact> Public Sub CreateCompilationForModule() Dim source = <text> Class A Shared Sub Main() End Sub End Class </text>.Value ' equivalent of vbc with no /moduleassemblyname specified: Dim c = VisualBasicCompilation.Create(assemblyName:=Nothing, options:=TestOptions.ReleaseModule, syntaxTrees:={Parse(source)}, references:={MscorlibRef}) c.VerifyDiagnostics() Assert.Null(c.AssemblyName) Assert.Equal("?", c.Assembly.Name) Assert.Equal("?", c.Assembly.Identity.Name) ' no name is allowed for assembly as well, although it isn't useful: c = VisualBasicCompilation.Create(assemblyName:=Nothing, options:=TestOptions.ReleaseModule, syntaxTrees:={Parse(source)}, references:={MscorlibRef}) c.VerifyDiagnostics() Assert.Null(c.AssemblyName) Assert.Equal("?", c.Assembly.Name) Assert.Equal("?", c.Assembly.Identity.Name) ' equivalent of vbc with /moduleassemblyname specified: c = VisualBasicCompilation.Create(assemblyName:="ModuleAssemblyName", options:=TestOptions.ReleaseModule, syntaxTrees:={Parse(source)}, references:={MscorlibRef}) c.VerifyDiagnostics() Assert.Equal("ModuleAssemblyName", c.AssemblyName) Assert.Equal("ModuleAssemblyName", c.Assembly.Name) Assert.Equal("ModuleAssemblyName", c.Assembly.Identity.Name) End Sub <WorkItem(8506, "https://github.com/dotnet/roslyn/issues/8506")> <Fact()> Public Sub CrossCorlibSystemObjectReturnType_Script() ' MinAsyncCorlibRef corlib Is used since it provides just enough corlib type definitions ' And Task APIs necessary for script hosting are provided by MinAsyncRef. This ensures that ' `System.Object, mscorlib, Version=4.0.0.0` will Not be provided (since it's unversioned). ' ' In the original bug, Xamarin iOS, Android, And Mac Mobile profile corlibs were ' realistic cross-compilation targets. Dim compilation = VisualBasicCompilation.CreateScriptCompilation( "submission-assembly", references:={MinAsyncCorlibRef}, syntaxTree:=Parse("? True", options:=TestOptions.Script) ).VerifyDiagnostics() Assert.True(compilation.IsSubmission) Dim taskOfT = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T) Dim taskOfObject = taskOfT.Construct(compilation.ObjectType) Dim entryPoint = compilation.GetEntryPoint(Nothing) Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfT.ContainingAssembly) Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfObject.ContainingAssembly) Assert.Equal(taskOfObject, entryPoint.ReturnType) End Sub <WorkItem(3719, "https://github.com/dotnet/roslyn/issues/3719")> <Fact()> Public Sub GetEntryPoint_Script() Dim source = <![CDATA[System.Console.WriteLine(1)]]> Dim compilation = CreateCompilationWithMscorlib45({VisualBasicSyntaxTree.ParseText(source.Value, options:=TestOptions.Script)}, options:=TestOptions.ReleaseDll) compilation.VerifyDiagnostics() Dim scriptMethod = compilation.GetMember("Script.<Main>") Assert.NotNull(scriptMethod) Dim method = compilation.GetEntryPoint(Nothing) Assert.Equal(method, scriptMethod) Dim entryPoint = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(entryPoint.MethodSymbol, scriptMethod) End Sub <Fact()> Public Sub GetEntryPoint_Script_MainIgnored() Dim source = <![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> Dim compilation = CreateCompilationWithMscorlib45({VisualBasicSyntaxTree.ParseText(source.Value, options:=TestOptions.Script)}, options:=TestOptions.ReleaseDll) compilation.VerifyDiagnostics(Diagnostic(ERRID.WRN_MainIgnored, "Main").WithArguments("Public Shared Sub Main()").WithLocation(3, 20)) Dim scriptMethod = compilation.GetMember("Script.<Main>") Assert.NotNull(scriptMethod) Dim entryPoint = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(entryPoint.MethodSymbol, scriptMethod) entryPoint.Diagnostics.Verify(Diagnostic(ERRID.WRN_MainIgnored, "Main").WithArguments("Public Shared Sub Main()").WithLocation(3, 20)) End Sub <Fact()> Public Sub GetEntryPoint_Submission() Dim source = "? 1 + 1" Dim compilation = VisualBasicCompilation.CreateScriptCompilation( "sub", references:={MscorlibRef}, syntaxTree:=Parse(source, options:=TestOptions.Script)) compilation.VerifyDiagnostics() Dim scriptMethod = compilation.GetMember("Script.<Factory>") Assert.NotNull(scriptMethod) Dim method = compilation.GetEntryPoint(Nothing) Assert.Equal(method, scriptMethod) Dim entryPoint = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(entryPoint.MethodSymbol, scriptMethod) entryPoint.Diagnostics.Verify() End Sub <Fact()> Public Sub GetEntryPoint_Submission_MainIgnored() Dim source = " Class A Shared Sub Main() End Sub End Class " Dim compilation = VisualBasicCompilation.CreateScriptCompilation( "Sub", references:={MscorlibRef}, syntaxTree:=Parse(source, options:=TestOptions.Script)) compilation.VerifyDiagnostics(Diagnostic(ERRID.WRN_MainIgnored, "Main").WithArguments("Public Shared Sub Main()").WithLocation(3, 20)) Dim scriptMethod = compilation.GetMember("Script.<Factory>") Assert.NotNull(scriptMethod) Dim entryPoint = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(entryPoint.MethodSymbol, scriptMethod) entryPoint.Diagnostics.Verify(Diagnostic(ERRID.WRN_MainIgnored, "Main").WithArguments("Public Shared Sub Main()").WithLocation(3, 20)) End Sub <Fact()> Public Sub GetEntryPoint_MainType() Dim source = <compilation name="Name1"> <file name="a.vb"><![CDATA[ Class A Shared Sub Main() End Sub End Class Class B Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B")) compilation.VerifyDiagnostics() Dim mainMethod = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("Main") Assert.Equal(mainMethod, compilation.GetEntryPoint(Nothing)) Dim entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol) entryPointAndDiagnostics.Diagnostics.Verify() End Sub <Fact> Public Sub ReferenceManagerReuse_WithOptions() Dim c1 = VisualBasicCompilation.Create("c", options:=TestOptions.ReleaseDll) Dim c2 = c1.WithOptions(TestOptions.ReleaseExe) Assert.True(c1.ReferenceManagerEquals(c2)) c2 = c1.WithOptions(New VisualBasicCompilationOptions(OutputKind.WindowsApplication)) Assert.True(c1.ReferenceManagerEquals(c2)) c2 = c1.WithOptions(TestOptions.ReleaseModule) Assert.False(c1.ReferenceManagerEquals(c2)) c1 = VisualBasicCompilation.Create("c", options:=TestOptions.ReleaseModule) c2 = c1.WithOptions(TestOptions.ReleaseExe) Assert.False(c1.ReferenceManagerEquals(c2)) c2 = c1.WithOptions(TestOptions.ReleaseDll) Assert.False(c1.ReferenceManagerEquals(c2)) c2 = c1.WithOptions(New VisualBasicCompilationOptions(OutputKind.WindowsApplication)) Assert.False(c1.ReferenceManagerEquals(c2)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithPreviousSubmission() Dim s1 = VisualBasicCompilation.CreateScriptCompilation("s1") Dim s2 = VisualBasicCompilation.CreateScriptCompilation("s2") Dim s3 = s2.WithScriptCompilationInfo(s2.ScriptCompilationInfo.WithPreviousScriptCompilation(s1)) Assert.True(s2.ReferenceManagerEquals(s3)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithXmlFileResolver() Dim c1 = VisualBasicCompilation.Create("c", options:=TestOptions.ReleaseDll) Dim c2 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(New XmlFileResolver(Nothing))) Assert.False(c1.ReferenceManagerEquals(c2)) Dim c3 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(c1.Options.XmlReferenceResolver)) Assert.True(c1.ReferenceManagerEquals(c3)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithMetadataReferenceResolver() Dim c1 = VisualBasicCompilation.Create("c", options:=TestOptions.ReleaseDll) Dim c2 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(New TestMetadataReferenceResolver())) Assert.False(c1.ReferenceManagerEquals(c2)) Dim c3 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(c1.Options.MetadataReferenceResolver)) Assert.True(c1.ReferenceManagerEquals(c3)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithName() Dim c1 = VisualBasicCompilation.Create("c1") Dim c2 = c1.WithAssemblyName("c2") Assert.False(c1.ReferenceManagerEquals(c2)) Dim c3 = c1.WithAssemblyName("c1") Assert.True(c1.ReferenceManagerEquals(c3)) Dim c4 = c1.WithAssemblyName(Nothing) Assert.False(c1.ReferenceManagerEquals(c4)) Dim c5 = c4.WithAssemblyName(Nothing) Assert.True(c4.ReferenceManagerEquals(c5)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithReferences() Dim c1 = VisualBasicCompilation.Create("c1") Dim c2 = c1.WithReferences({MscorlibRef}) Assert.False(c1.ReferenceManagerEquals(c2)) Dim c3 = c2.WithReferences({MscorlibRef, SystemCoreRef}) Assert.False(c3.ReferenceManagerEquals(c2)) c3 = c2.AddReferences(SystemCoreRef) Assert.False(c3.ReferenceManagerEquals(c2)) c3 = c2.RemoveAllReferences() Assert.False(c3.ReferenceManagerEquals(c2)) c3 = c2.ReplaceReference(MscorlibRef, SystemCoreRef) Assert.False(c3.ReferenceManagerEquals(c2)) c3 = c2.RemoveReferences(MscorlibRef) Assert.False(c3.ReferenceManagerEquals(c2)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithSyntaxTrees() Dim ta = Parse("Imports System") Dim tb = Parse("Imports System", options:=TestOptions.Script) Dim tc = Parse("#r ""bar"" ' error: #r in regular code") Dim tr = Parse("#r ""foo""", options:=TestOptions.Script) Dim ts = Parse("#r ""bar""", options:=TestOptions.Script) Dim a = VisualBasicCompilation.Create("c", syntaxTrees:={ta}) ' add: Dim ab = a.AddSyntaxTrees(tb) Assert.True(a.ReferenceManagerEquals(ab)) Dim ac = a.AddSyntaxTrees(tc) Assert.True(a.ReferenceManagerEquals(ac)) Dim ar = a.AddSyntaxTrees(tr) Assert.False(a.ReferenceManagerEquals(ar)) Dim arc = ar.AddSyntaxTrees(tc) Assert.True(ar.ReferenceManagerEquals(arc)) ' remove: Dim ar2 = arc.RemoveSyntaxTrees(tc) Assert.True(arc.ReferenceManagerEquals(ar2)) Dim c = arc.RemoveSyntaxTrees(ta, tr) Assert.False(arc.ReferenceManagerEquals(c)) Dim none1 = c.RemoveSyntaxTrees(tc) Assert.True(c.ReferenceManagerEquals(none1)) Dim none2 = arc.RemoveAllSyntaxTrees() Assert.False(arc.ReferenceManagerEquals(none2)) Dim none3 = ac.RemoveAllSyntaxTrees() Assert.True(ac.ReferenceManagerEquals(none3)) ' replace: Dim asc = arc.ReplaceSyntaxTree(tr, ts) Assert.False(arc.ReferenceManagerEquals(asc)) Dim brc = arc.ReplaceSyntaxTree(ta, tb) Assert.True(arc.ReferenceManagerEquals(brc)) Dim abc = arc.ReplaceSyntaxTree(tr, tb) Assert.False(arc.ReferenceManagerEquals(abc)) Dim ars = arc.ReplaceSyntaxTree(tc, ts) Assert.False(arc.ReferenceManagerEquals(ars)) End Sub Private Class EvolvingTestReference Inherits PortableExecutableReference Private ReadOnly _metadataSequence As IEnumerator(Of Metadata) Public QueryCount As Integer Public Sub New(metadataSequence As IEnumerable(Of Metadata)) MyBase.New(MetadataReferenceProperties.Assembly) Me._metadataSequence = metadataSequence.GetEnumerator() End Sub Protected Overrides Function CreateDocumentationProvider() As DocumentationProvider Return DocumentationProvider.Default End Function Protected Overrides Function GetMetadataImpl() As Metadata QueryCount = QueryCount + 1 _metadataSequence.MoveNext() Return _metadataSequence.Current End Function Protected Overrides Function WithPropertiesImpl(properties As MetadataReferenceProperties) As PortableExecutableReference Throw New NotImplementedException() End Function End Class <Fact> Public Sub MetadataConsistencyWhileEvolvingCompilation() Dim md1 = AssemblyMetadata.CreateFromImage(CreateCompilationWithMscorlib({"Public Class C : End Class"}, options:=TestOptions.ReleaseDll).EmitToArray()) Dim md2 = AssemblyMetadata.CreateFromImage(CreateCompilationWithMscorlib({"Public Class D : End Class"}, options:=TestOptions.ReleaseDll).EmitToArray()) Dim reference = New EvolvingTestReference({md1, md2}) Dim c1 = CreateCompilationWithMscorlib({"Public Class Main : Public Shared C As C : End Class"}, {reference, reference}, options:=TestOptions.ReleaseDll) Dim c2 = c1.WithAssemblyName("c2") Dim c3 = c2.AddSyntaxTrees(Parse("Public Class Main2 : Public Shared A As Integer : End Class")) Dim c4 = c3.WithOptions(New VisualBasicCompilationOptions(OutputKind.NetModule)) Dim c5 = c4.WithReferences({MscorlibRef, reference}) c3.VerifyDiagnostics() c1.VerifyDiagnostics() c4.VerifyDiagnostics() c2.VerifyDiagnostics() Assert.Equal(1, reference.QueryCount) c5.VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "C").WithArguments("C").WithLocation(1, 40)) Assert.Equal(2, reference.QueryCount) End Sub <Fact> Public Sub LinkedNetmoduleMetadataMustProvideFullPEImage() Dim moduleBytes = TestResources.MetadataTests.NetModule01.ModuleCS00 Dim headers = New PEHeaders(New MemoryStream(moduleBytes)) Dim pinnedPEImage = GCHandle.Alloc(moduleBytes.ToArray(), GCHandleType.Pinned) Try Using mdModule = ModuleMetadata.CreateFromMetadata(pinnedPEImage.AddrOfPinnedObject() + headers.MetadataStartOffset, headers.MetadataSize) Dim c = VisualBasicCompilation.Create("Foo", references:={MscorlibRef, mdModule.GetReference(display:="ModuleCS00")}, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics(Diagnostic(ERRID.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage).WithArguments("ModuleCS00").WithLocation(1, 1)) End Using Finally pinnedPEImage.Free() End Try End Sub <Fact> <WorkItem(797640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797640")> Public Sub GetMetadataReferenceAPITest() Dim comp = VisualBasicCompilation.Create("Compilation") Dim metadata = TestReferences.NetFx.v4_0_30319.mscorlib comp = comp.AddReferences(metadata) Dim assemblySmb = comp.GetReferencedAssemblySymbol(metadata) Dim reference = comp.GetMetadataReference(assemblySmb) Assert.NotNull(reference) Dim comp2 = VisualBasicCompilation.Create("Compilation") comp2 = comp.AddReferences(metadata) Dim reference2 = comp2.GetMetadataReference(assemblySmb) Assert.NotNull(reference2) End Sub <Fact()> Public Sub EqualityOfMergedNamespaces() Dim moduleComp = CompilationUtils.CreateCompilationWithoutReferences( <compilation> <file name="a.vb"> Namespace NS1 Namespace NS3 Interface T1 End Interface End Namespace End Namespace Namespace NS2 Namespace NS3 Interface T2 End Interface End Namespace End Namespace </file> </compilation>, TestOptions.ReleaseModule) Dim compilation = CompilationUtils.CreateCompilationWithReferences( <compilation> <file name="a.vb"> Namespace NS1 Namespace NS3 Interface T3 End Interface End Namespace End Namespace Namespace NS2 Namespace NS3 Interface T4 End Interface End Namespace End Namespace </file> </compilation>, {moduleComp.EmitToImageReference()}) TestEqualityRecursive(compilation.GlobalNamespace, compilation.GlobalNamespace, NamespaceKind.Compilation, Function(ns) compilation.GetCompilationNamespace(ns)) TestEqualityRecursive(compilation.Assembly.GlobalNamespace, compilation.Assembly.GlobalNamespace, NamespaceKind.Assembly, Function(ns) compilation.Assembly.GetAssemblyNamespace(ns)) End Sub Private Shared Sub TestEqualityRecursive(testNs1 As NamespaceSymbol, testNs2 As NamespaceSymbol, kind As NamespaceKind, factory As Func(Of NamespaceSymbol, NamespaceSymbol)) Assert.Equal(kind, testNs1.NamespaceKind) Assert.Same(testNs1, testNs2) Dim children1 = testNs1.GetMembers().OrderBy(Function(m) m.Name).ToArray() Dim children2 = testNs2.GetMembers().OrderBy(Function(m) m.Name).ToArray() For i = 0 To children1.Count - 1 Assert.Same(children1(i), children2(i)) If children1(i).Kind = SymbolKind.Namespace Then TestEqualityRecursive(DirectCast(testNs1.GetMembers(children1(i).Name).Single(), NamespaceSymbol), DirectCast(testNs1.GetMembers(children1(i).Name).Single(), NamespaceSymbol), kind, factory) End If Next Assert.Same(testNs1, factory(testNs1)) For Each constituent In testNs1.ConstituentNamespaces Assert.Same(testNs1, factory(constituent)) Next End Sub <Fact> Public Sub ConsistentParseOptions() Dim tree1 = SyntaxFactory.ParseSyntaxTree("", VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) Dim tree2 = SyntaxFactory.ParseSyntaxTree("", VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) Dim tree3 = SyntaxFactory.ParseSyntaxTree("", VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic11)) Dim assemblyName = GetUniqueName() Dim CompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) VisualBasicCompilation.Create(assemblyName, {tree1, tree2}, {MscorlibRef}, CompilationOptions) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create(assemblyName, {tree1, tree3}, {MscorlibRef}, CompilationOptions)) End Sub <Fact> Public Sub SubmissionCompilation_Errors() Dim genericParameter = GetType(List(Of)).GetGenericArguments()(0) Dim open = GetType(Dictionary(Of,)).MakeGenericType(GetType(Integer), genericParameter) Dim ptr = GetType(Integer).MakePointerType() Dim byRefType = GetType(Integer).MakeByRefType() Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", returnType:=genericParameter)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", returnType:=open)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", returnType:=GetType(Void))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", returnType:=byRefType)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=genericParameter)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=open)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=GetType(Void))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=GetType(Integer))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=ptr)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=byRefType)) Dim s0 = VisualBasicCompilation.CreateScriptCompilation("a0", globalsType:=GetType(List(Of Integer))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a1", previousScriptCompilation:=s0, globalsType:=GetType(List(Of Boolean)))) ' invalid options Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseExe)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeApplication))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithCryptoKeyContainer("foo"))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithCryptoKeyFile("foo.snk"))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithDelaySign(True))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithDelaySign(False))) End Sub <Fact> Public Sub HasSubmissionResult() Assert.False(VisualBasicCompilation.CreateScriptCompilation("sub").HasSubmissionResult()) Assert.True(CreateSubmission("?1", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.False(CreateSubmission("1", parseOptions:=TestOptions.Script).HasSubmissionResult()) ' TODO (https://github.com/dotnet/roslyn/issues/4763): '?' should be optional ' TestSubmissionResult(CreateSubmission("1", parseOptions:=TestOptions.Interactive), expectedType:=SpecialType.System_Int32, expectedHasValue:=True) ' TODO (https://github.com/dotnet/roslyn/issues/4766): ReturnType should not be ignored ' TestSubmissionResult(CreateSubmission("?1", parseOptions:=TestOptions.Interactive, returnType:=GetType(Double)), expectedType:=SpecialType.System_Double, expectedHasValue:=True) Assert.False(CreateSubmission(" Sub Foo() End Sub ").HasSubmissionResult()) Assert.False(CreateSubmission("Imports System", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.False(CreateSubmission("Dim i As Integer", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.False(CreateSubmission("System.Console.WriteLine()", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?System.Console.WriteLine()", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("System.Console.ReadLine()", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?System.Console.ReadLine()", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?Nothing", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?AddressOf System.Console.WriteLine", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?Function(x) x", parseOptions:=TestOptions.Script).HasSubmissionResult()) End Sub ''' <summary> ''' Previous submission has to have no errors. ''' </summary> <Fact> Public Sub PreviousSubmissionWithError() Dim s0 = CreateSubmission("Dim a As X = 1") s0.VerifyDiagnostics( Diagnostic(ERRID.ERR_UndefinedType1, "X").WithArguments("X")) Assert.Throws(Of InvalidOperationException)(Function() CreateSubmission("?a + 1", previous:=s0)) End Sub <Fact> <WorkItem(13925, "https://github.com/dotnet/roslyn/issues/13925")> Public Sub RemoveAllSyntaxTreesAndEmbeddedTrees_01() Dim compilation1 = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Public Module C Sub Main() System.Console.WriteLine(1) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True), references:={SystemRef}) compilation1.VerifyDiagnostics() Dim compilation2 = compilation1.RemoveAllSyntaxTrees() compilation2 = compilation2.AddSyntaxTrees(compilation1.SyntaxTrees) compilation2.VerifyDiagnostics() CompileAndVerify(compilation2, expectedOutput:="1") End Sub <Fact> <WorkItem(13925, "https://github.com/dotnet/roslyn/issues/13925")> Public Sub RemoveAllSyntaxTreesAndEmbeddedTrees_02() Dim compilation1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Public Module C Sub Main() System.Console.WriteLine(1) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True)) compilation1.VerifyDiagnostics() Dim compilation2 = compilation1.RemoveAllSyntaxTrees() compilation2 = compilation2.AddSyntaxTrees(compilation1.SyntaxTrees) compilation2.VerifyDiagnostics() CompileAndVerify(compilation2, expectedOutput:="1") End Sub End Class End Namespace
vslsnap/roslyn
src/Compilers/VisualBasic/Test/Semantic/Compilation/CompilationAPITests.vb
Visual Basic
apache-2.0
99,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 Microsoft.NetFramework.Analyzers Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.NetFramework.VisualBasic.Analyzers ''' <summary> ''' CA1300: Specify MessageBoxOptions ''' </summary> <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Public NotInheritable Class BasicSpecifyMessageBoxOptionsAnalyzer Inherits SpecifyMessageBoxOptionsAnalyzer End Class End Namespace
mavasani/roslyn-analyzers
src/NetAnalyzers/VisualBasic/Microsoft.NetFramework.Analyzers/BasicSpecifyMessageBoxOptions.vb
Visual Basic
apache-2.0
611
'Copyright 2013 Google Inc '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.Collections.Generic Imports System.IO Imports System.Threading Imports Google.Apis.Calendar.v3 Imports Google.Apis.Calendar.v3.Data Imports Google.Apis.Calendar.v3.EventsResource Imports Google.Apis.Services Imports Google.Apis.Auth.OAuth2 Imports Google.Apis.Util.Store ''' <summary> ''' An sample for the Calendar API which displays a list of calendars and events in the first calendar. ''' https://developers.google.com/google-apps/calendar/ ''' </summary> Module Program '' Calendar scopes which is initialized on the main method. Dim scopes As IList(Of String) = New List(Of String)() '' Calendar service. Dim service As CalendarService Sub Main() ' Add the calendar specific scope to the scopes list. scopes.Add(CalendarService.Scope.Calendar) ' Display the header and initialize the sample. Console.WriteLine("Google.Apis.Calendar.v3 Sample") Console.WriteLine("==============================") Dim credential As UserCredential Using stream As New FileStream("client_secrets.json", FileMode.Open, FileAccess.Read) credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, New FileDataStore("Calendar.VB.Sample")).Result End Using ' Create the calendar service using an initializer instance Dim initializer As New BaseClientService.Initializer() initializer.HttpClientInitializer = credential initializer.ApplicationName = "VB.NET Calendar Sample" service = New CalendarService(initializer) ' Fetch the list of calendar list Dim list As IList(Of CalendarListEntry) = service.CalendarList.List().Execute().Items() ' Display all calendars DisplayList(list) For Each calendar As Data.CalendarListEntry In list ' Display calendar's events DisplayFirstCalendarEvents(calendar) Next Console.WriteLine("Press any key to continue...") Console.ReadKey() End Sub ''' <summary>Displays all calendars.</summary> Private Sub DisplayList(list As IList(Of CalendarListEntry)) Console.WriteLine("Lists of calendars:") For Each item As CalendarListEntry In list Console.WriteLine(item.Summary & ". Location: " & item.Location & ", TimeZone: " & item.TimeZone) Next End Sub ''' <summary>Displays the calendar's events.</summary> Private Sub DisplayFirstCalendarEvents(list As CalendarListEntry) Console.WriteLine(Environment.NewLine & "Maximum 5 first events from {0}:", list.Summary) Dim requeust As ListRequest = service.Events.List(list.Id) ' Set MaxResults and TimeMin with sample values requeust.MaxResults = 5 requeust.TimeMin = New DateTime(2013, 10, 1, 20, 0, 0) ' Fetch the list of events For Each calendarEvent As Data.Event In requeust.Execute().Items Dim startDate As String = "Unspecified" If (Not calendarEvent.Start Is Nothing) Then If (Not calendarEvent.Start.Date Is Nothing) Then startDate = calendarEvent.Start.Date.ToString() End If End If Console.WriteLine(calendarEvent.Summary & ". Start at: " & startDate) Next End Sub End Module
simpleverso/google-api-dotnet-client-samples
Calendar.VB.ConsoleApp/Program.vb
Visual Basic
apache-2.0
4,111
' 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.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.Interop ' NOTE(DustinCa): The EditorFactory registration is in VisualStudioComponents\VisualBasicPackageRegistration.pkgdef. ' The reason for this is because the ProvideEditorLogicalView does not allow a name value to specified in addition to ' its GUID. This name value is used to identify untrusted logical views and link them to their physical view attributes. ' The net result is that using the attributes only causes designers to be loaded in the preview tab, even when they ' shouldn't be. Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic ' TODO(DustinCa): Put all of this in VisualBasicPackageRegistration.pkgdef rather than using attributes ' (See setupauthoring\vb\components\vblanguageservice.pkgdef for an example). ' VB option pages tree ' Basic ' General (from editor) ' Scroll Bars (from editor) ' Tabs (from editor) ' Advanced ' Code Style (category) ' General ' Naming <Guid(Guids.VisualBasicPackageIdString)> <PackageRegistration(UseManagedResourcesOnly:=True)> <ProvideLanguageExtension(GetType(VisualBasicLanguageService), ".bas")> <ProvideLanguageExtension(GetType(VisualBasicLanguageService), ".cls")> <ProvideLanguageExtension(GetType(VisualBasicLanguageService), ".ctl")> <ProvideLanguageExtension(GetType(VisualBasicLanguageService), ".dob")> <ProvideLanguageExtension(GetType(VisualBasicLanguageService), ".dsr")> <ProvideLanguageExtension(GetType(VisualBasicLanguageService), ".frm")> <ProvideLanguageExtension(GetType(VisualBasicLanguageService), ".pag")> <ProvideLanguageExtension(GetType(VisualBasicLanguageService), ".vb")> <ProvideLanguageEditorOptionPage(GetType(AdvancedOptionPage), "Basic", Nothing, "Advanced", "#102", 10160)> <ProvideLanguageEditorToolsOptionCategory("Basic", "Code Style", "#109")> <ProvideLanguageEditorOptionPage(GetType(CodeStylePage), "Basic", "Code Style", "General", "#111", 10161)> <ProvideLanguageEditorOptionPage(GetType(NamingStylesOptionPage), "Basic", "Code Style", "Naming", "#110", 10162)> <ProvideLanguageEditorOptionPage(GetType(IntelliSenseOptionPage), "Basic", Nothing, "IntelliSense", "#112", 312)> <ProvideAutomationProperties("TextEditor", "Basic", Guids.TextManagerPackageString, 103, 105, Guids.VisualBasicPackageIdString)> <ProvideAutomationProperties("TextEditor", "Basic-Specific", Guids.VisualBasicPackageIdString, 104, 106)> <ProvideService(GetType(VisualBasicLanguageService), ServiceName:="Visual Basic Language Service")> <ProvideService(GetType(IVbCompilerService), ServiceName:="Visual Basic Project System Shim")> <ProvideService(GetType(IVbTempPECompilerFactory), ServiceName:="Visual Basic TempPE Compiler Factory Service")> Friend Class VisualBasicPackage Inherits AbstractPackage(Of VisualBasicPackage, VisualBasicLanguageService) Implements IVbCompilerService Implements IVsUserSettingsQuery ' The property page for WinForms project has a special interface that it uses to get ' entry points that are Forms: IVbEntryPointProvider. The semantics for this ' interface are the same as VisualBasicProject::GetFormEntryPoints, but callers get ' the VB Package and cast it to IVbEntryPointProvider. The property page is managed ' and we've redefined the interface, so we have to register a COM aggregate of the ' VB package. This is the same pattern we use for the LanguageService and Razor. Private ReadOnly _comAggregate As Object Private _libraryManager As ObjectBrowserLibraryManager Private _libraryManagerCookie As UInteger Public Sub New() MyBase.New() _comAggregate = Interop.ComAggregate.CreateAggregatedObject(Me) End Sub Protected Overrides Function CreateWorkspace() As VisualStudioWorkspaceImpl Return Me.ComponentModel.GetService(Of VisualStudioWorkspaceImpl) End Function Protected Overrides Sub Initialize() Try MyBase.Initialize() RegisterLanguageService(GetType(IVbCompilerService), Function() _comAggregate) Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspaceImpl)() RegisterService(Of IVbTempPECompilerFactory)(Function() New TempPECompilerFactory(workspace)) RegisterObjectBrowserLibraryManager() Catch ex As Exception When FatalError.Report(ex) End Try End Sub Protected Overrides Sub Dispose(disposing As Boolean) UnregisterObjectBrowserLibraryManager() MyBase.Dispose(disposing) End Sub Private Sub RegisterObjectBrowserLibraryManager() Dim objectManager = TryCast(Me.GetService(GetType(SVsObjectManager)), IVsObjectManager2) If objectManager IsNot Nothing Then Me._libraryManager = New ObjectBrowserLibraryManager(Me) If ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(Me._libraryManager, Me._libraryManagerCookie)) Then Me._libraryManagerCookie = 0 End If End If End Sub Private Sub UnregisterObjectBrowserLibraryManager() If _libraryManagerCookie <> 0 Then Dim objectManager = TryCast(Me.GetService(GetType(SVsObjectManager)), IVsObjectManager2) If objectManager IsNot Nothing Then objectManager.UnregisterLibrary(Me._libraryManagerCookie) Me._libraryManagerCookie = 0 End If Me._libraryManager.Dispose() Me._libraryManager = Nothing End If End Sub Public Function NeedExport(pageID As String, <Out> ByRef needExportParam As Integer) As Integer Implements IVsUserSettingsQuery.NeedExport ' We need to override MPF's definition of NeedExport since it doesn't know about our automation object needExportParam = If(pageID = "TextEditor.Basic-Specific", 1, 0) Return VSConstants.S_OK End Function Protected Overrides Function GetAutomationObject(name As String) As Object If name = "Basic-Specific" Then Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Return New AutomationObject(workspace) End If Return MyBase.GetAutomationObject(name) End Function Protected Overrides Function CreateEditorFactories() As IEnumerable(Of IVsEditorFactory) Dim editorFactory = New VisualBasicEditorFactory(Me) Dim codePageEditorFactory = New VisualBasicCodePageEditorFactory(editorFactory) Return {editorFactory, codePageEditorFactory} End Function Protected Overrides Function CreateLanguageService() As VisualBasicLanguageService Return New VisualBasicLanguageService(Me) End Function Protected Overrides Sub RegisterMiscellaneousFilesWorkspaceInformation(miscellaneousFilesWorkspace As MiscellaneousFilesWorkspace) miscellaneousFilesWorkspace.RegisterLanguage( Guids.VisualBasicLanguageServiceId, LanguageNames.VisualBasic, ".vbx", VisualBasicParseOptions.Default) End Sub Protected Overrides ReadOnly Property RoslynLanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
bbarry/roslyn
src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.vb
Visual Basic
apache-2.0
8,688
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.MoveToTopOfFile Partial Friend Class MoveToTopOfFileCodeFixProvider Private Class MoveToLineCodeAction Inherits CodeAction Private ReadOnly _destinationLine As Integer Private ReadOnly _document As Document Private ReadOnly _token As SyntaxToken Private ReadOnly _title As String Public Sub New(document As Document, token As SyntaxToken, destinationLine As Integer, title As String) _document = document _token = token _destinationLine = destinationLine _title = title End Sub Public Overrides ReadOnly Property Title As String Get Return _title End Get End Property Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim text = Await _document.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim destinationLineSpan = text.Lines(_destinationLine).Start Dim lineToMove = _token.GetLocation().GetLineSpan().StartLinePosition.Line Dim textLineToMove = text.Lines(lineToMove) Dim textWithoutLine = text.WithChanges(New TextChange(textLineToMove.SpanIncludingLineBreak, "")) Dim textWithMovedLine = textWithoutLine.WithChanges(New TextChange(TextSpan.FromBounds(destinationLineSpan, destinationLineSpan), textLineToMove.ToString().TrimStart() + vbCrLf)) Return _document.WithText(textWithMovedLine) End Function End Class End Class End Namespace
physhi/roslyn
src/Features/VisualBasic/Portable/CodeFixes/MoveToTopOfFile/MoveToTopOfFileCodeFixProvider.MoveToLineCodeAction.vb
Visual Basic
apache-2.0
2,071
' 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class EmbeddedSymbolManager Friend NotInheritable Class EmbeddedNamedTypeSymbol Inherits SourceNamedTypeSymbol Private ReadOnly _kind As EmbeddedSymbolKind Public Sub New(decl As MergedTypeDeclaration, containingSymbol As NamespaceOrTypeSymbol, containingModule As SourceModuleSymbol, kind As EmbeddedSymbolKind) MyBase.New(decl, containingSymbol, containingModule) #If DEBUG Then Dim references As ImmutableArray(Of SyntaxReference) = decl.SyntaxReferences Debug.Assert(references.Length() = 1) Debug.Assert(references.First.SyntaxTree.IsEmbeddedSyntaxTree()) #End If Debug.Assert(kind <> VisualBasic.Symbols.EmbeddedSymbolKind.None) _kind = kind End Sub Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property AreMembersImplicitlyDeclared As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind Get Return _kind End Get End Property Friend Overrides Function GetMembersForCci() As ImmutableArray(Of Symbol) Dim builder = ArrayBuilder(Of Symbol).GetInstance() Dim manager As EmbeddedSymbolManager = Me.DeclaringCompilation.EmbeddedSymbolManager For Each member In Me.GetMembers If manager.IsSymbolReferenced(member) Then builder.Add(member) End If Next Return builder.ToImmutableAndFree() End Function End Class End Class End Namespace
mmitche/roslyn
src/Compilers/VisualBasic/Portable/Symbols/EmbeddedSymbols/Symbols/EmbeddedNamedTypeSymbol.vb
Visual Basic
apache-2.0
2,496
Namespace Cisco ''' <summary>Voltage Monitor</summary> ''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated> ''' <generator-date>08/02/2014 18:05:10</generator-date> ''' <generator-functions>1</generator-functions> ''' <generator-source>Caerus\_Cisco\Generated\VoltageMonitor.tt</generator-source> ''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template> ''' <generator-version>1</generator-version> <System.CodeDom.Compiler.GeneratedCode("Caerus\_Cisco\Generated\VoltageMonitor.tt", "1")> _ <System.Serializable()> _ Partial Public Class VoltageMonitor Inherits System.Object Implements System.IComparable Implements System.IFormattable Implements System.Xml.Serialization.IXmlSerializable #Region " Public Constructors " ''' <summary>Default Constructor</summary> Public Sub New() MyBase.New() End Sub ''' <summary>Parametered Constructor (1 Parameters)</summary> Public Sub New( _ ByVal _Index As System.Int32 _ ) MyBase.New() Index = _Index End Sub ''' <summary>Parametered Constructor (2 Parameters)</summary> Public Sub New( _ ByVal _Index As System.Int32, _ ByVal _Description As System.String _ ) MyBase.New() Index = _Index Description = _Description End Sub ''' <summary>Parametered Constructor (3 Parameters)</summary> Public Sub New( _ ByVal _Index As System.Int32, _ ByVal _Description As System.String, _ ByVal _State As EnvironmentalMonitoringState _ ) MyBase.New() Index = _Index Description = _Description State = _State End Sub #End Region #Region " Class Plumbing/Interface Code " #Region " IComparable Implementation " #Region " Public Methods " ''' <summary>Comparison Method</summary> Public Overridable Function IComparable_CompareTo( _ ByVal value As System.Object _ ) As System.Int32 Implements System.IComparable.CompareTo Dim typed_Value As VoltageMonitor = TryCast(value, VoltageMonitor) If typed_Value Is Nothing Then Throw New ArgumentException(String.Format("Value is not of comparable type: {0}", value.GetType.Name), "Value") Else Dim return_Value As Integer = 0 return_Value = Index.CompareTo(typed_Value.Index) If return_Value <> 0 Then Return return_Value Return return_Value End If End Function #End Region #End Region #Region " IFormattable Implementation " #Region " Public Constants " ''' <summary>Public Shared Reference to the Name of the Property: AsString</summary> ''' <remarks></remarks> Public Const PROPERTY_ASSTRING As String = "AsString" #End Region #Region " Public Properties " ''' <summary></summary> ''' <remarks></remarks> Public ReadOnly Property AsString() As System.String Get Return Me.ToString() End Get End Property #End Region #Region " Public Shared Methods " Public Shared Function ToString_default( _ ByVal Description As System.String _ ) As String Return String.Format( _ "{0}", _ Description) End Function #End Region #Region " Public Methods " Public Overloads Overrides Function ToString() As String Return Me.ToString(String.Empty, Nothing) End Function Public Overloads Function ToString( _ ByVal format As String _ ) As String If String.IsNullOrEmpty(format) OrElse String.Compare(format, "default", True) = 0 Then Return ToString_default( _ Description _ ) End If Return String.Empty End Function Public Overloads Function ToString( _ ByVal format As String, _ ByVal formatProvider As System.IFormatProvider _ ) As String Implements System.IFormattable.ToString If String.IsNullOrEmpty(format) OrElse String.Compare(format, "default", True) = 0 Then Return ToString_default( _ Description _ ) End If Return String.Empty End Function #End Region #End Region #Region " IXmlSerialisable Implementation " #Region " Public Methods " ''' <summary>Method to Return Schema Depicting Object/Class</summary> ''' <remarks></remarks> Public Function IXmlSerialisable_GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Leviathan.Configuration.XmlSerialiser.GenerateSchema(Me.GetType) End Function ''' <summary></summary> ''' <remarks></remarks> Public Sub IXmlSerialisable_ReadXml( _ ByVal reader As System.Xml.XmlReader _ ) Implements System.Xml.Serialization.IXmlSerializable.ReadXml Leviathan.Configuration.XmlSerialiser.ReadXml(Me, reader) End Sub ''' <summary></summary> ''' <remarks></remarks> Public Sub IXmlSerialisable_WriteXml( _ ByVal writer As System.Xml.XmlWriter _ ) Implements System.Xml.Serialization.IXmlSerializable.WriteXml Leviathan.Configuration.XmlSerialiser.WriteXml(Me, writer) End Sub #End Region #End Region #End Region #Region " Public Constants " ''' <summary>Public Shared Reference to the Name of the Property: Index</summary> ''' <remarks></remarks> Public Const PROPERTY_INDEX As String = "Index" ''' <summary>Public Shared Reference to the Name of the Property: Description</summary> ''' <remarks></remarks> Public Const PROPERTY_DESCRIPTION As String = "Description" ''' <summary>Public Shared Reference to the Name of the Property: State</summary> ''' <remarks></remarks> Public Const PROPERTY_STATE As String = "State" #End Region #Region " Private Variables " ''' <summary>Private Data Storage Variable for Property: Index</summary> ''' <remarks></remarks> Private m_Index As System.Int32 ''' <summary>Private Data Storage Variable for Property: Description</summary> ''' <remarks></remarks> Private m_Description As System.String ''' <summary>Private Data Storage Variable for Property: State</summary> ''' <remarks></remarks> Private m_State As EnvironmentalMonitoringState #End Region #Region " Public Properties " ''' <summary>Provides Access to the Property: Index</summary> ''' <remarks></remarks> <System.Xml.Serialization.XmlElement(ElementName:="Index")> _ Public Property Index() As System.Int32 Get Return m_Index End Get Set(value As System.Int32) m_Index = value End Set End Property ''' <summary>Provides Access to the Property: Description</summary> ''' <remarks></remarks> <System.Xml.Serialization.XmlElement(ElementName:="Description")> _ Public Property Description() As System.String Get Return m_Description End Get Set(value As System.String) m_Description = value End Set End Property ''' <summary>Provides Access to the Property: State</summary> ''' <remarks></remarks> <System.Xml.Serialization.XmlElement(ElementName:="State")> _ Public Property State() As EnvironmentalMonitoringState Get Return m_State End Get Set(value As EnvironmentalMonitoringState) m_State = value End Set End Property #End Region End Class End Namespace
thiscouldbejd/Caerus
_Cisco/Generated/VoltageMonitor.vb
Visual Basic
mit
7,424
Imports Aspose.Cloud Namespace Watermark Class AddImage Public Shared Sub Run() Dim inputfile As String = "doc-sample.doc" Dim imagefile As String = "Aspose Logo.png" Dim outfile As String = Common.GetOutputFilePath(inputfile, True) ' Upload input file from local directory to Cloud Storage Common.UploadFile(inputfile, String.Empty) ' Upload image file from local directory to Cloud Storage Common.UploadFile(imagefile, String.Empty) ' Add Watermark Image to a Word Document Common.WordsService.WordsDocumentWatermark.InsertDocumentWatermarkImage(inputfile, outfile, 45.0, imagefile, Common.FOLDER) ' Download output file from cloud storage and save on local directory Dim dataDir As String = Common.DownloadFile(inputfile, String.Empty) Console.WriteLine(Convert.ToString(vbLf & "Watermark image added successfully." & vbLf & "File saved at ") & dataDir) End Sub End Class End Namespace
farooqsheikhpk/Aspose_Words_Cloud
Examples/DotNET/SDK/VisualBasic/Watermark/AddImage.vb
Visual Basic
mit
1,067
Partial Class RepNota30 'NOTE: The following procedure is required by the telerik Reporting Designer 'It can be modified using the telerik Reporting Designer. 'Do not modify it using the code editor. Private Sub InitializeComponent() Dim ReportParameter1 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter() Dim ReportParameter2 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter() Dim ReportParameter3 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter() Dim StyleRule1 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule() Dim StyleRule2 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule() Dim StyleRule3 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule() Dim StyleRule4 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule() Me.SDSRepNota30 = New Telerik.Reporting.SqlDataSource() Me.labelsGroupHeader = New Telerik.Reporting.GroupHeaderSection() Me.montoCaptionTextBox = New Telerik.Reporting.TextBox() Me.nombreCaptionTextBox = New Telerik.Reporting.TextBox() Me.codigoCaptionTextBox = New Telerik.Reporting.TextBox() Me.labelsGroupFooter = New Telerik.Reporting.GroupFooterSection() Me.labelsGroup = New Telerik.Reporting.Group() Me.reportFooter = New Telerik.Reporting.ReportFooterSection() Me.montoSumFunctionTextBox = New Telerik.Reporting.TextBox() Me.TextBox1 = New Telerik.Reporting.TextBox() Me.pageHeader = New Telerik.Reporting.PageHeaderSection() Me.pageFooter = New Telerik.Reporting.PageFooterSection() Me.reportHeader = New Telerik.Reporting.ReportHeaderSection() Me.TextBox5 = New Telerik.Reporting.TextBox() Me.detail = New Telerik.Reporting.DetailSection() Me.montoDataTextBox = New Telerik.Reporting.TextBox() Me.nombreDataTextBox = New Telerik.Reporting.TextBox() Me.codigoDataTextBox = New Telerik.Reporting.TextBox() CType(Me, System.ComponentModel.ISupportInitialize).BeginInit() ' 'SDSRepNota30 ' Me.SDSRepNota30.ConnectionString = "cnx" Me.SDSRepNota30.Name = "SDSRepNota30" Me.SDSRepNota30.Parameters.AddRange(New Telerik.Reporting.SqlDataSourceParameter() {New Telerik.Reporting.SqlDataSourceParameter("@fechaFin", System.Data.DbType.DateTime, "=Parameters.fechaFin.Value"), New Telerik.Reporting.SqlDataSourceParameter("@idProyecto", System.Data.DbType.Int32, "=Parameters.idProyecto.Value"), New Telerik.Reporting.SqlDataSourceParameter("@tipo", System.Data.DbType.AnsiStringFixedLength, "=Parameters.tipo.Value")}) Me.SDSRepNota30.SelectCommand = "dbo.RepNota30" Me.SDSRepNota30.SelectCommandType = Telerik.Reporting.SqlDataSourceCommandType.StoredProcedure ' 'labelsGroupHeader ' Me.labelsGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.labelsGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.montoCaptionTextBox, Me.nombreCaptionTextBox, Me.codigoCaptionTextBox}) Me.labelsGroupHeader.Name = "labelsGroupHeader" Me.labelsGroupHeader.PrintOnEveryPage = True ' 'montoCaptionTextBox ' Me.montoCaptionTextBox.CanGrow = True Me.montoCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.montoCaptionTextBox.Name = "montoCaptionTextBox" Me.montoCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.montoCaptionTextBox.Style.Font.Name = "Arial" Me.montoCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.montoCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.montoCaptionTextBox.StyleName = "Caption" Me.montoCaptionTextBox.Value = "IMPORTE" ' 'nombreCaptionTextBox ' Me.nombreCaptionTextBox.CanGrow = True Me.nombreCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.nombreCaptionTextBox.Name = "nombreCaptionTextBox" Me.nombreCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(12.999600410461426R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.nombreCaptionTextBox.Style.Font.Name = "Arial" Me.nombreCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.nombreCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.nombreCaptionTextBox.StyleName = "Caption" Me.nombreCaptionTextBox.Value = "DESCRIPCIÓN" ' 'codigoCaptionTextBox ' Me.codigoCaptionTextBox.CanGrow = True Me.codigoCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.codigoCaptionTextBox.Name = "codigoCaptionTextBox" Me.codigoCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.codigoCaptionTextBox.Style.Font.Name = "Arial" Me.codigoCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.codigoCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.codigoCaptionTextBox.StyleName = "Caption" Me.codigoCaptionTextBox.Value = "CUENTA" ' 'labelsGroupFooter ' Me.labelsGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.labelsGroupFooter.Name = "labelsGroupFooter" Me.labelsGroupFooter.Style.Visible = False ' 'labelsGroup ' Me.labelsGroup.GroupFooter = Me.labelsGroupFooter Me.labelsGroup.GroupHeader = Me.labelsGroupHeader Me.labelsGroup.Name = "labelsGroup" ' 'reportFooter ' Me.reportFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.reportFooter.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.montoSumFunctionTextBox, Me.TextBox1}) Me.reportFooter.Name = "reportFooter" Me.reportFooter.Style.Visible = True ' 'montoSumFunctionTextBox ' Me.montoSumFunctionTextBox.CanGrow = True Me.montoSumFunctionTextBox.Format = "{0:N2}" Me.montoSumFunctionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.montoSumFunctionTextBox.Name = "montoSumFunctionTextBox" Me.montoSumFunctionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.montoSumFunctionTextBox.Style.BorderStyle.Bottom = Telerik.Reporting.Drawing.BorderType.[Double] Me.montoSumFunctionTextBox.Style.BorderStyle.Top = Telerik.Reporting.Drawing.BorderType.Solid Me.montoSumFunctionTextBox.Style.Font.Name = "Arial" Me.montoSumFunctionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.montoSumFunctionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right Me.montoSumFunctionTextBox.StyleName = "Data" Me.montoSumFunctionTextBox.Value = "=Sum(Fields.Monto)" ' 'TextBox1 ' Me.TextBox1.CanGrow = True Me.TextBox1.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox1.Name = "TextBox1" Me.TextBox1.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox1.Style.Font.Name = "Arial" Me.TextBox1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox1.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right Me.TextBox1.StyleName = "Caption" Me.TextBox1.Value = "TOTAL:" ' 'pageHeader ' Me.pageHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.pageHeader.Name = "pageHeader" Me.pageHeader.Style.Visible = False ' 'pageFooter ' Me.pageFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.pageFooter.Name = "pageFooter" ' 'reportHeader ' Me.reportHeader.Height = New Telerik.Reporting.Drawing.Unit(1.0000001192092896R, Telerik.Reporting.Drawing.UnitType.Cm) Me.reportHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox5}) Me.reportHeader.Name = "reportHeader" ' 'TextBox5 ' Me.TextBox5.CanGrow = True Me.TextBox5.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox5.Name = "TextBox5" Me.TextBox5.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(16.999900817871094R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox5.Style.Font.Bold = True Me.TextBox5.Style.Font.Name = "Arial" Me.TextBox5.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(8.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox5.StyleName = "Caption" Me.TextBox5.Value = "NOTA 31: INGRESOS FINANCIEROS" ' 'detail ' Me.detail.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.detail.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.montoDataTextBox, Me.nombreDataTextBox, Me.codigoDataTextBox}) Me.detail.Name = "detail" ' 'montoDataTextBox ' Me.montoDataTextBox.CanGrow = True Me.montoDataTextBox.Format = "{0:N2}" Me.montoDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.montoDataTextBox.Name = "montoDataTextBox" Me.montoDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.montoDataTextBox.Style.Font.Name = "Arial" Me.montoDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.montoDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right Me.montoDataTextBox.StyleName = "Data" Me.montoDataTextBox.Value = "=Fields.Monto" ' 'nombreDataTextBox ' Me.nombreDataTextBox.CanGrow = True Me.nombreDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.nombreDataTextBox.Name = "nombreDataTextBox" Me.nombreDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(12.999600410461426R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.nombreDataTextBox.Style.Font.Name = "Arial" Me.nombreDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.nombreDataTextBox.StyleName = "Data" Me.nombreDataTextBox.Value = "=Fields.Nombre" ' 'codigoDataTextBox ' Me.codigoDataTextBox.CanGrow = True Me.codigoDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.codigoDataTextBox.Name = "codigoDataTextBox" Me.codigoDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.codigoDataTextBox.Style.Font.Name = "Arial" Me.codigoDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.codigoDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.codigoDataTextBox.StyleName = "Data" Me.codigoDataTextBox.Value = "=Fields.Codigo" ' 'RepNota30 ' Me.DataSource = Me.SDSRepNota30 Me.Groups.AddRange(New Telerik.Reporting.Group() {Me.labelsGroup}) Me.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.labelsGroupHeader, Me.labelsGroupFooter, Me.reportFooter, Me.pageHeader, Me.pageFooter, Me.reportHeader, Me.detail}) Me.PageSettings.Landscape = False Me.PageSettings.Margins.Bottom = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.PageSettings.Margins.Left = New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.PageSettings.Margins.Right = New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.PageSettings.Margins.Top = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.PageSettings.PaperKind = System.Drawing.Printing.PaperKind.A4 ReportParameter1.Name = "fechaFin" ReportParameter1.Text = "fechaFin" ReportParameter1.Type = Telerik.Reporting.ReportParameterType.DateTime ReportParameter1.Visible = True ReportParameter2.Name = "idProyecto" ReportParameter2.Text = "idProyecto" ReportParameter2.Type = Telerik.Reporting.ReportParameterType.[Integer] ReportParameter2.Visible = True ReportParameter3.Name = "tipo" ReportParameter3.Text = "tipo" ReportParameter3.Visible = True Me.ReportParameters.Add(ReportParameter1) Me.ReportParameters.Add(ReportParameter2) Me.ReportParameters.Add(ReportParameter3) Me.Style.BackgroundColor = System.Drawing.Color.White StyleRule1.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Title")}) StyleRule1.Style.Color = System.Drawing.Color.Black StyleRule1.Style.Font.Bold = True StyleRule1.Style.Font.Italic = False StyleRule1.Style.Font.Name = "Tahoma" StyleRule1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(20.0R, Telerik.Reporting.Drawing.UnitType.Point) StyleRule1.Style.Font.Strikeout = False StyleRule1.Style.Font.Underline = False StyleRule2.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Caption")}) StyleRule2.Style.Color = System.Drawing.Color.Black StyleRule2.Style.Font.Name = "Tahoma" StyleRule2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point) StyleRule2.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle StyleRule3.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Data")}) StyleRule3.Style.Font.Name = "Tahoma" StyleRule3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point) StyleRule3.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle StyleRule4.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("PageInfo")}) StyleRule4.Style.Font.Name = "Tahoma" StyleRule4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point) StyleRule4.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle Me.StyleSheet.AddRange(New Telerik.Reporting.Drawing.StyleRule() {StyleRule1, StyleRule2, StyleRule3, StyleRule4}) Me.Width = New Telerik.Reporting.Drawing.Unit(16.999900817871094R, Telerik.Reporting.Drawing.UnitType.Cm) Me.Name = "RepNota30" CType(Me, System.ComponentModel.ISupportInitialize).EndInit() End Sub Friend WithEvents SDSRepNota30 As Telerik.Reporting.SqlDataSource Friend WithEvents labelsGroupHeader As Telerik.Reporting.GroupHeaderSection Friend WithEvents labelsGroupFooter As Telerik.Reporting.GroupFooterSection Friend WithEvents labelsGroup As Telerik.Reporting.Group Friend WithEvents reportFooter As Telerik.Reporting.ReportFooterSection Friend WithEvents pageHeader As Telerik.Reporting.PageHeaderSection Friend WithEvents pageFooter As Telerik.Reporting.PageFooterSection Friend WithEvents reportHeader As Telerik.Reporting.ReportHeaderSection Friend WithEvents detail As Telerik.Reporting.DetailSection Friend WithEvents TextBox5 As Telerik.Reporting.TextBox Friend WithEvents montoCaptionTextBox As Telerik.Reporting.TextBox Friend WithEvents nombreCaptionTextBox As Telerik.Reporting.TextBox Friend WithEvents codigoCaptionTextBox As Telerik.Reporting.TextBox Friend WithEvents montoDataTextBox As Telerik.Reporting.TextBox Friend WithEvents nombreDataTextBox As Telerik.Reporting.TextBox Friend WithEvents codigoDataTextBox As Telerik.Reporting.TextBox Friend WithEvents montoSumFunctionTextBox As Telerik.Reporting.TextBox Friend WithEvents TextBox1 As Telerik.Reporting.TextBox End Class
crackper/SistFoncreagro
SistFoncreagro.Report/RepNota30.Designer.vb
Visual Basic
mit
19,594
Option Strict Off Option Explicit On Module CodeModule '-- C Style argv Public Structure UNZIPnames <VBFixedArray(99)> Dim uzFiles() As String 'UPGRADE_TODO: "Initialize" must be called to initialize instances of this structure. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="B4BFF9E0-8631-45CF-910E-62AB3970F27B"' Public Sub Initialize() ReDim uzFiles(99) End Sub End Structure '-- Callback Large "String" Public Structure UNZIPCBChar <VBFixedArray(32800)> Dim ch() As Byte 'UPGRADE_TODO: "Initialize" must be called to initialize instances of this structure. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="B4BFF9E0-8631-45CF-910E-62AB3970F27B"' Public Sub Initialize() ReDim ch(32800) End Sub End Structure '-- Callback Small "String" Public Structure UNZIPCBCh <VBFixedArray(256)> Dim ch() As Byte 'UPGRADE_TODO: "Initialize" must be called to initialize instances of this structure. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="B4BFF9E0-8631-45CF-910E-62AB3970F27B"' Public Sub Initialize() ReDim ch(256) End Sub End Structure '-- UNZIP32.DLL DCL Structure Public Structure DCLIST Dim ExtractOnlyNewer As Integer ' 1 = Extract Only Newer, Else 0 Dim SpaceToUnderScore As Integer ' 1 = Convert Space To Underscore, Else 0 Dim PromptToOverwrite As Integer ' 1 = Prompt To Overwrite Required, Else 0 Dim fQuiet As Integer ' 2 = No Messages, 1 = Less, 0 = All Dim ncflag As Integer ' 1 = Write To Stdout, Else 0 Dim ntflag As Integer ' 1 = Test Zip File, Else 0 Dim nvflag As Integer ' 0 = Extract, 1 = List Zip Contents Dim nUflag As Integer ' 1 = Extract Only Newer, Else 0 Dim nzflag As Integer ' 1 = Display Zip File Comment, Else 0 Dim ndflag As Integer ' 1 = Honor Directories, Else 0 Dim noflag As Integer ' 1 = Overwrite Files, Else 0 Dim naflag As Integer ' 1 = Convert CR To CRLF, Else 0 Dim nZIflag As Integer ' 1 = Zip Info Verbose, Else 0 Dim C_flag As Integer ' 1 = Case Insensitivity, 0 = Case Sensitivity Dim fPrivilege As Integer ' 1 = ACL, 2 = Privileges Dim Zip As String ' The Zip Filename To Extract Files Dim ExtractDir As String ' The Extraction Directory, NULL If Extracting To Current Dir End Structure '-- UNZIP32.DLL Userfunctions Structure Public Structure USERFUNCTION Dim UZDLLPrnt As Integer ' Pointer To Apps Print Function Dim UZDLLSND As Integer ' Pointer To Apps Sound Function Dim UZDLLREPLACE As Integer ' Pointer To Apps Replace Function Dim UZDLLPASSWORD As Integer ' Pointer To Apps Password Function Dim UZDLLMESSAGE As Integer ' Pointer To Apps Message Function Dim UZDLLSERVICE As Integer ' Pointer To Apps Service Function (Not Coded!) Dim TotalSizeComp As Integer ' Total Size Of Zip Archive Dim TotalSize As Integer ' Total Size Of All Files In Archive Dim CompFactor As Integer ' Compression Factor Dim NumMembers As Integer ' Total Number Of All Files In The Archive Dim cchComment As Short ' Flag If Archive Has A Comment! End Structure '-- UNZIP32.DLL Version Structure Public Structure UZPVER Dim structlen As Integer ' Length Of The Structure Being Passed Dim flag As Integer ' Bit 0: is_beta bit 1: uses_zlib 'UPGRADE_WARNING: Fixed-length string size must fit in the buffer. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="3C1E4426-0B80-443E-B943-0627CD55D48B"' <VBFixedString(10),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=10)> Public beta() As Char ' e.g., "g BETA" or "" 'UPGRADE_WARNING: Fixed-length string size must fit in the buffer. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="3C1E4426-0B80-443E-B943-0627CD55D48B"' 'UPGRADE_NOTE: date was upgraded to date_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"' <VBFixedString(20),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=20)> Public date_Renamed() As Char ' e.g., "4 Sep 95" (beta) or "4 September 1995" 'UPGRADE_WARNING: Fixed-length string size must fit in the buffer. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="3C1E4426-0B80-443E-B943-0627CD55D48B"' <VBFixedString(10),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=10)> Public zlib() As Char ' e.g., "1.0.5" or NULL <VBFixedArray(4)> Dim Unzip() As Byte ' Version Type Unzip <VBFixedArray(4)> Dim zipinfo() As Byte ' Version Type Zip Info Dim os2dll As Integer ' Version Type OS2 DLL <VBFixedArray(4)> Dim windll() As Byte ' Version Type Windows DLL 'UPGRADE_TODO: "Initialize" must be called to initialize instances of this structure. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="B4BFF9E0-8631-45CF-910E-62AB3970F27B"' Public Sub Initialize() 'UPGRADE_WARNING: Lower bound of array Unzip was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"' ReDim Unzip(4) 'UPGRADE_WARNING: Lower bound of array zipinfo was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"' ReDim zipinfo(4) 'UPGRADE_WARNING: Lower bound of array windll was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"' ReDim windll(4) End Sub End Structure '-- This Assumes UNZIP32.DLL Is In Your \Windows\System Directory! 'UPGRADE_WARNING: Structure USERFUNCTION may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' 'UPGRADE_WARNING: Structure DCLIST may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' 'UPGRADE_WARNING: Structure UNZIPnames may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' 'UPGRADE_WARNING: Structure UNZIPnames may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' Private Declare Function Wiz_SingleEntryUnzip Lib "unzip32.dll" (ByVal ifnc As Integer, ByRef ifnv As UNZIPnames, ByVal xfnc As Integer, ByRef xfnv As UNZIPnames, ByRef dcll As DCLIST, ByRef Userf As USERFUNCTION) As Integer 'UPGRADE_WARNING: Structure UZPVER may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' Private Declare Sub UzpVersion2 Lib "unzip32.dll" (ByRef uzpv As UZPVER) 'argv Public Structure ZIPnames <VBFixedArray(99)> Dim s() As String 'UPGRADE_TODO: "Initialize" must be called to initialize instances of this structure. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="B4BFF9E0-8631-45CF-910E-62AB3970F27B"' Public Sub Initialize() ReDim s(99) End Sub End Structure 'ZPOPT is used to set options in the zip32.dll Private Structure ZPOPT Dim fSuffix As Integer Dim fEncrypt As Integer Dim fSystem As Integer Dim fVolume As Integer Dim fExtra As Integer Dim fNoDirEntries As Integer Dim fExcludeDate As Integer Dim fIncludeDate As Integer Dim fVerbose As Integer Dim fQuiet As Integer Dim fCRLF_LF As Integer Dim fLF_CRLF As Integer Dim fJunkDir As Integer Dim fRecurse As Integer Dim fGrow As Integer Dim fForce As Integer Dim fMove As Integer Dim fDeleteEntries As Integer Dim fUpdate As Integer Dim fFreshen As Integer Dim fJunkSFX As Integer Dim fLatestTime As Integer Dim fComment As Integer Dim fOffsets As Integer Dim fPrivilege As Integer Dim fEncryption As Integer Dim fRepair As Integer Dim flevel As Byte 'UPGRADE_NOTE: date was upgraded to date_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"' Dim date_Renamed As String ' 8 bytes long Dim szRootDir As String ' up to 256 bytes long End Structure Private Structure ZIPUSERFUNCTIONS Dim DLLPrnt As Integer Dim DLLPASSWORD As Integer Dim DLLCOMMENT As Integer Dim DLLSERVICE As Integer End Structure 'Structure ZCL - not used by VB 'Private Type ZCL ' argc As Long 'number of files ' filename As String 'Name of the Zip file ' fileArray As ZIPnames 'The array of filenames 'End Type ' Call back "string" (sic) Public Structure CBChar <VBFixedArray(4096)> Dim ch() As Byte 'UPGRADE_TODO: "Initialize" must be called to initialize instances of this structure. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="B4BFF9E0-8631-45CF-910E-62AB3970F27B"' Public Sub Initialize() ReDim ch(4096) End Sub End Structure 'Local declares ' Dim MYZCL As ZCL 'This assumes zip32.dll is in your \windows\system directory! 'UPGRADE_WARNING: Structure ZIPUSERFUNCTIONS may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' Private Declare Function ZpInit Lib "zip32.dll" (ByRef Zipfun As ZIPUSERFUNCTIONS) As Integer ' Set Zip Callbacks 'UPGRADE_WARNING: Structure ZPOPT may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' Private Declare Function ZpSetOptions Lib "zip32.dll" (ByRef Opts As ZPOPT) As Integer ' Set Zip options Private Declare Function ZpGetOptions Lib "zip32.dll" () As ZPOPT ' used to check encryption flag only 'UPGRADE_WARNING: Structure ZIPnames may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' Private Declare Function ZpArchive Lib "zip32.dll" (ByVal argc As Integer, ByVal funame As String, ByRef argv As ZIPnames) As Integer ' Real zipping action Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Integer) Private uZipNumber As Short Private uZipMessage As String Private uZipInfo As String Private uVBSkip As Short Public msOutput As String ' Puts a function pointer in a structure Function FnPtr(ByVal lp As Integer) As Integer FnPtr = lp End Function ' Callback for zip32.dll Function DLLPrnt(ByRef fname As CBChar, ByVal x As Integer) As Integer Dim s0 As String Dim xx As Integer Dim sVbZipInf As String ' always put this in callback routines! On Error Resume Next s0 = "" For xx = 0 To x If fname.ch(xx) = 0 Then xx = 99999 Else s0 = s0 & Chr(fname.ch(xx)) Next xx Debug.Print(sVbZipInf & s0) msOutput = msOutput & s0 sVbZipInf = "" System.Windows.Forms.Application.DoEvents() DLLPrnt = 0 End Function ' Callback for Zip32.dll ? Function DllServ(ByRef fname As CBChar, ByVal x As Integer) As Short Dim s0 As String Dim xx As Integer On Error Resume Next s0 = "" For xx = 0 To x - 1 If fname.ch(xx) = 0 Then Exit For s0 = s0 & Chr(fname.ch(xx)) Next DllServ = 0 End Function ' Callback for zip32.dll Function DllPass(ByRef s1 As Byte, ByRef x As Integer, ByRef s2 As Byte, ByRef s3 As Byte) As Short ' always put this in callback routines! On Error Resume Next ' not supported - always return 1 DllPass = 1 End Function ' Callback for zip32.dll Function DllComm(ByRef s1 As CBChar) As CBChar ' always put this in callback routines! On Error Resume Next ' not supported always return \0 s1.ch(0) = CByte(vbNullString) 'UPGRADE_WARNING: Couldn't resolve default property of object DllComm. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' DllComm = s1 End Function 'Main Subroutine Public Function VBZip(ByRef argc As Short, ByRef zipname As String, ByRef mynames As ZIPnames, ByRef junk As Short, ByRef recurse As Short, ByRef updat As Short, ByRef freshen As Short, ByRef basename As String, Optional ByRef Encrypt As Short = 0, Optional ByRef IncludeSystem As Short = 0, Optional ByRef IgnoreDirectoryEntries As Short = 0, Optional ByRef Verbose As Short = 0, Optional ByRef Quiet As Short = 0, Optional ByRef CRLFtoLF As Short = 0, Optional ByRef LFtoCRLF As Short = 0, Optional ByRef Grow As Short = 0, Optional ByRef Force As Short = 0, Optional ByRef iMove As Short = 0, Optional ByRef DeleteEntries As Short = 0) As Integer Dim hmem As Integer Dim xx As Short Dim retcode As Integer Dim MYUSER As ZIPUSERFUNCTIONS Dim MYOPT As ZPOPT On Error Resume Next ' nothing will go wrong :-) msOutput = "" ' Set address of callback functions 'UPGRADE_WARNING: Add a delegate for AddressOf DLLPrnt Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"' 'MYUSER.DLLPrnt = FnPtr(AddressOf DLLPrnt) 'UPGRADE_WARNING: Add a delegate for AddressOf DllPass Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"' 'MYUSER.DLLPASSWORD = FnPtr(AddressOf DllPass) 'UPGRADE_WARNING: Add a delegate for AddressOf DllComm Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"' 'MYUSER.DLLCOMMENT = FnPtr(AddressOf DllComm) MYUSER.DLLSERVICE = 0 ' not coded yet :-) ' retcode = ZpInit(MYUSER) ' Set zip options MYOPT.fSuffix = 0 ' include suffixes (not yet implemented) MYOPT.fEncrypt = Encrypt ' 1 if encryption wanted MYOPT.fSystem = IncludeSystem ' 1 to include system/hidden files MYOPT.fVolume = 0 ' 1 if storing volume label MYOPT.fExtra = 0 ' 1 if including extra attributes MYOPT.fNoDirEntries = IgnoreDirectoryEntries ' 1 if ignoring directory entries MYOPT.fExcludeDate = 0 ' 1 if excluding files earlier than a specified date MYOPT.fIncludeDate = 0 ' 1 if including files earlier than a specified date MYOPT.fVerbose = Verbose ' 1 if full messages wanted MYOPT.fQuiet = Quiet ' 1 if minimum messages wanted MYOPT.fCRLF_LF = CRLFtoLF ' 1 if translate CR/LF to LF MYOPT.fLF_CRLF = LFtoCRLF ' 1 if translate LF to CR/LF MYOPT.fJunkDir = junk ' 1 if junking directory names MYOPT.fRecurse = recurse ' 1 if recursing into subdirectories MYOPT.fGrow = Grow ' 1 if allow appending to zip file MYOPT.fForce = Force ' 1 if making entries using DOS names MYOPT.fMove = iMove ' 1 if deleting files added or updated MYOPT.fDeleteEntries = DeleteEntries ' 1 if files passed have to be deleted MYOPT.fUpdate = updat ' 1 if updating zip file--overwrite only if newer MYOPT.fFreshen = freshen ' 1 if freshening zip file--overwrite only MYOPT.fJunkSFX = 0 ' 1 if junking sfx prefix MYOPT.fLatestTime = 0 ' 1 if setting zip file time to time of latest file in archive MYOPT.fComment = 0 ' 1 if putting comment in zip file MYOPT.fOffsets = 0 ' 1 if updating archive offsets for sfx Files MYOPT.fPrivilege = 0 ' 1 if not saving privelages MYOPT.fEncryption = 0 'Read only property! MYOPT.fRepair = 0 ' 1=> fix archive, 2=> try harder to fix MYOPT.flevel = 0 ' compression level - should be 0!!! MYOPT.date_Renamed = vbNullString ' "12/31/79"? US Date? MYOPT.szRootDir = UCase(basename) retcode = ZpInit(MYUSER) ' Set options retcode = ZpSetOptions(MYOPT) ' ZCL not needed in VB ' MYZCL.argc = 2 ' MYZCL.filename = "c:\wiz\new.zip" ' MYZCL.fileArray = MYNAMES ' Go for it! retcode = ZpArchive(argc, zipname, mynames) VBZip = retcode End Function '-- Callback For UNZIP32.DLL - Receive Message Function Public Sub UZReceiveDLLMessage(ByVal ucsize As Integer, ByVal csiz As Integer, ByVal cfactor As Short, ByVal mo As Short, ByVal dy As Short, ByVal yr As Short, ByVal hh As Short, ByVal mm As Short, ByVal c As Byte, ByRef fname As UNZIPCBCh, ByRef meth As UNZIPCBCh, ByVal crc As Integer, ByVal fCrypt As Byte) Dim s0 As String Dim xx As Integer Dim strout As String '-- Always Put This In Callback Routines! On Error Resume Next '------------------------------------------------ '-- This Is Where The Received Messages Are '-- Printed Out And Displayed. '-- You Can Modify Below! '------------------------------------------------ strout = Space(80) '-- For Zip Message Printing If uZipNumber = 0 Then Mid(strout, 1, 50) = "Filename:" Mid(strout, 53, 4) = "Size" Mid(strout, 62, 4) = "Date" Mid(strout, 71, 4) = "Time" uZipMessage = strout & vbNewLine strout = Space(80) End If s0 = "" '-- Do Not Change This For Next!!! For xx = 0 To 255 If fname.ch(xx) = 0 Then Exit For s0 = s0 & Chr(fname.ch(xx)) Next '-- Assign Zip Information For Printing Mid(strout, 1, 50) = Mid(s0, 1, 50) Mid(strout, 51, 7) = Right(" " & Str(ucsize), 7) Mid(strout, 60, 3) = Right("0" & Trim(Str(mo)), 2) & "/" Mid(strout, 63, 3) = Right("0" & Trim(Str(dy)), 2) & "/" Mid(strout, 66, 2) = Right("0" & Trim(Str(yr)), 2) Mid(strout, 70, 3) = Right(Str(hh), 2) & ":" Mid(strout, 73, 2) = Right("0" & Trim(Str(mm)), 2) ' Mid(strout, 75, 2) = Right(" " & Str(cfactor), 2) ' Mid(strout, 78, 8) = Right(" " & Str(csiz), 8) ' s0 = "" ' For xx = 0 To 255 ' If meth.ch(xx) = 0 Then exit for ' s0 = s0 & Chr(meth.ch(xx)) ' Next xx '-- Do Not Modify Below!!! uZipMessage = uZipMessage & strout & vbNewLine uZipNumber = uZipNumber + 1 End Sub '-- Callback For UNZIP32.DLL - Print Message Function Public Function UZDLLPrnt(ByRef fname As UNZIPCBChar, ByVal x As Integer) As Integer Dim s0 As String Dim xx As Integer '-- Always Put This In Callback Routines! On Error Resume Next s0 = "" '-- Gets The UNZIP32.DLL Message For Displaying. For xx = 0 To x - 1 If fname.ch(xx) = 0 Then Exit For s0 = s0 & Chr(fname.ch(xx)) Next '-- Assign Zip Information If Mid(s0, 1, 1) = vbLf Then s0 = vbNewLine ' Damn UNIX :-) uZipInfo = uZipInfo & s0 msOutput = uZipInfo UZDLLPrnt = 0 End Function '-- Callback For UNZIP32.DLL - DLL Service Function Public Function UZDLLServ(ByRef mname As UNZIPCBChar, ByVal x As Integer) As Integer Dim s0 As String Dim xx As Integer '-- Always Put This In Callback Routines! On Error Resume Next s0 = "" '-- Get Zip32.DLL Message For processing For xx = 0 To x - 1 If mname.ch(xx) = 0 Then Exit For s0 = s0 & Chr(mname.ch(xx)) Next ' At this point, s0 contains the message passed from the DLL ' It is up to the developer to code something useful here :) UZDLLServ = 0 ' Setting this to 1 will abort the zip! End Function '-- Callback For UNZIP32.DLL - Password Function Public Function UZDLLPass(ByRef p As UNZIPCBCh, ByVal n As Integer, ByRef m As UNZIPCBCh, ByRef Name As UNZIPCBCh) As Short Dim prompt As String Dim xx As Short Dim szpassword As String '-- Always Put This In Callback Routines! On Error Resume Next UZDLLPass = 1 If uVBSkip = 1 Then Exit Function '-- Get The Zip File Password szpassword = InputBox("Please Enter The Password!") '-- No Password So Exit The Function If szpassword = "" Then uVBSkip = 1 Exit Function End If '-- Zip File Password So Process It For xx = 0 To 255 If m.ch(xx) = 0 Then Exit For Else prompt = prompt & Chr(m.ch(xx)) End If Next For xx = 0 To n - 1 p.ch(xx) = 0 Next For xx = 0 To Len(szpassword) - 1 p.ch(xx) = Asc(Mid(szpassword, xx + 1, 1)) Next p.ch(xx) = CByte(AscW(0)) ' Put Null Terminator For C UZDLLPass = 0 End Function '-- Callback For UNZIP32.DLL - Report Function To Overwrite Files. '-- This Function Will Display A MsgBox Asking The User '-- If They Would Like To Overwrite The Files. Public Function UZDLLRep(ByRef fname As UNZIPCBChar) As Integer Dim s0 As String Dim xx As Integer '-- Always Put This In Callback Routines! On Error Resume Next UZDLLRep = 100 ' 100 = Do Not Overwrite - Keep Asking User s0 = "" For xx = 0 To 255 If fname.ch(xx) = 0 Then xx = 99999 Else s0 = s0 & Chr(fname.ch(xx)) Next '-- This Is The MsgBox Code xx = MsgBox("Overwrite " & s0 & "?", CDbl(MsgBoxStyle.Exclamation & MsgBoxStyle.YesNoCancel), "VBUnZip32 - File Already Exists!") If xx = MsgBoxResult.No Then Exit Function If xx = MsgBoxResult.Cancel Then UZDLLRep = 104 ' 104 = Overwrite None Exit Function End If UZDLLRep = 102 ' 102 = Overwrite 103 = Overwrite All End Function '-- ASCIIZ To String Function Public Function szTrim(ByRef szString As String) As String Dim pos As Short Dim ln As Short pos = InStr(szString, Chr(0)) ln = Len(szString) Select Case pos Case Is > 1 szTrim = Trim(Left(szString, pos - 1)) Case 1 szTrim = "" Case Else szTrim = Trim(szString) End Select End Function Public Function VBUnzip(ByRef sZipFileName As Object, ByRef sUnzipDirectory As String, ByRef iExtractNewer As Short, ByRef iSpaceUnderScore As Short, ByRef iPromptOverwrite As Short, ByRef iQuiet As Short, ByRef iWriteStdOut As Short, ByRef iTestZip As Short, ByRef iExtractList As Short, ByRef iExtractOnlyNewer As Short, ByRef iDisplayComment As Short, ByRef iHonorDirectories As Short, ByRef iOverwriteFiles As Short, ByRef iConvertCR_CRLF As Short, ByRef iVerbose As Short, ByRef iCaseSensitivty As Short, ByRef iPrivilege As Short) As Integer On Error GoTo vbErrorHandler Dim lRet As Integer Dim UZDCL As DCLIST Dim UZUSER As USERFUNCTION 'UPGRADE_WARNING: Arrays in structure UZVER may need to be initialized before they can be used. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="814DF224-76BD-4BB4-BFFB-EA359CB9FC48"' Dim UZVER As UZPVER 'UPGRADE_WARNING: Arrays in structure uExcludeNames may need to be initialized before they can be used. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="814DF224-76BD-4BB4-BFFB-EA359CB9FC48"' Dim uExcludeNames As UNZIPnames 'UPGRADE_WARNING: Arrays in structure uZipNames may need to be initialized before they can be used. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="814DF224-76BD-4BB4-BFFB-EA359CB9FC48"' Dim uZipNames As UNZIPnames msOutput = "" uExcludeNames.uzFiles(0) = vbNullString uZipNames.uzFiles(0) = vbNullString uZipNumber = 0 uZipMessage = vbNullString uZipInfo = vbNullString uVBSkip = 0 With UZDCL .ExtractOnlyNewer = iExtractOnlyNewer .SpaceToUnderScore = iSpaceUnderScore .PromptToOverwrite = iPromptOverwrite .fQuiet = iQuiet .ncflag = iWriteStdOut .ntflag = iTestZip .nvflag = iExtractList .nUflag = iExtractNewer .nzflag = iDisplayComment .ndflag = iHonorDirectories .noflag = iOverwriteFiles .naflag = iConvertCR_CRLF .nZIflag = iVerbose .C_flag = iCaseSensitivty .fPrivilege = iPrivilege 'UPGRADE_WARNING: Couldn't resolve default property of object sZipFileName. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' .Zip = sZipFileName .ExtractDir = sUnzipDirectory End With With UZUSER 'UPGRADE_WARNING: Add a delegate for AddressOf UZDLLPrnt Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"' '.UZDLLPrnt = FnPtr(AddressOf UZDLLPrnt) .UZDLLSND = 0 'UPGRADE_WARNING: Add a delegate for AddressOf UZDLLRep Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"' '.UZDLLREPLACE = FnPtr(AddressOf UZDLLRep) 'UPGRADE_WARNING: Add a delegate for AddressOf UZDLLPass Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"' '.UZDLLPASSWORD = FnPtr(AddressOf UZDLLPass) 'UPGRADE_WARNING: Add a delegate for AddressOf UZReceiveDLLMessage Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"' '.UZDLLMESSAGE = FnPtr(AddressOf UZReceiveDLLMessage) 'UPGRADE_WARNING: Add a delegate for AddressOf UZDLLServ Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"' '.UZDLLSERVICE = FnPtr(AddressOf UZDLLServ) End With With UZVER .structlen = Len(UZVER) .beta = Space(9) & vbNullChar .date_Renamed = Space(19) & vbNullChar .zlib = Space(9) & vbNullChar End With UzpVersion2(UZVER) lRet = Wiz_SingleEntryUnzip(0, uZipNames, 0, uExcludeNames, UZDCL, UZUSER) VBUnzip = lRet Exit Function vbErrorHandler: Err.Raise(Err.Number, "CodeModule::VBUnzip", Err.Description) End Function End Module
nodoid/PointOfSale
VB/4PosBackOffice.NET/CodeModule.vb
Visual Basic
mit
28,220
Imports System.Data.SqlClient Public Class RegistrationPage Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Public Sub Validate_Email_Existance(ByVal source As Object, ByVal args As ServerValidateEventArgs) Handles email_custom_validation.ServerValidate Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString) Dim sql_command As New SqlCommand() sql_command.Connection = conn conn.Open() Response.Write("email value: " + args.Value.ToString()) sql_command.CommandText = "select count(*) from students where email ='" + args.Value + "'" sql_command.CommandType = CommandType.Text Dim email_count As Integer = sql_command.ExecuteScalar() Response.Write("email count: " + email_count.ToString()) If email_count = 1 Then args.IsValid = False Response.Write("email used") Else args.IsValid = True Response.Write("email not used") End If End Sub Private Function Register_User(first_name As String, last_name As String, password As String, email As String, gender As String, date_of_birth As String, specialisation As String) As Integer If (Not Page.IsValid()) Then Return 0 End If Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString) Dim sql_command As New SqlCommand() sql_command.Connection = conn sql_command.CommandText = "insert into students values('" + first_name + "','" + last_name + "','" + password + "','" + email + "','" + gender + "','" + date_of_birth + "','" + specialisation + "')" sql_command.CommandType = CommandType.Text email_custom_validation.Validate() conn.Open() Dim r As Integer = sql_command.ExecuteNonQuery() conn.Close() Response.Write("student added") Return 0 End Function Protected Sub register_button_Click(sender As Object, e As EventArgs) Handles register_button.Click Dim dob As String = dob_calendar.SelectedDate.ToString("yyyy-MM-dd") Register_User(first_name_box.Text, last_name_box.Text, password_box.Text, email_box.Text, gender_list.SelectedValue, dob, specialisation_list.Text) End Sub End Class
sabri916/ServerSideAssignment
ServerSideAssignment/RegistrationPage.aspx.vb
Visual Basic
mit
2,455