code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
Imports System.Runtime.InteropServices Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim objSEApplication As SolidEdgeFramework.Application = Nothing Dim objDoc As SolidEdgePart.SheetMetalDocument = Nothing Try ' Create/get the application with specific settings objSEApplication = Marshal.GetActiveObject("SolidEdge.Application") 'Get the active document. objDoc = objSEApplication.ActiveDocument() If objDoc.OrderedBodyInSyncVisible = True Then MsgBox("Ordered body status in sync is visible") 'Change the status to hidden if visible objDoc.OrderedBodyInSyncVisible = False Else MsgBox("Ordered body status in sync is hidden") 'Change the status to visible if hidden objDoc.OrderedBodyInSyncVisible = True End If 'Refresh view objSEApplication.StartCommand(SolidEdgeFramework.SolidEdgeCommandConstants.seRefreshViewCommand) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgePart.SheetMetalDocument.OrderedBodyInSyncVisible.vb
Visual Basic
mit
1,223
#Region "Microsoft.VisualBasic::02a2360c6f91b235d891be3b899f3656, src\visualize\MsImaging\PixelScan\InMemoryPixel.vb" ' Author: ' ' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.) ' ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD. ' ' ' MIT License ' ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. ' /********************************************************************************/ ' Summaries: ' Class InMemoryPixel ' ' Properties: X, Y ' ' Constructor: (+1 Overloads) Sub New ' ' Function: GetMs, GetMsPipe, HasAnyMzIon ' ' Sub: release ' ' ' /********************************************************************************/ #End Region Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1 Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra Namespace Pixel Public Class InMemoryPixel : Inherits PixelScan Public Overrides ReadOnly Property X As Integer Public Overrides ReadOnly Property Y As Integer Dim data As ms2() Sub New(x As Integer, y As Integer, data As ms2()) Me.X = x Me.Y = y Me.data = data End Sub Protected Friend Overrides Sub release() Erase data End Sub Public Overrides Function HasAnyMzIon(mz() As Double, tolerance As Tolerance) As Boolean Return data.Any(Function(x) mz.Any(Function(mzi) tolerance(mzi, x.mz))) End Function Public Overrides Function GetMs() As ms2() Return data End Function Protected Friend Overrides Function GetMsPipe() As IEnumerable(Of ms2) Return data End Function End Class End Namespace
xieguigang/MassSpectrum-toolkits
src/visualize/MsImaging/PixelScan/InMemoryPixel.vb
Visual Basic
mit
2,926
Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim documents As SolidEdgeFramework.Documents = Nothing Dim draftDocument As SolidEdgeDraft.DraftDocument = Nothing Dim sheet As SolidEdgeDraft.Sheet = Nothing Dim curves2d As SolidEdgeFrameworkSupport.Curves2d = Nothing Dim curve2d As SolidEdgeFrameworkSupport.Curve2d = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) documents = application.Documents draftDocument = CType(documents.Add("SolidEdge.DraftDocument"), SolidEdgeDraft.DraftDocument) sheet = draftDocument.ActiveSheet curves2d = sheet.Curves2d Dim Points = CType(New Double(), System.Array) { 0.15, 0.15, 0.25, 0.15, 0.25, 0.25, 0.15, 0.25 } curve2d = curves2d.AddByPoints(Points.Length \ 2, Points) curve2d.Copy() Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeFrameworkSupport.Curve2d.Copy.vb
Visual Basic
mit
1,661
' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ' ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO ' THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A ' PARTICULAR PURPOSE. ' ' Copyright (c) Microsoft Corporation. All rights reserved Imports System Imports System.Collections.ObjectModel Imports System.Runtime.InteropServices Imports System.Text #If Not WINRT_NOT_PRESENT Then Imports Windows.Data.Xml.Dom #End If Friend NotInheritable Class NotificationContentText Implements INotificationContentText Friend Sub New() End Sub Public Property Text() As String Implements INotificationContentText.Text Get Return m_Text End Get Set(ByVal value As String) m_Text = value End Set End Property Public Property Lang() As String Implements INotificationContentText.Lang Get Return m_Lang End Get Set(ByVal value As String) m_Lang = value End Set End Property Private m_Text As String Private m_Lang As String End Class Friend NotInheritable Class NotificationContentImage Implements INotificationContentImage Friend Sub New() End Sub Public Property Src() As String Implements INotificationContentImage.Src Get Return m_Src End Get Set(ByVal value As String) m_Src = value End Set End Property Public Property Alt() As String Implements INotificationContentImage.Alt Get Return m_Alt End Get Set(ByVal value As String) m_Alt = value End Set End Property Public Property AddImageQuery() As Boolean Implements INotificationContentImage.AddImageQuery Get If m_AddImageQueryNullable Is Nothing OrElse m_AddImageQueryNullable.Value = False Then Return False Else Return True End If End Get Set(ByVal value As Boolean) m_AddImageQueryNullable = value End Set End Property Public Property AddImageQueryNullable() As Boolean? Get Return m_AddImageQueryNullable End Get Set(ByVal value As Boolean?) m_AddImageQueryNullable = value End Set End Property Private m_Src As String Private m_Alt As String Private m_AddImageQueryNullable? As Boolean End Class Friend NotInheritable Class Util Private Sub New() End Sub Public Const NOTIFICATION_CONTENT_VERSION As Integer = 1 Public Shared Function HttpEncode(ByVal value As String) As String Return value.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("""", "&quot;").Replace("'", "&apos;") End Function End Class ''' <summary> ''' Base class for the notification content creation helper classes. ''' </summary> #If Not WINRT_NOT_PRESENT Then Friend MustInherit Class NotificationBase #Else Friend MustInherit Partial Class NotificationBase #End If Protected Sub New(ByVal templateName As String, ByVal fallbackName As String, ByVal imageCount As Integer, ByVal textCount As Integer) m_TemplateName = templateName m_FallbackName = fallbackName m_Images = New NotificationContentImage(imageCount - 1) {} For i As Integer = 0 To m_Images.Length - 1 m_Images(i) = New NotificationContentImage() Next i m_TextFields = New INotificationContentText(textCount - 1) {} For i As Integer = 0 To m_TextFields.Length - 1 m_TextFields(i) = New NotificationContentText() Next i End Sub Public Property StrictValidation() As Boolean Get Return m_StrictValidation End Get Set(ByVal value As Boolean) m_StrictValidation = value End Set End Property Public MustOverride Function GetContent() As String Public Overrides Function ToString() As String Return GetContent() End Function #If Not WINRT_NOT_PRESENT Then Public Overridable Function GetXml() As XmlDocument Dim xml As New XmlDocument() xml.LoadXml(GetContent()) Return xml End Function #End If ''' <summary> ''' Retrieves the list of images that can be manipulated on the notification content. ''' </summary> Public ReadOnly Property Images() As INotificationContentImage() Get Return m_Images End Get End Property ''' <summary> ''' Retrieves the list of text fields that can be manipulated on the notification content. ''' </summary> Public ReadOnly Property TextFields() As INotificationContentText() Get Return m_TextFields End Get End Property ''' <summary> ''' The base Uri path that should be used for all image references in the notification. ''' </summary> Public Property BaseUri() As String Get Return m_BaseUri End Get Set(ByVal value As String) If Me.StrictValidation AndAlso (Not String.IsNullOrEmpty(value)) Then Dim uri As Uri Try uri = New Uri(value) Catch e As Exception Throw New ArgumentException("Invalid URI. Use a valid URI or turn off StrictValidation", e) End Try If Not (uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) OrElse uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) OrElse uri.Scheme.Equals("ms-appx", StringComparison.OrdinalIgnoreCase) OrElse (uri.Scheme.Equals("ms-appdata", StringComparison.OrdinalIgnoreCase) AndAlso (String.IsNullOrEmpty(uri.Authority)) AndAlso (uri.AbsolutePath.StartsWith("/local/") OrElse uri.AbsolutePath.StartsWith("local/")))) Then ' both ms-appdata:local/ and ms-appdata:/local/ are valid - check to make sure the Uri isn't ms-appdata://foo/local Throw New ArgumentException("The BaseUri must begin with http://, https://, ms-appx:///, or ms-appdata:///local/.", "value") End If End If m_BaseUri = value End Set End Property Public Property Lang() As String Get Return m_Lang End Get Set(ByVal value As String) m_Lang = value End Set End Property Public Property AddImageQuery() As Boolean Get If m_AddImageQueryNullable Is Nothing OrElse m_AddImageQueryNullable.Value = False Then Return False Else Return True End If End Get Set(ByVal value As Boolean) m_AddImageQueryNullable = value End Set End Property Public Property AddImageQueryNullable() As Boolean? Get Return m_AddImageQueryNullable End Get Set(ByVal value As Boolean?) m_AddImageQueryNullable = value End Set End Property Protected Function SerializeProperties(ByVal globalLang As String, ByVal globalBaseUri As String, ByVal globalAddImageQuery As Boolean) As String globalLang = If(globalLang IsNot Nothing, globalLang, String.Empty) globalBaseUri = If(String.IsNullOrWhiteSpace(globalBaseUri), Nothing, globalBaseUri) Dim builder As New StringBuilder(String.Empty) For i As Integer = 0 To m_Images.Length - 1 If Not String.IsNullOrEmpty(m_Images(i).Src) Then Dim escapedSrc As String = Util.HttpEncode(m_Images(i).Src) If Not String.IsNullOrWhiteSpace(m_Images(i).Alt) Then Dim escapedAlt As String = Util.HttpEncode(m_Images(i).Alt) If m_Images(i).AddImageQueryNullable Is Nothing OrElse m_Images(i).AddImageQueryNullable = globalAddImageQuery Then builder.AppendFormat("<image id='{0}' src='{1}' alt='{2}'/>", i + 1, escapedSrc, escapedAlt) Else builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}' alt='{3}'/>", m_Images(i).AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc, escapedAlt) End If Else If m_Images(i).AddImageQueryNullable Is Nothing OrElse m_Images(i).AddImageQueryNullable = globalAddImageQuery Then builder.AppendFormat("<image id='{0}' src='{1}'/>", i + 1, escapedSrc) Else builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}'/>", m_Images(i).AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc) End If End If End If Next i For i As Integer = 0 To m_TextFields.Length - 1 If Not String.IsNullOrWhiteSpace(m_TextFields(i).Text) Then Dim escapedValue As String = Util.HttpEncode(m_TextFields(i).Text) If (Not String.IsNullOrWhiteSpace(m_TextFields(i).Lang)) AndAlso (Not m_TextFields(i).Lang.Equals(globalLang)) Then Dim escapedLang As String = Util.HttpEncode(m_TextFields(i).Lang) builder.AppendFormat("<text id='{0}' lang='{1}'>{2}</text>", i + 1, escapedLang, escapedValue) Else builder.AppendFormat("<text id='{0}'>{1}</text>", i + 1, escapedValue) End If End If Next i Return builder.ToString() End Function Public ReadOnly Property TemplateName() As String Get Return m_TemplateName End Get End Property Public ReadOnly Property FallbackName() As String Get Return m_FallbackName End Get End Property Private m_StrictValidation As Boolean = True Private m_Images() As NotificationContentImage Private m_TextFields() As INotificationContentText Private m_Lang As String Private m_BaseUri As String Private m_TemplateName As String Private m_FallbackName As String Private m_AddImageQueryNullable? As Boolean End Class ''' <summary> ''' Exception returned when invalid notification content is provided. ''' </summary> Friend NotInheritable Class NotificationContentValidationException Inherits COMException Public Sub New(ByVal message As String) MyBase.New(message, CInt(&H80070057)) End Sub End Class
zparnold/vs
VB/NotificationsExtensions/Common.vb
Visual Basic
mit
10,523
Public Class TipoContrato Public Property IdTipoContrato As System.Nullable(Of Int32) Public Property Descripcion As String Public Property ModeloContrato As String Public Property CodSunat As String Public Property CategoriaRrhh As CategoriaRrhh End Class
crackper/SistFoncreagro
SistFoncreagro.BussinessEntities/TipoContrato.vb
Visual Basic
mit
281
Module SelFunc ' #------------------------------------------------------------------------------- '# Name: selFunc '# Purpose: Contains a selection of simple functions '# '# Author: Petter '# '# Created: 14.05.2012 '# Copyright: (c) Petter 2012 '# Licence: <your licence> '#------------------------------------------------------------------------------- 'import numpy as np 'import re 'from datetime import datetime '#from pylab import * 'figureNumber = 1 'paraMeterArray = {} 'Returns the argument in degrees Function deg(ByVal a As Double) deg = a * 180 / Math.PI End Function 'Returns the argument in radians Function rad(ByVal a As Double) As Double rad = a / 180 * Math.PI End Function 'Returns the argument in rpm Function rpm(ByVal a As Double) As Double rpm = a * 30 / Math.PI End Function Function radPerS(a): """ Returns the argument in rad/s """ Return float(a) * np.pi / 30 Function temperature(y,T0): Return T0 - 0.0065 * y Function pressure(p0,T0,y): return p0*(1-0.0065*y/T0)**(g()/(287.058*0.0065)) Function density(p0,T0,y): Return pressure(p0, T0, y) / (287.058 * temperature(y, T0)) Function g(): Return 9.80665 Function p0ISA(): Return 101325 Function T0ISA(): Return 288.15 Function pSat(T): return (6.1078*10**(7.5*(T-273.15)/((T-273.15)+237.3)))*100 Function pVapour(T0,y,humidity): Return humidity * pSat(temperature(y, T0)) Function pDry(humidity,p0,T0,y): Return pressure(p0, T0, y) - pVapour(T0, y, humidity) Function densityWithHumidity(humidity,p0,T0,y): Return (pressure(p0, T0, y) / (287.058 * temperature(y, T0))) * (1 + humidity) / (1 + humidity * 461.495 / 287.058) Function dynamicViscosity(T): return 1.51204129*T**3/2/(T+120) Function kinematicViscocity(my,rho): Return my / rho Function reynoldsNumber(nu,velocity,c): Return c * velocity / nu Function setFigureNumber(): global figureNumber figureNumber = figureNumber + 1 Function getFigureNumber(): Return figureNumber Function getDateString(): collection = datetime.now() myString = collection.isoformat() #collection.year + collection.month +collection.day myString = re.sub("\:", "-", myString) myString = re.sub("\.", "MS", myString) Return myString Function writeDict(_dictonary,_fileName): f = open(_fileName,'w') temp = str(_dictonary) temp = re.sub(",", "\n", temp) f.write(str(temp)) f.close() Function readDict(_dictonary,_fileName): f = open(_fileName,'r') my_dict = eval1(f.read()) f.close() Function eval1(x): Try : Return eval(x) except: Return x A = { eval1(y[0]) : eval1(y[1]) for y in [x.split() for x in open(filename).readlines()] } Function vThermic(height,heightThermicCeil,vThermicCeil): """ Returns the thermic windspeed """ Return vThermicCeil / heightThermicCeil * height Function lengthToPlaneFromPulley(x,y): """ Returns the actual length of the line """ return (x**2+y**2)**0.5 End Module
mk-products/sailplane-launch
SailPlaneLaunch/SelFunc2.vb
Visual Basic
apache-2.0
3,402
Namespace JetBrains.ReSharper.Koans.Refactoring ' Move Refactoring ' ' Move a type to another file, folder Or namespace ' ' Ctrl+R, O (VS) ' F6 (IntelliJ) ' 1. Move to another file ' Place text caret on type definition ' Invoke Move refactoring ' Select Move to another file ' ReSharper suggests file name ' Accepting moves file, existing code still works Public Class MoveToAnotherFile Public Sub Method() End Sub End Class ' 2. Move to another folder in the project ' Place text caret on type definition ' Invoke Move refactoring ' Select Move to another folder ' ReSharper suggests classes to move And folder location ' Start typing New location - ReSharper provides suggestions of existing folders And projects ' Add "\MoveTarget" to end of current location ' ReSharper shows a validation error as the folder does Not exist ' Click "Create this folder" ' Accept move, check type Is moved to New location Public Class MoveToAnotherFolderInProject Public Sub Method() End Sub End Class ' 3. Move to another folder in another project ' Place text caret on type definition ' Invoke Move refactoring ' Select Move to another folder ' ReSharper suggests classes to move And folder location ' Start typing New location - ReSharper provides suggestions of existing folders And projects ' Add "-MoveTarget" to end of current location ' (Target folder should be: "04 Refactoring\Refactoring-MoveTarget") ' Accept move, check type Is moved to the New project ' ReSharper detects there Is no reference between this project And Refactoring-MoveTarget ' Can Cancel the refactoring And add the reference ' Or continue, And fix up the reference by Alt+Enter on the broken usage below Public Class MoveToAnotherFolderInOtherProject Public Sub Method() End Sub End Class ' 4. Move to another namespace ' Place text caret on type definition ' Invoke Move Refactoring ' Select Move to another namespace ' ReSharper suggests current namespace - add ".MoveTarget" to end of namespace ' (namespace should be JetBrains.ReSharper.Koans.Refactoring.Target) ' ReSharper moves the type to that namespace, but keeps type in current file ' Type should be at bottom of file Public Class MoveToAnotherNamespace Public Sub Method() End Sub End Class Public Class UsesOtherClasses Public Sub CallsMethods() ' 5. Ensure all types are still referenced correctly Call New MoveToAnotherFile().Method() Call New MoveToAnotherFolderInProject().Method() Call New MoveToAnotherFolderInOtherProject().Method() Call New MoveToAnotherNamespace().Method() End Sub End Class End Namespace Namespace JetBrains.ReSharper.Koans.Refactoring.MoveTarget End Namespace
yskatsumata/resharper-workshop
VisualBasic/04-Refactoring/Refactoring/04-Move.vb
Visual Basic
apache-2.0
3,075
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.VisualBasic Imports Microsoft.VisualStudio.Shell.Interop Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Globalization Imports System.Windows.Forms Imports System.ComponentModel Imports VSLangProj80 Imports VSLangProj90 Namespace Microsoft.VisualStudio.Editors.Common ''' <summary> ''' Support for retrieving and working with the available target framework assemblies ''' for a project. ''' </summary> ''' <remarks></remarks> Friend Class TargetFrameworkAssemblies ''' <summary> ''' Represents a supported target framework assembly. Can be placed directly into ''' a listbox or combobox (it will show the Description text in the listbox) ''' </summary> ''' <remarks></remarks> Friend Class TargetFramework Private m_version As UInteger Private m_description As String Public Sub New(ByVal version As UInteger, ByVal description As String) If description Is Nothing Then Throw New ArgumentNullException("description") End If m_version = version m_description = description End Sub Public ReadOnly Property Version() As UInteger Get Return m_version End Get End Property Public ReadOnly Property Description() As String Get Return m_description End Get End Property ''' <summary> ''' Provides the text to show inside of a combobox/listbox ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Overrides Function ToString() As String Return m_description End Function End Class ''' <summary> ''' Retrieves the set of target framework assemblies that are supported ''' </summary> ''' <param name="vsTargetFrameworkAssemblies"></param> ''' <returns></returns> ''' <remarks></remarks> Public Shared Function GetSupportedTargetFrameworkAssemblies(ByVal vsTargetFrameworkAssemblies As IVsTargetFrameworkAssemblies) As IEnumerable(Of TargetFramework) Dim versions As UInteger() = GetSupportedTargetFrameworkAssemblyVersions(vsTargetFrameworkAssemblies) Dim targetFrameworks As New List(Of TargetFramework) For Each version As UInteger In versions targetFrameworks.Add(New TargetFramework(version, GetTargetFrameworkDescriptionFromVersion(vsTargetFrameworkAssemblies, version))) Next Return targetFrameworks.ToArray() End Function ''' <summary> ''' Retrieve the localized description string for a given target framework ''' version number. ''' </summary> ''' <param name="vsTargetFrameworkAssemblies"></param> ''' <param name="version"></param> ''' <returns></returns> ''' <remarks></remarks> Private Shared Function GetTargetFrameworkDescriptionFromVersion(ByVal vsTargetFrameworkAssemblies As IVsTargetFrameworkAssemblies, ByVal version As UInteger) As String Dim pszDescription As String = Nothing VSErrorHandler.ThrowOnFailure(vsTargetFrameworkAssemblies.GetTargetFrameworkDescription(version, pszDescription)) Return pszDescription End Function ''' <summary> ''' Retrieve the list of assemblies versions (as uint) that are supported ''' </summary> ''' <param name="vsTargetFrameworkAssemblies"></param> ''' <returns></returns> ''' <remarks></remarks> Private Shared Function GetSupportedTargetFrameworkAssemblyVersions(ByVal vsTargetFrameworkAssemblies As IVsTargetFrameworkAssemblies) As UInteger() Dim targetFrameworkEnumerator As IEnumTargetFrameworks = Nothing VSErrorHandler.ThrowOnFailure(vsTargetFrameworkAssemblies.GetSupportedFrameworks(targetFrameworkEnumerator)) Dim supportedFrameworks As New List(Of UInteger) While True Dim rgFrameworks(0) As UInteger Dim cReturned As UInteger If VSErrorHandler.Failed(targetFrameworkEnumerator.Next(1, rgFrameworks, cReturned)) OrElse cReturned = 0 Then Exit While Else supportedFrameworks.Add(rgFrameworks(0)) End If End While Return supportedFrameworks.ToArray() End Function End Class End Namespace
chkn/fsharp
vsintegration/src/vs/FsPkgs/FSharp.Project/VB/FSharpPropPage/PropertyPages/TargetFrameworkAssemblies.vb
Visual Basic
apache-2.0
4,912
Imports NHibernate.Criterion Imports System Imports System.Collections Imports System.Collections.Generic Imports System.ComponentModel Namespace Query Partial Public Class OrderByClause ' Methods Public Sub New(ByVal name As String) Me.ascending = True Me.name = name End Sub Public Shared Widening Operator CType(ByVal order As OrderByClause) As Order Return New Order(order.name, order.ascending) End Operator ' Properties Public ReadOnly Property Asc() As OrderByClause Get Me.ascending = True Return Me End Get End Property Public ReadOnly Property Desc() As OrderByClause Get Me.ascending = False Return Me End Get End Property ' Fields Private ascending As Boolean Private name As String End Class Partial Public Class PropertyQueryBuilder(Of T) Inherits QueryBuilder(Of T) ' Methods Public Sub New(ByVal name As String, ByVal associationPath As String) MyBase.New(name, associationPath) End Sub Public Function Between(ByVal lo As Object, ByVal hi As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New BetweenExpression(MyBase.name, lo, hi) MyBase.AddCriterion(criterion1) Return Me End Function Public Function EqProperty(ByVal otherPropertyName As String) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New EqPropertyExpression(MyBase.name, otherPropertyName) MyBase.AddCriterion(criterion1) Return Me End Function Public Function Ge(ByVal value As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New GeExpression(MyBase.name, value) MyBase.AddCriterion(criterion1) Return Me End Function Public Function Gt(ByVal value As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New GtExpression(MyBase.name, value) MyBase.AddCriterion(criterion1) Return Me End Function Public Function InsensitiveLike(ByVal value As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New InsensitiveLikeExpression(MyBase.name, value) MyBase.AddCriterion(criterion1) Return Me End Function Public Function InsensitiveLike(ByVal value As String, ByVal matchMode As MatchMode) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New InsensitiveLikeExpression(MyBase.name, value, matchMode) MyBase.AddCriterion(criterion1) Return Me End Function Public Function Le(ByVal value As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New LeExpression(MyBase.name, value) MyBase.AddCriterion(criterion1) Return Me End Function Public Function LeProperty(ByVal otherPropertyName As String) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New LePropertyExpression(MyBase.name, otherPropertyName) MyBase.AddCriterion(criterion1) Return Me End Function Public Function [Like](ByVal value As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New LikeExpression(MyBase.name, value) MyBase.AddCriterion(criterion1) Return Me End Function Public Function [Like](ByVal value As String, ByVal matchMode As MatchMode) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New LikeExpression(MyBase.name, value, matchMode) MyBase.AddCriterion(criterion1) Return Me End Function Public Function Lt(ByVal value As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New LtExpression(MyBase.name, value) MyBase.AddCriterion(criterion1) Return Me End Function Public Function LtProperty(ByVal otherPropertyName As String) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New LtPropertyExpression(MyBase.name, otherPropertyName) MyBase.AddCriterion(criterion1) Return Me End Function Public Shared Operator >(ByVal expr As PropertyQueryBuilder(Of T), ByVal other As Object) As QueryBuilder(Of T) Return expr.Gt(other) End Operator Public Shared Operator >=(ByVal expr As PropertyQueryBuilder(Of T), ByVal other As Object) As QueryBuilder(Of T) Return expr.Ge(other) End Operator Public Shared Operator <(ByVal expr As PropertyQueryBuilder(Of T), ByVal other As Object) As QueryBuilder(Of T) Return expr.Lt(other) End Operator Public Shared Operator <=(ByVal expr As PropertyQueryBuilder(Of T), ByVal other As Object) As QueryBuilder(Of T) Return expr.Le(other) End Operator End Class Partial Public Class QueryBuilder(Of T) ' Methods Public Sub New(ByVal name As String, ByVal associationPath As String) Me.children = New List(Of QueryBuilder(Of T)) Me.criterions = New List(Of ICriterion) Me.name = name Me.associationPath = IIf(associationPath <> Nothing, associationPath, "this") End Sub Public Sub New(ByVal name As String, ByVal associationPath As String, ByVal backTrackAssociationsOnEquality As Boolean) Me.children = New List(Of QueryBuilder(Of T)) Me.criterions = New List(Of ICriterion) Me.name = name Me.associationPath = associationPath Me.backTrackAssociationsOnEquality = backTrackAssociationsOnEquality End Sub Private Sub AddByAssociationPath(ByVal criterionsByAssociation As IDictionary(Of String, ICollection(Of ICriterion))) If Not criterionsByAssociation.ContainsKey(Me.associationPath) Then criterionsByAssociation.Add(Me.associationPath, DirectCast(New List(Of ICriterion), ICollection(Of ICriterion))) End If Dim criterion1 As ICriterion For Each criterion1 In Me.criterions criterionsByAssociation.Item(Me.associationPath).Add(criterion1) Next Dim builder1 As QueryBuilder(Of T) For Each builder1 In Me.children builder1.AddByAssociationPath(criterionsByAssociation) Next End Sub Protected Sub AddCriterion(ByVal criterion As AbstractCriterion) Me.criterions.Add(criterion) End Sub Protected Shared Function BackTrackAssociationPath(ByVal associationPath As String) As String Dim num1 As Integer = associationPath.LastIndexOf("."c) If (num1 = -1) Then Return associationPath End If Return associationPath.Substring(0, num1) End Function Public Function Eq(ByVal value As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion If (value Is Nothing) Then criterion1 = Expression.IsNull(Me.name) Else criterion1 = Expression.Eq(Me.name, value) End If Dim builder1 As QueryBuilder(Of T) = Me If Me.backTrackAssociationsOnEquality Then builder1 = New QueryBuilder(Of T)(Me.name, QueryBuilder(Of T).BackTrackAssociationPath(Me.associationPath)) Me.children.Add(DirectCast(builder1, QueryBuilder(Of T))) End If builder1.AddCriterion(criterion1) Return Me End Function <Browsable(False), Localizable(False)> _ Public Overrides Function Equals(ByVal obj As Object) As Boolean Throw New InvalidOperationException("You can't use Equals()! Use Eq()") End Function <Localizable(False), Browsable(False)> _ Public Overrides Function GetHashCode() As Integer Return MyBase.GetHashCode End Function Public Function [In](Of K)(ByVal values As ICollection(Of K)) As QueryBuilder(Of T) Dim objArray1 As Object() = QueryBuilder(Of T).ToArray(Of K)(values) Dim criterion1 As AbstractCriterion = New InExpression(Me.name, objArray1) Me.AddCriterion(criterion1) Return Me End Function Public Function [In](ByVal ParamArray values As Object()) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New InExpression(Me.name, values) Me.AddCriterion(criterion1) Return Me End Function Public Function [In](ByVal values As ICollection) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion = New InExpression(Me.name, QueryBuilder(Of T).ToArray(values)) Me.AddCriterion(criterion1) Return Me End Function Public Function NotEq(ByVal value As Object) As QueryBuilder(Of T) Dim criterion1 As AbstractCriterion If (value Is Nothing) Then criterion1 = Expression.IsNotNull(Me.name) Else criterion1 = Expression.Not(Expression.Eq(Me.name, value)) End If Dim builder1 As QueryBuilder(Of T) = Me If Me.backTrackAssociationsOnEquality Then builder1 = New QueryBuilder(Of T)(Me.name, QueryBuilder(Of T).BackTrackAssociationPath(Me.associationPath)) Me.children.Add(DirectCast(builder1, QueryBuilder(Of T))) End If builder1.AddCriterion(criterion1) Return Me End Function Public Shared Operator And(ByVal lhs As QueryBuilder(Of T), ByVal rhs As QueryBuilder(Of T)) As QueryBuilder(Of T) Dim builder1 As New QueryBuilder(Of T)(lhs.name, Nothing) builder1.children.Add(DirectCast(lhs, QueryBuilder(Of T))) builder1.children.Add(DirectCast(rhs, QueryBuilder(Of T))) Return builder1 End Operator Public Shared Operator Or(ByVal lhs As QueryBuilder(Of T), ByVal rhs As QueryBuilder(Of T)) As QueryBuilder(Of T) Dim criterion1 As ICriterion Dim enumerator1 As IEnumerator(Of ICriterion) If (Not lhs.associationPath Is rhs.associationPath) Then Throw New InvalidOperationException(String.Format("OR attempted between {0} and {1}." & ChrW(13) & ChrW(10) & "You can't OR between two Query parts that belong to different associations." & ChrW(13) & ChrW(10) & "Use HQL for this functionality...", lhs.associationPath, rhs.associationPath)) End If Dim builder1 As New QueryBuilder(Of T)(lhs.name, Nothing) Dim conjunction1 As Conjunction = Expression.Conjunction Dim conjunction2 As Conjunction = Expression.Conjunction Using enumerator1 = lhs.criterions.GetEnumerator Do While enumerator1.MoveNext criterion1 = enumerator1.Current conjunction1.Add(criterion1) Loop End Using Using enumerator1 = rhs.criterions.GetEnumerator Do While enumerator1.MoveNext criterion1 = enumerator1.Current conjunction2.Add(criterion1) Loop End Using builder1.criterions.Add(Expression.Or(conjunction1, conjunction2)) Return builder1 End Operator Public Shared Operator =(ByVal expr As QueryBuilder(Of T), ByVal other As Object) As QueryBuilder(Of T) Return expr.Eq(other) End Operator Public Shared Operator IsFalse(ByVal exp As QueryBuilder(Of T)) As Boolean Return False End Operator Public Shared Widening Operator CType(ByVal expr As QueryBuilder(Of T)) As DetachedCriteria Dim criteria1 As DetachedCriteria = DetachedCriteria.For(Of T)() Dim dictionary1 As New Dictionary(Of String, ICollection(Of ICriterion)) expr.AddByAssociationPath(dictionary1) Dim pair1 As KeyValuePair(Of String, ICollection(Of ICriterion)) For Each pair1 In dictionary1 Dim criteria2 As DetachedCriteria = criteria1 If (Not pair1.Key Is "this") Then criteria2 = criteria1.CreateCriteria(pair1.Key) End If Dim criterion1 As ICriterion For Each criterion1 In pair1.Value criteria2.Add(criterion1) Next Next Return criteria1 End Operator Public Shared Operator <>(ByVal expr As QueryBuilder(Of T), ByVal other As Object) As QueryBuilder(Of T) Return expr.NotEq(other) End Operator Public Shared Operator IsTrue(ByVal exp As QueryBuilder(Of T)) As Boolean Return False End Operator Protected Shared Function ToArray(Of K)(ByVal values As ICollection(Of K)) As Object() Dim localArray1 As K() = New K(values.Count - 1) {} values.CopyTo(localArray1, 0) Return QueryBuilder(Of T).ToArray(localArray1) End Function Protected Shared Function ToArray(ByVal values As ICollection) As Object() Dim objArray1 As Object() = New Object(values.Count - 1) {} values.CopyTo(objArray1, 0) Return objArray1 End Function ' Properties Public ReadOnly Property IsNotNull() As QueryBuilder(Of T) Get Dim criterion1 As AbstractCriterion = New NotNullExpression(Me.name) Me.AddCriterion(criterion1) Return Me End Get End Property Public ReadOnly Property IsNull() As QueryBuilder(Of T) Get Dim criterion1 As AbstractCriterion = New NullExpression(Me.name) Me.AddCriterion(criterion1) Return Me End Get End Property ' Fields Protected associationPath As String Private backTrackAssociationsOnEquality As Boolean Private children As ICollection(Of QueryBuilder(Of T)) Private criterions As ICollection(Of ICriterion) Protected name As String End Class Partial Public Class ProjectBy Public Shared ReadOnly Property RowCount() As IProjection Get Return Projections.RowCount() End Get End Property Public Shared ReadOnly Property Id() As IProjection Get Return Projections.Id() End Get End Property Public Shared Function Distinct(ByVal projection As IProjection) As IProjection Return Projections.Distinct(projection) End Function Public Shared Function SqlProjection(ByVal sql As String, ByVal aliases() As String, ByVal types() As IType) As IProjection Return Projections.SqlProjection(sql, aliases, types) End Function Public Shared Function SqlGroupByProjection(ByVal sql As String, ByVal groupBy As String, ByVal aliases() As String, ByVal types() As IType) As IProjection Return Projections.SqlGroupProjection(sql, groupBy, aliases, types) End Function End Class _ Partial Public Class PropertyProjectionBuilder Protected name As String Public Sub New(ByVal name As String) Me.name = name End Sub Public ReadOnly Property Count() As IProjection Get Return Projections.Count(name) End Get End Property Public ReadOnly Property DistinctCount() As IProjection Get Return Projections.CountDistinct(name) End Get End Property Public ReadOnly Property Max() As IProjection Get Return Projections.Max(name) End Get End Property Public ReadOnly Property Min() As IProjection Get Return Projections.Min(name) End Get End Property Public Shared Widening Operator CType(ByVal projection As PropertyProjectionBuilder) As PropertyProjection Return Projections.Property(projection.name) End Operator End Class _ Partial Public Class NumericPropertyProjectionBuilder Inherits PropertyProjectionBuilder Public Sub New(ByVal name As String) MyBase.New(name) End Sub Public ReadOnly Property Avg() As IProjection Get Return Projections.Avg(name) End Get End Property Public ReadOnly Property Sum() As IProjection Get Return Projections.Sum(name) End Get End Property Public Shared Widening Operator CType(ByVal projection As NumericPropertyProjectionBuilder) As PropertyProjection Return Projections.Property(projection.name) End Operator End Class End Namespace
brumschlag/rhino-tools
NHibernate.Query.Generator/NHibernate.Query.Generator/QueryBuilders/QueryBuilder.vb
Visual Basic
bsd-3-clause
15,011
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets.SnippetFunctions Friend NotInheritable Class SnippetFunctionClassName Inherits AbstractSnippetFunctionClassName Public Sub New(snippetExpansionClient As SnippetExpansionClient, textView As ITextView, subjectBuffer As ITextBuffer, fieldName As String) MyBase.New(snippetExpansionClient, textView, subjectBuffer, fieldName) End Sub Protected Overrides Function GetContainingClassName(document As Document, subjectBufferFieldSpan As SnapshotSpan, cancellationToken As CancellationToken, ByRef value As String, ByRef hasDefaultValue As Integer) As Integer Dim syntaxTree = document.GetVisualBasicSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken) Dim typeBlock = syntaxTree.FindTokenOnLeftOfPosition(subjectBufferFieldSpan.Start.Position, cancellationToken).GetAncestor(Of TypeBlockSyntax) If typeBlock IsNot Nothing AndAlso Not String.IsNullOrWhiteSpace(typeBlock.GetNameToken().ValueText) Then value = typeBlock.GetNameToken().ValueText hasDefaultValue = 1 End If Return VSConstants.S_OK End Function End Class End Namespace
MavenRain/roslyn
src/VisualStudio/VisualBasic/Impl/Snippets/SnippetFunctions/SnippetFunctionClassName.vb
Visual Basic
apache-2.0
1,809
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ClsComplianceTests Inherits BasicTestBase <Fact> Public Sub NoAssemblyLevelAttributeRequired() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(True)> Public Class A End Class <CLSCompliant(False)> Public Class B End Class ]]> </file> </compilation> ' In C#, an assembly-level attribute is required. In VB, that is not the case. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub AssemblyLevelAttributeAllowed() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> <Module: CLSCompliant(True)> <CLSCompliant(True)> Public Class A End Class <CLSCompliant(False)> Public Class B End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub AttributeAllowedOnPrivate() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(True)> Public Class Outer <CLSCompliant(True)> Private Class A End Class <CLSCompliant(True)> Friend Class B End Class <CLSCompliant(True)> Protected Class C End Class <CLSCompliant(True)> Friend Protected Class D End Class <CLSCompliant(True)> Public Class E End Class End Class ]]> </file> </compilation> ' C# warns about putting the attribute on members not visible outside the assembly. ' VB does not. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub AttributeAllowedOnParameters() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(True)> Public Class C Public Function M(<CLSCompliant(True)> x As Integer) As Integer Return 0 End Function Public ReadOnly Property P(<CLSCompliant(True)> x As Integer) As Integer Get Return 0 End Get End Property End Class ]]> </file> </compilation> ' C# warns about putting the attribute on parameters. VB does not. ' C# also warns about putting the attribute on return types, but VB ' does not support the "return" attribute target. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub WRN_CLSMemberInNonCLSType3_Explicit() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(False)> Public Class Kinds <CLSCompliant(True)> Public Sub M() End Sub <CLSCompliant(True)> Public Property P As Integer <CLSCompliant(True)> Public Event E As ND <CLSCompliant(True)> Public F As Integer <CLSCompliant(True)> Public Class NC End Class <CLSCompliant(True)> Public Interface NI End Interface <CLSCompliant(True)> Public Structure NS End Structure <CLSCompliant(True)> Public Delegate Sub ND() End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40030: sub 'Public Sub M()' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Sub M() ~ BC40030: property 'Public Property P As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Property P As Integer ~ BC40030: event 'Public Event E As Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Event E As ND ~ BC40030: variable 'Public F As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public F As Integer ~ BC40030: class 'Kinds.NC' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Class NC ~~ BC40030: interface 'Kinds.NI' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Interface NI ~~ BC40030: structure 'Kinds.NS' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Structure NS ~~ BC40030: delegate Class 'Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Delegate Sub ND() ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_CLSMemberInNonCLSType3_Implicit() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly:CLSCompliant(False)> Public Class Kinds <CLSCompliant(True)> Public Sub M() End Sub <CLSCompliant(True)> Public Property P As Integer <CLSCompliant(True)> Public Event E As ND <CLSCompliant(True)> Public F As Integer <CLSCompliant(True)> Public Class NC End Class <CLSCompliant(True)> Public Interface NI End Interface <CLSCompliant(True)> Public Structure NS End Structure <CLSCompliant(True)> Public Delegate Sub ND() End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40030: sub 'Public Sub M()' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Sub M() ~ BC40030: property 'Public Property P As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Property P As Integer ~ BC40030: event 'Public Event E As Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Event E As ND ~ BC40030: variable 'Public F As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public F As Integer ~ BC40030: class 'Kinds.NC' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Class NC ~~ BC40030: interface 'Kinds.NI' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Interface NI ~~ BC40030: structure 'Kinds.NS' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Structure NS ~~ BC40030: delegate Class 'Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant. Public Delegate Sub ND() ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_CLSMemberInNonCLSType3_Alternating() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(True)> Public Class A <CLSCompliant(False)> Public Class B <CLSCompliant(True)> Public Class C <CLSCompliant(False)> Public Class D <CLSCompliant(True)> Public Class E End Class End Class End Class End Class End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40030: class 'A.B.C' cannot be marked CLS-compliant because its containing type 'A.B' is not CLS-compliant. Public Class C ~ BC40030: class 'A.B.C.D.E' cannot be marked CLS-compliant because its containing type 'A.B.C.D' is not CLS-compliant. Public Class E ~ ]]></errors>) End Sub <Fact> Public Sub WRN_BaseClassNotCLSCompliant2() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class A Inherits Bad End Class <CLSCompliant(False)> Public Class Bad End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40026: 'A' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant. Public Class A ~ ]]></errors>) End Sub <Fact> Public Sub WRN_BaseClassNotCLSCompliant2_OtherAssemblies() Dim lib1Source = <compilation name="lib1"> <file name="a.vb"> <![CDATA[ Public Class Bad1 End Class ]]> </file> </compilation> Dim lib2Source = <compilation name="lib2"> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> <CLSCompliant(False)> Public Class Bad2 End Class ]]> </file> </compilation> Dim lib3Source = <compilation name="lib3"> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(False)> Public Class Bad3 End Class ]]> </file> </compilation> Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class A1 Inherits Bad1 End Class Public Class A2 Inherits Bad2 End Class Public Class A3 Inherits Bad3 End Class ]]> </file> </compilation> Dim lib1Ref = CreateCompilationWithMscorlib40(lib1Source).EmitToImageReference() Dim lib2Ref = CreateCompilationWithMscorlib40(lib2Source).EmitToImageReference() Dim lib3Ref = CreateCompilationWithMscorlib40(lib3Source).EmitToImageReference() CreateCompilationWithMscorlib40AndReferences(source, {lib1Ref, lib2Ref, lib3Ref}).AssertTheseDiagnostics(<errors><![CDATA[ BC40026: 'A1' is not CLS-compliant because it derives from 'Bad1', which is not CLS-compliant. Public Class A1 ~~ BC40026: 'A2' is not CLS-compliant because it derives from 'Bad2', which is not CLS-compliant. Public Class A2 ~~ BC40026: 'A3' is not CLS-compliant because it derives from 'Bad3', which is not CLS-compliant. Public Class A3 ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_InheritedInterfaceNotCLSCompliant2_Interface() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Interface A Inherits Bad End Interface Public Interface B Inherits Bad, Good End Interface Public Interface C Inherits Good, Bad End Interface <CLSCompliant(True)> Public Interface Good End Interface <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40029: 'A' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant. Public Interface A ~ BC40029: 'B' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant. Public Interface B ~ BC40029: 'C' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant. Public Interface C ~ ]]></errors>) End Sub <Fact> Public Sub WRN_InheritedInterfaceNotCLSCompliant2_Class() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class A Implements Bad End Class Public Class B Implements Bad, Good End Class Public Class C Implements Good, Bad End Class <CLSCompliant(True)> Public Interface Good End Interface <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> ' Implemented interfaces are not required to be compliant - only inherited ones. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub WRN_NonCLSMemberInCLSInterface1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Interface A Function M1() As Bad <CLSCompliant(False)> Sub M2() End Interface Public Interface Kinds <CLSCompliant(False)> Sub M() <CLSCompliant(False)> Property P() <CLSCompliant(False)> Event E As Action End Interface <CLSCompliant(False)> Public Class Bad End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40027: Return type of function 'M1' is not CLS-compliant. Function M1() As Bad ~~ BC40033: Non CLS-compliant 'Sub M2()' is not allowed in a CLS-compliant interface. Sub M2() ~~ BC40033: Non CLS-compliant 'Sub M()' is not allowed in a CLS-compliant interface. Sub M() ~ BC40033: Non CLS-compliant 'Property P As Object' is not allowed in a CLS-compliant interface. Property P() ~ BC40033: Non CLS-compliant 'Event E As Action' is not allowed in a CLS-compliant interface. Event E As Action ~ ]]></errors>) End Sub <Fact> Public Sub WRN_NonCLSMustOverrideInCLSType1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public MustInherit Class A Public MustOverride Function M1() As Bad <CLSCompliant(False)> Public MustOverride Sub M2() End Class Public MustInherit Class Kinds <CLSCompliant(False)> Public MustOverride Sub M() <CLSCompliant(False)> Public MustOverride Property P() ' VB doesn't support generic events Public MustInherit Class C End Class End Class <CLSCompliant(False)> Public Class Bad End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40027: Return type of function 'M1' is not CLS-compliant. Public MustOverride Function M1() As Bad ~~ BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'A'. Public MustOverride Sub M2() ~~ BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'Kinds'. Public MustOverride Sub M() ~ BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'Kinds'. Public MustOverride Property P() ~ ]]></errors>) End Sub <Fact> Public Sub AbstractInCompliant_NoAssemblyAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(True)> Public Interface IFace <CLSCompliant(False)> Property Prop1() As Long <CLSCompliant(False)> Function F2() As Integer <CLSCompliant(False)> Event EV3(ByVal i3 As Integer) <CLSCompliant(False)> Sub Sub4() End Interface <CLSCompliant(True)> Public MustInherit Class QuiteCompliant <CLSCompliant(False)> Public MustOverride Sub Sub1() <CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer <CLSCompliant(False)> Protected Friend MustOverride Sub Sub3() <CLSCompliant(False)> Friend MustOverride Function Fun4(ByVal x As Long) As Long End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40033: Non CLS-compliant 'Property Prop1 As Long' is not allowed in a CLS-compliant interface. <CLSCompliant(False)> Property Prop1() As Long ~~~~~ BC40033: Non CLS-compliant 'Function F2() As Integer' is not allowed in a CLS-compliant interface. <CLSCompliant(False)> Function F2() As Integer ~~ BC40033: Non CLS-compliant 'Event EV3(i3 As Integer)' is not allowed in a CLS-compliant interface. <CLSCompliant(False)> Event EV3(ByVal i3 As Integer) ~~~ BC40033: Non CLS-compliant 'Sub Sub4()' is not allowed in a CLS-compliant interface. <CLSCompliant(False)> Sub Sub4() ~~~~ BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'. <CLSCompliant(False)> Public MustOverride Sub Sub1() ~~~~ BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'. <CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer ~~~~ BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'. <CLSCompliant(False)> Protected Friend MustOverride Sub Sub3() ~~~~ ]]></errors>) End Sub <Fact> Public Sub WRN_GenericConstraintNotCLSCompliant1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C1(Of t As {Good, Bad}, u As {Bad, Good}) End Class <CLSCompliant(False)> Public Class C2(Of t As {Good, Bad}, u As {Bad, Good}) End Class Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})() <CLSCompliant(False)> Public Delegate Sub D2(Of t As {Good, Bad}, u As {Bad, Good})() Public Class C Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})() End Sub <CLSCompliant(False)> Public Sub M2(Of t As {Good, Bad}, u As {Bad, Good})() End Sub End Class <CLSCompliant(True)> Public Interface Good End Interface <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> ' NOTE: Dev11 squiggles the problematic constraint, but we don't have enough info. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant. Public Class C1(Of t As {Good, Bad}, u As {Bad, Good}) ~ BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant. Public Class C1(Of t As {Good, Bad}, u As {Bad, Good}) ~ BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant. Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})() ~ BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant. Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})() ~ BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant. Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})() ~ BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant. Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})() ~ ]]></errors>) End Sub <Fact> Public Sub WRN_FieldNotCLSCompliant1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class Kinds1 Public F1 As Bad Private F2 As Bad End Class <CLSCompliant(False)> Public Class Kinds2 Public F3 As Bad Private F4 As Bad End Class <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40025: Type of member 'F1' is not CLS-compliant. Public F1 As Bad ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_ProcTypeNotCLSCompliant1_Method() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C1 Public Function M1() As Bad Throw New Exception() End Function Public Function M2() As Generic(Of Bad) Throw New Exception() End Function Public Function M3() As Generic(Of Generic(Of Bad)) Throw New Exception() End Function Public Function M4() As Bad() Throw New Exception() End Function Public Function M5() As Bad()() Throw New Exception() End Function Public Function M6() As Bad(,) Throw New Exception() End Function End Class <CLSCompliant(False)> Public Class C2 Public Function N1() As Bad Throw New Exception() End Function Public Function N2() As Generic(Of Bad) Throw New Exception() End Function Public Function N3() As Generic(Of Generic(Of Bad)) Throw New Exception() End Function Public Function N4() As Bad() Throw New Exception() End Function Public Function N5() As Bad()() Throw New Exception() End Function Public Function N6() As Bad(,) Throw New Exception() End Function End Class Public Class Generic(Of T) End Class <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40027: Return type of function 'M1' is not CLS-compliant. Public Function M1() As Bad ~~ BC40041: Type 'Bad' is not CLS-compliant. Public Function M2() As Generic(Of Bad) ~~ BC40041: Type 'Bad' is not CLS-compliant. Public Function M3() As Generic(Of Generic(Of Bad)) ~~ BC40027: Return type of function 'M4' is not CLS-compliant. Public Function M4() As Bad() ~~ BC40027: Return type of function 'M5' is not CLS-compliant. Public Function M5() As Bad()() ~~ BC40027: Return type of function 'M6' is not CLS-compliant. Public Function M6() As Bad(,) ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_ProcTypeNotCLSCompliant1_Property() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C1 Public Property P1() As Bad Public Property P2() As Generic(Of Bad) Public Property P3() As Generic(Of Generic(Of Bad)) Public Property P4() As Bad() Public Property P5() As Bad()() Public Property P6() As Bad(,) End Class <CLSCompliant(False)> Public Class C2 Public Property Q1() As Bad Public Property Q2() As Generic(Of Bad) Public Property Q3() As Generic(Of Generic(Of Bad)) Public Property Q4() As Bad() Public Property Q5() As Bad()() Public Property Q6() As Bad(,) End Class Public Class Generic(Of T) End Class <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40027: Return type of function 'P1' is not CLS-compliant. Public Property P1() As Bad ~~ BC40041: Type 'Bad' is not CLS-compliant. Public Property P2() As Generic(Of Bad) ~~ BC40041: Type 'Bad' is not CLS-compliant. Public Property P3() As Generic(Of Generic(Of Bad)) ~~ BC40027: Return type of function 'P4' is not CLS-compliant. Public Property P4() As Bad() ~~ BC40027: Return type of function 'P5' is not CLS-compliant. Public Property P5() As Bad()() ~~ BC40027: Return type of function 'P6' is not CLS-compliant. Public Property P6() As Bad(,) ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_ProcTypeNotCLSCompliant1_Delegate() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C1 Public Delegate Function M1() As Bad Public Delegate Function M2() As Generic(Of Bad) Public Delegate Function M3() As Generic(Of Generic(Of Bad)) Public Delegate Function M4() As Bad() Public Delegate Function M5() As Bad()() Public Delegate Function M6() As Bad(,) End Class <CLSCompliant(False)> Public Class C2 Public Delegate Function N1() As Bad Public Delegate Function N2() As Generic(Of Bad) Public Delegate Function N3() As Generic(Of Generic(Of Bad)) Public Delegate Function N4() As Bad() Public Delegate Function N5() As Bad()() Public Delegate Function N6() As Bad(,) End Class Public Class Generic(Of T) End Class <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40027: Return type of function 'Invoke' is not CLS-compliant. Public Delegate Function M1() As Bad ~~ BC40041: Type 'Bad' is not CLS-compliant. Public Delegate Function M2() As Generic(Of Bad) ~~ BC40041: Type 'Bad' is not CLS-compliant. Public Delegate Function M3() As Generic(Of Generic(Of Bad)) ~~ BC40027: Return type of function 'Invoke' is not CLS-compliant. Public Delegate Function M4() As Bad() ~~ BC40027: Return type of function 'Invoke' is not CLS-compliant. Public Delegate Function M5() As Bad()() ~~ BC40027: Return type of function 'Invoke' is not CLS-compliant. Public Delegate Function M6() As Bad(,) ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_ParamNotCLSCompliant1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C1 Public Function M1(p As Bad) Throw New Exception() End Function Public Function M2(p As Generic(Of Bad)) Throw New Exception() End Function Public Function M3(p As Generic(Of Generic(Of Bad))) Throw New Exception() End Function Public Function M4(p As Bad()) Throw New Exception() End Function Public Function M5(p As Bad()()) Throw New Exception() End Function Public Function M6(p As Bad(,)) Throw New Exception() End Function End Class <CLSCompliant(False)> Public Class C2 Public Function N1(p As Bad) Throw New Exception() End Function Public Function N2(p As Generic(Of Bad)) Throw New Exception() End Function Public Function N3(p As Generic(Of Generic(Of Bad))) Throw New Exception() End Function Public Function N4(p As Bad()) Throw New Exception() End Function Public Function N5(p As Bad()()) Throw New Exception() End Function Public Function N6(p As Bad(,)) Throw New Exception() End Function End Class Public Class Generic(Of T) End Class <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40028: Type of parameter 'p' is not CLS-compliant. Public Function M1(p As Bad) ~ BC40041: Type 'Bad' is not CLS-compliant. Public Function M2(p As Generic(Of Bad)) ~ BC40041: Type 'Bad' is not CLS-compliant. Public Function M3(p As Generic(Of Generic(Of Bad))) ~ BC40028: Type of parameter 'p' is not CLS-compliant. Public Function M4(p As Bad()) ~ BC40028: Type of parameter 'p' is not CLS-compliant. Public Function M5(p As Bad()()) ~ BC40028: Type of parameter 'p' is not CLS-compliant. Public Function M6(p As Bad(,)) ~ ]]></errors>) End Sub <Fact> Public Sub WRN_ParamNotCLSCompliant1_Kinds() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Interface I1 Sub M(x As Bad) Property P(x As Bad) As Integer Delegate Sub D(x As Bad) End Interface <CLSCompliant(False)> Public Interface I2 Sub M(x As Bad) Property P(x As Bad) As Integer Delegate Sub D(x As Bad) End Interface <CLSCompliant(False)> Public Interface Bad End Interface ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40028: Type of parameter 'x' is not CLS-compliant. Sub M(x As Bad) ~ BC40028: Type of parameter 'x' is not CLS-compliant. Property P(x As Bad) As Integer ~ BC40028: Type of parameter 'x' is not CLS-compliant. Delegate Sub D(x As Bad) ~ ]]></errors>) End Sub ' From LegacyTest\CSharp\Source\csharp\Source\ClsCompliance\generics\Rule_E_01.cs <Fact> Public Sub WRN_ParamNotCLSCompliant1_ConstructedTypeAccessibility() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C(Of T) Protected Class N End Class ' Not CLS-compliant since C(Of Integer).N is not accessible within C(Of T) in all languages. Protected Sub M1(n As C(Of Integer).N) End Sub ' Fine Protected Sub M2(n As C(Of T).N) End Sub Protected Class N2 ' Not CLS-compliant Protected Sub M3(n As C(Of ULong).N) End Sub End Class End Class Public Class D Inherits C(Of Long) ' Not CLS-compliant Protected Sub M4(n As C(Of Integer).N) End Sub ' Fine Protected Sub M5(n As C(Of Long).N) End Sub End Class ]]> </file> </compilation> ' Dev11 produces error BC30508 for M1 and M3 ' Dev11 produces error BC30389 for M4 and M5 ' Roslyn dropped these errors (since they weren't helpful) and, instead, reports CLS warnings. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub WRN_ParamNotCLSCompliant1_ProtectedContainer() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C1(Of T) Protected Class C2(Of U) Public Class C3(Of V) Public Sub M(Of W)(p As C1(Of Integer).C2(Of U)) End Sub Public Sub M(Of W)(p As C1(Of Integer).C2(Of U).C3(Of V)) End Sub End Class End Class End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub AttributeConstructorsWithArrayParameters() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class EmptyAttribute Inherits Attribute End Class Public Class PublicAttribute Inherits Attribute ' Not accessible Friend Sub New() End Sub ' Not compliant <CLSCompliant(False)> Public Sub New(x As Integer) End Sub ' Array argument Public Sub New(a As Integer(,)) End Sub ' Array argument Public Sub New(ParamArray a As Char()) End Sub End Class Friend Class InternalAttribute Inherits Attribute ' Not accessible Public Sub New() End Sub End Class <CLSCompliant(False)> Public Class BadAttribute Inherits Attribute ' Fine, since type isn't compliant. Public Sub New(array As Integer()) End Sub End Class Public Class NotAnAttribute ' Fine, since not an attribute type. Public Sub New(array As Integer()) End Sub End Class ]]> </file> </compilation> ' NOTE: C# requires that compliant attributes have at least one ' accessible constructor with no attribute parameters. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub AttributeConstructorsWithNonPredefinedParameters() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class MyAttribute Inherits Attribute Public Sub New(m As MyAttribute) End Sub End Class ]]> </file> </compilation> ' CLS only allows System.Type, string, char, bool, byte, short, int, long, float, double, and enums, ' but dev11 does not enforce this. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub ArrayArgumentToAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class ArrayAttribute Inherits Attribute Public Sub New(array As Integer()) End Sub End Class Friend Class InternalArrayAttribute Inherits Attribute Public Sub New(array As Integer()) End Sub End Class Public Class ObjectAttribute Inherits Attribute Public Sub New(array As Object) End Sub End Class Public Class NamedArgumentAttribute Inherits Attribute Public Property O As Object End Class <Array({1})> Public Class A End Class <[Object]({1})> Public Class B End Class <InternalArray({1})> Public Class C End Class <NamedArgument(O:={1})> Public Class D End Class ]]> </file> </compilation> ' CLS only allows System.Type, string, char, bool, byte, short, int, long, float, double, and enums, ' but dev11 does not enforce this. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub WRN_NameNotCLSCompliant1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class _A End Class Public Class B_ End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40031: Name '_A' is not CLS-compliant. Public Class _A ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_NameNotCLSCompliant1_Kinds() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class Kinds Public Sub _M() End Sub Public Property _P As Integer Public Event _E As _ND Public _F As Integer Public Class _NC End Class Public Interface _NI End Interface Public Structure _NS End Structure Public Delegate Sub _ND() Private _Private As Integer <CLSCompliant(False)> Public _NonCompliant As Integer End Class Namespace _NS1 End Namespace Namespace NS1._NS2 End Namespace ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40031: Name '_M' is not CLS-compliant. Public Sub _M() ~~ BC40031: Name '_P' is not CLS-compliant. Public Property _P As Integer ~~ BC40031: Name '_E' is not CLS-compliant. Public Event _E As _ND ~~ BC40031: Name '_F' is not CLS-compliant. Public _F As Integer ~~ BC40031: Name '_NC' is not CLS-compliant. Public Class _NC ~~~ BC40031: Name '_NI' is not CLS-compliant. Public Interface _NI ~~~ BC40031: Name '_NS' is not CLS-compliant. Public Structure _NS ~~~ BC40031: Name '_ND' is not CLS-compliant. Public Delegate Sub _ND() ~~~ BC40031: Name '_NS1' is not CLS-compliant. Namespace _NS1 ~~~~ BC40031: Name '_NS2' is not CLS-compliant. Namespace NS1._NS2 ~~~~ ]]></errors>) End Sub <Fact> Public Sub WRN_NameNotCLSCompliant1_Overrides() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class Base Public Overridable Sub _M() End Sub End Class Public Class Derived Inherits Base Public Overrides Sub _M() End Sub End Class ]]> </file> </compilation> ' NOTE: C# doesn't report this warning on overrides. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40031: Name '_M' is not CLS-compliant. Public Overridable Sub _M() ~~ BC40031: Name '_M' is not CLS-compliant. Public Overrides Sub _M() ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_NameNotCLSCompliant1_NotReferencable() Dim il = <![CDATA[ .class public abstract auto ansi B { .custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(true)} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public hidebysig newslot specialname abstract virtual instance int32 _getter() cil managed { } .property instance int32 P() { .get instance int32 B::_getter() } } ]]> Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Inherits B Public Overrides ReadOnly Property P As Integer Get Return 0 End Get End Property End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithCustomILSource(source, il) comp.AssertNoDiagnostics() Dim accessor = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of PropertySymbol)("P").GetMethod Assert.True(accessor.MetadataName.StartsWith("_", StringComparison.Ordinal)) End Sub <Fact> Public Sub WRN_NameNotCLSCompliant1_Parameter() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class B Public Sub M(_p As Integer) End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub ModuleLevel_NoAssemblyLevel() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Module: CLSCompliant(True)> ]]> </file> </compilation> ' C# warns. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Module: CLSCompliant(False)> ]]> </file> </compilation> ' C# warns. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub ModuleLevel_DisagreesWithAssemblyLevel() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(False)> <Module: CLSCompliant(True)> ]]> </file> </compilation> ' C# warns. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> <Module: CLSCompliant(False)> ]]> </file> </compilation> ' C# warns. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub DroppedAttributes() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(False)> <Module: CLSCompliant(True)> ]]> </file> </compilation> Dim validator = Function(expectAssemblyLevel As Boolean, expectModuleLevel As Boolean) _ Sub(m As ModuleSymbol) Dim predicate = Function(attr As VisualBasicAttributeData) attr.AttributeClass.Name = "CLSCompliantAttribute" If expectModuleLevel Then AssertEx.Any(m.GetAttributes(), predicate) Else AssertEx.None(m.GetAttributes(), predicate) End If If expectAssemblyLevel Then AssertEx.Any(m.ContainingAssembly.GetAttributes(), predicate) ElseIf m.ContainingAssembly IsNot Nothing Then AssertEx.None(m.ContainingAssembly.GetAttributes(), predicate) End If End Sub CompileAndVerify(source, options:=TestOptions.ReleaseDll, sourceSymbolValidator:=validator(True, True), symbolValidator:=validator(True, False)) CompileAndVerify(source, options:=TestOptions.ReleaseModule, sourceSymbolValidator:=validator(True, True), symbolValidator:=validator(False, True), verify:=Verification.Fails) ' PEVerify doesn't like netmodules End Sub <Fact> Public Sub ConflictingAssemblyLevelAttributes_ModuleVsAssembly() Dim source = <compilation name="A"> <file name="a.vb"> <![CDATA[ <Assembly: System.CLSCompliant(False)> ]]> </file> </compilation> Dim moduleComp = CreateCSharpCompilation("[assembly:System.CLSCompliant(true)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="A") Dim moduleRef = moduleComp.EmitToImageReference() CreateCompilationWithMscorlib40AndReferences(source, {moduleRef}).AssertTheseDiagnostics(<errors><![CDATA[ BC36978: Attribute 'CLSCompliantAttribute' in 'A.netmodule' cannot be applied multiple times. ]]></errors>) End Sub <Fact> Public Sub ConflictingAssemblyLevelAttributes_ModuleVsModule() Dim source = <compilation name="A"> <file name="a.vb"> </file> </compilation> Dim moduleComp1 = CreateCSharpCompilation("[assembly:System.CLSCompliant(true)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="A") Dim moduleRef1 = moduleComp1.EmitToImageReference() Dim moduleComp2 = CreateCSharpCompilation("[assembly:System.CLSCompliant(false)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="B") Dim moduleRef2 = moduleComp2.EmitToImageReference() CreateCompilationWithMscorlib40AndReferences(source, {moduleRef1, moduleRef2}).AssertTheseDiagnostics(<errors><![CDATA[ BC36978: Attribute 'CLSCompliantAttribute' in 'A.netmodule' cannot be applied multiple times. ]]></errors>) End Sub <Fact> Public Sub AssemblyIgnoresModuleAttribute() Dim source = <compilation name="A"> <file name="a.vb"> <![CDATA[ Imports System <Module: Clscompliant(True)> <CLSCompliant(True)> Public Class Test Inherits Bad End Class ' Doesn't inherit True from module, so not compliant. Public Class Bad End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant. Public Class Test ~~~~ ]]></errors>) End Sub <Fact> Public Sub ModuleIgnoresAssemblyAttribute() Dim source = <compilation name="A"> <file name="a.vb"> <![CDATA[ Imports System <Assembly: Clscompliant(True)> <CLSCompliant(True)> Public Class Test Inherits Bad End Class ' Doesn't inherit True from assembly, so not compliant. Public Class Bad End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source, OutputKind.NetModule).AssertTheseDiagnostics(<errors><![CDATA[ BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant. Public Class Test ~~~~ ]]></errors>) End Sub <Fact> Public Sub IgnoreModuleAttributeInReferencedAssembly() Dim source = <compilation name="A"> <file name="a.vb"><![CDATA[ Imports System <CLSCompliant(True)> Public Class Test Inherits Bad End Class ]]></file> </compilation> Dim assemblyLevelLibSource = <![CDATA[ [assembly:System.CLSCompliant(true)] public class Bad { } ]]> Dim moduleLevelLibSource = <![CDATA[ [module:System.CLSCompliant(true)] public class Bad { } ]]> Dim assemblyLevelLibRef = CreateCSharpCompilation(assemblyLevelLibSource).EmitToImageReference() Dim moduleLevelLibRef = CreateCSharpCompilation(moduleLevelLibSource).EmitToImageReference(Nothing) ' suppress warning ' Attribute respected. CreateCompilationWithMscorlib40AndReferences(source, {assemblyLevelLibRef}).AssertNoDiagnostics() ' Attribute not respected. CreateCompilationWithMscorlib40AndReferences(source, {moduleLevelLibRef}).AssertTheseDiagnostics(<errors><![CDATA[ BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant. Public Class Test ~~~~ ]]></errors>) End Sub <Fact> Public Sub WRN_EnumUnderlyingTypeNotCLS1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Enum E1 As UInteger A End Enum Friend Enum E2 As UInteger A End Enum <CLSCompliant(False)> Friend Enum E3 As UInteger A End Enum ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40032: Underlying type 'UInteger' of Enum is not CLS-compliant. Public Enum E1 As UInteger ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_TypeNotCLSCompliant1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(False)> Public Class Bad1 End Class Public Class Bad2 End Class Public Class BadGeneric(Of T, U) End Class <CLSCompliant(True)> Public Class Good End Class <CLSCompliant(True)> Public Class GoodGeneric(Of T, U) End Class <CLSCompliant(True)> Public Class Test ' Reported within compliant generic types. Public x1 As GoodGeneric(Of Good, Good) ' Fine Public x2 As GoodGeneric(Of Good, Bad1) Public x3 As GoodGeneric(Of Bad1, Good) Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported ' Reported within non-compliant generic types. Public Property y1 As BadGeneric(Of Good, Good) Public Property y2 As BadGeneric(Of Good, Bad1) Public Property y3 As BadGeneric(Of Bad1, Good) Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good)) Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40041: Type 'Bad1' is not CLS-compliant. Public x2 As GoodGeneric(Of Good, Bad1) ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public x3 As GoodGeneric(Of Bad1, Good) ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported ~~ BC40041: Type 'Bad2' is not CLS-compliant. Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported ~~ BC40027: Return type of function 'y1' is not CLS-compliant. Public Property y1 As BadGeneric(Of Good, Good) ~~ BC40027: Return type of function 'y2' is not CLS-compliant. Public Property y2 As BadGeneric(Of Good, Bad1) ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public Property y2 As BadGeneric(Of Good, Bad1) ~~ BC40027: Return type of function 'y3' is not CLS-compliant. Public Property y3 As BadGeneric(Of Bad1, Good) ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public Property y3 As BadGeneric(Of Bad1, Good) ~~ BC40027: Return type of function 'y4' is not CLS-compliant. Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported ~~ BC40041: Type 'Bad2' is not CLS-compliant. Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good)) ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good)) ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels ~~ BC40041: Type 'Bad1' is not CLS-compliant. Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels ~~ BC40041: Type 'BadGeneric(Of Bad1, Good)' is not CLS-compliant. Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels ~~ BC40041: Type 'BadGeneric(Of Bad1, Good)' is not CLS-compliant. Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_RootNamespaceNotCLSCompliant1() Dim source1 = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(False)> ]]> </file> </compilation> ' Nothing reported since the namespace inherits CLSCompliant(False) from the assembly. CreateCompilationWithMscorlib40(source1, options:=TestOptions.ReleaseDll.WithRootNamespace("_A")).AssertNoDiagnostics() Dim source2 = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> ]]> </file> </compilation> CreateCompilationWithMscorlib40(source2, options:=TestOptions.ReleaseDll.WithRootNamespace("_A")).AssertTheseDiagnostics(<errors><![CDATA[ BC40038: Root namespace '_A' is not CLS-compliant. ]]></errors>) Dim source3 = <compilation> <file name="a.vb"> <![CDATA[ Public Class Test End Class ]]> </file> </compilation> Dim moduleRef = CreateCompilationWithMscorlib40(source3, options:=TestOptions.ReleaseModule).EmitToImageReference() CreateCompilationWithMscorlib40AndReferences(source2, {moduleRef}, options:=TestOptions.ReleaseDll.WithRootNamespace("_A").WithConcurrentBuild(False)).AssertTheseDiagnostics(<errors><![CDATA[ BC40038: Root namespace '_A' is not CLS-compliant. ]]></errors>) Dim source4 = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Module: CLSCompliant(True)> ]]> </file> </compilation> CreateCompilationWithMscorlib40AndReferences(source4, {moduleRef}, options:=TestOptions.ReleaseModule.WithRootNamespace("_A").WithConcurrentBuild(True)).AssertTheseDiagnostics(<errors><![CDATA[ BC40038: Root namespace '_A' is not CLS-compliant. ]]></errors>) CreateCompilationWithMscorlib40AndReferences(source2, {moduleRef}, options:=TestOptions.ReleaseModule.WithRootNamespace("_A")).AssertTheseDiagnostics() End Sub <Fact> Public Sub WRN_RootNamespaceNotCLSCompliant2() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> ]]> </file> </compilation> CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("_A.B.C")).AssertTheseDiagnostics(<errors><![CDATA[ BC40039: Name '_A' in the root namespace '_A.B.C' is not CLS-compliant. ]]></errors>) CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("A._B.C")).AssertTheseDiagnostics(<errors><![CDATA[ BC40039: Name '_B' in the root namespace 'A._B.C' is not CLS-compliant. ]]></errors>) CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("A.B._C")).AssertTheseDiagnostics(<errors><![CDATA[ BC40039: Name '_C' in the root namespace 'A.B._C' is not CLS-compliant. ]]></errors>) CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("_A.B._C")).AssertTheseDiagnostics(<errors><![CDATA[ BC40039: Name '_A' in the root namespace '_A.B._C' is not CLS-compliant. BC40039: Name '_C' in the root namespace '_A.B._C' is not CLS-compliant. ]]></errors>) End Sub <Fact> Public Sub WRN_OptionalValueNotCLSCompliant1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public Sub M(Optional x00 As Object = SByte.MaxValue, Optional x01 As Object = Byte.MaxValue, Optional x02 As Object = Short.MaxValue, Optional x03 As Object = UShort.MaxValue, Optional x04 As Object = Integer.MaxValue, Optional x05 As Object = UInteger.MaxValue, Optional x06 As Object = Long.MaxValue, Optional x07 As Object = ULong.MaxValue, Optional x08 As Object = Char.MaxValue, Optional x09 As Object = True, Optional x10 As Object = Single.MaxValue, Optional x11 As Object = Double.MaxValue, Optional x12 As Object = Decimal.MaxValue, Optional x13 As Object = "ABC", Optional x14 As Object = #1/1/2001#) End Sub End Class ]]> </file> </compilation> ' As in dev11, this only applies to int8, uint16, uint32, and uint64 CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40042: Type of optional value for optional parameter 'x00' is not CLS-compliant. Public Sub M(Optional x00 As Object = SByte.MaxValue, ~~~ BC40042: Type of optional value for optional parameter 'x03' is not CLS-compliant. Optional x03 As Object = UShort.MaxValue, ~~~ BC40042: Type of optional value for optional parameter 'x05' is not CLS-compliant. Optional x05 As Object = UInteger.MaxValue, ~~~ BC40042: Type of optional value for optional parameter 'x07' is not CLS-compliant. Optional x07 As Object = ULong.MaxValue, ~~~ ]]></errors>) End Sub <Fact> Public Sub WRN_OptionalValueNotCLSCompliant1_ParameterTypeNonCompliant() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public Sub M(Optional x00 As SByte = SByte.MaxValue) End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40028: Type of parameter 'x00' is not CLS-compliant. Public Sub M(Optional x00 As SByte = SByte.MaxValue) ~~~ ]]></errors>) End Sub <Fact> Public Sub WRN_CLSAttrInvalidOnGetSet_True() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(True)> Public Class C <CLSCompliant(False)> Public Property P1 As UInteger <CLSCompliant(True)> Get Return 0 End Get <CLSCompliant(True)> Set(value As UInteger) End Set End Property <CLSCompliant(False)> Public ReadOnly Property P2 As UInteger <CLSCompliant(True)> Get Return 0 End Get End Property <CLSCompliant(False)> Public WriteOnly Property P3 As UInteger <CLSCompliant(True)> Set(value As UInteger) End Set End Property End Class ]]> </file> </compilation> ' NOTE: No warnings about non-compliant type UInteger. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'. <CLSCompliant(True)> ~~~~~~~~~~~~~~~~~~ BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'. <CLSCompliant(True)> ~~~~~~~~~~~~~~~~~~ BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'. <CLSCompliant(True)> ~~~~~~~~~~~~~~~~~~ BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'. <CLSCompliant(True)> ~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub WRN_CLSAttrInvalidOnGetSet_False() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(True)> Public Class C <CLSCompliant(True)> Public Property P1 As UInteger <CLSCompliant(False)> Get Return 0 End Get <CLSCompliant(False)> Set(value As UInteger) End Set End Property <CLSCompliant(True)> Public ReadOnly Property P2 As UInteger <CLSCompliant(False)> Get Return 0 End Get End Property <CLSCompliant(True)> Public WriteOnly Property P3 As UInteger <CLSCompliant(False)> Set(value As UInteger) End Set End Property End Class ]]> </file> </compilation> ' NOTE: See warnings about non-compliant type UInteger. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40027: Return type of function 'P1' is not CLS-compliant. Public Property P1 As UInteger ~~ BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'. <CLSCompliant(False)> ~~~~~~~~~~~~~~~~~~~ BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'. <CLSCompliant(False)> ~~~~~~~~~~~~~~~~~~~ BC40027: Return type of function 'P2' is not CLS-compliant. Public ReadOnly Property P2 As UInteger ~~ BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'. <CLSCompliant(False)> ~~~~~~~~~~~~~~~~~~~ BC40027: Return type of function 'P3' is not CLS-compliant. Public WriteOnly Property P3 As UInteger ~~ BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'. <CLSCompliant(False)> ~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub WRN_CLSEventMethodInNonCLSType3() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(False)> Public Class C Public Custom Event E1 As Action(Of UInteger) <CLSCompliant(True)> AddHandler(value As Action(Of UInteger)) End AddHandler <CLSCompliant(True)> RemoveHandler(value As Action(Of UInteger)) End RemoveHandler <CLSCompliant(True)> RaiseEvent() End RaiseEvent End Event <CLSCompliant(False)> Public Custom Event E2 As Action(Of UInteger) <CLSCompliant(True)> AddHandler(value As Action(Of UInteger)) End AddHandler <CLSCompliant(True)> RemoveHandler(value As Action(Of UInteger)) End RemoveHandler <CLSCompliant(True)> RaiseEvent() End RaiseEvent End Event End Class ]]> </file> </compilation> ' NOTE: No warnings about non-compliant type UInteger. ' NOTE: No warnings about RaiseEvent accessors. ' NOTE: CLSCompliant(False) on event doesn't suppress warnings. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40053: 'AddHandler' method for event 'E1' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant. <CLSCompliant(True)> ~~~~~~~~~~~~~~~~~~ BC40053: 'RemoveHandler' method for event 'E1' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant. <CLSCompliant(True)> ~~~~~~~~~~~~~~~~~~ BC40053: 'AddHandler' method for event 'E2' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant. <CLSCompliant(True)> ~~~~~~~~~~~~~~~~~~ BC40053: 'RemoveHandler' method for event 'E2' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant. <CLSCompliant(True)> ~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub EventAccessors() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <CLSCompliant(True)> Public Class C <CLSCompliant(False)> Public Custom Event E1 As Action(Of UInteger) <CLSCompliant(True)> AddHandler(value As Action(Of UInteger)) End AddHandler <CLSCompliant(True)> RemoveHandler(value As Action(Of UInteger)) End RemoveHandler <CLSCompliant(True)> RaiseEvent() End RaiseEvent End Event <CLSCompliant(True)> Public Custom Event E2 As Action(Of UInteger) <CLSCompliant(False)> AddHandler(value As Action(Of UInteger)) End AddHandler <CLSCompliant(False)> RemoveHandler(value As Action(Of UInteger)) End RemoveHandler <CLSCompliant(False)> RaiseEvent() End RaiseEvent End Event End Class ]]> </file> </compilation> ' NOTE: As in dev11, we do not warn that we are ignoring CLSCompliantAttribute on event accessors. ' NOTE: See warning about non-compliant type UInteger only for E2. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40041: Type 'UInteger' is not CLS-compliant. Public Custom Event E2 As Action(Of UInteger) ~~ ]]></errors>) End Sub <Fact> Public Sub WRN_EventDelegateTypeNotCLSCompliant2() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Namespace Q <CLSCompliant(False)> Public Delegate Sub Bad() End Namespace <CLSCompliant(True)> Public Class C Public Custom Event E1 As Q.Bad AddHandler(value As Q.Bad) End AddHandler RemoveHandler(value As Q.Bad) End RemoveHandler RaiseEvent() End RaiseEvent End Event Public Event E2 As Q.Bad Public Event E3(x As UInteger) <CLSCompliant(False)> Public Custom Event E4 As Q.Bad AddHandler(value As Q.Bad) End AddHandler RemoveHandler(value As Q.Bad) End RemoveHandler RaiseEvent() End RaiseEvent End Event <CLSCompliant(False)> Public Event E5 As Q.Bad <CLSCompliant(False)> Public Event E6(x As UInteger) End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40050: Delegate type 'Bad' of event 'E1' is not CLS-compliant. Public Custom Event E1 As Q.Bad ~~ BC40050: Delegate type 'Bad' of event 'E2' is not CLS-compliant. Public Event E2 As Q.Bad ~~ BC40028: Type of parameter 'x' is not CLS-compliant. Public Event E3(x As UInteger) ~ ]]></errors>) End Sub <Fact> Public Sub TopLevelMethod_NoAssemblyAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Public Sub M() End Sub ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC30001: Statement is not valid in a namespace. Public Sub M() ~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub TopLevelMethod_AttributeTrue() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Sub M() End Sub ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC30001: Statement is not valid in a namespace. Public Sub M() ~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub TopLevelMethod_AttributeFalse() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Sub M() End Sub ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC30001: Statement is not valid in a namespace. Public Sub M() ~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub NonCompliantInaccessible() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Private Function M(b As Bad) As Bad Return b End Function Private Property P(b As Bad) As Bad Get Return b End Get Set(value As Bad) End Set End Property End Class <CLSCompliant(False)> Public Class Bad End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub NonCompliantAbstractInNonCompliantType() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> <CLSCompliant(False)> Public MustInherit Class Bad Public MustOverride Function M(b As Bad) As Bad End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub SpecialTypes() Dim sourceTemplate = <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public Sub M(p As {0}) End Sub End Class ]]>.Value.Replace(vbCr, vbCrLf) Dim helper = CreateCompilationWithMscorlib40({""}, Nothing) Dim integerType = helper.GetSpecialType(SpecialType.System_Int32) For Each st As SpecialType In [Enum].GetValues(GetType(SpecialType)) Select Case (st) Case SpecialType.None, SpecialType.System_Void, SpecialType.System_Runtime_CompilerServices_IsVolatile Continue For End Select Dim type = helper.GetSpecialType(st) If type.Arity > 0 Then type = type.Construct(ArrayBuilder(Of TypeSymbol).GetInstance(type.Arity, integerType).ToImmutableAndFree()) End If Dim qualifiedName = type.ToTestDisplayString() Dim source = String.Format(sourceTemplate, qualifiedName) Dim comp = CreateCompilationWithMscorlib40({source}, Nothing) Select Case (st) Case SpecialType.System_SByte, SpecialType.System_UInt16, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UIntPtr, SpecialType.System_TypedReference Assert.Equal(ERRID.WRN_ParamNotCLSCompliant1, DirectCast(comp.GetDeclarationDiagnostics().Single().Code, ERRID)) End Select Next End Sub <WorkItem(697178, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697178")> <Fact> Public Sub ConstructedSpecialTypes() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic <Assembly: CLSCompliant(True)> Public Class C Public Sub M(p As IEnumerable(Of UInteger)) End Sub End Class ]]> </file> </compilation> ' Native C# misses this diagnostic CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40041: Type 'UInteger' is not CLS-compliant. Public Sub M(p As IEnumerable(Of UInteger)) ~ ]]></errors>) End Sub <Fact> Public Sub MissingAttributeType() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> <Missing> Public Class C End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Missing' is not defined. <Missing> ~~~~~~~ ]]></errors>) End Sub <WorkItem(709317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709317")> <Fact> Public Sub Repro709317() Dim libSource = <compilation name="Lib"> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C End Class ]]> </file> </compilation> Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class D Public Function M() As C Return Nothing End Function End Class ]]> </file> </compilation> Dim libRef = CreateCompilationWithMscorlib40(libSource).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40AndReferences(source, {libRef}) Dim tree = comp.SyntaxTrees.Single() comp.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, tree) End Sub <WorkItem(709317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709317")> <Fact> Public Sub FilterTree() Dim sourceTemplate = <![CDATA[ Imports System Namespace N{0} <CLSCompliant(False)> Public Class NonCompliant End Class <CLSCompliant(False)> Public Interface INonCompliant End Interface <CLSCompliant(True)> Public Class Compliant Inherits NonCompliant Implements INonCompliant Public Function M(Of T As NonCompliant)(n As NonCompliant) Throw New Exception End Function Public F As NonCompliant Public Property P As NonCompliant End Class End Namespace ]]>.Value.Replace(vbCr, vbCrLf) Dim tree1 = VisualBasicSyntaxTree.ParseText(String.Format(sourceTemplate, 1), path:="a.vb") Dim tree2 = VisualBasicSyntaxTree.ParseText(String.Format(sourceTemplate, 2), path:="b.vb") Dim comp = CreateCompilationWithMscorlib40({tree1, tree2}, options:=TestOptions.ReleaseDll) ' Two copies of each diagnostic - one from each file. comp.AssertTheseDiagnostics(<errors><![CDATA[ BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant. Public Class Compliant ~~~~~~~~~ BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant. Public Function M(Of T As NonCompliant)(n As NonCompliant) ~ BC40028: Type of parameter 'n' is not CLS-compliant. Public Function M(Of T As NonCompliant)(n As NonCompliant) ~ BC40025: Type of member 'F' is not CLS-compliant. Public F As NonCompliant ~ BC40027: Return type of function 'P' is not CLS-compliant. Public Property P As NonCompliant ~ BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant. Public Class Compliant ~~~~~~~~~ BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant. Public Function M(Of T As NonCompliant)(n As NonCompliant) ~ BC40028: Type of parameter 'n' is not CLS-compliant. Public Function M(Of T As NonCompliant)(n As NonCompliant) ~ BC40025: Type of member 'F' is not CLS-compliant. Public F As NonCompliant ~ BC40027: Return type of function 'P' is not CLS-compliant. Public Property P As NonCompliant ~ ]]></errors>) CompilationUtils.AssertTheseDiagnostics(comp.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, tree1, filterSpanWithinTree:=Nothing, includeEarlierStages:=False), <errors><![CDATA[ BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant. Public Class Compliant ~~~~~~~~~ BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant. Public Function M(Of T As NonCompliant)(n As NonCompliant) ~ BC40028: Type of parameter 'n' is not CLS-compliant. Public Function M(Of T As NonCompliant)(n As NonCompliant) ~ BC40025: Type of member 'F' is not CLS-compliant. Public F As NonCompliant ~ BC40027: Return type of function 'P' is not CLS-compliant. Public Property P As NonCompliant ~ ]]></errors>) End Sub <WorkItem(718503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718503")> <Fact> Public Sub ErrorTypeAccessibility() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Implements IError End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'IError' is not defined. Implements IError ~~~~~~ ]]></errors>) End Sub ' Make sure nothing blows up when a protected symbol has no containing type. <Fact> Public Sub ProtectedTopLevelType() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Protected Class C Public F As UInteger End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC31047: Protected types can only be declared inside of a class. Protected Class C ~ ]]></errors>) End Sub <Fact> Public Sub ProtectedMemberOfSealedType() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public NotInheritable Class C Protected F As UInteger ' No warning, since not accessible outside assembly. End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub InheritedCompliance1() Dim libSource = <compilation name="Lib"> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(False)> <CLSCompliant(True)> Public Class Base End Class Public Class Derived Inherits Base End Class ]]> </file> </compilation> Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public B as Base Public D as Derived End Class ]]> </file> </compilation> ' NOTE: As in dev11, we ignore the fact that Derived inherits CLSCompliant(True) from Base. Dim libRef = CreateCompilationWithMscorlib40(libSource).EmitToImageReference() CreateCompilationWithMscorlib40AndReferences(source, {libRef}).AssertTheseDiagnostics(<errors><![CDATA[ BC40025: Type of member 'D' is not CLS-compliant. Public D as Derived ~ ]]></errors>) End Sub <Fact> Public Sub InheritedCompliance2() Dim il = <![CDATA[.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly a { .hash algorithm 0x00008004 .ver 0:0:0:0 .custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(true)} } .module a.dll .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(false)} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit Derived extends Base { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } }]]> Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public B as Base Public D as Derived End Class ]]> </file> </compilation> ' NOTE: As in dev11, we consider the fact that Derived inherits CLSCompliant(False) from Base ' (since it is not from the current assembly). Dim libRef = CompileIL(il.Value, prependDefaultHeader:=False) CreateCompilationWithMscorlib40AndReferences(source, {libRef}).AssertTheseDiagnostics(<errors><![CDATA[ BC40025: Type of member 'B' is not CLS-compliant. Public B as Base ~ BC40025: Type of member 'D' is not CLS-compliant. Public D as Derived ~ ]]></errors>) End Sub <Fact> Public Sub AllAttributeConstructorsRequireArrays() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class MyAttribute Inherits Attribute Public Sub New(a As Integer()) End Sub End Class ]]> </file> </compilation> ' C# would warn. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub ApplyAttributeWithArrayArgument() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class ObjectAttribute Inherits Attribute Public Sub New(o As Object) End Sub End Class Public Class ArrayAttribute Inherits Attribute Public Sub New(o As Integer()) End Sub End Class Public Class ParamsAttribute Inherits Attribute Public Sub New(ParamArray o As Integer()) End Sub End Class <[Object]({1})> <Array({1})> <Params(1)> Public Class C End Class ]]> </file> </compilation> ' C# would warn. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub ApplyAttributeWithNonCompliantArgument() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class ObjectAttribute Inherits Attribute Public Sub New(o As Object) End Sub End Class <[Object](1ui)> Public Class C End Class ]]> </file> </compilation> ' C# would warn. CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub Overloading_ArrayRank() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class Compliant Public Sub M1(x As Integer()) End Sub Public Sub M1(x As Integer(,)) 'BC40035 End Sub Public Sub M2(x As Integer(,,)) End Sub Public Sub M2(x As Integer(,)) 'BC40035 End Sub Public Sub M3(x As Integer()) End Sub Private Sub M3(x As Integer(,)) ' Fine, since inaccessible. End Sub Public Sub M4(x As Integer()) End Sub <CLSCompliant(False)> Private Sub M4(x As Integer(,)) ' Fine, since flagged. End Sub End Class Friend Class Internal Public Sub M1(x As Integer()) End Sub Public Sub M1(x As Integer(,)) ' Fine, since inaccessible. End Sub End Class <CLSCompliant(False)> Public Class NonCompliant Public Sub M1(x As Integer()) End Sub Public Sub M1(x As Integer(,)) ' Fine, since tagged. End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40035: 'Public Sub M1(x As Integer(*,*))' is not CLS-compliant because it overloads 'Public Sub M1(x As Integer())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M1(x As Integer(,)) 'BC40035 ~~ BC40035: 'Public Sub M2(x As Integer(*,*))' is not CLS-compliant because it overloads 'Public Sub M2(x As Integer(*,*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M2(x As Integer(,)) 'BC40035 ~~ ]]></errors>) End Sub <Fact> Public Sub Overloading_RefKind() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(False)> Public Class Compliant Public Sub M1(x As Integer()) End Sub Public Sub M1(ByRef x As Integer()) 'BC30345 End Sub End Class ]]> </file> </compilation> ' NOTE: Illegal, even without compliance checking. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC30345: 'Public Sub M1(x As Integer())' and 'Public Sub M1(ByRef x As Integer())' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. Public Sub M1(x As Integer()) ~~ ]]></errors>) End Sub <Fact> Public Sub Overloading_ArrayOfArrays() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class Compliant Public Sub M1(x As Long()()) End Sub Public Sub M1(x As Char()()) 'BC40035 End Sub Public Sub M2(x As Integer()()()) End Sub Public Sub M2(x As Integer()()) 'BC40035 End Sub Public Sub M3(x As Integer()()) End Sub Public Sub M3(x As Integer()) 'Fine (C# warns) End Sub Public Sub M4(x As Integer(,)(,)) End Sub Public Sub M4(x As Integer()(,)) 'BC40035 End Sub Public Sub M5(x As Integer(,)(,)) End Sub Public Sub M5(x As Integer(,)()) 'BC40035 End Sub Public Sub M6(x As Long()()) End Sub Private Sub M6(x As Char()()) ' Fine, since inaccessible. End Sub Public Sub M7(x As Long()()) End Sub <CLSCompliant(False)> Public Sub M7(x As Char()()) ' Fine, since tagged (dev11 reports BC40035) End Sub End Class Friend Class Internal Public Sub M1(x As Long()()) End Sub Public Sub M1(x As Char()()) ' Fine, since inaccessible. End Sub End Class <CLSCompliant(False)> Public Class NonCompliant Public Sub M1(x As Long()()) End Sub Public Sub M1(x As Char()()) ' Fine, since tagged. End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40035: 'Public Sub M1(x As Char()())' is not CLS-compliant because it overloads 'Public Sub M1(x As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M1(x As Char()()) 'BC40035 ~~ BC40035: 'Public Sub M2(x As Integer()())' is not CLS-compliant because it overloads 'Public Sub M2(x As Integer()()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M2(x As Integer()()) 'BC40035 ~~ BC40035: 'Public Sub M4(x As Integer()(*,*))' is not CLS-compliant because it overloads 'Public Sub M4(x As Integer(*,*)(*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M4(x As Integer()(,)) 'BC40035 ~~ BC40035: 'Public Sub M5(x As Integer(*,*)())' is not CLS-compliant because it overloads 'Public Sub M5(x As Integer(*,*)(*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M5(x As Integer(,)()) 'BC40035 ~~ ]]></errors>) End Sub <Fact> Public Sub Overloading_Properties() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class Compliant Public Property P1(x As Long()()) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P1(x As Char()()) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P2(x As String()) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P2(x As String(,)) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40035: 'Public Property P1(x As Char()()) As Integer' is not CLS-compliant because it overloads 'Public Property P1(x As Long()()) As Integer' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Property P1(x As Char()()) As Integer ~~ BC40035: 'Public Property P2(x As String(*,*)) As Integer' is not CLS-compliant because it overloads 'Public Property P2(x As String()) As Integer' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Property P2(x As String(,)) As Integer ~~ ]]></errors>) End Sub <Fact> Public Sub Overloading_MethodKinds() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public Sub New(p As Long()()) End Sub Public Sub New(p As Char()()) End Sub Public Shared Widening Operator CType(p As Long()) As C Return Nothing End Operator Public Shared Widening Operator CType(p As Long(,)) As C ' Not reported by dev11. Return Nothing End Operator Public Shared Narrowing Operator CType(p As String(,,)) As C Return Nothing End Operator Public Shared Narrowing Operator CType(p As String(,)) As C ' Not reported by dev11. Return Nothing End Operator ' Static constructors can't be overloaded ' Destructors can't be overloaded. ' Accessors are tested separately. End Class ]]> </file> </compilation> ' BREAK : Dev11 doesn't report BC40035 for operators. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40035: 'Public Sub New(p As Char()())' is not CLS-compliant because it overloads 'Public Sub New(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub New(p As Char()()) ~~~ BC40035: 'Public Shared Widening Operator CType(p As Long(*,*)) As C' is not CLS-compliant because it overloads 'Public Shared Widening Operator CType(p As Long()) As C' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Shared Widening Operator CType(p As Long(,)) As C ' Not reported by dev11. ~~~~~ BC40035: 'Public Shared Narrowing Operator CType(p As String(*,*)) As C' is not CLS-compliant because it overloads 'Public Shared Narrowing Operator CType(p As String(*,*,*)) As C' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Shared Narrowing Operator CType(p As String(,)) As C ' Not reported by dev11. ~~~~~ ]]></errors>) End Sub <Fact> Public Sub Overloading_Operators() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public Shared Widening Operator CType(p As C) As Integer Return Nothing End Operator Public Shared Widening Operator CType(p As C) As Long Return Nothing End Operator End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub Overloading_TypeParameterArray() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C(Of T) Public Sub M1(t As T()) End Sub Public Sub M1(t As Integer()) End Sub Public Sub M2(Of U)(t As U()) End Sub Public Sub M2(Of U)(t As Integer()) End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertNoDiagnostics() End Sub <Fact> Public Sub Overloading_InterfaceMember() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Interface I Sub M(p As Long()()) End Interface Public Class ImplementWithSameName Implements I Public Sub M(p()() As Long) Implements I.M End Sub Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn) End Sub End Class Public Class ImplementWithOtherName Implements I Public Sub I_M(p()() As Long) Implements I.M End Sub Public Sub M(p()() As String) 'BC40035 (roslyn only) End Sub End Class Public Class Base Implements I Public Sub I_M(p()() As Long) Implements I.M End Sub End Class Public Class Derived1 Inherits Base Implements I Public Sub M(p()() As Boolean) 'BC40035 (roslyn only) End Sub End Class Public Class Derived2 Inherits Base Public Sub M(p()() As Short) 'Mimic (C#) dev11 bug - don't report conflict with interface member. End Sub End Class ]]> </file> </compilation> ' BREAK : Dev11 doesn't report BC40035 for interface members. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40035: 'Public Sub M(p As Char()())' is not CLS-compliant because it overloads 'Public Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn) ~ BC40035: 'Public Sub M(p As Char()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn) ~ BC40035: 'Public Sub M(p As String()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M(p()() As String) 'BC40035 (roslyn only) ~ BC40035: 'Public Sub M(p As Boolean()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Sub M(p()() As Boolean) 'BC40035 (roslyn only) ~ ]]></errors>) End Sub <Fact> Public Sub Overloading_BaseMember() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class Base Public Overridable Sub M(p As Long()()) End Sub Public Overridable WriteOnly Property P(q As Long()()) Set(value) End Set End Property End Class Public Class Derived_Overload Inherits Base Public Overloads Sub M(p As Char()()) End Sub Public Overloads WriteOnly Property P(q As Char()()) Set(value) End Set End Property End Class Public Class Derived_Hide Inherits Base Public Shadows Sub M(p As Long()()) End Sub Public Shadows WriteOnly Property P(q As Long()()) Set(value) End Set End Property End Class Public Class Derived_Override Inherits Base Public Overrides Sub M(p As Long()()) End Sub Public Overrides WriteOnly Property P(q As Long()()) Set(value) End Set End Property End Class Public Class Derived1 Inherits Base End Class Public Class Derived2 Inherits Derived1 Public Overloads Sub M(p As String()()) End Sub Public Overloads WriteOnly Property P(q As String()()) Set(value) End Set End Property End Class ]]> </file> </compilation> ' BREAK : Dev11 doesn't report BC40035 for base type members. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40035: 'Public Overloads Sub M(p As Char()())' is not CLS-compliant because it overloads 'Public Overridable Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Overloads Sub M(p As Char()()) ~ BC40035: 'Public Overloads WriteOnly Property P(q As Char()()) As Object' is not CLS-compliant because it overloads 'Public Overridable WriteOnly Property P(q As Long()()) As Object' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Overloads WriteOnly Property P(q As Char()()) ~ BC40035: 'Public Overloads Sub M(p As String()())' is not CLS-compliant because it overloads 'Public Overridable Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Overloads Sub M(p As String()()) ~ BC40035: 'Public Overloads WriteOnly Property P(q As String()()) As Object' is not CLS-compliant because it overloads 'Public Overridable WriteOnly Property P(q As Long()()) As Object' which differs from it only by array of array parameter types or by the rank of the array parameter types. Public Overloads WriteOnly Property P(q As String()()) ~ ]]></errors>) End Sub <Fact> Public Sub WithEventsWarning() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public WithEvents F As Bad End Class <CLSCompliant(False)> Public Class Bad End Class ]]> </file> </compilation> ' Make sure we don't produce a bunch of spurious warnings for synthesized members. CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40027: Return type of function 'F' is not CLS-compliant. Public WithEvents F As Bad ~ ]]></errors>) End Sub <WorkItem(749432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749432")> <Fact> Public Sub InvalidAttributeArgument() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Public Module VBCoreHelperFunctionality <CLSCompliant((New With {.anonymousField = False}).anonymousField)> Public Function Len(ByVal Expression As SByte) As Integer Return (New With {.anonymousField = 1}).anonymousField End Function <CLSCompliant((New With {.anonymousField = False}).anonymousField)> Public Function Len(ByVal Expression As UInt16) As Integer Return (New With {.anonymousField = 2}).anonymousField End Function End Module ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).AssertTheseDiagnostics(<errors><![CDATA[ BC30059: Constant expression is required. <CLSCompliant((New With {.anonymousField = False}).anonymousField)> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. <CLSCompliant((New With {.anonymousField = False}).anonymousField)> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(749352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749352")> <Fact> Public Sub Repro749352() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Namespace ClsCompClass001f <CLSCompliant(False)> Public Class ContainerClass 'COMPILEWARNING: BC40030, "Scen6" <CLSCompliant(True)> Public Event Scen6(ByVal x As Integer) End Class End Namespace ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[ BC40030: event 'Public Event Scen6(x As Integer)' cannot be marked CLS-compliant because its containing type 'ContainerClass' is not CLS-compliant. Public Event Scen6(ByVal x As Integer) ~~~~~ ]]></errors>) End Sub <Fact, WorkItem(1026453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1026453")> Public Sub Bug1026453() Dim source1 = <compilation> <file name="a.vb"> <![CDATA[ Namespace N1 Public Class A End Class End Namespace ]]> </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1, TestOptions.ReleaseModule) Dim source2 = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> <Module: CLSCompliant(True)> Namespace N1 Public Class B End Class End Namespace ]]> </file> </compilation> Dim comp2 = CreateCompilationWithMscorlib40AndReferences(source2, {comp1.EmitToImageReference()}, TestOptions.ReleaseDll.WithConcurrentBuild(False)) comp2.AssertNoDiagnostics() comp2.WithOptions(TestOptions.ReleaseDll.WithConcurrentBuild(True)).AssertNoDiagnostics() Dim comp3 = comp2.WithOptions(TestOptions.ReleaseModule.WithConcurrentBuild(False)) comp3.AssertNoDiagnostics() comp3.WithOptions(TestOptions.ReleaseModule.WithConcurrentBuild(True)).AssertNoDiagnostics() End Sub <Fact, WorkItem(9719, "https://github.com/dotnet/roslyn/issues/9719")> Public Sub Bug9719() ' repro was simpler than what's on the github issue - before any fixes, the below snippit triggered the crash Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: CLSCompliant(True)> Public Class C Public Sub Problem(item As DummyModule) End Sub End Class Public Module DummyModule End Module ]]> </file> </compilation> CreateCompilationWithMscorlib45AndVBRuntime(source).AssertTheseDiagnostics(<errors><![CDATA[ BC30371: Module 'DummyModule' cannot be used as a type. Public Sub Problem(item As DummyModule) ~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub TupleDefersClsComplianceToUnderlyingType() Dim libCompliant_vb = " Namespace System <CLSCompliant(True)> Public Structure ValueTuple(Of T1, T2) Public Sub New(item1 As T1, item2 As T2) End Sub End Structure End Namespace " Dim libNotCompliant_vb = " Namespace System <CLSCompliant(False)> Public Structure ValueTuple(Of T1, T2) Public Sub New(item1 As T1, item2 As T2) End Sub End Structure End Namespace " Dim source = " Imports System <assembly:CLSCompliant(true)> Public Class C Public Function Method() As (Integer, Integer) Throw New Exception() End Function Public Function Method2() As (Bad, Bad) Throw New Exception() End Function End Class <CLSCompliant(false)> Public Class Bad End Class " Dim libCompliant = CreateCompilationWithMscorlib40({libCompliant_vb}, options:=TestOptions.ReleaseDll).EmitToImageReference() Dim compCompliant = CreateCompilationWithMscorlib40({source}, {libCompliant}, TestOptions.ReleaseDll) compCompliant.AssertTheseDiagnostics( <errors> BC40041: Type 'Bad' is not CLS-compliant. Public Function Method2() As (Bad, Bad) ~~~~~~~ BC40041: Type 'Bad' is not CLS-compliant. Public Function Method2() As (Bad, Bad) ~~~~~~~ </errors>) Dim libNotCompliant = CreateCompilationWithMscorlib40({libNotCompliant_vb}, options:=TestOptions.ReleaseDll).EmitToImageReference() Dim compNotCompliant = CreateCompilationWithMscorlib40({source}, {libNotCompliant}, TestOptions.ReleaseDll) compNotCompliant.AssertTheseDiagnostics( <errors> BC40027: Return type of function 'Method' is not CLS-compliant. Public Function Method() As (Integer, Integer) ~~~~~~ BC40027: Return type of function 'Method2' is not CLS-compliant. Public Function Method2() As (Bad, Bad) ~~~~~~~ BC40041: Type 'Bad' is not CLS-compliant. Public Function Method2() As (Bad, Bad) ~~~~~~~ BC40041: Type 'Bad' is not CLS-compliant. Public Function Method2() As (Bad, Bad) ~~~~~~~ </errors>) End Sub End Class End Namespace
Giftednewt/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ClsComplianceTests.vb
Visual Basic
apache-2.0
112,077
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. '----------------------------------------------------------------------------------------------------------- 'Code the generate a dumper class for a given parse tree. Reads the parse tree and outputs 'a dumper utility class. '----------------------------------------------------------------------------------------------------------- Imports System.IO Class WriteDumper Inherits WriteUtils Private _writer As TextWriter 'output is sent here. Public Sub New(parseTree As ParseTree) MyBase.New(parseTree) End Sub ' Write the dumper utility function to the given file. Public Sub WriteDumper(filename As String) _writer = New StreamWriter(filename) Using _writer GenerateFile() End Using End Sub ' Write the whole contents of the file. Private Sub GenerateFile() _writer.WriteLine("' Definition of parse trees dumper.") _writer.WriteLine("' Generated by a tool on {0:g}", DateTime.Now) _writer.WriteLine("' DO NOT HAND EDIT") _writer.WriteLine() GenerateNamespace() End Sub ' Create imports and the namespace declaration around the whole file Private Sub GenerateNamespace() _writer.WriteLine("Imports System.Collections.Generic") _writer.WriteLine("Imports System.IO") _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", _parseTree.NamespaceName) _writer.WriteLine() End If GenerateDumperClass() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If End Sub ' Generate the partial part of the utilities class with the DumpTree function in it. Private Sub GenerateDumperClass() _writer.WriteLine(" Public Partial Class NodeInfo") _writer.WriteLine() ' Create the nested visitor class that does all the real work. GenerateDumpVisitor() _writer.WriteLine(" End Class") End Sub Private Sub GenerateDumpVisitor() ' Write out the first boilerplate part of the visitor _writer.WriteLine(" Private Class Visitor") _writer.WriteLine(" Inherits VisualBasicSyntaxVisitor(Of NodeInfo)") _writer.WriteLine() GenerateDumpVisitorMethods() _writer.WriteLine(" End Class") End Sub ' Generate the Visitor class definition Private Sub GenerateDumpVisitorMethods() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateDumpVisitorMethod(nodeStructure) Next End Sub ' Generate a method in the Visitor class that dumps the given node type. Private Sub GenerateDumpVisitorMethod(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As NodeInfo", VisitorMethodName(nodeStructure), StructureTypeName(nodeStructure)) ' Node, and name of the node structure _writer.WriteLine(" Return New NodeInfo(") _writer.WriteLine(" ""{0}"",", StructureTypeName(nodeStructure)) ' Fields of the node structure Dim fieldList = GetAllFieldsOfStructure(nodeStructure) If fieldList.Count > 0 Then _writer.WriteLine(" { ") For i = 0 To fieldList.Count - 1 GenerateFieldInfo(fieldList(i), i = fieldList.Count - 1) Next _writer.WriteLine(" },") Else _writer.WriteLine(" Nothing,") End If ' Children (including child lists) Dim childList = GetAllChildrenOfStructure(nodeStructure) _writer.WriteLine(" { ") For i = 0 To childList.Count - 1 GenerateChildInfo(childList(i), i = childList.Count - 1) Next _writer.WriteLine(" })") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Write out the code to create info about a simple field; just a primitive Private Sub GenerateFieldInfo(field As ParseNodeField, last As Boolean) _writer.Write(" New NodeInfo.FieldInfo(""{0}"", GetType({1}), node.{0})", FieldPropertyName(field), FieldTypeRef(field)) If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub ' Write out the code to create info about a child or child list Private Sub GenerateChildInfo(child As ParseNodeChild, last As Boolean) If child.IsList Then If child.IsSeparated Then _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SeparatedNodeList, GetType({1}), node.{0}, node.{0}.Separators)", ChildPropertyName(child), BaseTypeReference(child)) Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.NodeList, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SingleNode, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub End Class
ManishJayaswal/roslyn
src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/Util/WriteDumper.vb
Visual Basic
apache-2.0
5,840
' 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.VisualBasic.EndConstructGeneration Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Imports Roslyn.Test.EditorUtilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration Public Class TypeBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterClassStatement() VerifyStatementEndConstructApplied( before:={"Class c1"}, beforeCaret:={0, -1}, after:={"Class c1", "", "End Class"}, afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterModuleStatement() VerifyStatementEndConstructApplied( before:={"Module m1"}, beforeCaret:={0, -1}, after:={"Module m1", "", "End Module"}, afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyForMatchedClass() VerifyStatementEndConstructNotApplied( text:={"Class c1", "End Class"}, caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterInterfaceStatement() VerifyStatementEndConstructApplied( before:={"Interface IFoo"}, beforeCaret:={0, -1}, after:={"Interface IFoo", "", "End Interface"}, afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterStructureStatement() VerifyStatementEndConstructApplied( before:={"Structure Foo"}, beforeCaret:={0, -1}, after:={"Structure Foo", "", "End Structure"}, afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterEnumStatement() VerifyStatementEndConstructApplied( before:={"Enum Foo"}, beforeCaret:={0, -1}, after:={"Enum Foo", "", "End Enum"}, afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyGenericClass() VerifyStatementEndConstructApplied( before:={"NameSpace X", " Class C(of T)"}, beforeCaret:={1, -1}, after:={"NameSpace X", " Class C(of T)", "", " End Class"}, afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyStructInAClass() VerifyStatementEndConstructApplied( before:={"Class C", " Structure s", "End Class"}, beforeCaret:={1, -1}, after:={"Class C", " Structure s", "", " End Structure", "End Class"}, afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyClassInAModule() VerifyStatementEndConstructApplied( before:={"Module M", " Class C", "End Module"}, beforeCaret:={1, -1}, after:={"Module M", " Class C", "", " End Class", "End Module"}, afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyClassDeclaration() VerifyStatementEndConstructApplied( before:={"Partial Friend MustInherit Class C"}, beforeCaret:={0, -1}, after:={"Partial Friend MustInherit Class C", "", "End Class"}, afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyEnumInAClass() VerifyStatementEndConstructApplied( before:={"Class C", " Public Enum e", "End Class"}, beforeCaret:={1, -1}, after:={"Class C", " Public Enum e", "", " End Enum", "End Class"}, afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax() VerifyStatementEndConstructNotApplied( text:={"Class EC", " Sub S", " Class B", " End Sub", "End Class"}, caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax01() VerifyStatementEndConstructNotApplied( text:={"Enum e(Of T)"}, caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax02() VerifyStatementEndConstructNotApplied( text:={"Class C Class"}, caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInheritsDecl() VerifyStatementEndConstructApplied( before:={"Class C : Inherits B"}, beforeCaret:={0, -1}, after:={"Class C : Inherits B", "", "End Class"}, afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInheritsDeclNotApplied() VerifyStatementEndConstructNotApplied( text:={"Class C : Inherits B", "End Class"}, caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyImplementsDecl() VerifyStatementEndConstructApplied( before:={"Class C : Implements IB"}, beforeCaret:={0, -1}, after:={"Class C : Implements IB", "", "End Class"}, afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyImplementsDeclNotApplied() VerifyStatementEndConstructNotApplied( text:={"Class C : Implements IB", "End Class"}, caret:={0, -1}) End Sub End Class End Namespace
jbhensley/roslyn
src/EditorFeatures/VisualBasicTest/EndConstructGeneration/TypeBlockTests.vb
Visual Basic
apache-2.0
8,157
' 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.Diagnostics 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 Partial Friend NotInheritable Class LocalRewriter ''' <summary> ''' Rewrites ForTo loop. ''' </summary> Public Overrides Function VisitForToStatement(node As BoundForToStatement) As BoundNode Dim rewrittenControlVariable = VisitExpressionNode(node.ControlVariable) ' loop with object control variable is a special kind of loop ' its logic is governed by runtime helpers. Dim isObjectLoop = rewrittenControlVariable.Type.IsObjectType Dim rewrittenInitialValue = VisitExpressionNode(node.InitialValue) Dim rewrittenLimit As BoundExpression = VisitExpressionNode(node.LimitValue) Dim rewrittenStep = VisitExpressionNode(node.StepValue) If Not isObjectLoop Then Return FinishNonObjectForLoop(node, rewrittenControlVariable, rewrittenInitialValue, rewrittenLimit, rewrittenStep) Else Debug.Assert(node.OperatorsOpt Is Nothing) Return FinishObjectForLoop(node, rewrittenControlVariable, rewrittenInitialValue, rewrittenLimit, rewrittenStep) End If End Function Private Function FinishNonObjectForLoop(forStatement As BoundForToStatement, rewrittenControlVariable As BoundExpression, rewrittenInitialValue As BoundExpression, rewrittenLimit As BoundExpression, rewrittenStep As BoundExpression) As BoundBlock Dim blockSyntax = DirectCast(forStatement.Syntax, ForBlockSyntax) Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(forStatement) Dim loopResumeTarget As ImmutableArray(Of BoundStatement) = Nothing If generateUnstructuredExceptionHandlingResumeCode Then loopResumeTarget = RegisterUnstructuredExceptionHandlingResumeTarget(blockSyntax, canThrow:=True) End If Dim cacheAssignments = ArrayBuilder(Of BoundExpression).GetInstance() ' need to do this early while constant values are still constants ' (may become sequences that capture initialization later) Dim unconditionalEntry As Boolean = WillDoAtLeastOneIteration(rewrittenInitialValue, rewrittenLimit, rewrittenStep) ' For loop must ensure that loop range and step do not change while iterating so it needs to ' cache non-constant values. ' We do not need to do this for object loops though. Object loop helpers do caching internally. ' NOTE the order of the following initializations is important!!!! ' Values are evaluated before hoisting and it must be done in the order of declaration (value, limit, step). Dim locals = ArrayBuilder(Of LocalSymbol).GetInstance() rewrittenInitialValue = CacheToLocalIfNotConst(_currentMethodOrLambda, rewrittenInitialValue, locals, cacheAssignments, SynthesizedLocalKind.ForInitialValue, blockSyntax) rewrittenLimit = CacheToLocalIfNotConst(_currentMethodOrLambda, rewrittenLimit, locals, cacheAssignments, SynthesizedLocalKind.ForLimit, blockSyntax) rewrittenStep = CacheToLocalIfNotConst(_currentMethodOrLambda, rewrittenStep, locals, cacheAssignments, SynthesizedLocalKind.ForStep, blockSyntax) Dim positiveFlag As SynthesizedLocal = Nothing If forStatement.OperatorsOpt IsNot Nothing Then ' calculate and cache result of a positive check := step >= (step - step). AddPlaceholderReplacement(forStatement.OperatorsOpt.LeftOperandPlaceholder, rewrittenStep) AddPlaceholderReplacement(forStatement.OperatorsOpt.RightOperandPlaceholder, rewrittenStep) Dim subtraction = VisitExpressionNode(forStatement.OperatorsOpt.Subtraction) UpdatePlaceholderReplacement(forStatement.OperatorsOpt.RightOperandPlaceholder, subtraction) Dim greaterThanOrEqual = VisitExpressionNode(forStatement.OperatorsOpt.GreaterThanOrEqual) positiveFlag = New SynthesizedLocal(_currentMethodOrLambda, greaterThanOrEqual.Type, SynthesizedLocalKind.ForDirection, blockSyntax) locals.Add(positiveFlag) cacheAssignments.Add(New BoundAssignmentOperator(forStatement.OperatorsOpt.Syntax, New BoundLocal(forStatement.OperatorsOpt.Syntax, positiveFlag, positiveFlag.Type), greaterThanOrEqual, suppressObjectClone:=True, type:=positiveFlag.Type)) RemovePlaceholderReplacement(forStatement.OperatorsOpt.LeftOperandPlaceholder) RemovePlaceholderReplacement(forStatement.OperatorsOpt.RightOperandPlaceholder) ElseIf rewrittenStep.ConstantValueOpt Is Nothing AndAlso Not rewrittenStep.Type.GetEnumUnderlyingTypeOrSelf.IsSignedIntegralType AndAlso Not rewrittenStep.Type.GetEnumUnderlyingTypeOrSelf.IsUnsignedIntegralType Then Dim stepValue As BoundExpression = rewrittenStep Dim stepHasValue As BoundExpression = Nothing If stepValue.Type.IsNullableType Then stepHasValue = NullableHasValue(stepValue) stepValue = NullableValueOrDefault(stepValue) End If If stepValue.Type.GetEnumUnderlyingTypeOrSelf.IsNumericType Then ' this one is tricky. ' step value is not used directly in the loop condition ' however its value determines the iteration direction ' isUp = IsTrue(step >= step - step) ' which implies that "step = null" ==> "isUp = false" Dim literalUnderlyingType As TypeSymbol = stepValue.Type.GetEnumUnderlyingTypeOrSelf Dim literal As BoundExpression = New BoundLiteral(rewrittenStep.Syntax, ConstantValue.Default(literalUnderlyingType.SpecialType), stepValue.Type) ' Rewrite decimal literal if needed If literalUnderlyingType.IsDecimalType Then literal = RewriteDecimalConstant(literal, literal.ConstantValueOpt, Me._topMethod, Me._diagnostics) End If Dim isUp As BoundExpression = TransformRewrittenBinaryOperator( New BoundBinaryOperator(rewrittenStep.Syntax, BinaryOperatorKind.GreaterThanOrEqual, stepValue, literal, checked:=False, type:=GetSpecialType(SpecialType.System_Boolean))) If stepHasValue IsNot Nothing Then ' null step is considered "not isUp" isUp = MakeBooleanBinaryExpression(isUp.Syntax, BinaryOperatorKind.AndAlso, stepHasValue, isUp) End If positiveFlag = New SynthesizedLocal(_currentMethodOrLambda, isUp.Type, SynthesizedLocalKind.ForDirection, blockSyntax) locals.Add(positiveFlag) cacheAssignments.Add(New BoundAssignmentOperator(isUp.Syntax, New BoundLocal(isUp.Syntax, positiveFlag, positiveFlag.Type), isUp, suppressObjectClone:=True, type:=positiveFlag.Type)) Else ' not numeric control variables are special and should not be handled here. Throw ExceptionUtilities.Unreachable End If End If If cacheAssignments.Count > 0 Then rewrittenInitialValue = New BoundSequence(rewrittenInitialValue.Syntax, ImmutableArray(Of LocalSymbol).Empty, cacheAssignments.ToImmutable(), rewrittenInitialValue, rewrittenInitialValue.Type) End If cacheAssignments.Free() Dim rewrittenInitializer As BoundStatement = New BoundExpressionStatement( rewrittenInitialValue.Syntax, New BoundAssignmentOperator( rewrittenInitialValue.Syntax, rewrittenControlVariable, rewrittenInitialValue, suppressObjectClone:=True, type:=rewrittenInitialValue.Type ) ) If Not loopResumeTarget.IsDefaultOrEmpty Then rewrittenInitializer = New BoundStatementList(rewrittenInitializer.Syntax, loopResumeTarget.Add(rewrittenInitializer)) End If Dim instrument As Boolean = Me.Instrument(forStatement) If instrument Then ' first sequence point to highlight the for statement rewrittenInitializer = _instrumenterOpt.InstrumentForLoopInitialization(forStatement, rewrittenInitializer) End If Dim rewrittenBody = DirectCast(Visit(forStatement.Body), BoundStatement) Dim rewrittenIncrement As BoundStatement = RewriteForLoopIncrement( rewrittenControlVariable, rewrittenStep, forStatement.Checked, forStatement.OperatorsOpt) If generateUnstructuredExceptionHandlingResumeCode Then rewrittenIncrement = RegisterUnstructuredExceptionHandlingResumeTarget(blockSyntax, rewrittenIncrement, canThrow:=True) End If If instrument Then rewrittenIncrement = _instrumenterOpt.InstrumentForLoopIncrement(forStatement, rewrittenIncrement) End If Dim rewrittenCondition = RewriteForLoopCondition(rewrittenControlVariable, rewrittenLimit, rewrittenStep, forStatement.OperatorsOpt, positiveFlag) Dim startLabel = GenerateLabel("start") Dim ifConditionGotoStart As BoundStatement = New BoundConditionalGoto( blockSyntax, rewrittenCondition, True, startLabel) ' For i as Integer = 3 To 6 step 2 ' body ' Next ' ' becomes ' ' { ' ' NOTE: control variable life time is as in Dev10, Dev11 may change this!!!! ' dim i as Integer = 3 '<-- all iterations share same variable (important for closures) ' dim temp1, temp2 ... ' temps if needed for hoisting of Limit/Step/Direction ' ' goto postIncrement; ' start: ' body ' continue: ' i += 2 ' postIncrement: ' if i <= 6 goto start ' exit: ' } 'optimization for a case where limit and initial value are constant and the first 'iteration is definite so we can simply drop through without initial branch Dim postIncrementLabel As GeneratedLabelSymbol = Nothing Dim gotoPostIncrement As BoundStatement = Nothing If Not unconditionalEntry Then 'mark the initial jump as hidden. 'We do not want to associate it with statement before. 'This jump may be a target of another jump (for example if loops are nested) and that will make 'impression of the previous statement being re-executed postIncrementLabel = New GeneratedLabelSymbol("PostIncrement") Dim postIncrement As New BoundLabelStatement(blockSyntax, postIncrementLabel) gotoPostIncrement = New BoundGotoStatement(blockSyntax, postIncrementLabel, Nothing) If instrument Then gotoPostIncrement = SyntheticBoundNodeFactory.HiddenSequencePoint(gotoPostIncrement) End If End If Dim statements = ArrayBuilder(Of BoundStatement).GetInstance() statements.Add(rewrittenInitializer) If gotoPostIncrement IsNot Nothing Then statements.Add(gotoPostIncrement) End If statements.Add(New BoundLabelStatement(blockSyntax, startLabel)) statements.Add(rewrittenBody) statements.Add(New BoundLabelStatement(blockSyntax, forStatement.ContinueLabel)) statements.Add(rewrittenIncrement) If postIncrementLabel IsNot Nothing Then Dim label As BoundStatement = New BoundLabelStatement(blockSyntax, postIncrementLabel) If instrument Then gotoPostIncrement = SyntheticBoundNodeFactory.HiddenSequencePoint(label) End If statements.Add(label) End If If instrument Then ifConditionGotoStart = SyntheticBoundNodeFactory.HiddenSequencePoint(ifConditionGotoStart) End If statements.Add(ifConditionGotoStart) statements.Add(New BoundLabelStatement(blockSyntax, forStatement.ExitLabel)) Dim localSymbol = forStatement.DeclaredOrInferredLocalOpt If localSymbol IsNot Nothing Then locals.Add(localSymbol) End If Return New BoundBlock( blockSyntax, Nothing, locals.ToImmutableAndFree(), statements.ToImmutableAndFree ) End Function Private Shared Function WillDoAtLeastOneIteration(rewrittenInitialValue As BoundExpression, rewrittenLimit As BoundExpression, rewrittenStep As BoundExpression) As Boolean Dim initialConst = rewrittenInitialValue.ConstantValueOpt If initialConst Is Nothing Then Return False End If Dim limitConst = rewrittenLimit.ConstantValueOpt If limitConst Is Nothing Then Return False End If Dim isSteppingDown As Boolean Dim stepConst = rewrittenStep.ConstantValueOpt If stepConst Is Nothing Then If rewrittenStep.Type.GetEnumUnderlyingTypeOrSelf.IsUnsignedIntegralType Then isSteppingDown = False Else Return False End If Else isSteppingDown = stepConst.IsNegativeNumeric End If ' handle unsigned integrals If initialConst.IsUnsigned Then Dim initialValue As ULong = initialConst.UInt64Value Dim limitValue As ULong = limitConst.UInt64Value Return If(isSteppingDown, initialValue >= limitValue, initialValue <= limitValue) End If ' handle remaining (signed) integrals If initialConst.IsIntegral Then Dim initialValue As Long = initialConst.Int64Value Dim limitValue As Long = limitConst.Int64Value Return If(isSteppingDown, initialValue >= limitValue, initialValue <= limitValue) End If ' handle decimals If initialConst.IsDecimal Then Dim initialValue As Decimal = initialConst.DecimalValue Dim limitValue As Decimal = limitConst.DecimalValue Return If(isSteppingDown, initialValue >= limitValue, initialValue <= limitValue) End If ' the rest should be floats Debug.Assert(initialConst.IsFloating) If True Then Dim initialValue As Double = initialConst.DoubleValue Dim limitValue As Double = limitConst.DoubleValue Return If(isSteppingDown, initialValue >= limitValue, initialValue <= limitValue) End If Throw ExceptionUtilities.Unreachable End Function Private Function FinishObjectForLoop(forStatement As BoundForToStatement, rewrittenControlVariable As BoundExpression, rewrittenInitialValue As BoundExpression, rewrittenLimit As BoundExpression, rewrittenStep As BoundExpression) As BoundBlock Dim locals = ArrayBuilder(Of LocalSymbol).GetInstance() Dim blockSyntax = DirectCast(forStatement.Syntax, ForBlockSyntax) Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(forStatement) ' For i as Object = 3 To 6 step 2 ' body ' Next ' ' becomes ==> ' ' { ' Dim loopObj ' mysterious object that holds the loop state ' ' ' helper does internal initialization and tells if we need to do any iterations ' if Not ObjectFlowControl.ForLoopControl.ForLoopInitObj(ctrl, init, limit, step, ref loopObj, ref ctrl) ' goto exit: ' start: ' body ' ' continue: ' ' helper updates loop state and tels if we need to do another iteration. ' if ObjectFlowControl.ForLoopControl.ForNextCheckObj(ctrl, loopObj, ref ctrl) ' GoTo start ' } ' exit: Debug.Assert(Compilation.GetSpecialType(SpecialType.System_Object) Is rewrittenControlVariable.Type) Dim objType = rewrittenControlVariable.Type Dim loopObjLocal = New SynthesizedLocal(Me._currentMethodOrLambda, objType, SynthesizedLocalKind.ForInitialValue, blockSyntax) locals.Add(loopObjLocal) Dim loopObj = New BoundLocal(blockSyntax, loopObjLocal, isLValue:=True, type:=loopObjLocal.Type) ' Create loop initialization and entrance criteria - ' if Not ObjectFlowControl.ForLoopControl.ForLoopInitObj(ctrl, init, limit, step, ref loopObj, ref ctrl) ' goto exit: Dim rewrittenInitCondition As BoundExpression Dim arguments = ImmutableArray.Create( rewrittenControlVariable.MakeRValue(), rewrittenInitialValue, rewrittenLimit, rewrittenStep, loopObj, rewrittenControlVariable) Dim ForLoopInitObj As MethodSymbol = Nothing If TryGetWellknownMember(ForLoopInitObj, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj, blockSyntax) Then ' ForLoopInitObj(ctrl, init, limit, step, ref loopObj, ref ctrl) rewrittenInitCondition = New BoundCall( rewrittenLimit.Syntax, ForLoopInitObj, Nothing, Nothing, arguments, Nothing, Compilation.GetSpecialType(SpecialType.System_Boolean), suppressObjectClone:=True) Else rewrittenInitCondition = New BoundBadExpression(rewrittenLimit.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, arguments, Compilation.GetSpecialType(SpecialType.System_Boolean), hasErrors:=True) End If ' EnC: We need to insert a hidden sequence point to handle function remapping in case ' the containing method is edited while the invoked method is being executed. Debug.Assert(rewrittenInitCondition IsNot Nothing) Dim instrument = Me.Instrument(forStatement) If instrument Then rewrittenInitCondition = _instrumenterOpt.InstrumentObjectForLoopInitCondition(forStatement, rewrittenInitCondition, _currentMethodOrLambda) End If Dim ifNotInitObjExit As BoundStatement = New BoundConditionalGoto( blockSyntax, rewrittenInitCondition, False, forStatement.ExitLabel) If generateUnstructuredExceptionHandlingResumeCode Then ifNotInitObjExit = RegisterUnstructuredExceptionHandlingResumeTarget(blockSyntax, ifNotInitObjExit, canThrow:=True) End If If instrument Then ' first sequence point to highlight the for statement ifNotInitObjExit = _instrumenterOpt.InstrumentForLoopInitialization(forStatement, ifNotInitObjExit) End If '### body Dim rewrittenBody = DirectCast(Visit(forStatement.Body), BoundStatement) ' Create loop condition (ifConditionGotoStart) - ' if ObjectFlowControl.ForLoopControl.ForNextCheckObj(ctrl, loopObj, ref ctrl) ' GoTo start Dim rewrittenLoopCondition As BoundExpression arguments = ImmutableArray.Create( rewrittenControlVariable.MakeRValue(), loopObj.MakeRValue, rewrittenControlVariable) Dim ForNextCheckObj As MethodSymbol = Nothing If TryGetWellknownMember(ForNextCheckObj, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj, blockSyntax) Then ' ForNextCheckObj(ctrl, loopObj, ref ctrl) rewrittenLoopCondition = New BoundCall( rewrittenLimit.Syntax, ForNextCheckObj, Nothing, Nothing, arguments, Nothing, Compilation.GetSpecialType(SpecialType.System_Boolean), suppressObjectClone:=True) Else rewrittenLoopCondition = New BoundBadExpression(rewrittenLimit.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, arguments, Compilation.GetSpecialType(SpecialType.System_Boolean), hasErrors:=True) End If Dim startLabel = GenerateLabel("start") ' EnC: We need to insert a hidden sequence point to handle function remapping in case ' the containing method is edited while the invoked function is being executed. Debug.Assert(rewrittenLoopCondition IsNot Nothing) If instrument Then rewrittenLoopCondition = _instrumenterOpt.InstrumentObjectForLoopCondition(forStatement, rewrittenLoopCondition, _currentMethodOrLambda) End If Dim ifConditionGotoStart As BoundStatement = New BoundConditionalGoto( blockSyntax, rewrittenLoopCondition, True, startLabel) If generateUnstructuredExceptionHandlingResumeCode Then ifConditionGotoStart = RegisterUnstructuredExceptionHandlingResumeTarget(blockSyntax, ifConditionGotoStart, canThrow:=True) End If If instrument Then ifConditionGotoStart = _instrumenterOpt.InstrumentForLoopIncrement(forStatement, ifConditionGotoStart) End If Dim label As BoundStatement = New BoundLabelStatement(blockSyntax, forStatement.ContinueLabel) If instrument Then label = SyntheticBoundNodeFactory.HiddenSequencePoint(label) ifConditionGotoStart = SyntheticBoundNodeFactory.HiddenSequencePoint(ifConditionGotoStart) End If 'Build the rewritten loop Dim statements = ImmutableArray.Create( ifNotInitObjExit, New BoundLabelStatement(blockSyntax, startLabel), rewrittenBody, label, ifConditionGotoStart, New BoundLabelStatement(blockSyntax, forStatement.ExitLabel)) Dim localSymbol = forStatement.DeclaredOrInferredLocalOpt If localSymbol IsNot Nothing Then locals.Add(localSymbol) End If Return New BoundBlock( blockSyntax, Nothing, locals.ToImmutableAndFree(), statements) End Function Private Function RewriteForLoopIncrement(controlVariable As BoundExpression, stepValue As BoundExpression, isChecked As Boolean, operatorsOpt As BoundForToUserDefinedOperators) As BoundStatement Debug.Assert(controlVariable.IsLValue) Dim newValue As BoundExpression If operatorsOpt Is Nothing Then Dim controlVariableUnwrapped = controlVariable ' if control variable happen to be nullable ' unlift the increment by applying Add to the unwrapped step ' and controlVariable. ' since limit and control var are locals, GetValueOrDefault ' should be cheap enough to not bother with hoisting values into locals. Dim hasValues As BoundExpression = Nothing If controlVariable.Type.IsNullableType Then hasValues = MakeBooleanBinaryExpression(controlVariable.Syntax, BinaryOperatorKind.And, NullableHasValue(stepValue), NullableHasValue(controlVariable)) controlVariableUnwrapped = NullableValueOrDefault(controlVariable) stepValue = NullableValueOrDefault(stepValue) End If newValue = TransformRewrittenBinaryOperator( New BoundBinaryOperator(stepValue.Syntax, BinaryOperatorKind.Add, controlVariableUnwrapped.MakeRValue(), stepValue, isChecked, controlVariableUnwrapped.Type)) If controlVariable.Type.IsNullableType Then newValue = MakeTernaryConditionalExpression(newValue.Syntax, hasValues, WrapInNullable(newValue, controlVariable.Type), NullableNull(controlVariable.Syntax, controlVariable.Type)) End If Else ' Generate: controlVariable + stepValue AddPlaceholderReplacement(operatorsOpt.LeftOperandPlaceholder, controlVariable.MakeRValue()) AddPlaceholderReplacement(operatorsOpt.RightOperandPlaceholder, stepValue) newValue = VisitExpressionNode(operatorsOpt.Addition) RemovePlaceholderReplacement(operatorsOpt.LeftOperandPlaceholder) RemovePlaceholderReplacement(operatorsOpt.RightOperandPlaceholder) End If Return New BoundExpressionStatement( stepValue.Syntax, New BoundAssignmentOperator( stepValue.Syntax, controlVariable, newValue, suppressObjectClone:=True, type:=controlVariable.Type ) ) End Function ''' <summary> ''' Negates the value if step is negative ''' </summary> Private Function NegateIfStepNegative(value As BoundExpression, [step] As BoundExpression) As BoundExpression Dim int32Type = [step].Type.ContainingAssembly.GetPrimitiveType(Microsoft.Cci.PrimitiveTypeCode.Int32) Dim bits As Integer Dim typeCode As Microsoft.Cci.PrimitiveTypeCode = [step].Type.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode Select Case typeCode Case Microsoft.Cci.PrimitiveTypeCode.Int8 bits = 7 Case Microsoft.Cci.PrimitiveTypeCode.Int16 bits = 15 Case Microsoft.Cci.PrimitiveTypeCode.Int32 bits = 31 Case Microsoft.Cci.PrimitiveTypeCode.Int64 bits = 63 Case Else Throw ExceptionUtilities.UnexpectedValue(typeCode) End Select Dim shiftConst = New BoundLiteral(value.Syntax, ConstantValue.Create(bits), int32Type) Dim shiftedStep = TransformRewrittenBinaryOperator( New BoundBinaryOperator(value.Syntax, BinaryOperatorKind.RightShift, [step], shiftConst, False, [step].Type)) Return TransformRewrittenBinaryOperator(New BoundBinaryOperator(value.Syntax, BinaryOperatorKind.Xor, shiftedStep, value, False, value.Type)) End Function ''' <summary> ''' Given the control variable, limit and step, produce the loop condition. ''' The principle is simple - ''' if step is negative (stepping "Up") then it is "control >= limit" ''' otherwise it is "control &lt;= limit" ''' ''' It gets more complicated when step is not a constant or not a numeric or ''' involves overloaded comparison/IsTrue operators ''' </summary> Private Function RewriteForLoopCondition(controlVariable As BoundExpression, limit As BoundExpression, stepValue As BoundExpression, operatorsOpt As BoundForToUserDefinedOperators, positiveFlag As SynthesizedLocal) As BoundExpression Debug.Assert(operatorsOpt Is Nothing OrElse positiveFlag IsNot Nothing) If operatorsOpt IsNot Nothing Then ' Generate If(positiveFlag, controlVariable <= limit, controlVariable >= limit) AddPlaceholderReplacement(operatorsOpt.LeftOperandPlaceholder, controlVariable.MakeRValue()) AddPlaceholderReplacement(operatorsOpt.RightOperandPlaceholder, limit) Dim result = MakeTernaryConditionalExpression(operatorsOpt.Syntax, New BoundLocal(operatorsOpt.Syntax, positiveFlag, isLValue:=False, type:=positiveFlag.Type), VisitExpressionNode(operatorsOpt.LessThanOrEqual), VisitExpressionNode(operatorsOpt.GreaterThanOrEqual)) RemovePlaceholderReplacement(operatorsOpt.LeftOperandPlaceholder) RemovePlaceholderReplacement(operatorsOpt.RightOperandPlaceholder) Return result End If Dim booleanType = GetSpecialType(SpecialType.System_Boolean) ' unsigned step is always Up If stepValue.Type.GetEnumUnderlyingTypeOrSelf.IsUnsignedIntegralType Then Return TransformRewrittenBinaryOperator( New BoundBinaryOperator(limit.Syntax, BinaryOperatorKind.LessThanOrEqual, controlVariable.MakeRValue(), limit, checked:=False, type:=booleanType)) End If 'Up/Down for numeric constants is also simple Dim constStep = stepValue.ConstantValueOpt If constStep IsNot Nothing Then Dim comparisonOperator As BinaryOperatorKind If constStep.IsNegativeNumeric Then comparisonOperator = BinaryOperatorKind.GreaterThanOrEqual ElseIf constStep.IsNumeric Then comparisonOperator = BinaryOperatorKind.LessThanOrEqual Else ' it is a constant, but not numeric. Can this happen? Throw ExceptionUtilities.UnexpectedValue(constStep) End If Return TransformRewrittenBinaryOperator( New BoundBinaryOperator(limit.Syntax, comparisonOperator, controlVariable.MakeRValue(), limit, checked:=False, type:=booleanType)) End If ' for signed integral steps not known at compile time ' we do " (val Xor (step >> 31)) <= (limit Xor (step >> 31)) " ' where 31 is actually the size-1 ' TODO: we could hoist (step >> 31) into a temp. Dev10 does not do this. ' Perhaps not worth it since non-const steps are uncommon If stepValue.Type.GetEnumUnderlyingTypeOrSelf.IsSignedIntegralType Then Return TransformRewrittenBinaryOperator( New BoundBinaryOperator(stepValue.Syntax, BinaryOperatorKind.LessThanOrEqual, NegateIfStepNegative(controlVariable.MakeRValue(), stepValue), NegateIfStepNegative(limit, stepValue), checked:=False, type:=booleanType)) End If Dim condition As BoundExpression Dim ctrlLimitHasValue As BoundExpression = Nothing If controlVariable.Type.IsNullableType Then ' if either limit or control variable is null, we exit the loop ctrlLimitHasValue = MakeBooleanBinaryExpression(controlVariable.Syntax, BinaryOperatorKind.And, NullableHasValue(limit), NullableHasValue(controlVariable)) controlVariable = NullableValueOrDefault(controlVariable) limit = NullableValueOrDefault(limit) End If If positiveFlag IsNot Nothing Then 'If (stepValue >= 0.0, ctrl <= limit, ctrl >= limit) Dim lte = TransformRewrittenBinaryOperator( New BoundBinaryOperator(limit.Syntax, BinaryOperatorKind.LessThanOrEqual, controlVariable.MakeRValue(), limit, checked:=False, type:=booleanType)) Dim gte = TransformRewrittenBinaryOperator( New BoundBinaryOperator(limit.Syntax, BinaryOperatorKind.GreaterThanOrEqual, controlVariable.MakeRValue(), limit, checked:=False, type:=booleanType)) Dim isUp As BoundExpression = New BoundLocal(limit.Syntax, positiveFlag, isLValue:=False, type:=positiveFlag.Type) condition = MakeTernaryConditionalExpression(limit.Syntax, isUp, lte, gte) Else ' not numeric control variables are special and should not be handled here. Throw ExceptionUtilities.Unreachable End If If ctrlLimitHasValue IsNot Nothing Then ' check for has values before checking condition condition = MakeBooleanBinaryExpression(condition.Syntax, BinaryOperatorKind.AndAlso, ctrlLimitHasValue, condition) End If Return condition End Function End Class End Namespace
jeffanders/roslyn
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_ForTo.vb
Visual Basic
apache-2.0
40,600
' 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. ' vbc /t:library /vbruntime- D.vb Imports System.Collections.Generic Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices <Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b5826D")> <Assembly: ImportedFromTypeLib("D.dll")> <ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f200D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface ID End Interface
physhi/roslyn
src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/D.vb
Visual Basic
apache-2.0
630
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 'vbc /t:library /vbruntime- MultiModule.vb /addmodule:mod2.netmodule,mod3.netmodule Public Class Class1 Sub Goo() Dim x = {1,2} Dim y = x.Count() End Sub End Class
mmitche/roslyn
src/Compilers/Test/Resources/Core/SymbolsTests/MultiModule/MultiModule.vb
Visual Basic
apache-2.0
329
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Loop" statement. ''' </summary> Friend Class LoopKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword) Dim targetToken = context.TargetToken If context.IsSingleLineStatementContext Then Dim doBlock = targetToken.GetAncestor(Of DoLoopBlockSyntax)() If doBlock Is Nothing OrElse Not doBlock.LoopStatement.IsMissing Then Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End If If doBlock.Kind <> SyntaxKind.SimpleDoLoopBlock Then Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement)) Else Return {New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement), New RecommendedKeyword("Loop Until", VBFeaturesResources.Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition), New RecommendedKeyword("Loop While", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition)} End If End If Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End Function End Class End Namespace
mmitche/roslyn
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/LoopKeywordRecommender.vb
Visual Basic
apache-2.0
2,105
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Cheatlyzer.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property '''<summary> ''' Looks up a localized string similar to cmbValHP2=00 '''cmbValHP1=00 '''cmbValHP0=00 '''cmbValMana2=00 '''cmbKeyHP2=-- '''cmbKeyMana2=-- '''cmbKeyHP1=-- '''cmbKeyMana0=-- '''cmbKeyHP0=-- '''cmbValMana1=00 '''cmbKeyMana1=-- '''cmbValMana0=00 '''checkHealerEnabled=0 '''numericRecastMana2=2000 '''numericRecastMana1=2000 '''numericRecastMana0=2000 '''numericRecastHP2=2000 '''numericRecastHP1=2000 '''numericRecastHP0=2000 '''checkAntiAFKEnabled=0 '''numericAntiAFKMaximum=60 '''numericAntiAFKMinimum=20 '''cmbValManaTrainNearMax=95 '''cmbKeyManaTrain=-- '''checkManaTrainEnabled=0 '''numericRecastManaTr [rest of string was truncated]&quot;;. '''</summary> Friend ReadOnly Property _default() As String Get Return ResourceManager.GetString("_default", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized resource of type System.IO.UnmanagedMemoryStream similar to System.IO.MemoryStream. '''</summary> Friend ReadOnly Property Alarm() As System.IO.UnmanagedMemoryStream Get Return ResourceManager.GetStream("Alarm", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to [Memory] '''; [[[[[[[[[[[[[[[[[[[[[[[[[[[ '''; BEGIN AUTOMATIC UPDATE ZONE '''version=11.01 '''tibiamainname=client '''tibiaclassname=Qt5QWindowOwnDCIcon '''tibiatitle=Tibia '''tibiamainname_updater=tibia '''tibiaclassname_updater=Qt5QWindowIcon '''tibiatitle_updater=Tibia '''adrChatLog_tabStruct=&quot;Qt5Core.dll&quot; + 4555C8 &gt; 8 &gt; 118 '''adrServerList_CollectionStart=&quot;Qt5Core.dll&quot; + 4555C8 &gt; 8 &gt; 168 &gt; 54 &gt; 18 &gt; 2c '''adrSkills_CollectionStart=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 1D8 &gt; 60 &gt; 9c '''adrXPos=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 134 &gt; 24 &gt; [rest of string was truncated]&quot;;. '''</summary> Friend ReadOnly Property config1101() As String Get Return ResourceManager.GetString("config1101", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to [Memory] '''; [[[[[[[[[[[[[[[[[[[[[[[[[[[ '''; BEGIN - MEMORY PATHS '''version=11.02 '''tibiamainname=client '''tibiaclassname=Qt5QWindowOwnDCIcon '''tibiatitle=Tibia '''tibiamainname_updater=tibia '''tibiaclassname_updater=Qt5QWindowIcon '''tibiatitle_updater=Tibia '''adrSelectedItem_height=&quot;Qt5Widgets.dll&quot; + 00401DC4 &gt; 70 &gt; 4 &gt; a8 ''' '''adrGameRect_Width_Double=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 10C &gt; 18 &gt; 4 &gt; 74 &gt; 4 &gt; 88 ''' '''adrChatLog_tabStruct=&quot;Qt5Core.dll&quot; + 4555C8 &gt; 8 &gt; 118 '''SELECTEDCHANNEL_FirstLineText_Unicode=&quot;Qt5Core.dll &quot; [rest of string was truncated]&quot;;. '''</summary> Friend ReadOnly Property config1102() As String Get Return ResourceManager.GetString("config1102", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to [Memory] '''; [[[[[[[[[[[[[[[[[[[[[[[[[[[ '''; BEGIN - MEMORY PATHS '''version=11.03 '''tibiamainname=client '''tibiaclassname=Qt5QWindowOwnDCIcon '''tibiatitle=Tibia '''tibiamainname_updater=tibia '''tibiaclassname_updater=Qt5QWindowIcon '''tibiatitle_updater=Tibia '''adrSelectedItem_height=&quot;Qt5Widgets.dll&quot; + 00401DC4 &gt; 70 &gt; 4 &gt; a8 ''' '''adrGameRect_Width_Double=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 10C &gt; 18 &gt; 4 &gt; 74 &gt; 4 &gt; 88 ''' '''adrChatLog_tabStruct=&quot;Qt5Core.dll&quot; + 4555C8 &gt; 8 &gt; 118 '''SELECTEDCHANNEL_FirstLineText_Unicode=&quot;Qt5Core.dll &quot; [rest of string was truncated]&quot;;. '''</summary> Friend ReadOnly Property config1103() As String Get Return ResourceManager.GetString("config1103", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to [Memory] '''; [[[[[[[[[[[[[[[[[[[[[[[[[[[ '''; BEGIN - MEMORY PATHS '''version=11.04 '''tibiamainname=client '''tibiaclassname=Qt5QWindowOwnDCIcon '''tibiatitle=Tibia '''tibiamainname_updater=tibia '''tibiaclassname_updater=Qt5QWindowIcon '''tibiatitle_updater=Tibia '''adrSelectedItem_height=&quot;Qt5Widgets.dll&quot; + 00401DC4 &gt; 70 &gt; 4 &gt; a8 ''' '''adrGameRect_Width_Double=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 10C &gt; 18 &gt; 4 &gt; 74 &gt; 4 &gt; 88 ''' '''adrChatLog_tabStruct=&quot;Qt5Core.dll&quot; + 4555C8 &gt; 8 &gt; 118 '''SELECTEDCHANNEL_FirstLineText_Unicode=&quot;Qt5Core.dll &quot; [rest of string was truncated]&quot;;. '''</summary> Friend ReadOnly Property config1104() As String Get Return ResourceManager.GetString("config1104", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to [Memory] '''; [[[[[[[[[[[[[[[[[[[[[[[[[[[ '''; BEGIN - MEMORY PATHS '''version=11.10 '''tibiamainname=client '''tibiaclassname=Qt5QWindowOwnDCIcon '''tibiatitle=Tibia '''tibiamainname_updater=tibia '''tibiaclassname_updater=Qt5QWindowIcon '''tibiatitle_updater=Tibia '''adrSelectedItem_height=&quot;Qt5Widgets.dll&quot; + 00401DC4 &gt; 70 &gt; 4 &gt; a8 ''' '''adrGameRect_Width_Double=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 10C &gt; 18 &gt; 4 &gt; 74 &gt; 4 &gt; 88 '''adrSidebar_Count=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 10C &gt; 18 &gt; 4 &gt; F8 ''' '''adrChatLog_tabStruct=&quot;Qt5Core.dll&quot; + 4555 [rest of string was truncated]&quot;;. '''</summary> Friend ReadOnly Property config1110() As String Get Return ResourceManager.GetString("config1110", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized string similar to [Memory] '''; [[[[[[[[[[[[[[[[[[[[[[[[[[[ '''; BEGIN - MEMORY PATHS '''version=11.11 '''tibiamainname=client '''tibiaclassname=Qt5QWindowOwnDCIcon '''tibiatitle=Tibia '''tibiamainname_updater=tibia '''tibiaclassname_updater=Qt5QWindowIcon '''tibiatitle_updater=Tibia '''adrSelectedItem_height=&quot;Qt5Widgets.dll&quot; + 00401DC4 &gt; 70 &gt; 4 &gt; a8 ''' '''adrGameRect_Width_Double=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 10C &gt; 18 &gt; 4 &gt; 74 &gt; 4 &gt; 88 '''adrSidebar_Count=&quot;Qt5Core.dll&quot; + 004555C8 &gt; 8 &gt; 10C &gt; 18 &gt; 4 &gt; F8 ''' '''adrChatLog_tabStruct=&quot;Qt5Core.dll&quot; + 4555 [rest of string was truncated]&quot;;. '''</summary> Friend ReadOnly Property config1111() As String Get Return ResourceManager.GetString("config1111", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized resource of type System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property miniIcon() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("miniIcon", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Looks up a localized string similar to [Global] '''AddressFile=config1110.ini '''timerMS=100 '''totalFriends=0 '''settingsVersion=127. '''</summary> Friend ReadOnly Property settings() As String Get Return ResourceManager.GetString("settings", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized resource of type System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property tibia_back() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("tibia_back", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property End Module End Namespace
blackdtools/Cheatlyzer
My Project/Resources.Designer.vb
Visual Basic
mit
11,869
 Class MittelPaket(Of T) Inherits Paket(Of T) Private schwimmerVonOben As T Private schwimmerVonUnten As T Sub New(suchePaarungen As SuchePaarungen(Of T), ByVal aktuelleRunde As Integer, istAltschwimmer As Predicate(Of T), setzeAltschwimmer As Action(Of T)) MyBase.New(suchePaarungen, aktuelleRunde, istAltschwimmer, setzeAltschwimmer) End Sub Sub New(ByVal mittelPaket As MittelPaket(Of T)) MyBase.New(mittelPaket) schwimmerVonOben = mittelPaket.schwimmerVonOben schwimmerVonUnten = mittelPaket.schwimmerVonUnten End Sub Public Overrides Property aktuellerSchwimmer As T Get If Absteigend Then Return schwimmerVonOben Else Return schwimmerVonUnten End If End Get Set(ByVal value As T) MyBase.aktuellerSchwimmer = value End Set End Property Sub ÜbernimmPaarungen(ByVal vorgänger As Paket(Of T)) Dim tempPaarungen = vorgänger.Partien.ToList tempPaarungen.Reverse() For Each partie In tempPaarungen Dim spielerL = partie.Item1 Dim spielerR = partie.Item2 If Not _IstAltschwimmer(spielerL) Then If Not _IstAltschwimmer(spielerR) Then vorgänger.Partien.Remove(partie) vorgänger.SpielerListe.Remove(spielerL) vorgänger.SpielerListe.Remove(spielerR) Me.SpielerListe.Add(spielerL) Me.SpielerListe.Add(spielerR) Return End If End If Next Dim MyPartie = vorgänger.Partien.Last vorgänger.Partien.Remove(MyPartie) vorgänger.SpielerListe.Remove(MyPartie.Item1) vorgänger.SpielerListe.Remove(MyPartie.Item2) Me.SpielerListe.Add(MyPartie.Item1) Me.SpielerListe.Add(MyPartie.Item2) End Sub End Class
GoppeltM/PPC-Manager
Trunk/PPC Manager/PPC Manager/Model/MittelPaket.vb
Visual Basic
mit
2,010
Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim documents As SolidEdgeFramework.Documents = Nothing Dim partDocument As SolidEdgePart.PartDocument = Nothing Dim refPlanes As SolidEdgePart.RefPlanes = Nothing Dim profileSets As SolidEdgePart.ProfileSets = Nothing Dim profileSet As SolidEdgePart.ProfileSet = Nothing Dim profiles As SolidEdgePart.Profiles = Nothing Dim profile As SolidEdgePart.Profile = Nothing Dim arcs2d As SolidEdgeFrameworkSupport.Arcs2d = Nothing Dim arc2d As SolidEdgeFrameworkSupport.Arc2d = Nothing 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)) arcs2d = profile.Arcs2d arc2d = arcs2d.AddByCenterStartEnd(0, 0, 0.05, 0, 0, 0.05) arc2d.SetCenterPoint(-0.01, -0.01) Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeFrameworkSupport.Arc2d.SetCenterPoint.vb
Visual Basic
mit
2,017
Imports ExcelDna.Integration Imports ExcelDna.IntelliSense Imports System.CodeDom.Compiler Imports System.Reflection Namespace TheAddin Public Class MyAddIn Implements IExcelAddIn Public Sub AutoOpen() Implements IExcelAddIn.AutoOpen IntelliSenseServer.Install() ' Get the default list of exported assemblies Dim assemblies As New List(Of Assembly) assemblies.AddRange(ExcelIntegration.GetExportedAssemblies()) ' Compile and add the dyanmic assembly to the list Dim dynamicAssembly As Assembly = CreateFunctionAssembly() If Not dynamicAssembly Is Nothing Then assemblies.Add(dynamicAssembly) End If ' Use our own registration helper to do the registration RegistrationHelper.PerformRegistration(assemblies) End Sub Public Sub AutoClose() Implements IExcelAddIn.AutoClose IntelliSenseServer.Uninstall() End Sub Private Function CreateFunctionAssembly() As Assembly Dim dq As String = """" Dim c As VBCodeProvider = New VBCodeProvider Dim cp As CompilerParameters = New CompilerParameters Dim code As String = "Namespace NewFunctions Public Module MyNewUDF Function GETNAME() Return " + dq + "My name is Jeff" + dq + " End Function Function GETAGE() Return " + dq + "My age is 23" + dq + " End Function End Module End Namespace" Dim results As CompilerResults = c.CompileAssemblyFromSource(cp, code) If results.Errors.HasErrors Then For Each er As CompilerError In results.Errors MsgBox(er.ErrorNumber + ". " + er.ErrorText) Next Return Nothing End If Return results.CompiledAssembly End Function End Class End Namespace Namespace OldFunctions Public Module MyOldUDF Function GETHEIGHT() As String Return "Height is 170cm" End Function Function GETWEIGHT() As String Return "Weight is 70KG" End Function End Module End Namespace
Excel-DNA/Samples
DynamicCompiledVB/AddIn.vb
Visual Basic
mit
2,537
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:2.0.50727.3603 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On '''<summary> '''DTIMenu class. '''</summary> '''<remarks> '''Auto-generated class. '''</remarks> Partial Public Class DTIMenu '''<summary> '''Head1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead '''<summary> '''form1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm '''<summary> '''Menu1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents Menu1 As Global.DTIAdminPanel.Menu End Class
Micmaz/DTIControls
DTIAdminPanel/DTIAdminPanelTestProject/page/DTIMenu.aspx.designer.vb
Visual Basic
mit
1,383
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Form1 Inherits System.Windows.Forms.Form 'Form remplace la méthode Dispose pour nettoyer la liste des composants. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Requise par le Concepteur Windows Form Private components As System.ComponentModel.IContainer 'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form 'Elle peut être modifiée à l'aide du Concepteur Windows Form. 'Ne la modifiez pas à l'aide de l'éditeur de code. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.Label1 = New System.Windows.Forms.Label() Me.SuspendLayout ' 'Label1 ' Me.Label1.AutoSize = true Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 18!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0,Byte)) Me.Label1.Location = New System.Drawing.Point(12, 46) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(485, 36) Me.Label1.TabIndex = 0 Me.Label1.Text = "Hello Travis, do you compile me?" ' 'Form1 ' Me.AutoScaleDimensions = New System.Drawing.SizeF(8!, 16!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(516, 127) Me.Controls.Add(Me.Label1) Me.Name = "Form1" Me.Text = "Simple VB.Net application to debug Travis CI" Me.ResumeLayout(false) Me.PerformLayout End Sub Friend WithEvents Label1 As Label End Class
fredatgithub/VB.Net_Travis_Test
WindowsApplicationTravisDemo/Form1.Designer.vb
Visual Basic
mit
1,959
Imports System.Configuration Imports System.Data.SqlClient Imports System Imports System.Text Imports System.Security.Cryptography Public Class UC_License Private Sub UC_License_Load(sender As Object, e As EventArgs) Handles MyBase.Load LBLTitle.Text = "License" txtLicense.Clear() If My.Settings.LIC <> "" Then Dim LIC As String = DecryptString(My.Settings.LIC) Dim installdate As String = Get_License(4, LIC) lblInstallDate.Text = ": " & Format(CDate(installdate), "dd MMMM yyy") Dim valid As String = Get_License(5, LIC) If valid <> "4ever" Then lblValidDate.Text = ": " & Format(CDate(valid), "dd MMMM yyy") lblVersion.Text = ": 2.0 - Trial Version" Else lblVersion.Text = ": 2.0 - Full Version" lblValidDate.Text = ": - " End If Else lblInstallDate.Text = ": - " lblValidDate.Text = ": - " End If End Sub Private Function DecryptString(ByVal sourceText As String) As String Dim DES As New TripleDESCryptoServiceProvider Dim Md5 As New MD5CryptoServiceProvider DES.Key = Md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes("#W0L3Stech!++")) DES.Mode = CipherMode.ECB Dim Buffer As Byte() = Convert.FromBase64String(sourceText) Dim ByteHash() As Byte = DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length) Return ASCIIEncoding.ASCII.GetString(ByteHash) End Function Public Function Get_License(ByVal iType As Int16, ByVal LIC As String) As String Try Dim sArray() As String sArray = LIC.Split(CChar("$")) '# 1 - Key '# 2 - PC Name '# 3 - CPU ID '# 4 - Tanggal Install '# 5 - Valid Return sArray(iType - 1) Catch ex As Exception Return "" End Try End Function Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click If txtLicense.Text = "" Then MsgBox("Please fill license", MsgBoxStyle.Exclamation, "") Else If MessageBox.Show("Are you sure ?", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then My.Settings.LIC = txtLicense.Text.Trim My.Settings.Save() MsgBox("Success", MsgBoxStyle.Information, "") WriteLog("License", "Update Success") menu_utama.Hide() menu_utama.Kosongkan() SPLASH.Show() End If End If End Sub Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click menu_utama.PNLUtama.Controls.Clear() Dim a As New UC_MasterData a.Dock = DockStyle.Fill menu_utama.PNLUtama.Controls.Add(a) End Sub End Class
anakpantai/busus
SIMARSIP/User Control/UC_License.vb
Visual Basic
apache-2.0
3,064
Imports System Imports Microsoft.VisualBasic Imports ChartDirector Public Class finance2 Implements DemoModule 'Name of demo module Public Function getName() As String Implements DemoModule.getName Return "Finance Chart (2)" End Function 'Number of charts produced in this demo module Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts Return 1 End Function 'Main code for creating chart. 'Note: the argument chartIndex is unused because this demo only has 1 chart. Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _ Implements DemoModule.createChart ' Create a finance chart demo containing 100 days of data Dim noOfDays As Integer = 100 ' To compute moving averages starting from the first day, we need to get extra data points ' before the first day Dim extraDays As Integer = 30 ' In this exammple, we use a random number generator utility to simulate the data. We set up ' the random table to create 6 cols x (noOfDays + extraDays) rows, using 9 as the seed. Dim rantable As RanTable = New RanTable(9, 6, noOfDays + extraDays) ' Set the 1st col to be the timeStamp, starting from Sep 4, 2002, with each row representing ' one day, and counting week days only (jump over Sat and Sun) rantable.setDateCol(0, DateSerial(2002, 9, 4), 86400, True) ' Set the 2nd, 3rd, 4th and 5th columns to be high, low, open and close data. The open value ' starts from 100, and the daily change is random from -5 to 5. rantable.setHLOCCols(1, 100, -5, 5) ' Set the 6th column as the vol data from 5 to 25 million rantable.setCol(5, 50000000, 250000000) ' Now we read the data from the table into arrays Dim timeStamps() As Double = rantable.getCol(0) Dim highData() As Double = rantable.getCol(1) Dim lowData() As Double = rantable.getCol(2) Dim openData() As Double = rantable.getCol(3) Dim closeData() As Double = rantable.getCol(4) Dim volData() As Double = rantable.getCol(5) ' Create a FinanceChart object of width 640 pixels Dim c As FinanceChart = New FinanceChart(640) ' Add a title to the chart c.addTitle("Finance Chart Demonstration") ' Set the data into the finance chart object c.setData(timeStamps, highData, lowData, openData, closeData, volData, extraDays) ' Add a slow stochastic chart (75 pixels high) with %K = 14 and %D = 3 c.addSlowStochastic(75, 14, 3, &H006060, &H606000) ' Add the main chart with 240 pixels in height c.addMainChart(240) ' Add a 10 period simple moving average to the main chart, using brown color c.addSimpleMovingAvg(10, &H663300) ' Add a 20 period simple moving average to the main chart, using purple color c.addSimpleMovingAvg(20, &H9900ff) ' Add candlestick symbols to the main chart, using green/red for up/down days c.addCandleStick(&H00ff00, &Hff0000) ' Add 20 days donchian channel to the main chart, using light blue (9999ff) as the border ' and semi-transparent blue (c06666ff) as the fill color c.addDonchianChannel(20, &H9999ff, &Hc06666ff) ' Add a 75 pixels volume bars sub-chart to the bottom of the main chart, using ' green/red/grey for up/down/flat days c.addVolBars(75, &H99ff99, &Hff9999, &H808080) ' Append a MACD(26, 12) indicator chart (75 pixels high) after the main chart, using 9 days ' for computing divergence. c.addMACD(75, 26, 12, 9, &H0000ff, &Hff00ff, &H008000) ' Output the chart viewer.Chart = c End Sub End Class
jojogreen/Orbital-Mechanix-Suite
NetWinCharts/VBNetWinCharts/finance2.vb
Visual Basic
apache-2.0
3,821
Public Class Ikaslea Private n_email_helbidea As String Private n_izena As String Private n_abizena As String Private n_pasahitza As String Private n_galdera_ezkutua As String Private n_galdera_ezkutuaren_erantzunak As String Private n_egiaztatze_zenbakia As Integer Private n_egiaztatua As Boolean Private n_erabiltzaileMota As String Public Sub New() End Sub Public Property email_helbidea As String Get Return n_email_helbidea End Get Set(ByVal value As String) n_email_helbidea = value End Set End Property Public Property izena As String Get Return n_izena End Get Set(ByVal value As String) n_izena = value End Set End Property Public Property abizena As String Get Return n_abizena End Get Set(ByVal value As String) n_abizena = value End Set End Property Public Property pasahitza As String Get Return n_pasahitza End Get Set(ByVal value As String) n_pasahitza = value End Set End Property Public Property galdera_ezkutua As String Get Return n_galdera_ezkutua End Get Set(ByVal value As String) n_galdera_ezkutua = value End Set End Property Public Property galdera_ezkutuaren_erantzunak As String Get Return n_galdera_ezkutuaren_erantzunak End Get Set(ByVal value As String) n_galdera_ezkutuaren_erantzunak = value End Set End Property Public Property egiaztatze_zenbakia As Integer Get Return n_egiaztatze_zenbakia End Get Set(ByVal value As Integer) n_egiaztatze_zenbakia = value End Set End Property Public Property egiaztatua As Boolean Get Return n_egiaztatua End Get Set(ByVal value As Boolean) n_egiaztatua = value End Set End Property Public Property erabiltzaileMota As String Get Return n_erabiltzaileMota End Get Set(ByVal value As String) n_erabiltzaileMota = value End Set End Property End Class
CarlosIribarren/Ejemplos-Examples
Net/03_ASP.NET_XML.NET/DBKudeatzailea/DBKudeatzailea/Ikaslea.vb
Visual Basic
apache-2.0
2,358
' Copyright (c) $CopyrightYear$ $YourCompany$ ' All rights reserved. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. ' Imports DotNetNuke.Entities.Modules ''' <summary> ''' This base class can be used to define custom properties for multiple controls. ''' An example module, DNNSimpleArticle (http://dnnsimplearticle.codeplex.com) uses this for an ArticleId ''' ''' Because the class inherits from SettingsModuleBase, properties like ModuleId, TabId, UserId, and others, ''' are accessible to your module's controls (that inherity from $safeprojectname$SettingsBase ''' ''' </summary> Public Class $safeprojectname$SettingsBase Inherits ModuleSettingsBase End Class
aspose-total/Aspose.Total-for-.NET
Plugins/DNN/DevelopementTemplate/VisualStudio_2013/VB/SettingsBase.vb
Visual Basic
mit
1,146
Imports Csla Imports Csla.Security <Serializable()> Public Class DynamicRootBindingList Inherits DynamicBindingListBase(Of DynamicRoot) Protected Overrides Function AddNewCore() As Object Dim item As DynamicRoot = DataPortal.Create(Of DynamicRoot)() Add(item) Return item End Function Private Shared Sub AddObjectAuthorizationRules() 'TODO: add authorization rules 'AuthorizationRules.AllowGet(GetType(DynamicRootBindingList), "Role") 'AuthorizationRules.AllowEdit(GetType(DynamicRootBindingList), "Role") End Sub <Fetch> Private Sub Fetch() ' TODO: load values RaiseListChangedEvents = False Dim listData As Object = Nothing For Each oneItemData As Object In CType(listData, List(Of Object)) Add(DataPortal.Fetch(Of DynamicRoot)(oneItemData)) Next RaiseListChangedEvents = True End Sub End Class
MarimerLLC/csla
Support/Templates/vb/Files/DynamicRootBindingList.vb
Visual Basic
mit
876
' 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.Options Imports Microsoft.CodeAnalysis.Simplification Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class TypeInferenceSimplifierTests Inherits AbstractSimplificationTests <WorkItem(734369)> <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestDontSimplify1() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Class C End Class Class B Inherits C Public Shared Funtion Foo() As Integer End Function End Class Module Program Sub Main(args As String()) Dim {|SimplifyParent:AA|} Dim {|SimplifyParent:A As Integer|} Dim {|SimplifyParent:F(), G() As String|} Dim {|SimplifyParent:M() As String|}, {|SimplifyParent:N() As String|} Dim {|SimplifyParent:E As String = 5|} Dim {|SimplifyParent:arr(,) As Double = {{1,2},{3,2}}|} Dim {|SimplifyParent:arri() As Double = {1,2}|} Dim {|SimplifyParent:x As IEnumerable(Of C) = New List(Of B)|} Dim {|SimplifyParent:obj As C = New B()|} Dim {|SimplifyParent:ret as Double = B.Foo()|} Const {|SimplifyParent:con As Double = 1|} End Sub End Module </Document> </Project> </Workspace> Dim expected = <text> Imports System Class C End Class Class B Inherits C Public Shared Funtion Foo() As Integer End Function End Class Module Program Sub Main(args As String()) Dim AA Dim A As Integer Dim F(), G() As String Dim M() As String, N() As String Dim E As String = 5 Dim arr(,) As Double = {{1,2},{3,2}} Dim arri() As Double = {1,2} Dim x As IEnumerable(Of C) = New List(Of B) Dim obj As C = New B() Dim ret as Double = B.Foo() Const con As Double = 1 End Sub End Module </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub <WorkItem(734369)> <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestSimplify_ArrayElementConversion() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module Program Sub Main(args As String()) Dim {|SimplifyParent:arr(,) As Double = {{1.9,2},{3,2}}|} End Sub End Module </Document> </Project> </Workspace> Dim expected = <text> Imports System Module Program Sub Main(args As String()) Dim arr = {{1.9,2},{3,2}} End Sub End Module </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestDontSimplify_Using() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Class B Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Class D Inherits B End Class Class Program Sub Main(args As String()) Using {|SimplifyParent:b As B|} = New D() End Using End Sub End Class </Document> </Project> </Workspace> Dim expected = <text> Imports System Imports System.Collections.Generic Imports System.Linq Class B Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Class D Inherits B End Class Class Program Sub Main(args As String()) Using b As B = New D() End Using End Sub End Class </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestDontSimplify_For_0() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module Program Sub Main(args As String()) For {|SimplifyParent:index As Long|} = 1 To 5 Next For Each {|SimplifyParent:index As Long|} In New Integer() {1, 2, 3} Next End Sub End Module </Document> </Project> </Workspace> Dim expected = <text> Imports System Module Program Sub Main(args As String()) For index As Long = 1 To 5 Next For Each index As Long In New Integer() {1, 2, 3} Next End Sub End Module </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestDontSimplify_For_1() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Class B End Class Class Program Inherits B Sub Main(args As String()) End Sub Sub Madin(args As IEnumerable(Of Program)) For Each {|SimplifyParent:index As B|} In args Next End Sub End Class </Document> </Project> </Workspace> Dim expected = <text> Imports System Imports System.Collections.Generic Imports System.Linq Class B End Class Class Program Inherits B Sub Main(args As String()) End Sub Sub Madin(args As IEnumerable(Of Program)) For Each index As B In args Next End Sub End Class </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub <WorkItem(734377)> <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestSimplify1() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports I = System.Int32 Module Program Public Dim {|SimplifyParent:x As Integer = 5|} Function Foo() As Integer End Function Sub Main(args As String()) Dim {|SimplifyParent:A As Integer = 5|} Dim {|SimplifyParent:M() As String = New String(){}|}, {|SimplifyParent:N() As String|} Dim {|SimplifyParent:B(,) As Integer = {{1,2},{2,3}}|} Dim {|SimplifyParent:ret As Integer = Foo()|} Const {|SimplifyParent:con As Integer = 1|} Dim {|SimplifyParent:in As I = 1|} End Sub End Module </Document> </Project> </Workspace> Dim expected = <text> Imports System Imports I = System.Int32 Module Program Public Dim x = 5 Function Foo() As Integer End Function Sub Main(args As String()) Dim A = 5 Dim M = New String(){}, N() As String Dim B = {{1,2},{2,3}} Dim ret = Foo() Const con = 1 Dim in = 1 End Sub End Module </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestSimplify2() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Linq Imports I = System.Int32 Module Program Sub Main(args As String()) Using {|SimplifyParent:proc As Process|} = New Process End Using For {|SimplifyParent:index As Integer|} = 1 To 5 Next For {|SimplifyParent:index As I|} = 1 to 5 Next For Each {|SimplifyParent:index As Integer|} In New Integer() {1, 2, 3} Next End Sub End Module </Document> </Project> </Workspace> Dim expected = <text> Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Linq Imports I = System.Int32 Module Program Sub Main(args As String()) Using proc = New Process End Using For index = 1 To 5 Next For index = 1 to 5 Next For Each index In New Integer() {1, 2, 3} Next End Sub End Module </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestSimplify_For_1() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Class B End Class Class Program Inherits B Sub Main(args As String()) End Sub Sub Madin(args As IEnumerable(Of Program)) For Each {|SimplifyParent:index As Program|} In args Next End Sub End Class </Document> </Project> </Workspace> Dim expected = <text> Imports System Imports System.Collections.Generic Imports System.Linq Class B End Class Class Program Inherits B Sub Main(args As String()) End Sub Sub Madin(args As IEnumerable(Of Program)) For Each index In args Next End Sub End Class </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub #Region "Type Argument Expand/Reduce for Generic Method Calls - 639136" <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestSimplify_For_GenericMethods() Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ interface I { void Foo<T>(T x); } class C : I { public void Foo<T>(T x) { } } class D : C { public void Foo(int x) { } public void Sub() { {|SimplifyParent:base.Foo<int>(1)|}; } } ]]> </Document> </Project> </Workspace> Dim expected = <text><![CDATA[ interface I { void Foo<T>(T x); } class C : I { public void Foo<T>(T x) { } } class D : C { public void Foo(int x) { } public void Sub() { base.Foo(1); } }]]> </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInference, True}} Test(input, expected, simplificationOptionSet) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestSimplify_For_GenericMethods_VB() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class C Public Sub Foo(Of T)(ByRef x As T) End Sub End Class Class D Inherits C Public Sub Foo(ByRef x As Integer) End Sub Public Sub Test() Dim x As String {|SimplifyParent:MyBase.Foo(Of String)(x)|} End Sub End Class ]]> </Document> </Project> </Workspace> Dim expected = <text><![CDATA[ Class C Public Sub Foo(Of T)(ByRef x As T) End Sub End Class Class D Inherits C Public Sub Foo(ByRef x As Integer) End Sub Public Sub Test() Dim x As String MyBase.Foo(x) End Sub End Class ]]> </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInference, True}} Test(input, expected, simplificationOptionSet) End Sub <WorkItem(734377)> <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub VisualBasic_ExplicitTypeDecl_FieldDecl() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace X Module Program Public Dim {|SimplifyParent:t as Integer = {|SimplifyParent:X.A|}.getInt()|} Sub Main(args As String()) End Sub End Module Class A Public Shared Function getInt() As Integer Return 0 End Function End Class End Namespace </Document> </Project> </Workspace> Dim expected = <text> Namespace X Module Program Public Dim t = A.getInt() Sub Main(args As String()) End Sub End Module Class A Public Shared Function getInt() As Integer Return 0 End Function End Class End Namespace </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub <WorkItem(860111)> <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub VisualBasic_ExplicitTypeDecl_MustGetNewSMForAnyReducer() Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace Y Namespace X Module Program Public Dim {|SimplifyParent:t as Integer = {|SimplifyParentParent:Y.X.A|}.getInt()|} Sub Main(args As String()) End Sub End Module Class A Public Shared Function getInt() As Integer Return 0 End Function End Class End Namespace End Namespace </Document> </Project> </Workspace> Dim expected = <text> Namespace Y Namespace X Module Program Public Dim t = A.getInt() Sub Main(args As String()) End Sub End Module Class A Public Shared Function getInt() As Integer Return 0 End Function End Class End Namespace End Namespace </text> Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{SimplificationOptions.PreferImplicitTypeInLocalDeclaration, True}} Test(input, expected, simplificationOptionSet) End Sub #End Region End Class End Namespace
Inverness/roslyn
src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb
Visual Basic
apache-2.0
21,013
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.UseAutoProperty Public Class UseAutoPropertyTests Inherits AbstractCrossLanguageUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider) If language = LanguageNames.CSharp Then Return (New CSharp.UseAutoProperty.UseAutoPropertyAnalyzer(), New CSharp.UseAutoProperty.UseAutoPropertyCodeFixProvider()) ElseIf language = LanguageNames.VisualBasic Then Return (New VisualBasic.UseAutoProperty.UseAutoPropertyAnalyzer(), New VisualBasic.UseAutoProperty.UseAutoPropertyCodeFixProvider()) Else Throw New Exception() End If End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)> Public Async Function TestMultiFile_CSharp() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> partial class C { int $$i; } </Document> <Document FilePath='Test2.cs'> partial class C { int P { get { return i; } } } </Document> </Project> </Workspace> Await TestAsync(input, fileNameToExpected:= New Dictionary(Of String, String) From { {"Test1.cs", <text> partial class C { } </text>.Value.Trim()}, {"Test2.cs", <text> partial class C { int P { get; } } </text>.Value.Trim()} }) End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)> Public Async Function TestMultiFile_VisualBasic() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language='Visual Basic' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.vb'> partial class C dim $$i as Integer end class </Document> <Document FilePath='Test2.vb'> partial class C property P as Integer get return i end get end property end class </Document> </Project> </Workspace> Await TestAsync(input, fileNameToExpected:= New Dictionary(Of String, String) From { {"Test1.vb", <text> partial class C end class </text>.Value.Trim()}, {"Test2.vb", <text> partial class C ReadOnly property P as Integer end class </text>.Value.Trim()} }) End Function End Class End Namespace
jkotas/roslyn
src/EditorFeatures/Test2/Diagnostics/UseAutoProperty/UseAutoPropertyTests.vb
Visual Basic
apache-2.0
3,196
'********************************************************* ' ' Copyright (c) Microsoft. All rights reserved. ' This code is licensed under the MIT License (MIT). ' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY ' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR ' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ' '********************************************************* Imports ScreenCasting.Controls Imports System Imports System.Threading.Tasks Imports Windows.UI.Core Imports Windows.UI.ViewManagement Imports Windows.UI.Xaml Imports Windows.UI.Xaml.Controls Imports Windows.UI.Xaml.Navigation Namespace Global.ScreenCasting Partial Public NotInheritable Class ProjectionViewPage Inherits Page Public Sub New() Me.InitializeComponent() Dim pmtcs As ProjectedMediaTransportControls = TryCast(Me.Player.TransportControls, ProjectedMediaTransportControls) If pmtcs IsNot Nothing Then AddHandler pmtcs.StopProjectingButtonClick, AddressOf ProjectionViewPage_StopProjectingButtonClick End If AddHandler Me.Player.MediaOpened, AddressOf Player_MediaOpened End Sub Private Sub Player_MediaOpened(sender As Object, e As RoutedEventArgs) Me.Player.IsFullWindow = True Me.Player.AreTransportControlsEnabled = True End Sub Private Sub ProjectionViewPage_StopProjectingButtonClick(sender As Object, e As EventArgs) Me.StopProjecting() End Sub Public Async Function SetMediaSource(source As Uri, position As TimeSpan) As Task(Of Boolean) Await Me.Player.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Sub() Me.Player.Source = source Me.Player.Position = position Me.Player.Play() End Sub) Return True End Function Public ReadOnly Property Player As MediaElement Get Return _player End Get End Property Dim broker As ProjectionViewBroker = Nothing Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs) broker = CType(e.Parameter, ProjectionViewBroker) broker.ProjectedPage = Me AddHandler broker.ProjectionViewPageControl.Released, AddressOf thisViewControl_Released End Sub Private Async Sub thisViewControl_Released(sender As Object, e As EventArgs) RemoveHandler broker.ProjectionViewPageControl.Released, AddressOf thisViewControl_Released Await broker.ProjectionViewPageControl.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() Me.broker.NotifyProjectionStopping() MainPage.Current.ProjectionViewPageControl = Nothing End Sub) Me.Player.Stop() Me.Player.Source = Nothing Window.Current.Close() End Sub Public Async Sub SwapViews() broker.ProjectionViewPageControl.StartViewInUse() Await ProjectionManager.SwapDisplaysForViewsAsync(ApplicationView.GetForCurrentView().Id, broker.MainViewId) broker.ProjectionViewPageControl.StopViewInUse() End Sub Private Sub SwapViews_Click(sender As Object, e As RoutedEventArgs) SwapViews() End Sub Public Async Sub StopProjecting() broker.NotifyProjectionStopping() Await Me.Player.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Async Sub() Me.Player.Stop() Me.Player.Source = Nothing broker.ProjectionViewPageControl.StartViewInUse() Try Await ProjectionManager.StopProjectingAsync(broker.ProjectionViewPageControl.Id, broker.MainViewId) Catch End Try Window.Current.Close() End Sub) broker.ProjectionViewPageControl.StopViewInUse() End Sub Private Sub StopProjecting_Click(sender As Object, e As RoutedEventArgs) StopProjecting() End Sub End Class End Namespace
drummendejef/Windows-universal-samples
Samples/AdvancedCasting/vb/ProjectionViewPage.xaml.vb
Visual Basic
mit
5,589
Public Class NPC : Implements IHasRect Public Enum TargetType None = 0 NPC = 1 Location = 2 End Enum Public x As Double Public y As Double Public id As Integer Public name As String Public alive As Boolean = True Public rad As Short Public speed As Double Public speedX As Double Public speedY As Double 'Public rotSpeed As Double = Math.PI Public curTarget As TargetType Public curTargetPt As Point Public curTargetNPC As NPC Private curMesh As Integer = -1 Public myRange As Double Private myRangeSq As Double Public myangle As Double Public targetAngle As Double Public targetDist As Double Public myAI As AI Private active As Boolean = False Private rand As New Random Private path As New List(Of Point) Public myObjective As Objective Public checkPts As List(Of CheckPoint) Public myMeshptVisibleFromCheckpt As List(Of Integer) Private meshptCovered As Short = 0 Public iBasicMeshVisited As Integer = 0 Private col As Pen, colb As Brush Public Sub New(ByVal p As Point, ByVal clever As Integer, ByVal c As Color, Optional ByVal nm As String = "") x = p.X : y = p.Y rad = 10 If nm <> "" Then name = nm speedX = 0 : speedY = 0 If clever >= 0 Then myAI = New AI(clever) If clever > 0 Then myObjective = New Objective(Me) End If myRange = 400 : myRangeSq = myRange * myRange myangle = 90 checkPts = New List(Of CheckPoint) myMeshptVisibleFromCheckpt = New List(Of Integer) col = New Pen(c) : colb = New SolidBrush(c) End Sub Public ReadOnly Property Rect() As Rectangle Implements IHasRect.Rect Get Dim r2 As Short = rad + rad Return New Rectangle(x - rad, y - rad, r2, r2) End Get End Property Public Function DistanceTo(ByVal np As NPC) As Double Return LineDist(x, y, np.x, np.y) End Function Public Sub InitMyMesh(ByVal v As Integer) If myAI.clever < 1 Then Exit Sub myMeshptVisibleFromCheckpt = New List(Of Integer) For i As Short = 0 To v - 1 myMeshptVisibleFromCheckpt.Add(-1) Next End Sub 'which mesh points are visible from this checkpoint, tell those mesh points about this checkpoint Public Function PlotCheckpt(ByVal i As Integer) As Boolean Dim l As Integer = checkPts.Count For ii As Short = 0 To l - 1 If checkPts(ii).i = i Then Debug.WriteLine("checkpt already" & i) : Return False Next checkPts.Add(New CheckPoint(i)) ': Debug.WriteLine("=>" & i) Dim c As Short = 0 For ii As Short = 0 To mesh.Count - 1 If myMeshptVisibleFromCheckpt(ii) = -1 Then If ii = i Then myMeshptVisibleFromCheckpt(ii) = l : c += 1 ElseIf mesh(ii).visibleNgbrs.ContainsValue(i) Then myMeshptVisibleFromCheckpt(ii) = l : c += 1 End If End If Next meshptCovered += c 'Debug.WriteLine("+" & c) Return IIf(c = 0, False, True) End Function Public Function IsAllMeshptCovered() As Boolean meshptCovered = 0 For Each v As Integer In myMeshptVisibleFromCheckpt If v = -1 Then Return False Next Return True End Function Public Sub Activate() If myAI.clever < 1 Then Exit Sub Dim myThread As New Threading.Thread(AddressOf Update) active = True myThread.Name = "An NPC" & id myThread.Start() myAI.State = AI.NPState.SpecialPathfindForDebug curTarget = TargetType.None End Sub Public Function CanSee(ByVal n As NPC) As Boolean Return LineOfSight(x, y, n.x, n.y) End Function Public ReadOnly Property Loc() As Point Get Return New Point(x, y) End Get End Property Public Sub Deactivate() active = False End Sub Private Sub DoElse() speedX = 0 speedY = 0 If rand.NextDouble() * 50 > 40 Then myangle = CInt(rand.NextDouble() * 360) End Sub Private Sub checkTarget() If curTarget = TargetType.None Then Exit Sub If myObjective.lastObjective = Objective.ObjectiveType.Avoidable Then targetAngle = myObjective.closestRunAngle Else targetAngle = Angle(curTargetPt.X, curTargetPt.Y, x, y) End If targetDist = LineDist(x, y, curTargetPt.X, curTargetPt.Y) End Sub Private Function Reached() As Boolean If targetDist > speed Then Return False x = curTargetPt.X : y = curTargetPt.Y Return True End Function Private Function canSee() As Boolean If Ang_Dif(targetAngle, myangle) < 90 AndAlso _ targetDist <= myRange AndAlso _ LineOfSight(x, y, curTargetPt.X, curTargetPt.Y) Then _ Return True Return False End Function Private Sub Kill(np As NPC) If np.id = 0 Then gameOver = True : active = False myObjective.RemoveObj(np) npcs(np.id).Deactivate() npcs(np.id).alive = False End Sub Public Sub SetSpeeds(ByVal hspd As Double, ByVal vspd As Double) speedX = hspd : speedY = vspd End Sub Public ReadOnly Property GetDirection() As Double Get If id = 0 Then If speedY > 0 AndAlso speedX > 0 Then myangle = 315 ElseIf speedY > 0 AndAlso speedX < 0 Then myangle = 225 ElseIf speedY > 0 AndAlso speedX = 0 Then myangle = 270 ElseIf speedY < 0 AndAlso speedX > 0 Then myangle = 45 ElseIf speedY = 0 AndAlso speedX > 0 Then myangle = 0 ElseIf speedY < 0 AndAlso speedX < 0 Then myangle = 135 ElseIf speedY = 0 AndAlso speedX < 0 Then myangle = 180 Else myangle = 90 End If End If Return myangle End Get End Property Public ReadOnly Property GetSpeed() As Double Get If speed = 0 Then speed = Math.Sqrt(speedX * speedX + speedY * speedY) Return speed End Get End Property Public Sub ToMesh(ByVal idd As Integer) curTarget = TargetType.Location curTargetPt = mesh(idd).Location checkTarget() speed = myAI.Speed myangle = targetAngle Force(speed, myangle, speedX, speedY) End Sub Public Sub Go(ByVal p As Point) x = p.X : y = p.Y End Sub Public Sub Go(ByVal xx As Integer, ByVal yy As Integer, Optional ByVal check As Boolean = False) x += xx : y += yy If check Then MoveOutside(x, y) End Sub Public Sub Go(Optional ByVal check As Boolean = False) 'Dim xx As Double = x + speedX, yy As Double = y + speedY x += speedX : y += speedY If check Then MoveOutside(x, y) End Sub Private Sub Update() While active Dim t As Long = Now.Millisecond If myObjective.Running = False Then myObjective.StartEvaluate() If myObjective.Done Then Select Case myObjective.lastObjective Case Objective.ObjectiveType.Reachable curTarget = TargetType.NPC curTargetNPC = myObjective.reachTarget(myObjective.lastTarget) curTargetPt = curTargetNPC.Loc myAI.State = AI.NPState.Chase Case Objective.ObjectiveType.Collectable curTarget = TargetType.Location curTargetNPC = npcs(myObjective.lastTarget) curTargetPt = curTargetNPC.Loc myAI.State = AI.NPState.Chase Case Objective.ObjectiveType.Avoidable 'If myAI.State = AI.NPState.Flee Then 'Else curTarget = TargetType.NPC curTargetNPC = myObjective.avoidTarget(myObjective.lastTarget) curTargetPt = curTargetNPC.Loc myAI.State = AI.NPState.Avoid 'End If Case Else If meshptCovered < cMesh Then If myAI.State = AI.NPState.Stay Then Dim ii As Integer = GetNearestMeshpt(x, y) If ii < 0 Then myAI.State = AI.NPState.Stay Else ToMesh(ii) : myAI.State = AI.NPState.UnknownExplorePhase1Move : curMesh = ii End If End If Else If myAI.State = AI.NPState.Stay Then myAI.State = AI.NPState.VisiblePathMove path = NavMesh.FindPath3(Me.Loc, mesh(checkPts(iBasicMeshVisited).i).Location) iBasicMeshVisited = (iBasicMeshVisited + 1) Mod checkPts.Count curTarget = TargetType.Location curTargetPt = path(0) : path.RemoveAt(0) speed = myAI.Speed End If End If End Select End If checkTarget() Select Case myAI.State Case AI.NPState.Stay DoElse() Case AI.NPState.Chase If Reached() Then Kill(curTargetNPC) If curTarget = TargetType.Location Then If DOCS.Count = 0 Then gameOver = True End If End If Exit Select End If If LineOfSight(x, y, curTargetPt.X, curTargetPt.Y) Then If myangle <> targetAngle Then myangle = targetAngle speed = AI.ChaseSpeed Force(speed, myangle, speedX, speedY) End If Go(True) ' GoToTargetOutside() Else If myObjective.lastObjective = Objective.ObjectiveType.Reachable Then myObjective.lastObjective = Objective.ObjectiveType.None Dim b As Boolean = False speed = myAI.Speed If myAI.LocEstimate Then '' to do Dim pa As Double = curTargetNPC.GetDirection * d2r Dim playertogo As Point = New Point(curTargetPt.X + Math.Cos(pa) * targetDist, curTargetPt.Y + Math.Sin(pa) * targetDist) If playertogo.X < 5 Then playertogo.X = 5 If playertogo.X > worldWidth - 5 Then playertogo.X = worldWidth - 5 If playertogo.Y < 5 Then playertogo.Y = 5 If playertogo.Y > worldHeight - 5 Then playertogo.Y = worldHeight - 5 MoveOutside(playertogo.X, playertogo.Y) curTargetPt = playertogo If GetPath() Then Debug.WriteLine("estimated") myAI.State = AI.NPState.SearchAlert curTarget = TargetType.Location : b = True myAI.DoingLocEst = True Else curTargetPt = curTargetNPC.Loc End If End If If Not b Then myAI.State = AI.NPState.Investigate curTarget = TargetType.Location End If End If Case AI.NPState.Investigate If Reached() Then myAI.State = AI.NPState.Stay curTarget = TargetType.None ElseIf LineOfSight(x, y, curTargetPt.X, curTargetPt.Y) Then If myangle <> targetAngle Then myangle = targetAngle : Force(speed, myangle, speedX, speedY) Go(True) Else 'shortest path myAI.State = AI.NPState.SearchAlert : curTarget = TargetType.Location 'GoToTargetOutside() If Not GetPath() Then myAI.State = AI.NPState.Stay curTarget = TargetType.None End If End If Case AI.NPState.SearchAlert If CanSee(curTargetNPC) Then myAI.State = AI.NPState.Chase : curTarget = TargetType.NPC If Not path Is Nothing Then path.Clear() ElseIf Reached() Then If path.Count = 0 Then If myAI.DoingLocEst Then myAI.LocEstimate = False myAI.State = AI.NPState.Stay curTarget = TargetType.None Else curTargetPt = New Point(path(0)) : path.RemoveAt(0) End If Else If myangle <> targetAngle Then myangle = targetAngle speed = AI.ChaseSpeed Force(speed, myangle, speedX, speedY) End If 'If GoToTargetOutside() = 0 Then myAI.State = AI.NPState.SearchNormal Go(True) End If Case AI.NPState.SpecialPathfindForDebug 'Dim ii As Integer = GetNearestMeshpt(x, y) 'If ii < 0 Then ' myAI.State = AI.NPState.Stay 'Else 'ToMesh(ii) : myAI.State = AI.NPState.UnknownExplorePhase1Move : curMesh = ii 'End If 'path = NavMesh.FindPath3(npcs(0).Loc, Loc) myAI.State = AI.NPState.Stay 'curTarget = TargetType.Player speed = 4 'curTargetPt = npcs(0).Loc 'myAI.State = AI.NPState.Avoid Case AI.NPState.VisiblePathMove If Reached() Then For i As Short = 0 To cMesh - 1 If x = mesh(i).x AndAlso y = mesh(i).y Then curMesh = i : Exit For Next If path.Count > 0 Then curTarget = TargetType.Location curTargetPt = New Point(path(0)) : path.RemoveAt(0) Else Debug.WriteLine("finish path") path = NavMesh.FindPath3(Me.Loc, mesh(checkPts(iBasicMeshVisited).i).Location) curMesh = checkPts(iBasicMeshVisited).i iBasicMeshVisited = (iBasicMeshVisited + 1) Mod checkPts.Count curTarget = TargetType.Location curTargetPt = path(0) : path.RemoveAt(0) End If Else If myangle <> targetAngle Then myangle = targetAngle : Force(speed, myangle, speedX, speedY) End If Go() End If Case AI.NPState.UnknownExploreMovePath If Reached() Then If path.Count > 0 Then 'Debug.WriteLine("Count " & path.Count) curTarget = TargetType.Location curTargetPt = New Point(path(0)) : path.RemoveAt(0) Else 'Debug.WriteLine("finish path") myAI.State = AI.NPState.UnknownExplorePhase1 curTarget = TargetType.None myAI.memory = 0 End If Else If myangle <> targetAngle Then myangle = targetAngle : Force(speed, myangle, speedX, speedY) Go() End If Case AI.NPState.UnknownExplorePhase1Move If Reached() Then curTarget = TargetType.None myAI.State = AI.NPState.UnknownExplorePhase1 Else If myangle <> targetAngle Then myangle = targetAngle : Force(speed, myangle, speedX, speedY) Go() End If Case AI.NPState.UnknownExplorePhase1 If myAI.memory = 0 Then GoTo plot Dim mp As Integer = GetNearestMeshptInvisible(curMesh, myMeshptVisibleFromCheckpt) If mp = -1 Then If meshptCovered < cMesh Then Dim mmp As Integer = -1 mp = GetNearestMesptInvisibleFromNgbr(curMesh, myMeshptVisibleFromCheckpt, mmp) If mp = -1 Then path = GetNearestInvisibleMeshpt(curMesh, mp, myMeshptVisibleFromCheckpt) If mp >= 0 Then curMesh = mp myAI.State = AI.NPState.UnknownExploreMovePath curTargetPt = path(0) : path.RemoveAt(0) curTarget = TargetType.Location Else Debug.WriteLine("no path! " & (cMesh - meshptCovered)) myAI.State = AI.NPState.Stay End If Else If mmp >= 0 Then myAI.memory = mmp : ToMesh(mp) : myAI.State = AI.NPState.UnknownExplorePhase2Move : curMesh = mp Else ToMesh(mp) : myAI.State = AI.NPState.UnknownExplorePhase1Move : curMesh = mp If myMeshptVisibleFromCheckpt(mp) = -1 Then myAI.memory = 0 Else myAI.memory = -1 End If End If Else Debug.WriteLine("all covered") myAI.State = AI.NPState.Stay End If Else If myMeshptVisibleFromCheckpt(curMesh) >= 0 Then ToMesh(mp) : curMesh = mp : myAI.State = AI.NPState.UnknownExplorePhase1Move Else plot: If Not PlotCheckpt(curMesh) Then If meshptCovered = cMesh Then Debug.WriteLine("all cover done") Else Debug.WriteLine("check point error") myAI.State = AI.NPState.Stay Else 'Debug.WriteLine("checkpt, " & (cMesh - meshptCovered)) If myAI.memory = 0 Then myAI.memory = -1 : mp = curMesh If cMesh = meshptCovered Then Debug.WriteLine("All done") myAI.State = AI.NPState.Stay Else Dim mmp As Integer = GetNearestMesptInvisibleFromNgbr(mp, myMeshptVisibleFromCheckpt) If mmp >= 0 Then If myMeshptVisibleFromCheckpt(mp) = -1 Then ToMesh(mp) : myAI.State = AI.NPState.UnknownExplorePhase1Move : curMesh = mp myAI.memory = 0 Else ToMesh(mp) : myAI.State = AI.NPState.UnknownExplorePhase2Move : myAI.memory = mmp : curMesh = mp End If Else path = GetNearestInvisibleMeshpt(curMesh, mp, myMeshptVisibleFromCheckpt) If mp >= 0 Then 'Debug.WriteLine("pathhh") curMesh = mp myAI.State = AI.NPState.UnknownExploreMovePath curTargetPt = path(0) : path.RemoveAt(0) curTarget = TargetType.Location Else Debug.WriteLine("no path again") myAI.State = AI.NPState.Stay End If End If End If End If End If End If Case AI.NPState.UnknownExplorePhase2Move If Reached() Then curTarget = TargetType.None myAI.State = AI.NPState.UnknownExplorePhase2 Else If myangle <> targetAngle Then myangle = targetAngle : Force(speed, myangle, speedX, speedY) Go() End If Case AI.NPState.UnknownExplorePhase2 ToMesh(myAI.memory) : myAI.State = AI.NPState.UnknownExplorePhase1Move : curMesh = myAI.memory : myAI.memory = -1 Case AI.NPState.Avoid 'go away If targetDist < 200 Then 'myangle = (targetAngle + 180) Mod 360 myangle = targetAngle Dim d As Double Dim p As Point = HitToWorldRayCast(x, y, myangle, d) If p <> Nothing Then myObjective.GetFlee() If myObjective.FleePathFound Then 'myObjective.FleePathFound = False path = myObjective.FleePath curTargetPt = path(0) : path.RemoveAt(0) curTarget = TargetType.Location speed = AI.ChaseSpeed myAI.State = AI.NPState.Flee myObjective.lastObjective = Objective.ObjectiveType.None myObjective.lastTarget = -1 Else speed = AI.ChaseSpeed Force(speed, myangle, speedX, speedY) Go(True) End If Else speed = AI.ChaseSpeed Force(speed, myangle, speedX, speedY) Go(True) End If Else 'not stay but go to covered location 'speed = myAI.Speed 'myAI.State = AI.NPState.Stay If myObjective.FleePathFound Then myObjective.FleePathFound = False path = myObjective.FleePath curTargetPt = path(0) : path.RemoveAt(0) curTarget = TargetType.Location speed = AI.ChaseSpeed myAI.State = AI.NPState.Flee myObjective.lastObjective = Objective.ObjectiveType.None myObjective.lastTarget = -1 Else myAI.State = AI.NPState.Stay End If End If Case AI.NPState.Flee If Reached() Then If path.Count > 0 Then curTarget = TargetType.Location curTargetPt = New Point(path(0)) : path.RemoveAt(0) Dim i As Short = GetMeshID(curTargetPt.X, curTargetPt.Y) If i >= 0 Then If myMeshptVisibleFromCheckpt(i) = -1 Then PlotCheckpt(i) End If Else myObjective.curAvoiders.Clear() speed = myAI.Speed myAI.State = AI.NPState.Stay End If Else If myangle <> targetAngle Then myangle = targetAngle : Force(speed, myangle, speedX, speedY) End If Go() End If End Select t = Now.Millisecond - t If t < 60 Then Threading.Thread.Sleep(60 - t) End While End Sub Private Function GetPath() As Boolean Try path = NavMesh.JKImmediateThetaStar(New Point(x, y), curTargetPt, myMeshptVisibleFromCheckpt) If path Is Nothing Then path = New List(Of Point) : Return False curTargetPt = path(0) : path.RemoveAt(0) Return True Catch ex As Exception path.Clear() Return False End Try End Function Public Sub Draw(ByVal g As Graphics, Optional ByVal st As Boolean = True) If id = 0 Then 'g.DrawPie(Pens.Blue, CInt(x - 80), CInt(y - 80), 160, 160, CInt(-myangle) - 45, 90) ElseIf myAI.clever = 0 Then g.DrawRectangle(Pens.Green, CInt(x - 8), CInt(y - 2), 16, 4) g.DrawRectangle(Pens.Green, CInt(x - 10), CInt(y - 6), 6, 12) g.DrawRectangle(Pens.Green, CInt(x + 5), CInt(y + 2), 2, 3) Exit Sub Else g.DrawPie(Pens.Red, CInt(x - 80), CInt(y - 80), 160, 160, CInt(-myangle) - 45, 90) End If Dim r As Short = rad / 2 If st Then g.DrawEllipse(col, CInt(x - r), CInt(y - r), rad, rad) g.DrawString(name, Form2.Font, Brushes.Black, x - 10, y) ElseIf id > 0 Then g.FillEllipse(colb, CInt(x - r), CInt(y - r), rad, rad) g.DrawString(name & "-" & myAI.State, Form2.Font, Brushes.Black, x - 10, y) End If 'If Not curTargetPt = Nothing Then g.DrawEllipse(Pens.Green, curTargetPt.X - 2, curTargetPt.Y - 2, 4, 4) If showMeshpt Then For Each c As CheckPoint In checkPts g.DrawEllipse(col, c.x - 4, c.y - 4, 8, 8) Next If myMeshptVisibleFromCheckpt.Count > 0 Then For i As Short = 0 To mesh.Count - 1 If myMeshptVisibleFromCheckpt(i) >= 0 Then g.DrawEllipse(col, mesh(i).x - 1, mesh(i).y - 1, 2, 2) Next End If End If End Sub End Class
thekoushik/Darker-Unknown
WindowsApplication3/WindowsApplication3/WindowsApplication3/NPC.vb
Visual Basic
mit
27,928
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "CGS_fPedidos" '-------------------------------------------------------------------------------------------' Partial Class CGS_fPedidos Inherits vis2formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine("SELECT Pedidos.Cod_Cli, ") loComandoSeleccionar.AppendLine(" Clientes.Nom_Cli, ") loComandoSeleccionar.AppendLine(" Clientes.Rif, ") loComandoSeleccionar.AppendLine(" Clientes.Dir_Fis, ") loComandoSeleccionar.AppendLine(" Clientes.Telefonos, ") loComandoSeleccionar.AppendLine(" Pedidos.Documento,") loComandoSeleccionar.AppendLine(" Pedidos.Fec_Ini, ") loComandoSeleccionar.AppendLine(" Pedidos.Comentario, ") loComandoSeleccionar.AppendLine(" Pedidos.Status, ") loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Cod_Art, ") loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Comentario AS Com_Ren,") loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Notas, ") loComandoSeleccionar.AppendLine(" Articulos.Nom_Art, ") loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Can_Art1, ") loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Cod_Uni, ") loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Precio1,") loComandoSeleccionar.AppendLine(" Renglones_Pedidos.Mon_Net AS Neto,") loComandoSeleccionar.AppendLine(" Pedidos.Mon_Bru, ") loComandoSeleccionar.AppendLine(" Pedidos.Por_Imp1, ") loComandoSeleccionar.AppendLine(" Pedidos.Mon_Imp1, ") loComandoSeleccionar.AppendLine(" Pedidos.Mon_Net, ") loComandoSeleccionar.AppendLine(" (SELECT Nom_Usu FROM Factory_Global.dbo.Usuarios WHERE Cod_Usu COLLATE DATABASE_DEFAULT = Pedidos.Usu_Cre COLLATE DATABASE_DEFAULT) AS Usuario") loComandoSeleccionar.AppendLine(" ") loComandoSeleccionar.AppendLine("FROM Pedidos ") loComandoSeleccionar.AppendLine(" JOIN Renglones_Pedidos ON Pedidos.Documento = Renglones_Pedidos.Documento ") loComandoSeleccionar.AppendLine(" JOIN Clientes ON Pedidos.Cod_Cli = Clientes.Cod_Cli ") loComandoSeleccionar.AppendLine(" JOIN Formas_Pagos ON Pedidos.Cod_For = Formas_Pagos.Cod_For ") loComandoSeleccionar.AppendLine(" JOIN Vendedores ON Pedidos.Cod_Ven = Vendedores.Cod_Ven ") loComandoSeleccionar.AppendLine(" JOIN Articulos ON Articulos.Cod_Art = Renglones_Pedidos.Cod_Art ") loComandoSeleccionar.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) 'Me.mEscribirConsulta(loComandoSeleccionar.ToString()) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") '-------------------------------------------------------------------------------------------' ' Carga la imagen del logo en cusReportes ' '-------------------------------------------------------------------------------------------' Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa") '-------------------------------------------------------------------------------------------' ' Verificando si el select (tabla nº0) trae registros ' '-------------------------------------------------------------------------------------------' If (laDatosReporte.Tables(0).Rows.Count <= 0) Then Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _ "No se Encontraron Registros para los Parámetros Especificados. ", _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _ "350px", _ "200px") End If loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("CGS_fPedidos", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvCGS_fPedidos.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 '-------------------------------------------------------------------------------------------' ' JJD: 19/12/09: Ajuste al formato del impuesto IVA '-------------------------------------------------------------------------------------------' ' CMS: 17/03/10: Se aplicaron los metodos carga de imagen y validacion de registro cero '-------------------------------------------------------------------------------------------' ' CMS: 11/06/10: Proveedor Genarico '-------------------------------------------------------------------------------------------' ' JJD: 11/03/5: Ajustes al formato para el cliente CEGASA '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
CGS_fPedidos.aspx.vb
Visual Basic
mit
6,789
Option Strict Off Option Explicit On Friend Class frmPricelistList Inherits System.Windows.Forms.Form Dim gFilter As String Dim gRS As ADODB.Recordset Dim gFilterSQL As String Dim gID As Integer Dim gSection As Short Private Sub loadLanguage() rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1183 'Select a Price List Group|Checked If rsLang.RecordCount Then Me.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Me.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1080 'Search|Checked If rsLang.RecordCount Then lbl.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : lbl.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1065 'New|Checked If rsLang.RecordCount Then cmdNew.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdNew.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 frmPricelistList.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 Public Function getItem() As Integer cmdNew.Visible = False loadLanguage() Me.ShowDialog() getItem = gID End Function Private Sub getNamespace() 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 cmdNamespace_Click() frmFilter.loadFilter(gFilter) getNamespace() End Sub Private Sub cmdNew_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdNew.Click frmPriceList.loadItem(0) doSearch() End Sub Private Sub DataList1_DblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles DataList1.DoubleClick If cmdNew.Visible Then If DataList1.BoundText <> "" Then frmPriceList.loadItem(CInt(DataList1.BoundText)) End If doSearch() Else If DataList1.BoundText = "" Then gID = 0 Else gID = CInt(DataList1.BoundText) End If Select Case gSection Case 0 Me.Close() Case 1 report_StockTake(CInt(DataList1.BoundText)) Case 2 frmStockTake.loadItem(CInt(DataList1.BoundText)) Case 3 report_StockQuantityData(CInt(DataList1.BoundText)) End Select End If End Sub Private Sub DataList1_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As KeyPressEventArgs) Handles DataList1.KeyPress Select Case eventArgs.KeyChar Case ChrW(13) DataList1_DblClick(DataList1, New System.EventArgs()) eventArgs.KeyChar = ChrW(0) Case ChrW(27) Me.Close() eventArgs.KeyChar = ChrW(0) End Select End Sub Private Sub frmPricelistList_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 Public Sub loadItem(ByRef section As Short) gSection = section If gSection Then cmdNew.Visible = False doSearch() loadLanguage() Me.ShowDialog() End Sub Private Sub frmPricelistList_FormClosed(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed gRS.Close() End Sub Private Sub txtSearch_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtSearch.Enter txtSearch.SelectionStart = 0 txtSearch.SelectionLength = 999 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 Select Case KeyCode Case 40 Me.DataList1.Focus() End Select 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 doSearch() KeyAscii = 0 End Select eventArgs.KeyChar = Chr(KeyAscii) If KeyAscii = 0 Then eventArgs.Handled = True End If End Sub Private Sub doSearch() Dim sql As String Dim lString As String lString = Trim(txtSearch.Text) lString = Replace(lString, " ", " ") lString = Replace(lString, " ", " ") lString = Replace(lString, " ", " ") lString = Replace(lString, " ", " ") lString = Replace(lString, " ", " ") lString = Replace(lString, " ", " ") If lString = "" Then Else lString = "WHERE (Pricelist_Name LIKE '%" & Replace(lString, " ", "%' AND Pricelist_Name LIKE '%") & "%')" End If gRS = getRS("SELECT DISTINCT PricelistID, Pricelist_Name FROM Pricelist " & lString & " ORDER BY Pricelist_Name") 'Display the list of Titles in the DataCombo DataList1.DataSource = gRS DataList1.listField = "Pricelist_Name" 'Bind the DataCombo to the ADO Recordset 'UPGRADE_ISSUE: VBControlExtender property DataList1.DataSource is not supported at runtime. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="74E732F3-CAD8-417B-8BC9-C205714BB4A7"' DataList1.DataSource = gRS DataList1.boundColumn = "PricelistID" End Sub End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmPricelistList.vb
Visual Basic
mit
6,258
' ' DotNetNuke® - http://www.dotnetnuke.com ' Copyright (c) 2002-2013 ' by DotNetNuke Corporation ' ' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ' documentation files (the "Software"), to deal in the Software without restriction, including without limitation ' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and ' to permit persons to whom the Software is furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all copies or substantial portions ' of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. ' Imports System.DirectoryServices Imports DotNetNuke.Common.Utilities Namespace DotNetNuke.Authentication.ActiveDirectory.ADSI Public Class Domain Inherits DirectoryEntry Private mChildDomains As New ArrayList 'One level child Private mAllChildDomains As New ArrayList 'All level child Private mParentDomain As Domain Private mDistinguishedName As String = "" Private mNetBIOSName As String = "" Private mCanonicalName As String = "" Private mLevel As Integer Private mChildPopulate As Boolean = False ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Sub New() MyBase.New() End Sub ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Sub New (ByVal Path As String, ByVal UserName As String, ByVal Password As String, _ ByVal AuthenticationType As AuthenticationTypes) MyBase.New (Path, UserName, Password, AuthenticationType) PopulateInfo() PopulateChild (Me) mChildPopulate = True End Sub ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Sub New (ByVal Path As String) MyBase.New (Path) PopulateInfo() PopulateChild (Me) mChildPopulate = True End Sub ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Private Sub PopulateInfo() Dim config As Configuration = Configuration.GetConfig() mDistinguishedName = CType (MyBase.Properties (Configuration.ADSI_DISTINGUISHEDNAME).Value, String) mCanonicalName = Utilities.ConvertToCanonical (mDistinguishedName, False) ' Note that this property will be null string if LDAP is unaccessible mNetBIOSName = Utilities.CanonicalToNetBIOS (mCanonicalName) End Sub ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Private Sub PopulateChild (ByVal Domain As Domain) Dim objSearch As New Search (Domain) objSearch.SearchScope = SearchScope.OneLevel objSearch.AddFilter (Configuration.ADSI_CLASS, CompareOperator.Is, ObjectClass.domainDNS.ToString) Dim resDomains As ArrayList = objSearch.GetEntries Dim entry As DirectoryEntry For Each entry In resDomains Dim child As Domain = GetDomain (entry.Path) If Not child Is Nothing Then child.ParentDomain = Domain child.Level = Domain.Level + 1 ' Add this child into childDomains collection Domain.ChildDomains.Add (child) ' add this child and all it's child into allchilddomains collection Domain.AllChildDomains.Add (child) Domain.AllChildDomains.AddRange (child.AllChildDomains) End If Next End Sub ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' Accessing ADs costs lots of resource so we better put ADs object into app cache ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public Shared Function GetDomain (ByVal Path As String) As Domain Return GetDomain (Path, "", "", AuthenticationTypes.Delegation) End Function ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' Accessing ADs costs lots of resource so we better put ADs object into app cache ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public Shared Function GetDomain (ByVal Path As String, ByVal UserName As String, ByVal Password As String, _ ByVal AuthenticationType As AuthenticationTypes) As Domain Dim Domain As Domain = CType (DataCache.GetCache (Path), Domain) If Domain Is Nothing Then If (UserName.Length > 0) AndAlso (Password.Length > 0) Then Domain = New Domain (Path, UserName, Password, AuthenticationType) Else Domain = New Domain (Path) End If DataCache.SetCache (Path, Domain) End If Return Domain End Function ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' Clear domain object in cache ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public Shared Sub ResetDomain (ByVal Path As String) DataCache.RemoveCache (Path) End Sub ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' Return one level child domains ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public ReadOnly Property ChildDomains() As ArrayList Get Return mChildDomains End Get End Property ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' Return child all level child domains ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public ReadOnly Property AllChildDomains() As ArrayList Get Return mAllChildDomains End Get End Property ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' Return parent domain of this domain ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public Property ParentDomain() As Domain Get Return mParentDomain End Get Set (ByVal Value As Domain) mParentDomain = Value End Set End Property ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public Property Level() As Integer Get Return mLevel End Get Set (ByVal Value As Integer) mLevel = Value End Set End Property ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public Property DistinguishedName() As String Get Return mDistinguishedName End Get Set (ByVal Value As String) mDistinguishedName = Value End Set End Property ''' ------------------------------------------------------------------- ''' <summary> ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' [tamttt] 08/01/2004 Created ''' </history> ''' ------------------------------------------------------------------- Public Property ChildPopulate() As Boolean Get Return mChildPopulate End Get Set (ByVal Value As Boolean) mChildPopulate = Value End Set End Property End Class End Namespace
ainsofsoo/DNN.ActiveDirectory
Providers/ADSIProvider/Domain.vb
Visual Basic
mit
11,280
Option Strict On Imports System.Text.RegularExpressions Module Module1 ReadOnly IsinRegex As New Regex("^[A-Z]{2}[A-Z0-9]{9}\d$", RegexOptions.Compiled) Function DigitValue(c As Char) As Integer Dim temp As Integer If Asc(c) >= Asc("0"c) AndAlso Asc(c) <= Asc("9"c) Then temp = Asc(c) - Asc("0"c) Else temp = Asc(c) - Asc("A"c) + 10 End If Return temp End Function Function LuhnTest(number As String) As Boolean Return number.Select(Function(c, i) (AscW(c) - 48) << ((number.Length - i - 1) And 1)).Sum(Function(n) If(n > 9, n - 9, n)) Mod 10 = 0 End Function Function Digitize(isin As String) As String Return String.Join("", isin.Select(Function(c) $"{DigitValue(c)}")) End Function Function IsValidIsin(isin As String) As Boolean Return IsinRegex.IsMatch(isin) AndAlso LuhnTest(Digitize(isin)) End Function Sub Main() Dim isins() = { "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" } For Each isin In isins If IsValidIsin(isin) Then Console.WriteLine("{0} is valid", isin) Else Console.WriteLine("{0} is not valid", isin) End If Next End Sub End Module
ncoe/rosetta
Validate_International_Securities_Identification_Number/Visual Basic .NET/ValidateISIN/Module1.vb
Visual Basic
mit
1,447
Public Class Form4 Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click Me.Close() Form1.Label18.Text = My.Settings.Ppronon End Sub Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click Me.Close() Form1.Label18.Text = My.Settings.Ppronon End Sub Private Sub Form4_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing My.Settings.Ppronon = TextBox1.Text My.Settings.Save() e.Cancel = False End Sub Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load TextBox1.Text = Form1.Label18.Text If Form1.ComboBox11.Text = "FR" Then Label1.Text = "Enregistrer" Label1.Location = New Point(100, 60) End If If Form1.ComboBox11.Text = "EN" Then Label1.Text = "Done" Label1.Location = New Point(111, 60) End If End Sub End Class
colt05/Tomodachi-Life-Save-Editor
Tomodachi Life Save Editor/Form4.vb
Visual Basic
mit
1,011
Private Sub Summary_Create_Lookup_Sheet() Dim wb As Workbook Dim Sheet As Worksheet Dim Table_Obj As ListObject Dim StartCell As Range Dim WkNames As Variant Dim TblNames As Variant Dim PivotNames As Variant Dim PivotSheetNames As Variant Dim lastrow As Long Dim LastColumn As Long Dim rList As Range Dim WkExistCheck As Variant 'DEBUG 'This disables settings to improve macro performance. Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Application.EnableEvents = False WkNames = Array("Potential Mapping Issues", "Unmapped Codes", "Clinical Documentation") WkExistCheck = Array(False, False, False) TblNames = Array("Potential_Table", "Unmapped_Table", "Clinical_Table") PivotNames = Array("Potential_Pivot", "Unmapped_Pivot", "Clinical_Pivot") PivotSheetNames = Array("Potential_Summary_Pivot", "Unmapped_Summary_Pivot", "Clinical_Summary_Pivot") ' Unhides the needed Worksheets For Each Sheet in Worksheets For i = 0 to UBound(WkNames) If WkNames(i) = Sheet.Name Then Sheet.Visible = xlSheetVisible End If Next i Next Sheet 'Deletes the Sheets if they already exist to allow user to re-run program Application.DisplayAlerts = False For Each Sheet In Worksheets If Sheet.Name = "Clinical_Summary_Pivot" _ Or Sheet.Name = "Potential_Summary_Pivot" _ Or Sheet.Name = "Unmapped_Summary_Pivot" _ Or Sheet.Name = "Combined Registry Measures" _ Then Sheet.Delete End If Next Sheet Application.DisplayAlerts = True 'Checks if Wk Exists For i = 0 To UBound(WkNames) On Error GoTo NoSheet Sheets(WkNames(i)).Select WkExistCheck(i) = True NoSheet: Resume ClearError ClearError: Next i ' Loop through each of the worksheets needed and format them in a standardized way ' That is used later on with different programs For i = 0 To UBound(WkNames) CurrentExistCheck = WkExistCheck(i) CurrentWkName = WkNames(i) CurrentTblName = TblNames(i) CurrentPivotName = PivotNames(i) CurrentPivotSheetName = PivotSheetNames(i) If CurrentExistCheck = True Then Sheets(WkNames(i)).Select If ActiveSheet.AutoFilterMode = True Then ActiveSheet.AutoFilterMode = False End If 'Checks the current sheet. If it is in table format, convert it to range. If ActiveSheet.ListObjects.Count > 0 Then With ActiveSheet.ListObjects(1) Set rList = .Range .Unlist End With 'Reverts the color of the range back to standard. With rList .Interior.ColorIndex = xlColorIndexNone .Font.ColorIndex = xlColorIndexAutomatic .Borders.LineStyle = xlLineStyleNone End With End If Set sht = Worksheets(WkNames(i)) 'Sets value Set StartCell = Range("A2") 'Start cell used to determine where to begin creating the table range 'Find Last Row and Column lastrow = StartCell.SpecialCells(xlCellTypeLastCell).Row LastColumn = StartCell.SpecialCells(xlCellTypeLastCell).Column Sheet_Name = WkNames(i) 'Assigns sheet name to a variable as a string 'Select Range sht.Range(StartCell, sht.Cells(lastrow, LastColumn)).Select 'Creates the table Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes) tbl.Name = TblNames(i) 'Names the table tbl.TableStyle = "TableStyleLight12" 'Sets table color theme Rows("2:2").Select With Selection.Font .ThemeColor = xlThemeColorDark1 .TintAndShade = 0 End With 'Creates a new sheet which will house the validated codes pivot table With ThisWorkbook .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = CurrentPivotSheetName End With Sheets(CurrentWkName).Select Range(CurrentTblName).Select ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ CurrentTblName, Version:=6).CreatePivotTable TableDestination:= _ CurrentPivotSheetName & "!R1C1", TableName:=CurrentPivotName, DefaultVersion:=6 Sheets(CurrentPivotSheetName).Select Cells(1, 1).Select ActiveSheet.PivotTables(CurrentPivotName).AddDataField ActiveSheet.PivotTables( _ CurrentPivotName).PivotFields("Source"), "Count of Source", xlCount With ActiveSheet.PivotTables(CurrentPivotName).PivotFields("Registry") .Orientation = xlRowField .Position = 1 End With With ActiveSheet.PivotTables(CurrentPivotName).PivotFields("Measure") .Orientation = xlRowField .Position = 2 End With 'Sets pivot table layout to OUTLINE ActiveSheet.PivotTables(CurrentPivotName).RowAxisLayout xlOutlineRow 'Turns on repeat blank lines ActiveSheet.PivotTables(CurrentPivotName).RepeatAllLabels xlRepeatLabels 'Sets empty values to 0 which helps in a couple places! but also allows the below autofill to have a range reference' ActiveSheet.PivotTables(CurrentPivotName).NullString = "0" Range("D1").Select lastrow = ActiveSheet.Range("C2").End(xlDown).Row Sheets(CurrentPivotSheetName).Select Range("D2").Select ActiveCell.Formula = "=IF(B2 <>"""",CONCATENATE(A2,""|"",B2),"""")" With ActiveSheet.Range("D2") .AutoFill Destination:=Range("D2:D" & lastrow&) End With End If Next i 'Re-enables previously disabled settings after all code has run. Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic Application.EnableEvents = True End Sub
Jonnokc/Excel_VBA
Validation_Form/Summary Page Code/Old/Summary_Create_Lookup_Sheets.vb
Visual Basic
mit
6,334
 Imports MySql.Data.MySqlClient Public Class frmListOfTeachersLoad #Region "Database" Public Sub GetTeachersLoadByTeacher(ByVal intID As Integer) Dim dtaTable As New DataTable dtaTable = GetDataAndReturnDataTableByTermYearByTeacherID(ConnectionString, "GetTeachersLoadByTeacher", 4, CurrentTerm, CurrentSchoolYear, intID) Me.dvgList.DataSource = dtaTable ArrangeDatagridView(Me.dvgList) End Sub Private Sub GetEmployees() Dim dtatable As New DataTable dtatable = GetDataAndReturnDataTable(ConnectionString, "GetEmployeesAllForCombo", 4) With Me.cboInstructor .DataSource = dtatable .DisplayMember = "EmployeeName" .ValueMember = "EmpID" End With End Sub #End Region #Region "Helper" Private Sub ArrangeDatagridView(ByVal TheGridView As DataGridView) Try With TheGridView .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter .Columns(0).Visible = False .Columns(1).Visible = False .Columns(2).HeaderText = "Section Code" .Columns(3).HeaderText = "Subj. Code" .Columns(4).HeaderText = "Descriptive Title" .Columns(5).HeaderText = "Time1" .Columns(6).HeaderText = "Day1" .Columns(7).HeaderText = "Room1" .Columns(8).HeaderText = "Time2" .Columns(9).HeaderText = "Day2" .Columns(10).HeaderText = "Room2" .Columns(11).HeaderText = "Units" .Columns(12).HeaderText = "Num. of Seats" .Columns(13).HeaderText = "Num. of Enrolled" .Columns(2).Width = "85" .Columns(4).Width = "95" .Columns(5).Width = "130" .Columns(6).Width = "65" .Columns(7).Width = "65" .Columns(8).Width = "130" .Columns(9).Width = "65" .Columns(10).Width = "65" .Columns(11).Width = "65" .Columns(12).Width = "100" .Columns(13).Width = "100" '.Columns(3).DefaultCellStyle.Format = "MMM/dd/yyyy" '.Columns(5).DefaultCellStyle.Format = "MMM/dd/yyyy" .Columns(12).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight .Columns(13).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight .Columns(4).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill 'add a column button 'Dim column1 As New DataGridViewButtonColumn 'column1.Name = "Buttons" 'column1.HeaderText = "View Class List" 'column1.Text = "Class List" '.Columns.Add(column1) End With Catch ex As Exception End Try End Sub Private Sub GenerateReport() Dim ListOfFacultyLoad As New List(Of ClassFacultyLoad) For Each row As DataGridViewRow In Me.dvgList.Rows If row.IsNewRow = True Then Else Dim newitem As New ClassFacultyLoad With newitem .SectionCode = row.Cells(2).Value.ToString .SubjectCode = row.Cells(3).Value.ToString .DescriptiveTitle = row.Cells(4).Value.ToString .Time1 = row.Cells(5).Value.ToString .Day1 = row.Cells(6).Value.ToString .Room1 = row.Cells(7).Value.ToString .Time2 = row.Cells(8).Value.ToString .Day2 = row.Cells(9).Value.ToString .Room2 = row.Cells(10).Value.ToString .Units = row.Cells(11).Value .NumStudents = row.Cells(13).Value 'add item to collection ListOfFacultyLoad.Add(newitem) End With End If Next Dim newfrm As New frmReportFacultyLoad With newfrm .FacultyLoadsList = ListOfFacultyLoad .FacultyName = Me.cboInstructor.Text .ShowDialog() End With End Sub #End Region Private Sub cmdClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClose.Click Me.Close() End Sub Private Sub frmListOfDepartments_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Me.ToolStripStatusLabel1.Text = SetWindowHeader(Me, "List of Faculty Loads") 'Me.Text = "List of Departments" 'Me.cmdRefresh.PerformClick() GetEmployees() Me.cboInstructor.SelectedValue = -1 End Sub Private Sub cmdAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddNew.Click Dim newfrm As New frmAddEditDepartment With newfrm .IsAdding = True .FormHeading = "Add New Department" .ShowDialog() If .MustUpdate = True Then Me.cmdRefresh.PerformClick() Me.txtSearch.Text = .txtDescriptiveTitle.Text End If End With End Sub Private Sub cmdRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRefresh.Click Me.dvgList.DataSource = Nothing If Me.cboInstructor.SelectedValue <= 0 Then Me.cboInstructor.Focus() Else GetTeachersLoadByTeacher(Me.cboInstructor.SelectedValue) End If End Sub Private Sub cmdModify_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdModify.Click Dim newfrm As New frmAddEditDepartment With newfrm .IsAdding = False .FormHeading = "Modify Department" .CurrentSujectID = Me.dvgList.CurrentRow.Cells(0).Value .txtDescriptiveTitle.Text = Me.dvgList.CurrentRow.Cells(2).Value .txtSubjectCode.Text = Me.dvgList.CurrentRow.Cells(1).Value .ShowDialog() If .MustUpdate = True Then Me.cmdRefresh.PerformClick() Me.txtSearch.Text = .txtDescriptiveTitle.Text End If End With End Sub Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click Me.dvgList.DataSource = Nothing If Me.cboInstructor.SelectedValue <= 0 Then Me.cboInstructor.Focus() Else GetTeachersLoadByTeacher(Me.cboInstructor.SelectedValue) End If End Sub Private Sub cboInstructor_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboInstructor.SelectedIndexChanged Me.dvgList.DataSource = Nothing Try GetTeachersLoadByTeacher(Me.cboInstructor.SelectedValue) Catch ex As Exception End Try End Sub Private Sub cmdPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrint.Click GenerateReport() End Sub Private Sub cmdClassList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClassList.Click Dim newfrm As New frmClassListBySectionCode Try With newfrm .txtSecCode.Text = Me.dvgList.CurrentRow.Cells(2).Value .txtSubject.Text = Me.dvgList.CurrentRow.Cells(3).Value.ToString & " - " & _ Me.dvgList.CurrentRow.Cells(4).Value.ToString .SectionCode = Me.dvgList.CurrentRow.Cells(2).Value .SubjectCode = Me.dvgList.CurrentRow.Cells(3).Value.ToString .DescTitle = Me.dvgList.CurrentRow.Cells(4).Value.ToString .Time1 = Me.dvgList.CurrentRow.Cells(5).Value.ToString & " / " & _ Me.dvgList.CurrentRow.Cells(8).Value.ToString .Day1 = Me.dvgList.CurrentRow.Cells(6).Value.ToString & " / " & _ Me.dvgList.CurrentRow.Cells(9).Value.ToString .Room1 = Me.dvgList.CurrentRow.Cells(7).Value.ToString & " / " & _ Me.dvgList.CurrentRow.Cells(10).Value.ToString .Units = Me.dvgList.CurrentRow.Cells(11).Value .Instructor = Me.cboInstructor.SelectedValue .txtInstructor.Text = Me.cboInstructor.Text .ShowDialog() End With Catch ex As Exception End Try End Sub Private Sub dvgList_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles dvgList.CellPainting AddNumberingToTheDataGridView(Me.dvgList, e, Me.dvgList.Font) End Sub End Class
JeffreyAReyes/eSMS
Forms/FormsListings/frmListOfTeachersLoad.vb
Visual Basic
mit
8,925
'------------------------------------------------------------------------------ ' <generado automáticamente> ' Este código fue generado por una herramienta. ' ' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si ' se vuelve a generar el código. ' </generado automáticamente> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Partial Public Class VentanaCentroCostoxDetalleReq '''<summary> '''Control Head1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead '''<summary> '''Control form1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm '''<summary> '''Control RadScriptManager1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents RadScriptManager1 As Global.Telerik.Web.UI.RadScriptManager '''<summary> '''Control TextBox1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents TextBox1 As Global.System.Web.UI.WebControls.TextBox '''<summary> '''Control rcbCentroCosto. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents rcbCentroCosto As Global.Telerik.Web.UI.RadComboBox '''<summary> '''Control lbAgregar. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents lbAgregar As Global.System.Web.UI.WebControls.LinkButton '''<summary> '''Control gvCentroCosto. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents gvCentroCosto As Global.System.Web.UI.WebControls.GridView '''<summary> '''Control odsCentroCostoxDetalleRequerimiento. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents odsCentroCostoxDetalleRequerimiento As Global.System.Web.UI.WebControls.ObjectDataSource '''<summary> '''Control odsCentroCostoByProyecto. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents odsCentroCostoByProyecto As Global.System.Web.UI.WebControls.ObjectDataSource '''<summary> '''Control RadAjaxManager1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents RadAjaxManager1 As Global.Telerik.Web.UI.RadAjaxManager End Class
crackper/SistFoncreagro
SistFoncreagro.WebSite/Logistica/VentanaCentroCostoxDetalleReq.aspx.designer.vb
Visual Basic
mit
3,978
Namespace Inspection ''' <summary>Enum Representing Type Member Location.</summary> ''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated> ''' <generator-date>10/02/2014 15:51:43</generator-date> ''' <generator-functions>1</generator-functions> ''' <generator-source>Leviathan\_Inspection\Enums\MemberLocation.tt</generator-source> ''' <generator-version>1</generator-version> <System.CodeDom.Compiler.GeneratedCode("Leviathan\_Inspection\Enums\MemberLocation.tt", "1")> _ <Flags()> _ Public Enum MemberLocation As System.Int32 ''' <summary>Member is located as an Instance Member.</summary> Instance = 1 ''' <summary>Member is located as a Static Member.</summary> [Static] = 2 ''' <summary>All Flags</summary> All = Instance Or _ [Static] End Enum End Namespace
thiscouldbejd/Leviathan
_Inspection/Enums/MemberLocation.vb
Visual Basic
mit
875
Imports BVSoftware.BVC5.Core Partial Class BVAdmin_People_PriceGroups Inherits BaseAdminPage Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack() Then BindGrids() End If End Sub Protected Sub BindGrids() PricingGroupsGridView.DataSource = Contacts.PriceGroup.FindAll() PricingGroupsGridView.DataBind() End Sub Protected Sub Page_PreInit1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit Me.PageTitle = "Price Groups" Me.CurrentTab = AdminTabType.People ValidateCurrentUserHasPermission(Membership.SystemPermissions.PeopleView) End Sub Protected Sub SaveImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles SaveImageButton.Click For Each row As GridViewRow In PricingGroupsGridView.Rows Dim key As String = PricingGroupsGridView.DataKeys(row.RowIndex).Value Dim pricingGroup As Contacts.PriceGroup = Contacts.PriceGroup.FindByBvin(key) Dim NameTextBox As TextBox = DirectCast(row.FindControl("NameTextBox"), TextBox) Dim PricingTypeDropDownList As DropDownList = DirectCast(row.FindControl("PricingTypeDropDownList"), DropDownList) Dim AdjustmentAmountTextBox As TextBox = DirectCast(row.FindControl("AdjustmentAmountTextBox"), TextBox) Dim needToUpdate As Boolean = False If pricingGroup.Name <> NameTextBox.Text Then pricingGroup.Name = NameTextBox.Text needToUpdate = True End If If pricingGroup.PricingType <> PricingTypeDropDownList.SelectedValue Then pricingGroup.PricingType = PricingTypeDropDownList.SelectedValue needToUpdate = True End If If pricingGroup.AdjustmentAmount <> Decimal.Parse(AdjustmentAmountTextBox.Text, System.Globalization.NumberStyles.Currency) Then pricingGroup.AdjustmentAmount = Decimal.Parse(AdjustmentAmountTextBox.Text, System.Globalization.NumberStyles.Currency) needToUpdate = True End If If needToUpdate Then Contacts.PriceGroup.Update(pricingGroup) End If Next MessageBox1.ShowOk("Price groups updated") End Sub Protected Sub PricingGroupsGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles PricingGroupsGridView.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DataItem IsNot Nothing Then Dim pricingGroup As Contacts.PriceGroup = DirectCast(e.Row.DataItem, Contacts.PriceGroup) DirectCast(e.Row.FindControl("NameTextBox"), TextBox).Text = pricingGroup.Name DirectCast(e.Row.FindControl("PricingTypeDropDownList"), DropDownList).SelectedValue = pricingGroup.PricingType DirectCast(e.Row.FindControl("AdjustmentAmountTextBox"), TextBox).Text = pricingGroup.AdjustmentAmount.ToString("N") End If End If End Sub Protected Sub AddNewImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles AddNewImageButton.Click Dim pricingGroup As New Contacts.PriceGroup() pricingGroup.Name = "New Pricing Group" If Contacts.PriceGroup.Insert(pricingGroup) Then MessageBox1.ShowOk("New price group added") Else MessageBox1.ShowError("An error occurred while price group was being added.") End If BindGrids() End Sub Protected Sub CancelImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles CancelImageButton.Click BindGrids() MessageBox1.ShowOk("Price group values have been reset") End Sub Protected Sub PricingGroupsGridView_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles PricingGroupsGridView.RowDeleting Dim key As String = PricingGroupsGridView.DataKeys(e.RowIndex).Value If Contacts.PriceGroup.Delete(key) Then MessageBox1.ShowOk("Pricing group deleted") Else MessageBox1.ShowError("An error occurred while price group was being deleted") End If BindGrids() End Sub End Class
ajaydex/Scopelist_2015
BVAdmin/People/PriceGroups.aspx.vb
Visual Basic
apache-2.0
4,498
'------------------------------------------------------------------------------ ' <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", "16.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("mzkit.quantify.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
xieguigang/spectrum
Rscript/Library/mzkit.quantify/My Project/Resources.Designer.vb
Visual Basic
mit
2,721
' 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 ''' <summary> ''' Represents a <see cref="VisualBasicSyntaxVisitor"/> that descends an entire <see cref="SyntaxNode"/> tree ''' visiting each SyntaxNode and its child <see cref="SyntaxNode"/>s and <see cref="SyntaxToken"/>s in depth-first order. ''' </summary> Public MustInherit Class VisualBasicSyntaxWalker Inherits VisualBasicSyntaxVisitor Protected ReadOnly Depth As SyntaxWalkerDepth Protected Sub New(Optional depth As SyntaxWalkerDepth = SyntaxWalkerDepth.Node) Me.Depth = depth End Sub Private _recursionDepth As Integer Public Overrides Sub Visit(node As SyntaxNode) If node IsNot Nothing Then _recursionDepth += 1 If _recursionDepth > Syntax.InternalSyntax.Parser.MaxUncheckedRecursionDepth Then PortableShim.RuntimeHelpers.EnsureSufficientExecutionStack() End If DirectCast(node, VisualBasicSyntaxNode).Accept(Me) _recursionDepth -= 1 End If End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) Dim list = node.ChildNodesAndTokens() Dim childCnt = list.Count Dim i As Integer = 0 Do Dim child = list(i) i = i + 1 Dim asNode = child.AsNode() If asNode IsNot Nothing Then If Depth >= SyntaxWalkerDepth.Node Then Me.Visit(asNode) End If Else If Depth >= SyntaxWalkerDepth.Token Then Me.VisitToken(child.AsToken()) End If End If Loop While i < childCnt End Sub Public Overridable Sub VisitToken(token As SyntaxToken) If Depth >= SyntaxWalkerDepth.Trivia Then Me.VisitLeadingTrivia(token) Me.VisitTrailingTrivia(token) End If End Sub Public Overridable Sub VisitLeadingTrivia(token As SyntaxToken) If token.HasLeadingTrivia Then For Each tr In token.LeadingTrivia VisitTrivia(tr) Next End If End Sub Public Overridable Sub VisitTrailingTrivia(token As SyntaxToken) If token.HasTrailingTrivia Then For Each tr In token.TrailingTrivia VisitTrivia(tr) Next End If End Sub Public Overridable Sub VisitTrivia(trivia As SyntaxTrivia) If Depth >= SyntaxWalkerDepth.StructuredTrivia AndAlso trivia.HasStructure Then Visit(DirectCast(trivia.GetStructure(), VisualBasicSyntaxNode)) End If End Sub End Class End Namespace
furesoft/roslyn
src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxWalker.vb
Visual Basic
apache-2.0
3,217
Imports System Imports System.Windows.Controls Imports ESRI.ArcGIS.Client Partial Public Class EditToolsSelectionOnly Inherits UserControl Private _featureDataFormOpen As Boolean = False Public Sub New() InitializeComponent() End Sub Private Sub FeatureLayer_Initialized(ByVal sender As Object, ByVal e As EventArgs) Dim editor = TryCast(LayoutRoot.Resources("MyEditor"), Editor) If editor.Select.CanExecute("new") Then editor.Select.Execute("new") End If End Sub Private Sub Editor_EditCompleted(ByVal sender As Object, ByVal e As Editor.EditEventArgs) Dim editor = TryCast(sender, Editor) If e.Action = Editor.EditAction.Select Then For Each edit In e.Edits If edit.Graphic IsNot Nothing AndAlso edit.Graphic.Selected Then Dim layer = TryCast(edit.Layer, FeatureLayer) If layer IsNot Nothing AndAlso layer.IsGeometryUpdateAllowed(edit.Graphic) Then If editor.EditVertices.CanExecute(edit.Graphic) Then editor.EditVertices.Execute(edit.Graphic) End If FeatureDataFormBorder.Visibility = System.Windows.Visibility.Visible _featureDataFormOpen = True Dim layerDefinition As New LayerDefinition() With {.LayerID = 2, .Definition = String.Format("{0} <> {1}", layer.LayerInfo.ObjectIdField, edit.Graphic.Attributes(layer.LayerInfo.ObjectIdField).ToString())} TryCast(MyMap.Layers("WildFireDynamic"), ArcGISDynamicMapServiceLayer).LayerDefinitions = New System.Collections.ObjectModel.ObservableCollection(Of LayerDefinition)() From {layerDefinition} TryCast(MyMap.Layers("WildFireDynamic"), ESRI.ArcGIS.Client.ArcGISDynamicMapServiceLayer).Refresh() End If MyFeatureDataForm.GraphicSource = edit.Graphic Exit For End If Next edit ElseIf e.Action = Editor.EditAction.ClearSelection Then FeatureDataFormBorder.Visibility = System.Windows.Visibility.Collapsed MyFeatureDataForm.GraphicSource = Nothing TryCast(MyMap.Layers("WildFirePolygons"), FeatureLayer).ClearSelection() TryCast(MyMap.Layers("WildFireDynamic"), ArcGISDynamicMapServiceLayer).LayerDefinitions = Nothing TryCast(MyMap.Layers("WildFireDynamic"), ESRI.ArcGIS.Client.ArcGISDynamicMapServiceLayer).Refresh() End If End Sub Private Sub ResetEditableSelection() If Not _featureDataFormOpen Then MyFeatureDataForm.GraphicSource = Nothing TryCast(MyMap.Layers("WildFireDynamic"), ArcGISDynamicMapServiceLayer).LayerDefinitions = Nothing TryCast(MyMap.Layers("WildFirePolygons"), FeatureLayer).ClearSelection() End If TryCast(MyMap.Layers("WildFireDynamic"), ESRI.ArcGIS.Client.ArcGISDynamicMapServiceLayer).Refresh() End Sub Private Sub FeatureLayer_EndSaveEdits(ByVal sender As Object, ByVal e As ESRI.ArcGIS.Client.Tasks.EndEditEventArgs) ResetEditableSelection() End Sub Private Sub FeatureLayer_SaveEditsFailed(ByVal sender As Object, ByVal e As ESRI.ArcGIS.Client.Tasks.TaskFailedEventArgs) ResetEditableSelection() End Sub Private Sub MyFeatureDataForm_EditEnded(ByVal sender As Object, ByVal e As EventArgs) FeatureDataFormBorder.Visibility = System.Windows.Visibility.Collapsed _featureDataFormOpen = False End Sub End Class
Esri/arcgis-samples-silverlight
src/VBNet/ArcGISSilverlightSDK/Editing/EditToolsSelectionOnly.xaml.vb
Visual Basic
apache-2.0
3,324
' Copyright (c) 2015 ZZZ Projects. All rights reserved ' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) ' Website: http://www.zzzprojects.com/ ' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 ' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library Public Module Extensions_475 ''' <summary> ''' Returns a value indicating the sign of a single-precision floating-point number. ''' </summary> ''' <param name="value">A signed number.</param> ''' <returns> ''' A number that indicates the sign of , as shown in the following table.Return value Meaning -1 is less than ''' zero. 0 is equal to zero. 1 is greater than zero. ''' </returns> <System.Runtime.CompilerServices.Extension> _ Public Function Sign(value As [Single]) As Int32 Return Math.Sign(value) End Function End Module
huoxudong125/Z.ExtensionMethods
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Single/System.Math/Single.Sign.vb
Visual Basic
mit
941
' 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 Roslyn.Test.Utilities Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBConstLocalTests Inherits BasicTestBase <Fact()> Public Sub TestSimpleLocalConstants() Dim source = <compilation> <file> Imports System Public Class C Public Sub M() const x as integer = 1 const y as integer = 2 Console.WriteLine(x + y) end sub end class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( source, TestOptions.DebugDll) compilation.VerifyDiagnostics() compilation.VerifyPdb("C.M", <symbols> <methods> <method containingType="C" name="M"> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="19" document="0"/> <entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="33" document="0"/> <entry offset="0x8" startLine="7" startColumn="5" endLine="7" endColumn="12" document="0"/> </sequencePoints> <locals> <constant name="x" value="1" type="Int32"/> <constant name="y" value="2" type="Int32"/> </locals> <scope startOffset="0x0" endOffset="0x9"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <constant name="x" value="1" type="Int32"/> <constant name="y" value="2" type="Int32"/> </scope> </method> </methods> </symbols>) End Sub <Fact()> Public Sub TestLambdaLocalConstants() Dim source = <compilation> <file> Imports System Public Class C Public Sub M(a as action) const x as integer = 1 M( Sub() const y as integer = 2 const z as integer = 3 Console.WriteLine(x + y + z) end Sub ) end sub end class </file> </compilation> Dim c = CompileAndVerify(source, options:=TestOptions.DebugDll) c.VerifyPdb( <symbols> <methods> <method containingType="C" name="M" parameterNames="a"> <customDebugInfo> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="48"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="30" document="0"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="11" endColumn="11" document="0"/> <entry offset="0x2c" startLine="12" startColumn="5" endLine="12" endColumn="12" document="0"/> </sequencePoints> <locals> <constant name="x" value="1" type="Int32"/> </locals> <scope startOffset="0x0" endOffset="0x2d"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <constant name="x" value="1" type="Int32"/> </scope> </method> <method containingType="C+_Closure$__" name="_Lambda$__1-0"> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="13" endLine="6" endColumn="18" document="0"/> <entry offset="0x1" startLine="9" startColumn="17" endLine="9" endColumn="45" document="0"/> <entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="20" document="0"/> </sequencePoints> <locals> <constant name="y" value="2" type="Int32"/> <constant name="z" value="3" type="Int32"/> </locals> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="C" methodName="M" parameterNames="a"/> <constant name="y" value="2" type="Int32"/> <constant name="z" value="3" type="Int32"/> </scope> </method> </methods> </symbols>) End Sub #If False Then <WorkItem(11017)> <Fact()> Public Sub TestIteratorLocalConstants() Dim text = <text> using System.Collections.Generic; class C { IEnumerable&lt;int&gt; M() { const int x = 1; for (int i = 0; i &lt; 10; i++) { const int y = 2; yield return x + y + i; } } } </text>.Value AssertXmlEqual(expected, actual) End Sub #End If <WorkItem(529101, "DevDiv")> <Fact()> Public Sub TestLocalConstantsTypes() Dim source = <compilation> <file> Imports System Public Class C Sub M() const o as object = nothing const s as string = "hello" const f as single = single.MinValue const d as double = double.MaxValue const dec as decimal = 1.5D const dt as datetime = #2/29/2012# End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( source, TestOptions.DebugDll) compilation.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocalConst, "o").WithArguments("o"), Diagnostic(ERRID.WRN_UnusedLocalConst, "s").WithArguments("s"), Diagnostic(ERRID.WRN_UnusedLocalConst, "f").WithArguments("f"), Diagnostic(ERRID.WRN_UnusedLocalConst, "d").WithArguments("d"), Diagnostic(ERRID.WRN_UnusedLocalConst, "dec").WithArguments("dec"), Diagnostic(ERRID.WRN_UnusedLocalConst, "dt").WithArguments("dt")) Dim actual As XElement = GetPdbXml(compilation, "C.M") Dim invariantStr = actual.ToString() invariantStr = invariantStr.Replace("-3,402823E+38", "-3.402823E+38") invariantStr = invariantStr.Replace("1,79769313486232E+308", "1.79769313486232E+308") invariantStr = invariantStr.Replace("2,98187743664301E-266", "2.98187743664301E-266") invariantStr = invariantStr.Replace("value=""1,5""", "value=""1.5""") Dim expected = <symbols> <methods> <method containingType="C" name="M"> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="12" document="0"/> <entry offset="0x1" startLine="10" startColumn="5" endLine="10" endColumn="12" document="0"/> </sequencePoints> <locals> <constant name="o" value="0" type="Int32"/> <constant name="s" value="hello" type="String"/> <constant name="f" value="-3.402823E+38" type="Single"/> <constant name="d" value="1.79769313486232E+308" type="Double"/> <constant name="dec" value="1.5" type="Decimal"/> <constant name="dt" value="2.98187743664301E-266" type="Double"/> </locals> <scope startOffset="0x0" endOffset="0x2"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <constant name="o" value="0" type="Int32"/> <constant name="s" value="hello" type="String"/> <constant name="f" value="-3.402823E+38" type="Single"/> <constant name="d" value="1.79769313486232E+308" type="Double"/> <constant name="dec" value="1.5" type="Decimal"/> <constant name="dt" value="2.98187743664301E-266" type="Double"/> </scope> </method> </methods> </symbols> 'AssertXmlEqual(expected, actual) Assert.Equal(expected.ToString(), invariantStr) End Sub End Class End Namespace
akoeplinger/roslyn
src/Compilers/VisualBasic/Test/Emit/PDB/PDBConstLocalTests.vb
Visual Basic
apache-2.0
9,108
' 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.ChangeNamespace Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ChangeNamespace <ExportLanguageService(GetType(IChangeNamespaceService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicChangeNamespaceService Inherits AbstractChangeNamespaceService(Of NamespaceStatementSyntax, CompilationUnitSyntax, StatementSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function TryGetReplacementReferenceSyntax(reference As SyntaxNode, newNamespaceParts As ImmutableArray(Of String), syntaxFacts As ISyntaxFactsService, ByRef old As SyntaxNode, ByRef [new] As SyntaxNode) As Boolean Dim nameRef = TryCast(reference, SimpleNameSyntax) old = nameRef [new] = nameRef If nameRef Is Nothing Or newNamespaceParts.IsDefaultOrEmpty Then Return False End If If syntaxFacts.IsRightOfQualifiedName(nameRef) Then old = nameRef.Parent If IsGlobalNamespace(newNamespaceParts) Then [new] = SyntaxFactory.QualifiedName(SyntaxFactory.GlobalName(), nameRef.WithoutTrivia()) Else Dim qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, newNamespaceParts.Length - 1) [new] = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()) End If [new] = [new].WithTriviaFrom(old) ElseIf syntaxFacts.IsNameOfsimpleMemberAccessExpression(nameRef) Then old = nameRef.Parent If IsGlobalNamespace(newNamespaceParts) Then [new] = SyntaxFactory.SimpleMemberAccessExpression(SyntaxFactory.GlobalName(), nameRef.WithoutTrivia()) Else Dim memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, newNamespaceParts.Length - 1) [new] = SyntaxFactory.SimpleMemberAccessExpression(memberAccessNamespaceName, nameRef.WithoutTrivia()) End If [new] = [new].WithTriviaFrom(old) End If Return True End Function ' TODO: Implement the service for VB Protected Overrides Function GetValidContainersFromAllLinkedDocumentsAsync(document As Document, container As SyntaxNode, cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of (DocumentId, SyntaxNode))) Return SpecializedTasks.Default(Of ImmutableArray(Of (DocumentId, SyntaxNode)))() End Function ' This is only reachable when called from a VB service, which is not implemented yet. Protected Overrides Function ChangeNamespaceDeclaration(root As CompilationUnitSyntax, declaredNamespaceParts As ImmutableArray(Of String), targetNamespaceParts As ImmutableArray(Of String)) As CompilationUnitSyntax Throw ExceptionUtilities.Unreachable End Function ' This is only reachable when called from a VB service, which is not implemented yet. Protected Overrides Function GetMemberDeclarationsInContainer(container As SyntaxNode) As SyntaxList(Of StatementSyntax) Throw ExceptionUtilities.Unreachable End Function ' This is only reachable when called from a VB service, which is not implemented yet. Protected Overrides Function TryGetApplicableContainerFromSpanAsync(document As Document, span As TextSpan, cancellationToken As CancellationToken) As Task(Of SyntaxNode) Throw ExceptionUtilities.Unreachable End Function ' This is only reachable when called from a VB service, which is not implemented yet. Protected Overrides Function GetDeclaredNamespace(container As SyntaxNode) As String Throw ExceptionUtilities.Unreachable End Function Private Shared Function CreateNamespaceAsQualifiedName(namespaceParts As ImmutableArray(Of String), index As Integer) As NameSyntax Dim part = namespaceParts(index).EscapeIdentifier() Dim namePiece = SyntaxFactory.IdentifierName(part) If index = 0 Then Return namePiece Else Return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, index - 1), namePiece) End If End Function Private Shared Function CreateNamespaceAsMemberAccess(namespaceParts As ImmutableArray(Of String), index As Integer) As ExpressionSyntax Dim part = namespaceParts(index).EscapeIdentifier() Dim namePiece = SyntaxFactory.IdentifierName(part) If index = 0 Then Return namePiece Else Return SyntaxFactory.SimpleMemberAccessExpression(CreateNamespaceAsMemberAccess(namespaceParts, index - 1), namePiece) End If End Function End Class End Namespace
CyrusNajmabadi/roslyn
src/Features/VisualBasic/Portable/CodeRefactorings/SyncNamespace/VisualBasicChangeNamespaceService.vb
Visual Basic
mit
5,528
' 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.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Public Class ImplementedByGraphQueryTests <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub TestImplementedBy1() Using testState = New ProgressionTestState( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; interface $$IBlah { } abstract class Base { public abstract int CompareTo(object obj); } class Foo : Base, IComparable, IBlah { public override int CompareTo(object obj) { throw new NotImplementedException(); } } class Foo2 : Base, IBlah { public override int CompareTo(object obj) { throw new NotImplementedException(); } } </Document> </Project> </Workspace>) Dim inputGraph = testState.GetGraphWithMarkedSymbolNode() Dim outputContext = testState.GetGraphContextAfterQuery(inputGraph, New ImplementedByGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=Foo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Foo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Foo"/> <Node Id="(@1 Type=Foo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Foo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Foo2"/> <Node Id="(@1 Type=IBlah)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="IBlah" Icon="Microsoft.VisualStudio.Interface.Internal" Label="IBlah"/> </Nodes> <Links> <Link Source="(@1 Type=Foo)" Target="(@1 Type=IBlah)" Category="Implements"/> <Link Source="(@1 Type=Foo2)" Target="(@1 Type=IBlah)" Category="Implements"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> </IdentifierAliases> </DirectedGraph>) End Using End Sub End Class End Namespace
DavidKarlas/roslyn
src/VisualStudio/Core/Test/Progression/ImplementedByGraphQueryTests.vb
Visual Basic
apache-2.0
2,928
Imports CodeCracker.VisualBasic.Usage Imports Xunit Namespace Usage Public Class RemovePrivateMethodNeverUsedAnalyzerTest Inherits CodeFixVerifier(Of RemovePrivateMethodNeverUsedAnalyzer, RemovePrivateMethodNeverUsedCodeFixProvider) <Fact> Public Async Function DoesNotGenerateDiagnostics() As Task Const test = " Public Class Foo Public Sub PublicFoo PrivateFoo() End Sub Private Sub PrivateFoo PrivateFoo2 End Sub Private Sub PrivateFoo2 End Sub End Class" Await VerifyBasicHasNoDiagnosticsAsync(test) End Function <Fact> Public Async Function WhenPrivateMethodUsedInPartialClassesDoesNotGenerateDiagnostics() As Task Const test = " Public Partial Class Foo Public Sub PublicFoo PrivateFoo() End Sub End Class Public Partial Class Foo Private Sub PrivateFoo End Sub End Class" Await VerifyBasicHasNoDiagnosticsAsync(test) End Function <Fact> Public Async Function WhenPrivateMethodIsNotUsedInPartialClassesItShouldBeRemoved() As Task Const test = " Public Partial Class Foo Public Sub PublicFoo End Sub End Class Public Partial Class Foo Private Sub PrivateFoo End Sub End Class" Const fix = " Public Partial Class Foo Public Sub PublicFoo End Sub End Class Public Partial Class Foo End Class" Await VerifyBasicFixAsync(test, fix) End Function <Fact> Public Async Function WhenPrivateMethodUsedDoesNotGenerateDiagnostics() As Task Const test = " Public Class Foo Public Sub PublicFoo PrivateFoo() End Sub End Class" Await VerifyBasicHasNoDiagnosticsAsync(test) End Function <Fact> Public Async Function WhenPrivateMethodIsNotUsedShouldCreateDiagnostic() As Task Const test = " Class Foo Private Sub PrivateFoo() End Sub End Class" Const fix = " Class Foo End Class" Await VerifyBasicFixAsync(test, fix) End Function <Fact> Public Async Function WhenPrivateMethodUsedInAttributionDoesNotGenerateDiagnostics() As Task Const test = " Imports System Class Foo Public Sub PublicFoo() Dim method As Action = AddressOf PrivateFoo End Sub Private Sub PrivateFoo() End Sub End Class" Await VerifyBasicHasNoDiagnosticsAsync(test) End Function End Class End Namespace
dmgandini/code-cracker
test/VisualBasic/CodeCracker.Test/Usage/RemovePrivateMethodNeverUsedAnalyzerTest.vb
Visual Basic
apache-2.0
2,417
' 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.Reflection Imports Microsoft.CodeAnalysis.Scripting Imports Microsoft.CodeAnalysis.Scripting.Hosting Imports Microsoft.CodeAnalysis.Scripting.Test Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests Public Class CommandLineRunnerTests Inherits TestBase Private Shared ReadOnly s_compilerVersion As String = GetType(VisualBasicInteractiveCompiler).GetTypeInfo().Assembly.GetCustomAttribute(Of AssemblyFileVersionAttribute)().Version Private Shared ReadOnly s_defaultArgs As String() = {"/R:System"} Private Shared Function CreateRunner( Optional args As String() = Nothing, Optional input As String = "", Optional responseFile As String = Nothing, Optional workingDirectory As String = Nothing ) As CommandLineRunner Dim io = New TestConsoleIO(input) Dim compiler = New VisualBasicInteractiveCompiler( responseFile, If(workingDirectory, AppContext.BaseDirectory), CorLightup.Desktop.TryGetRuntimeDirectory(), AppContext.BaseDirectory, If(args, s_defaultArgs), New NotImplementedAnalyzerLoader()) Return New CommandLineRunner( io, compiler, VisualBasicScriptCompiler.Instance, VisualBasicObjectFormatter.Instance) End Function <Fact()> Public Sub TestPrint() Dim runner = CreateRunner(input:="? 10") runner.RunInteractive() AssertEx.AssertEqualToleratingWhitespaceDifferences( "Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + " Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > ? 10 10 >", runner.Console.Out.ToString()) End Sub <Fact()> Public Sub TestImportArgument() Dim runner = CreateRunner(args:={"/Imports:<xmlns:xmlNamespacePrefix='xmlNamespaceName'>"}) runner.RunInteractive() AssertEx.AssertEqualToleratingWhitespaceDifferences( "Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + " Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. >", runner.Console.Out.ToString()) End Sub <Fact()> Public Sub TestReferenceDirective() Dim file1 = Temp.CreateFile("1.dll").WriteAllBytes(TestCompilationFactory.CreateVisualBasicCompilationWithMscorlib(" public Class C1 Public Function Foo() As String Return ""Bar"" End Function End Class", "1").EmitToArray()) Dim runner = CreateRunner(args:={}, input:="#r """ & file1.Path & """" & vbCrLf & "? New C1().Foo()") runner.RunInteractive() AssertEx.AssertEqualToleratingWhitespaceDifferences( "Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + " Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > #r """ & file1.Path & """ > ? New C1().Foo() ""Bar"" >", runner.Console.Out.ToString()) runner = CreateRunner(args:={}, input:="? New C1().Foo()") runner.RunInteractive() AssertEx.AssertEqualToleratingWhitespaceDifferences( "Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + " Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > ? New C1().Foo() «Red» (1) : error BC30002: Type 'C1' is not defined. «Gray» >", runner.Console.Out.ToString()) End Sub <Fact()> Public Sub TestReferenceDirectiveWhenReferenceMissing() Dim runner = CreateRunner(args:={}, input:="#r ""://invalidfilepath""") runner.RunInteractive() AssertEx.AssertEqualToleratingWhitespaceDifferences( "Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + " Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > #r ""://invalidfilepath"" «Red» (1) : error BC2017: could not find library '://invalidfilepath' «Gray» >", runner.Console.Out.ToString()) End Sub <Fact()> <WorkItem(7133, "https://github.com/dotnet/roslyn/issues/7133")> Public Sub TestDisplayResultsWithCurrentUICulture() Dim runner = CreateRunner(args:={}, input:="Imports System.Globalization System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"") ? System.Math.PI System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""de-DE"") ? System.Math.PI") runner.RunInteractive() AssertEx.AssertEqualToleratingWhitespaceDifferences( "Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + " Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > Imports System.Globalization > System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"") > ? System.Math.PI 3.1415926535897931 > System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""de-DE"") > ? System.Math.PI 3,1415926535897931 >", runner.Console.Out.ToString()) ' Tests that DefaultThreadCurrentUICulture is respected and not DefaultThreadCurrentCulture. runner = CreateRunner(args:={}, input:="Imports System.Globalization System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"") System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"") ? System.Math.PI System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(""de-DE"") ? System.Math.PI") runner.RunInteractive() AssertEx.AssertEqualToleratingWhitespaceDifferences( "Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + " Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > Imports System.Globalization > System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"") > System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"") > ? System.Math.PI 3.1415926535897931 > System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(""de-DE"") > ? System.Math.PI 3.1415926535897931 >", runner.Console.Out.ToString()) End Sub End Class End Namespace
MatthieuMEZIL/roslyn
src/Scripting/VisualBasicTest/CommandLineRunnerTests.vb
Visual Basic
apache-2.0
7,265
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_Property1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; namespace ConsoleApplication22 { class Program { static public int {|Definition:F$$oo|} { get { return 1; } } static void Main(string[] args) { int temp = Program.[|Foo|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_Property2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; namespace ConsoleApplication22 { class Program { static public int {|Definition:Foo|} { get { return 1; } } static void Main(string[] args) { int temp = Program.[|Fo$$o|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyCascadeThroughInterface1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { int {|Definition:$$P|} { get; } } class C : I { public int {|Definition:P|} { get; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyCascadeThroughInterface2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { int {|Definition:P|} { get; } } class C : I { public int {|Definition:$$P|} { get; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:$$Area|} { get; } } class C1 : I1 { public int {|Definition:Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:Area|} { get; } } class C1 : I1 { public int {|Definition:$$Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase3() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int Definition:Area { get; } } class C1 : I1 { public int Definition:Area { get { return 1; } } } class C2 : C1 { public int {|Definition:$$Area|} { get { return base.Area; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase4() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:Area|} { get; } } class C1 : I1 { public int {|Definition:Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|$$Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_ExplicitProperty1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public interface DD { int {|Definition:$$Prop|} { get; set; } } public class A : DD { int DD.{|Definition:Prop|} { get { return 1; } set { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_ExplicitProperty2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public interface DD { int {|Definition:Prop|} { get; set; } } public class A : DD { int DD.{|Definition:$$Prop|} { get { return 1; } set { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:$$Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T Name { get; set; } } interface I2 { int {|Definition:$$Name|} { get; set; } } interface I3<T> : I2 { new T Name { get; set; } } public class M<T> : I1<T>, I3<T> { public T Name { get; set; } int I2.{|Definition:Name|} { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface3() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:$$Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface4() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T Name { get; set; } } interface I2 { int {|Definition:Name|} { get; set; } } interface I3<T> : I2 { new T Name { get; set; } } public class M<T> : I1<T>, I3<T> { public T Name { get; set; } int I2.{|Definition:$$Name|} { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface5() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:$$Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_PropertyFunctionValue1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Module Program ReadOnly Property {|Definition:$$X|} As Integer ' Rename X to Y Get [|X|] = 1 End Get End Property End Module]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_PropertyFunctionValue2() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Module Program ReadOnly Property {|Definition:X|} As Integer ' Rename X to Y Get [|$$X|] = 1 End Get End Property End Module]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { $$[|{|Definition:P|}|] = 4 }; var b = new { P = "asdf" }; var c = new { [|P|] = 4 }; var d = new { P = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { [|P|] = 4 }; var b = new { P = "asdf" }; var c = new { $$[|{|Definition:P|}|] = 4 }; var d = new { P = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties3() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { P = 4 }; var b = new { $$[|{|Definition:P|}|] = "asdf" }; var c = new { P = 4 }; var d = new { [|P|] = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties4() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { P = 4 }; var b = new { [|P|] = "asdf" }; var c = new { P = 4 }; var d = new { $$[|{|Definition:P|}|] = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.at = New With {.s = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key {|Definition:a1|}} Dim hello = query.First() Console.WriteLine(hello.$$[|a1|].at.s) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties2() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.[|{|Definition:at|}|] = New With {.s = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key a1} Dim hello = query.First() Console.WriteLine(hello.a1.$$[|at|].s) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties3() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.at = New With {.[|{|Definition:s|}|] = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key a1} Dim hello = query.First() Console.WriteLine(hello.a1.at.$$[|s|]) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenPropertyAndField1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property {|Definition:$$X|}() Sub Foo() Console.WriteLine([|_X|]) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenPropertyAndField2() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property {|Definition:X|}() Sub Foo() Console.WriteLine([|$$_X|]) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod1() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:$$X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:get_X|}(int y) { return base.[|get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod2() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:$$get_X|}(int y) { return base.[|get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod3() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:get_X|}(int y) { return base.[|$$get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_DefaultProperties() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Strict On Public Interface IA Default Property Foo(ByVal x As Integer) As Integer End Interface Public Interface IC Inherits IA Default Overloads Property {|Definition:$$Foo|}(ByVal x As Long) As String ' Rename Foo to Bar End Interface Class M Sub F(x As IC) Dim y = x[||](1L) Dim y2 = x(1) End Sub End Class </Document> <Document> Class M2 Sub F(x As IC) Dim y = x[||](1L) Dim y2 = x(1) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function <WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")> <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_DefaultProperties2() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Strict On Public Interface IA Default Property {|Definition:$$Foo|}(ByVal x As Integer) As Integer End Interface Public Interface IC Inherits IA Default Overloads Property Foo(ByVal x As Long) As String ' Rename Foo to Bar End Interface Class M Sub F(x As IC) Dim y = x(1L) Dim y2 = x[||](1) End Sub End Class </Document> <Document> Class M2 Sub F(x As IC) Dim y = x(1L) Dim y2 = x[||](1) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input) End Function End Class End Namespace
weltkante/roslyn
src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PropertySymbols.vb
Visual Basic
apache-2.0
23,729
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualBasic Public Module Interaction Friend Function IIf(Of T)(ByVal condition As Boolean, ByVal truePart As T, ByVal falsePart As T) As T If condition Then Return truePart End If Return falsePart End Function End Module End Namespace
DnlHarvey/corefx
src/Microsoft.VisualBasic/src/Microsoft/VisualBasic/Interaction.vb
Visual Basic
mit
540
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus Friend Module ContainedLanguageStaticEventBinding ''' <summary> ''' Find all the methods that handle events (though "Handles" clauses). ''' </summary> ''' <returns></returns> Public Function GetStaticEventBindings(document As Document, className As String, objectName As String, cancellationToken As CancellationToken) As IEnumerable(Of Tuple(Of String, String, String)) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim methods = type.GetMembers(). Where(Function(m) m.CanBeReferencedByName AndAlso m.Kind = SymbolKind.Method). Cast(Of IMethodSymbol)() Dim syntaxFacts = document.Project.LanguageServices.GetService(Of ISyntaxFactsService)() Dim methodAndMethodSyntaxesWithHandles = methods. Select(Function(m) Tuple.Create(m, GetMethodStatement(syntaxFacts, m))). Where(Function(t) t.Item2.HandlesClause IsNot Nothing). ToArray() If Not methodAndMethodSyntaxesWithHandles.Any() Then Return SpecializedCollections.EmptyEnumerable(Of Tuple(Of String, String, String))() End If Dim result As New List(Of Tuple(Of String, String, String))() For Each methodAndMethodSyntax In methodAndMethodSyntaxesWithHandles For Each handleClauseItem In methodAndMethodSyntax.Item2.HandlesClause.Events If handleClauseItem.EventContainer.ToString() = objectName OrElse (String.IsNullOrEmpty(objectName) AndAlso handleClauseItem.EventContainer.IsKind(SyntaxKind.MeKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword)) Then result.Add(Tuple.Create(handleClauseItem.EventMember.Identifier.ToString(), methodAndMethodSyntax.Item2.Identifier.ToString(), ContainedLanguageCodeSupport.ConstructMemberId(methodAndMethodSyntax.Item1))) End If Next Next Return result End Function Public Sub AddStaticEventBinding(document As Document, visualStudioWorkspace As VisualStudioWorkspace, className As String, memberId As String, objectName As String, nameOfEvent As String, cancellationToken As CancellationToken) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim memberSymbol = ContainedLanguageCodeSupport.LookupMemberId(type, memberId) Dim targetDocument = document.Project.Solution.GetDocument(memberSymbol.Locations.First().SourceTree) Dim syntaxFacts = targetDocument.Project.LanguageServices.GetService(Of ISyntaxFactsService)() If HandlesEvent(GetMethodStatement(syntaxFacts, memberSymbol), objectName, nameOfEvent) Then Return End If Dim textBuffer = targetDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).Container.TryGetTextBuffer() If textBuffer Is Nothing Then Using visualStudioWorkspace.OpenInvisibleEditor(targetDocument.Id) targetDocument = visualStudioWorkspace.CurrentSolution.GetDocument(targetDocument.Id) AddStaticEventBinding(targetDocument, visualStudioWorkspace, className, memberId, objectName, nameOfEvent, cancellationToken) End Using Else Dim memberStatement = GetMemberBlockOrBegin(syntaxFacts, memberSymbol) Dim codeModel = targetDocument.Project.LanguageServices.GetService(Of ICodeModelService)() codeModel.AddHandlesClause(targetDocument, objectName & "." & nameOfEvent, memberStatement, cancellationToken) End If End Sub Public Sub RemoveStaticEventBinding(document As Document, visualStudioWorkspace As VisualStudioWorkspace, className As String, memberId As String, objectName As String, nameOfEvent As String, cancellationToken As CancellationToken) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim memberSymbol = ContainedLanguageCodeSupport.LookupMemberId(type, memberId) Dim targetDocument = document.Project.Solution.GetDocument(memberSymbol.Locations.First().SourceTree) Dim syntaxFacts = targetDocument.Project.LanguageServices.GetService(Of ISyntaxFactsService)() If Not HandlesEvent(GetMethodStatement(syntaxFacts, memberSymbol), objectName, nameOfEvent) Then Return End If Dim textBuffer = targetDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).Container.TryGetTextBuffer() If textBuffer Is Nothing Then Using visualStudioWorkspace.OpenInvisibleEditor(targetDocument.Id) targetDocument = visualStudioWorkspace.CurrentSolution.GetDocument(targetDocument.Id) RemoveStaticEventBinding(targetDocument, visualStudioWorkspace, className, memberId, objectName, nameOfEvent, cancellationToken) End Using Else Dim memberStatement = GetMemberBlockOrBegin(syntaxFacts, memberSymbol) Dim codeModel = targetDocument.Project.LanguageServices.GetService(Of ICodeModelService)() codeModel.RemoveHandlesClause(targetDocument, objectName & "." & nameOfEvent, memberStatement, cancellationToken) End If End Sub Public Function HandlesEvent(methodStatement As MethodStatementSyntax, objectName As String, eventName As String) As Boolean If methodStatement.HandlesClause Is Nothing Then Return False End If For Each handlesClauseItem In methodStatement.HandlesClause.Events If handlesClauseItem.EventMember.ToString() = eventName Then If String.IsNullOrEmpty(objectName) AndAlso handlesClauseItem.EventContainer.IsKind(SyntaxKind.MeKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword) Then Return True ElseIf handlesClauseItem.EventContainer.ToString() = objectName Then Return True End If End If Next Return False End Function Private Function GetMemberBlockOrBegin(syntaxFacts As ISyntaxFactsService, member As ISymbol) As SyntaxNode Return member.DeclaringSyntaxReferences.Select(Function(r) r.GetSyntax()).FirstOrDefault() End Function Private Function GetMethodStatement(syntaxFacts As ISyntaxFactsService, member As ISymbol) As MethodStatementSyntax Dim node = GetMemberBlockOrBegin(syntaxFacts, member) If node.Kind = SyntaxKind.SubBlock OrElse node.Kind = SyntaxKind.FunctionBlock Then Return DirectCast(DirectCast(node, MethodBlockSyntax).BlockStatement, MethodStatementSyntax) ElseIf node.Kind = SyntaxKind.SubStatement OrElse node.Kind = SyntaxKind.FunctionStatement Then Return DirectCast(node, MethodStatementSyntax) Else Throw New InvalidOperationException() End If End Function End Module End Namespace
jhendrixMSFT/roslyn
src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.vb
Visual Basic
apache-2.0
8,903
#Region "Microsoft.VisualBasic::4eb6aa5548520f30cc37b963c7db4478, src\metadb\Chemoinformatics\Formula\Isotopic\IsotopeCount.vb" ' Author: ' ' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.) ' ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD. ' ' ' MIT License ' ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. ' /********************************************************************************/ ' Summaries: ' Structure IsotopeCount ' ' Properties: Formula ' ' Function: Normalize, ToString ' ' ' /********************************************************************************/ #End Region Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel Imports Microsoft.VisualBasic.Language Imports Microsoft.VisualBasic.Math Namespace Formula.IsotopicPatterns Public Structure IsotopeCount ''' <summary> ''' [0] atom_type ''' </summary> Dim atoms As String() ''' <summary> ''' [1] nom_mass ''' </summary> Dim nom_mass As Double() ''' <summary> ''' [2] probility ''' </summary> Dim prob# ''' <summary> ''' normalized by <see cref="prob"/> ''' </summary> Dim abundance As Double ''' <summary> ''' [3] exact mass ''' </summary> Dim abs_mass# Default Public ReadOnly Property Item(i As Integer) As Object Get Select Case i Case 0 : Return atoms Case 1 : Return nom_mass Case 2 : Return prob Case 3 : Return abs_mass Case Else Throw New NotImplementedException End Select End Get End Property Public ReadOnly Property Formula As Formula Get Return New Formula(atoms.GroupBy(Function(a) a).ToDictionary(Function(a) a.Key, Function(a) a.Count)) End Get End Property Public Overrides Function ToString() As String Return $"[{nom_mass.Sum}][{Formula.ToString}, {abs_mass.ToString("F4")}], prob = {prob.ToString("G3")}, abundance = {(abundance).ToString("F2")}" End Function Public Shared Iterator Function Normalize(isotopes As IEnumerable(Of IsotopeCount)) As IEnumerable(Of IsotopeCount) Dim all As NamedCollection(Of IsotopeCount)() = isotopes.GroupBy(Function(i) i.abs_mass, offsets:=0.3).ToArray If all.Length = 0 Then Return End If Dim j As i32 = 0 Dim prob As Double() = all.Select(Function(i) i.Sum(Function(a) a.prob)).ToArray Dim maxProb As Double = Aggregate i In prob Into Max(i) For Each i As NamedCollection(Of IsotopeCount) In all Dim top = i.OrderByDescending(Function(a) a.prob).First Yield New IsotopeCount With { .abs_mass = top.abs_mass, .abundance = 100 * prob(j) / maxProb,' logRange.ScaleMapping(log(++j), percentage), .atoms = top.atoms, .prob = prob(++j), .nom_mass = top.nom_mass } Next End Function Public Shared Widening Operator CType(itm As (atom_type As String(), nom_mass As Double(), prob#, abs_mass#)) As IsotopeCount Return New IsotopeCount With { .abs_mass = itm.abs_mass, .atoms = itm.atom_type, .nom_mass = itm.nom_mass, .prob = itm.prob } End Operator End Structure End Namespace
xieguigang/MassSpectrum-toolkits
src/metadb/Chemoinformatics/Formula/Isotopic/IsotopeCount.vb
Visual Basic
mit
4,888
Option Explicit On Option Strict On Public Class OptionsDialog Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents OutlineDraggingCheckBox As System.Windows.Forms.CheckBox Friend WithEvents StatusBarCheckBox As System.Windows.Forms.CheckBox Friend WithEvents TimedGameCheckBox As System.Windows.Forms.CheckBox Friend WithEvents ScoringGroupBox As System.Windows.Forms.GroupBox Friend WithEvents ScoreNoneRadioButton As System.Windows.Forms.RadioButton Friend WithEvents ScoreVegasRadioButton As System.Windows.Forms.RadioButton Friend WithEvents ScoreStandardRadioButton As System.Windows.Forms.RadioButton Friend WithEvents DrawGroupBox As System.Windows.Forms.GroupBox Friend WithEvents DrawThreeRadioButton As System.Windows.Forms.RadioButton Friend WithEvents DrawOneRadioButton As System.Windows.Forms.RadioButton Friend WithEvents OkButton As System.Windows.Forms.Button Friend WithEvents CummulativeScoreCheckBox As System.Windows.Forms.CheckBox Friend WithEvents CancelActionButton As System.Windows.Forms.Button Friend WithEvents HelpProvider As System.Windows.Forms.HelpProvider <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.OutlineDraggingCheckBox = New System.Windows.Forms.CheckBox Me.StatusBarCheckBox = New System.Windows.Forms.CheckBox Me.TimedGameCheckBox = New System.Windows.Forms.CheckBox Me.ScoringGroupBox = New System.Windows.Forms.GroupBox Me.ScoreNoneRadioButton = New System.Windows.Forms.RadioButton Me.ScoreVegasRadioButton = New System.Windows.Forms.RadioButton Me.ScoreStandardRadioButton = New System.Windows.Forms.RadioButton Me.DrawGroupBox = New System.Windows.Forms.GroupBox Me.DrawThreeRadioButton = New System.Windows.Forms.RadioButton Me.DrawOneRadioButton = New System.Windows.Forms.RadioButton Me.CancelActionButton = New System.Windows.Forms.Button Me.OkButton = New System.Windows.Forms.Button Me.CummulativeScoreCheckBox = New System.Windows.Forms.CheckBox Me.HelpProvider = New System.Windows.Forms.HelpProvider Me.ScoringGroupBox.SuspendLayout() Me.DrawGroupBox.SuspendLayout() Me.SuspendLayout() ' 'OutlineDraggingCheckBox ' Me.OutlineDraggingCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System Me.HelpProvider.SetHelpString(Me.OutlineDraggingCheckBox, "Specifies that an outline of a card (rather than the actual card) appears while y" & _ "ou drag a card to a new location.") Me.OutlineDraggingCheckBox.Location = New System.Drawing.Point(16, 114) Me.OutlineDraggingCheckBox.Name = "OutlineDraggingCheckBox" Me.HelpProvider.SetShowHelp(Me.OutlineDraggingCheckBox, True) Me.OutlineDraggingCheckBox.Size = New System.Drawing.Size(108, 24) Me.OutlineDraggingCheckBox.TabIndex = 13 Me.OutlineDraggingCheckBox.Text = "Outline dragging" ' 'StatusBarCheckBox ' Me.StatusBarCheckBox.Checked = True Me.StatusBarCheckBox.CheckState = System.Windows.Forms.CheckState.Checked Me.StatusBarCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System Me.HelpProvider.SetHelpString(Me.StatusBarCheckBox, "Specifies whether the notification area showing the score and time played will be" & _ " visible.") Me.StatusBarCheckBox.Location = New System.Drawing.Point(16, 94) Me.StatusBarCheckBox.Name = "StatusBarCheckBox" Me.HelpProvider.SetShowHelp(Me.StatusBarCheckBox, True) Me.StatusBarCheckBox.Size = New System.Drawing.Size(80, 24) Me.StatusBarCheckBox.TabIndex = 12 Me.StatusBarCheckBox.Text = "Status bar" ' 'TimedGameCheckBox ' Me.TimedGameCheckBox.Checked = True Me.TimedGameCheckBox.CheckState = System.Windows.Forms.CheckState.Checked Me.TimedGameCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System Me.HelpProvider.SetHelpString(Me.TimedGameCheckBox, "Specifies whether the game will be timed. To play a more challenging game, click" & _ " to select Timed game.") Me.TimedGameCheckBox.Location = New System.Drawing.Point(16, 72) Me.TimedGameCheckBox.Name = "TimedGameCheckBox" Me.HelpProvider.SetShowHelp(Me.TimedGameCheckBox, True) Me.TimedGameCheckBox.Size = New System.Drawing.Size(88, 24) Me.TimedGameCheckBox.TabIndex = 11 Me.TimedGameCheckBox.Text = "Timed game" ' 'ScoringGroupBox ' Me.ScoringGroupBox.Controls.Add(Me.ScoreNoneRadioButton) Me.ScoringGroupBox.Controls.Add(Me.ScoreVegasRadioButton) Me.ScoringGroupBox.Controls.Add(Me.ScoreStandardRadioButton) Me.ScoringGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System Me.ScoringGroupBox.ForeColor = System.Drawing.SystemColors.ActiveCaption Me.ScoringGroupBox.Location = New System.Drawing.Point(120, 8) Me.ScoringGroupBox.Name = "ScoringGroupBox" Me.ScoringGroupBox.Size = New System.Drawing.Size(96, 78) Me.ScoringGroupBox.TabIndex = 10 Me.ScoringGroupBox.TabStop = False Me.ScoringGroupBox.Text = "Scoring" ' 'ScoreNoneRadioButton ' Me.ScoreNoneRadioButton.FlatStyle = System.Windows.Forms.FlatStyle.System Me.ScoreNoneRadioButton.ForeColor = System.Drawing.SystemColors.ControlText Me.HelpProvider.SetHelpString(Me.ScoreNoneRadioButton, "Specifies the type of scoring to be used. Click None to play without keeping sco" & _ "re.") Me.ScoreNoneRadioButton.Location = New System.Drawing.Point(6, 51) Me.ScoreNoneRadioButton.Name = "ScoreNoneRadioButton" Me.HelpProvider.SetShowHelp(Me.ScoreNoneRadioButton, True) Me.ScoreNoneRadioButton.Size = New System.Drawing.Size(81, 24) Me.ScoreNoneRadioButton.TabIndex = 2 Me.ScoreNoneRadioButton.Text = "None" ' 'ScoreVegasRadioButton ' Me.ScoreVegasRadioButton.FlatStyle = System.Windows.Forms.FlatStyle.System Me.ScoreVegasRadioButton.ForeColor = System.Drawing.SystemColors.ControlText Me.HelpProvider.SetHelpString(Me.ScoreVegasRadioButton, "Specifies the type of scoring to be used. Click Vegas to play a more challenging" & _ " game. The object of the Vegas-style game is to earn more money than your wager" & _ ". You start the game with a debt of 52 dollars and you win 5 dollars for every " & _ "card you play on the suit stack.") Me.ScoreVegasRadioButton.Location = New System.Drawing.Point(6, 32) Me.ScoreVegasRadioButton.Name = "ScoreVegasRadioButton" Me.HelpProvider.SetShowHelp(Me.ScoreVegasRadioButton, True) Me.ScoreVegasRadioButton.Size = New System.Drawing.Size(81, 24) Me.ScoreVegasRadioButton.TabIndex = 1 Me.ScoreVegasRadioButton.Text = "Vegas" ' 'ScoreStandardRadioButton ' Me.ScoreStandardRadioButton.Checked = True Me.ScoreStandardRadioButton.FlatStyle = System.Windows.Forms.FlatStyle.System Me.ScoreStandardRadioButton.ForeColor = System.Drawing.SystemColors.ControlText Me.HelpProvider.SetHelpString(Me.ScoreStandardRadioButton, "Specifies the type of scoring to be used. Click Standard to play a game where yo" & _ "u start the game with 0 dollars and you win 10 dollars for every card you play o" & _ "n a suit stack.") Me.ScoreStandardRadioButton.Location = New System.Drawing.Point(6, 13) Me.ScoreStandardRadioButton.Name = "ScoreStandardRadioButton" Me.HelpProvider.SetShowHelp(Me.ScoreStandardRadioButton, True) Me.ScoreStandardRadioButton.Size = New System.Drawing.Size(81, 24) Me.ScoreStandardRadioButton.TabIndex = 0 Me.ScoreStandardRadioButton.TabStop = True Me.ScoreStandardRadioButton.Text = "Standard" ' 'DrawGroupBox ' Me.DrawGroupBox.Controls.Add(Me.DrawThreeRadioButton) Me.DrawGroupBox.Controls.Add(Me.DrawOneRadioButton) Me.DrawGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System Me.DrawGroupBox.ForeColor = System.Drawing.SystemColors.ActiveCaption Me.DrawGroupBox.Location = New System.Drawing.Point(8, 8) Me.DrawGroupBox.Name = "DrawGroupBox" Me.DrawGroupBox.Size = New System.Drawing.Size(106, 58) Me.DrawGroupBox.TabIndex = 9 Me.DrawGroupBox.TabStop = False Me.DrawGroupBox.Text = "Draw" ' 'DrawThreeRadioButton ' Me.DrawThreeRadioButton.FlatStyle = System.Windows.Forms.FlatStyle.System Me.DrawThreeRadioButton.ForeColor = System.Drawing.SystemColors.ControlText Me.HelpProvider.SetHelpString(Me.DrawThreeRadioButton, "Specifies the number of cards drawn each time you click the deck of cards. Click" & _ " Draw One to turn over one card at a time, or click Draw Three to turn over thre" & _ "e cards at a time.") Me.DrawThreeRadioButton.Location = New System.Drawing.Point(6, 32) Me.DrawThreeRadioButton.Name = "DrawThreeRadioButton" Me.HelpProvider.SetShowHelp(Me.DrawThreeRadioButton, True) Me.DrawThreeRadioButton.Size = New System.Drawing.Size(81, 24) Me.DrawThreeRadioButton.TabIndex = 1 Me.DrawThreeRadioButton.Text = "Draw Three" ' 'DrawOneRadioButton ' Me.DrawOneRadioButton.Checked = True Me.DrawOneRadioButton.FlatStyle = System.Windows.Forms.FlatStyle.System Me.DrawOneRadioButton.ForeColor = System.Drawing.SystemColors.ControlText Me.HelpProvider.SetHelpString(Me.DrawOneRadioButton, "Specifies the number of cards drawn each time you click the deck of cards. Click" & _ " Draw One to turn over one card at a time, or click Draw Three to turn over thre" & _ "e cards at a time.") Me.DrawOneRadioButton.Location = New System.Drawing.Point(6, 13) Me.DrawOneRadioButton.Name = "DrawOneRadioButton" Me.HelpProvider.SetShowHelp(Me.DrawOneRadioButton, True) Me.DrawOneRadioButton.Size = New System.Drawing.Size(75, 24) Me.DrawOneRadioButton.TabIndex = 0 Me.DrawOneRadioButton.TabStop = True Me.DrawOneRadioButton.Text = "Draw One" ' 'CancelActionButton ' Me.CancelActionButton.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.CancelActionButton.FlatStyle = System.Windows.Forms.FlatStyle.System Me.HelpProvider.SetHelpString(Me.CancelActionButton, "Closes the dialog box without saving any changes you have made.") Me.CancelActionButton.Location = New System.Drawing.Point(120, 144) Me.CancelActionButton.Name = "CancelActionButton" Me.HelpProvider.SetShowHelp(Me.CancelActionButton, True) Me.CancelActionButton.Size = New System.Drawing.Size(60, 24) Me.CancelActionButton.TabIndex = 16 Me.CancelActionButton.Text = "Cancel" ' 'OkButton ' Me.OkButton.DialogResult = System.Windows.Forms.DialogResult.OK Me.OkButton.FlatStyle = System.Windows.Forms.FlatStyle.System Me.HelpProvider.SetHelpString(Me.OkButton, "Closes the dialog box and saves any changes you have made.") Me.OkButton.Location = New System.Drawing.Point(56, 144) Me.OkButton.Name = "OkButton" Me.HelpProvider.SetShowHelp(Me.OkButton, True) Me.OkButton.Size = New System.Drawing.Size(56, 24) Me.OkButton.TabIndex = 15 Me.OkButton.Text = "OK" ' 'CummulativeScoreCheckBox ' Me.CummulativeScoreCheckBox.Enabled = False Me.CummulativeScoreCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System Me.HelpProvider.SetHelpString(Me.CummulativeScoreCheckBox, "Only available on Vegas scoring, keeps track of your score through multiple games" & _ ".") Me.CummulativeScoreCheckBox.Location = New System.Drawing.Point(120, 96) Me.CummulativeScoreCheckBox.Name = "CummulativeScoreCheckBox" Me.HelpProvider.SetShowHelp(Me.CummulativeScoreCheckBox, True) Me.CummulativeScoreCheckBox.Size = New System.Drawing.Size(88, 32) Me.CummulativeScoreCheckBox.TabIndex = 14 Me.CummulativeScoreCheckBox.Text = "Cumulative Score" Me.CummulativeScoreCheckBox.TextAlign = System.Drawing.ContentAlignment.TopLeft ' 'OptionsDialog ' Me.AcceptButton = Me.OkButton Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.CancelButton = Me.CancelActionButton Me.ClientSize = New System.Drawing.Size(224, 182) Me.Controls.Add(Me.OutlineDraggingCheckBox) Me.Controls.Add(Me.StatusBarCheckBox) Me.Controls.Add(Me.TimedGameCheckBox) Me.Controls.Add(Me.ScoringGroupBox) Me.Controls.Add(Me.DrawGroupBox) Me.Controls.Add(Me.CancelActionButton) Me.Controls.Add(Me.OkButton) Me.Controls.Add(Me.CummulativeScoreCheckBox) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.HelpButton = True Me.MaximizeBox = False Me.MaximumSize = New System.Drawing.Size(230, 214) Me.MinimizeBox = False Me.MinimumSize = New System.Drawing.Size(230, 214) Me.Name = "OptionsDialog" Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent Me.Text = "Options" Me.ScoringGroupBox.ResumeLayout(False) Me.DrawGroupBox.ResumeLayout(False) Me.ResumeLayout(False) End Sub #End Region Private m_originalDraw As Draw = Draw.One Private m_originalScoring As Scoring = Scoring.Standard Private m_originalTimedGame As Boolean = True Sub OptionsDialog_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Cache options when dialog is shown to be able to calculate Redraw property. m_originalDraw = Draw m_originalScoring = Scoring m_originalTimedGame = TimedGame End Sub Private Sub ScoreStandardRadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ScoreStandardRadioButton.CheckedChanged CummulativeScoreCheckBox.Enabled = False End Sub Private Sub ScoreVegasRadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ScoreVegasRadioButton.CheckedChanged CummulativeScoreCheckBox.Enabled = True End Sub Private Sub ScoreNoneRadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ScoreNoneRadioButton.CheckedChanged CummulativeScoreCheckBox.Enabled = False End Sub Public Property Draw() As Draw Get Return CType(IIf(DrawOneRadioButton.Checked, Draw.One, Draw.Three), Draw) End Get Set(ByVal Value As Draw) DrawOneRadioButton.Checked = (Value = Draw.One) DrawThreeRadioButton.Checked = (Value = Draw.Three) End Set End Property Public Property Scoring() As Scoring Get If ScoreNoneRadioButton.Checked Then Return Scoring.None End If If ScoreStandardRadioButton.Checked Then Return Scoring.Standard End If If ScoreVegasRadioButton.Checked Then Return CType(IIf(CummulativeScoreCheckBox.Checked, Scoring.VegasCumulative, Scoring.Vegas), Scoring) End If Debug.Assert(False) Return Scoring.None End Get Set(ByVal Value As Scoring) ScoreNoneRadioButton.Checked = False ScoreStandardRadioButton.Checked = False ScoreVegasRadioButton.Checked = False CummulativeScoreCheckBox.Checked = False CummulativeScoreCheckBox.Enabled = False Select Case Value Case Scoring.None ScoreNoneRadioButton.Checked = True Case Scoring.Standard ScoreStandardRadioButton.Checked = True Case Scoring.Vegas ScoreVegasRadioButton.Checked = True Case Scoring.VegasCumulative ScoreVegasRadioButton.Checked = True CummulativeScoreCheckBox.Checked = True CummulativeScoreCheckBox.Enabled = True Case Else Debug.Assert(False) End Select End Set End Property Public Property TimedGame() As Boolean Get Return TimedGameCheckBox.Checked End Get Set(ByVal Value As Boolean) TimedGameCheckBox.Checked = Value End Set End Property Public Property StatusBar() As Boolean Get Return StatusBarCheckBox.Checked End Get Set(ByVal Value As Boolean) StatusBarCheckBox.Checked = Value End Set End Property Public Property OutlineDragging() As Boolean Get Return OutlineDraggingCheckBox.Checked End Get Set(ByVal Value As Boolean) OutlineDraggingCheckBox.Checked = Value End Set End Property Public ReadOnly Property Redeal() As Boolean Get If Me.Draw <> m_originalDraw OrElse Me.TimedGame <> m_originalTimedGame Then Return True End If If Me.Scoring <> m_originalScoring Then ' Vegas -> VegasCummulative or VegasCummulative -> Vegas not worth a redeal. If Me.Scoring = Scoring.Vegas AndAlso m_originalScoring = Scoring.VegasCumulative Then Return False End If If Me.Scoring = Scoring.VegasCumulative AndAlso m_originalScoring = Scoring.Vegas Then Return False End If Return True End If Return False End Get End Property End Class
DualBrain/Solitaire
OptionsDialog.vb
Visual Basic
mit
17,564
Public Class GateSave Inherits SkyEditorBase.GenericSave Public Sub New(Data As Byte()) MyBase.New(Data) End Sub Public Overrides Sub FixChecksum() End Sub Public Overrides Function DefaultSaveID() As String Return GameStrings.GateSave End Function End Class
evandixon/Sky-Editor
CheatGenerator/Library/GateSave.vb
Visual Basic
mit
320
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18449 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
blakepell/AsciiArt
TextArt/My Project/Resources.Designer.vb
Visual Basic
mit
2,705
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 profileSets As SolidEdgePart.ProfileSets = Nothing Dim profileSet As SolidEdgePart.ProfileSet = 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 profileSets = partDocument.ProfileSets For i As Integer = 1 To profileSets.Count profileSet = profileSets.Item(i) Dim profiles = profileSet.Profiles 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.ProfileSet.Profiles.vb
Visual Basic
mit
1,501
Imports BVSoftware.Bvc5.Core Partial Class BVModules_Editors_None_editor Inherits Content.TextEditorBase Public Overrides Property EditorHeight() As Integer Get Return Me.EditorField.Height.Value End Get Set(ByVal value As Integer) Me.EditorField.Height = UI.WebControls.Unit.Pixel(value) End Set End Property Public Overrides Property EditorWidth() As Integer Get Return Me.EditorField.Width.Value End Get Set(ByVal value As Integer) Me.EditorField.Width = UI.WebControls.Unit.Pixel(value) End Set End Property Public Overrides Property EditorWrap() As Boolean Get Return Me.EditorField.Wrap End Get Set(ByVal value As Boolean) Me.EditorField.Wrap = value End Set End Property Public Overrides Property PreTransformText() As String Get Return Me.EditorField.Text End Get Set(ByVal value As String) Me.EditorField.Text = value End Set End Property Public Overrides ReadOnly Property SupportsTransform() As Boolean Get Return False End Get End Property Public Overrides Property TabIndex() As Integer Get Return Me.EditorField.TabIndex End Get Set(ByVal value As Integer) Me.EditorField.TabIndex = value End Set End Property Public Overrides Property Text() As String Get Return Me.EditorField.Text End Get Set(ByVal value As String) Me.EditorField.Text = value End Set End Property End Class
ajaydex/Scopelist_2015
BVModules/Editors/None/editor.ascx.vb
Visual Basic
apache-2.0
1,726
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("Al Tor")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("Al Tor")> <Assembly: AssemblyCopyright("Copyright © 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("cb6f8e98-0f6a-4d79-91a5-90de8a666ae3")> ' 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")>
Andronew/AlTor
Al Tor/Al Tor/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
1,165
Imports System.Data.Common Imports Databasic.ActiveRecord Partial Public MustInherit Class Statement ''' <summary> ''' Execute any non select SQL statement and return affected rows count. ''' </summary> ''' <returns>Affected rows count.</returns> Public Function Exec() As Int32 Dim r As Int32 = 0 Try r = Me.Command.ExecuteNonQuery() Catch ex As Exception Events.RaiseError(ex) End Try Return r End Function ''' <summary> ''' Execute any non select SQL statement and return affected rows count. ''' </summary> ''' <param name="sqlParams">Anonymous object with named keys as SQL statement params without any '@' chars in object keys.</param> ''' <returns>Affected rows count.</returns> Public Function Exec(sqlParams As Object) As Int32 Me.addParamsWithValue(sqlParams) Return Me.Exec() End Function ''' <summary> ''' Execute any non select SQL statement and return affected rows count. ''' </summary> ''' <param name="sqlParams">Dictionary with named keys as SQL statement params without any '@' chars in dictionary keys.</param> ''' <returns>Affected rows count.</returns> Public Function Exec(sqlParams As Dictionary(Of String, Object)) As Int32 Me.addParamsWithValue(sqlParams) Dim r As Int32 = 0 Try r = Me.Command.ExecuteNonQuery() Catch ex As Exception Events.RaiseError(ex) End Try Return r End Function End Class
databasic-net/databasic-core
Statement/Exec.vb
Visual Basic
bsd-3-clause
1,380
Imports Aspose.Email.Outlook Imports Aspose.Email.Outlook.Pst ' 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 AccessContactInformation Public Shared Sub Run() ' ExStart:AccessContactInformation ' Load the Outlook file Dim dataDir As String = RunExamples.GetDataDir_Outlook() ' Load the Outlook PST file Dim personalStorage1 As PersonalStorage = PersonalStorage.FromFile(dataDir & Convert.ToString("SampleContacts.pst")) ' Get the Contacts folder Dim folderInfo As FolderInfo = personalStorage1.RootFolder.GetSubFolder("Contacts") ' Loop through all the contacts in this folder Dim messageInfoCollection As MessageInfoCollection = folderInfo.GetContents() For Each messageInfo As MessageInfo In messageInfoCollection ' Get the contact information Dim mapi As MapiMessage = personalStorage1.ExtractMessage(messageInfo) Dim contact As MapiContact = DirectCast(mapi.ToMapiMessageItem(), MapiContact) ' Display some contents on screen Console.WriteLine("Name: " + contact.NameInfo.DisplayName) ' Save to disk in MSG format If contact.NameInfo.DisplayName IsNot Nothing Then Dim message As MapiMessage = personalStorage1.ExtractMessage(messageInfo) ' Get rid of illegal characters that cannot be used as a file name Dim messageName As String = message.Subject.Replace(":", " ").Replace("\", " ").Replace("?", " ").Replace("/", " ") message.Save((Convert.ToString(dataDir & Convert.ToString("Contacts\")) & messageName) + "_out.msg") End If Next ' ExEnd:AccessContactInformation End Sub End Class End Namespace
maria-shahid-aspose/Aspose.Email-for-.NET
Examples/VisualBasic/Outlook/AccessContactInformation.vb
Visual Basic
mit
2,465
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic <[UseExportProvider]> Public Class DeclarationConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenFields() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Dim [|$$goo|] As Integer Dim {|Conflict:bar|} As Integer End Module </Document> </Project> </Workspace>, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenFieldAndMethod() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Dim [|$$goo|] As Integer Sub {|Conflict:bar|}() End Module </Document> </Project> </Workspace>, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoMethodsWithSameSignature() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub [|$$goo|]() End Sub Sub {|Conflict:bar|}() End Sub End Module </Document> </Project> </Workspace>, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoParameters() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub f([|$$goo|] As Integer, {|Conflict:bar|} As Integer) End Sub End Module </Document> </Project> </Workspace>, renameTo:="bar") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenMethodsWithDifferentSignatures() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module GooModule Sub [|$$goo|]() End Sub Sub bar(parameter As Integer) End Sub End Module </Document> </Project> </Workspace>, renameTo:="bar") End Using End Sub <Fact> <WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoLocals() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim {|stmt1:$$i|} = 1 Dim {|Conflict:j|} = 2 End Sub End Module </Document> </Project> </Workspace>, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLocalAndParameter() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main({|Conflict:args|} As String()) Dim {|stmt1:$$i|} = 1 End Sub End Module </Document> </Project> </Workspace>, renameTo:="args") result.AssertLabeledSpansAre("stmt1", "args", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenQueryVariableAndParameter() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main({|Conflict:args|} As String()) Dim z = From {|stmt1:$$x|} In args End Sub End Module </Document> </Project> </Workspace>, renameTo:="args") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenTwoQueryVariables() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim z = From {|Conflict:x|} In args From {|stmt1:$$y|} In args End Sub End Module </Document> </Project> </Workspace>, renameTo:="x") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLambdaParametersInsideMethod() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Sub Main() Dim y = Sub({|Conflict:c|}) Call (Sub(a, {|stmt1:$$b|}) Exit Sub)(c) End Sub End Module </Document> </Project> </Workspace>, renameTo:="c") result.AssertLabeledSpansAre("stmt1", "c", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLambdaParametersInFieldInitializer() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Dim y = Sub({|Conflict:c|}) Call (Sub({|stmt:$$b|}) Exit Sub)(c) End Module </Document> </Project> </Workspace>, renameTo:="c") result.AssertLabeledSpansAre("stmt", "c", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenLambdaParameterAndField() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M1 Dim y = Sub({|fieldinit:$$c|}) Exit Sub End Module </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("fieldinit", "y", RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabels() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Program Sub Main() {|Conflict:Goo|}: [|$$Bar|]: Dim f = Sub() Goo: End Sub End Sub End Class </Document> </Project> </Workspace>, renameTo:="Goo") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenMethodsDifferingByByRef() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub {|Conflict:a|}(x As Integer) End Sub Sub [|$$c|](ByRef x As Integer) End Sub End Module </Document> </Project> </Workspace>, renameTo:="a") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenMethodsDifferingByOptional() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub {|Conflict:a|}(x As Integer) End Sub Sub [|$$d|](x As Integer, Optional y As Integer = 0) End Sub End Module </Document> </Project> </Workspace>, renameTo:="a") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenMethodsDifferingByArity() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub a(Of T)(x As Integer) End Sub Sub [|$$d|](x As Integer, Optional y As Integer = 0) End Sub End Module </Document> </Project> </Workspace>, renameTo:="a") End Using End Sub <Fact> <WorkItem(546902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546902")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitlyDeclaredLocalAndNamespace() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Explicit Off Module Program Sub Main() __ = {|Conflict1:$$Google|} {|Conflict2:Google|} = __ End Sub End Module </Document> </Project> </Workspace>, renameTo:="Microsoft") result.AssertLabeledSpansAre("Conflict1", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("Conflict2", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(529556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529556")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitlyDeclaredLocalAndAndGlobalFunction() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Dim q = From i In a Where i Mod 2 = 0 Select Function() i * i For Each {|Conflict:$$sq|} In q Console.Write({|Conflict:sq|}()) Next End Sub End Module </Document> </Project> </Workspace>, renameTo:="Write") result.AssertLabeledSpansAre("Conflict", "Write", RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(542217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542217")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenAliases() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports A = X.Something Imports {|Conflict:$$B|} = X.SomethingElse Namespace X Class Something End Class Class SomethingElse End Class End Namespace </Document> </Project> </Workspace>, renameTo:="A") result.AssertLabeledSpansAre("Conflict", "A", RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(530125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530125")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenImplicitVariableAndClass() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Explicit Off Class X End Class Module M Sub Main() {|conflict:$$Y|} = 1 End Sub End Module </Document> </Project> </Workspace>, renameTo:="X") result.AssertLabeledSpansAre("conflict", "X", RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(530038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530038")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedAlias() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports [|$$A|] = NS1.Something Imports {|conflict1:Something|} = NS1 Namespace NS1 Class Something Public Something() End Class End Namespace Class Program Dim a As {|noconflict:A|} Dim q As {|conflict2:Something|}.{|conflict3:Something|} End Class </Document> </Project> </Workspace>, renameTo:="Something") result.AssertLabeledSpansAre("conflict1", "Something", RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("conflict2", "NS1", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("conflict3", "Something", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("noconflict", "Something", RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Property [|$$X|]({|declconflict:Y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Overridable Property [|X|]({|declconflict:Y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class Public Class B Inherits A Public Overrides Property [|$$X|]({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class Public Class C Inherits A Public Overrides Property [|X|]({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class A Public Overridable Property {|declconflict:X|}([|$$Y|] As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> </Workspace>, renameTo:="X") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(608198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608198"), WorkItem(798375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798375")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictInFieldInitializerOfFieldAndModuleNameResolvedThroughFullQualification() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module [|$$M|] ' Rename M to X Dim x As Action = Sub() Console.WriteLine({|stmt1:M|}.x) End Module </Document> </Project> </Workspace>, renameTo:="X") result.AssertLabeledSpansAre("stmt1", "Console.WriteLine(Global.X.x)", type:=RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Fact> <WorkItem(528706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528706")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableNotBindingToTypeAnyMore() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main For Each {|conflict:x|} In "" Next End Sub End Module End Namespace Namespace X Class [|$$X|] ' Rename X to M End Class End Namespace </Document> </Project> </Workspace>, renameTo:="M") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main For Each {|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main For Each {|ctrlvar:goo|} As Integer In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main Dim {|stmt1:goo|} as Integer For Each {|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First() Console.WriteLine({|stmt2:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="g") result.AssertLabeledSpansAre("stmt1", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_4() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Public [|goo|] as Integer Sub Main For Each Program.{|ctrlvar:goo|} In {1, 2, 3} Dim y As Integer = (From g In {{|query:goo|}} Select g).First() Console.WriteLine({|stmt:$$goo|}) Next End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="g") result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("query", "g", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System.Linq Namespace X Module Program Sub Main Using {|usingstmt:v1|} = new Object, v2 as Object = new Object(), v3, v4 as new Object() Dim o As Object = (From {|declconflict:c|} In {{|query:v1|}} Select c).First() Console.WriteLine({|stmt:$$v1|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="c") result.AssertLabeledSpansAre("usingstmt", "c", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "c", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Using {|usingstmt:v3|}, {|declconflict:v4|} as new Object() Dim o As Object = (From c In {{|query:v3|}} Select c).First() Console.WriteLine({|stmt:$$v3|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="v4") result.AssertLabeledSpansAre("usingstmt", "v4", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "v4", type:=RelatedLocationType.NoConflict) End Using End Sub <WpfFact(Skip:="657210")> <WorkItem(653311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653311")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForUsingVariableAndRangeVariable_3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Using {|usingstmt:v3|} as new Object() Dim o As Object = (From c In {{|query:v3|}} Let {|declconflict:d|} = c Select {|declconflict:d|}).First() Console.WriteLine({|stmt:$$v3|}) End Using End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="d") result.AssertLabeledSpansAre("usingstmt", "d", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt", "d", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictForCatchVariable_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Namespace X Module Program Sub Main Try Catch {|catchstmt:$$x|} as Exception dim {|declconflict:y|} = 23 End Try End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("catchstmt", "y", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInTypeDeclaration() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:T|} as {New}, [|$$U|]) End Class </Document> </Project> </Workspace>, renameTo:="T") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo Public Sub M(Of {|declconflict:T|} as {New}, [|$$U|])() End Sub End Class </Document> </Project> </Workspace>, renameTo:="T") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo Public Sub M(Of {|declconflict:[T]|} as {New}, [|$$U|])() End Sub End Class </Document> </Project> </Workspace>, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParameterAndMember_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:[T]|}) Public Sub [|$$M|]() End Sub End Class </Document> </Project> </Workspace>, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenTypeParameterAndMember_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of {|declconflict:[T]|}) Public [|$$M|] as Integer = 23 End Class </Document> </Project> </Workspace>, renameTo:="t") result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact> <WorkItem(658437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658437")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_ConflictBetweenEscapedForEachControlVariableAndQueryRangeVariable() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Linq Module Program Sub Main(args As String()) For Each {|stmt1:goo|} In {1, 2, 3} Dim x As Integer = (From {|declconflict:g|} In {{|stmt3:goo|}} Select g).First() Console.WriteLine({|stmt2:$$goo|}) Next End Sub End Module </Document> </Project> </Workspace>, renameTo:="[g]") result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt3", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(658801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658801")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() For Each x In New C() Next End Sub Public Sub {|possibleImplicitConflict:$$Goo|}() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, renameTo:="movenext") result.AssertLabeledSpansAre("possibleImplicitConflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() For Each x In New C() Next End Sub Public Overloads Sub [|$$Goo|](of T)() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, renameTo:="movenext") End Using End Sub <WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VB_OverridingImplicitlyUsedMethod_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Option Infer On Imports System Class A Public Property current As Integer Public Function MOVENext(of T)() As Boolean Return False End Function Public Function GetEnumerator() As C Return Me End Function End Class Class C Inherits A Shared Sub Main() End Sub Public Sub [|$$Goo|]() ' Rename Goo to MoveNext End Sub End Class ]]></Document> </Project> </Workspace>, renameTo:="movenext") End Using End Sub <WorkItem(851604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/851604")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictInsideSimpleArgument() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.ComponentModel Imports System.Reflection Class C Const {|first:$$M|} As MemberTypes = MemberTypes.Method Delegate Sub D(&lt;DefaultValue({|second:M|})> x As Object); End Class </Document> </Project> </Workspace>, renameTo:="Method") result.AssertLabeledSpansAre("first", "Method", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("second", "C.Method", type:=RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(18566, "https://github.com/dotnet/roslyn/issues/18566")> Public Sub ParameterInPartialMethodDefinitionConflictingWithLocalInPartialMethodImplementation() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C Partial Private Sub M({|parameter0:$$x|} As Integer) End Sub End Class </Document> <Document> Partial Class C Private Sub M({|parameter1:x|} As Integer) Dim {|local0:y|} = 1 End Sub End Class </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("parameter0", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("parameter1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("local0", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(941271, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/941271")> Public Sub AsNewClauseSpeculationResolvesConflicts() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Main Private T As {|class0:$$Test|} = Nothing End Class Public Class {|class1:Test|} Private Rnd As New {|classConflict:Random|} End Class </Document> </Project> </Workspace>, renameTo:="Random") result.AssertLabeledSpansAre("class0", "Random", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("class1", "Random", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("classConflict", "System.Random", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub End Class End Namespace
aelij/roslyn
src/EditorFeatures/Test2/Rename/VisualBasic/DeclarationConflictTests.vb
Visual Basic
apache-2.0
45,717
' 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 Analyzer.Utilities Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.ApiDesignGuidelines.Analyzers ''' <summary> ''' CA2224: Override Equals on overloading operator equals ''' </summary> ''' <remarks> ''' CA2224 is not applied to C# since it already reports CS0660. ''' </remarks> <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Public NotInheritable Class BasicOverrideEqualsOnOverloadingOperatorEqualsAnalyzer Inherits DiagnosticAnalyzer Friend Const RuleId As String = "CA2224" Private Shared ReadOnly s_localizableTitle As LocalizableString = New LocalizableResourceString(NameOf(MicrosoftApiDesignGuidelinesAnalyzersResources.OverrideEqualsOnOverloadingOperatorEqualsTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, GetType(MicrosoftApiDesignGuidelinesAnalyzersResources)) Private Shared ReadOnly s_localizableMessage As LocalizableString = New LocalizableResourceString(NameOf(MicrosoftApiDesignGuidelinesAnalyzersResources.OverrideEqualsOnOverloadingOperatorEqualsMessage), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, GetType(MicrosoftApiDesignGuidelinesAnalyzersResources)) Private Shared ReadOnly s_localizableDescription As LocalizableString = New LocalizableResourceString(NameOf(MicrosoftApiDesignGuidelinesAnalyzersResources.OverrideEqualsOnOverloadingOperatorEqualsDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, GetType(MicrosoftApiDesignGuidelinesAnalyzersResources)) Friend Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor( RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Usage, DiagnosticSeverity.Warning, True, s_localizableDescription, "https://msdn.microsoft.com/en-us/library/ms182357.aspx", WellKnownDiagnosticTags.Telemetry) Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule) Public Overrides Sub Initialize(analysisContext As AnalysisContext) analysisContext.RegisterSymbolAction( Sub(symbolContext) Dim method = DirectCast(symbolContext.Symbol, IMethodSymbol) Debug.Assert(method.IsDefinition) Dim type = method.ContainingType If type.TypeKind = TypeKind.Interface OrElse type.IsImplicitClass OrElse type.SpecialType = SpecialType.System_Object Then ' Don't apply this rule to interfaces, the implicit class (i.e. error case), or System.Object. Return End If ' If there's a = operator... If method.MethodKind <> MethodKind.UserDefinedOperator OrElse Not CaseInsensitiveComparison.Equals(method.Name, WellKnownMemberNames.EqualityOperatorName) Then Return End If ' ...search for a corresponding Equals override. If type.OverridesEquals() Then Return End If symbolContext.ReportDiagnostic(type.CreateDiagnostic(Rule)) End Sub, SymbolKind.Method) End Sub End Class End Namespace
Anniepoh/roslyn-analyzers
src/Microsoft.ApiDesignGuidelines.Analyzers/VisualBasic/BasicOverrideEqualsOnOverloadingOperatorEquals.vb
Visual Basic
apache-2.0
3,685
Imports Usergrid.Sdk Imports Usergrid.Sdk.Model Public Class Utils Public Shared Function GetFollowers(userName As String) As IList Dim conn As Connection = New Connection() conn.ConnectorIdentifier = userName conn.ConnectorCollectionName = "users" conn.ConnectionName = "following" Return Globals.client.GetConnections(conn) End Function Public Shared Function GetFollowed(userName As String) As IList Dim conn As Connection = New Connection() conn.ConnectorIdentifier = userName conn.ConnectorCollectionName = "users" conn.ConnectionName = "followed" Return Globals.client.GetConnections(conn) End Function Public Shared Sub FollowUser(follower As String, followed As String) Dim conn As Connection = New Connection() conn.ConnecteeCollectionName = "users" conn.ConnectorCollectionName = "users" conn.ConnectorIdentifier = follower conn.ConnecteeIdentifier = followed conn.ConnectionName = "following" Globals.client.CreateConnection(conn) End Sub Public Shared Sub AddFollower(follower As String, followed As String) Dim conn As Connection = New Connection() conn.ConnecteeCollectionName = "users" conn.ConnectorCollectionName = "users" conn.ConnectorIdentifier = followed conn.ConnecteeIdentifier = follower conn.ConnectionName = "followed" Globals.client.CreateConnection(conn) End Sub Public Shared Sub DeleteFollowUser(follower As String, followed As String) Dim conn As Connection = New Connection() conn.ConnecteeCollectionName = "users" conn.ConnectorCollectionName = "users" conn.ConnectorIdentifier = follower conn.ConnecteeIdentifier = followed conn.ConnectionName = "following" Dim clist As IList = Globals.client.GetConnections(conn) Globals.client.DeleteConnection(conn) End Sub Public Shared Sub DeleteFollower(follower As String, followed As String) Dim conn As Connection = New Connection() conn.ConnecteeCollectionName = "users" conn.ConnectorCollectionName = "users" conn.ConnectorIdentifier = followed conn.ConnecteeIdentifier = follower conn.ConnectionName = "followed" Globals.client.DeleteConnection(conn) End Sub End Class
apigee/usergrid-.net-sdk
samples/messageeTutorial/Messagee/Utils.vb
Visual Basic
apache-2.0
2,424
' 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 Imports System.Runtime.InteropServices Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests Inherits BasicTestBase #Region "Function Tests" <WorkItem(530310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530310")> <Fact> Public Sub PEParameterSymbolParamArrayAttribute() Dim source1 = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(int32 x, int32[] y) { .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } }]]>.Value Dim reference1 = CompileIL(source1, prependDefaultHeader:=False) Dim source2 = <compilation> <file name="a.vb"> <![CDATA[ Class C Shared Sub Main(args As String()) A.M(1, 2, 3) A.M(1, 2, 3, 4) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndReferences(source2, {reference1}) Dim method = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of PEMethodSymbol)("M") Dim yParam = method.Parameters.Item(1) Assert.Equal(0, yParam.GetAttributes().Length) Assert.True(yParam.IsParamArray) CompilationUtils.AssertNoDiagnostics(comp) End Sub <Fact> <WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")> Public Sub TestNamedArgumentOnStringParamsArgument() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Class MarkAttribute Inherits Attribute Public Sub New(ByVal otherArg As Boolean, ParamArray args As Object()) End Sub End Class <Mark(args:=New String() {"Hello", "World"}, otherArg:=True)> Module Program Private Sub Test(ByVal otherArg As Boolean, ParamArray args As Object()) End Sub Sub Main() Console.WriteLine("Method call") Test(args:=New String() {"Hello", "World"}, otherArg:=True) End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30455: Argument not specified for parameter 'otherArg' of 'Public Sub New(otherArg As Boolean, ParamArray args As Object())'. <Mark(args:=New String() {"Hello", "World"}, otherArg:=True)> ~~~~ BC30661: Field or property 'args' is not found. <Mark(args:=New String() {"Hello", "World"}, otherArg:=True)> ~~~~ BC30661: Field or property 'otherArg' is not found. <Mark(args:=New String() {"Hello", "World"}, otherArg:=True)> ~~~~~~~~ BC30587: Named argument cannot match a ParamArray parameter. Test(args:=New String() {"Hello", "World"}, otherArg:=True) ~~~~ ]]></errors>) End Sub ''' <summary> ''' This function is the same as PEParameterSymbolParamArray ''' except that we check attributes first (to check for race ''' conditions). ''' </summary> <WorkItem(530310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530310")> <Fact> Public Sub PEParameterSymbolParamArrayAttribute2() Dim source1 = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(int32 x, int32[] y) { .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } }]]>.Value Dim reference1 = CompileIL(source1, prependDefaultHeader:=False) Dim source2 = <compilation> <file name="a.vb"> <![CDATA[ Class C Shared Sub Main(args As String()) A.M(1, 2, 3) A.M(1, 2, 3, 4) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndReferences(source2, {reference1}) Dim method = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of PEMethodSymbol)("M") Dim yParam = method.Parameters.Item(1) Assert.True(yParam.IsParamArray) Assert.Equal(0, yParam.GetAttributes().Length) CompilationUtils.AssertNoDiagnostics(comp) End Sub <Fact> Public Sub BindingScope_Parameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class A Inherits System.Attribute Public Sub New(value As Integer) End Sub End Class Class C Const Value As Integer = 0 Sub method1(<A(Value)> x As Integer) End Sub End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub <Fact> Public Sub TestAssemblyAttributes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices <assembly: InternalsVisibleTo("Roslyn.Compilers.UnitTests")> <assembly: InternalsVisibleTo("Roslyn.Compilers.CSharp")> <assembly: InternalsVisibleTo("Roslyn.Compilers.CSharp.UnitTests")> <assembly: InternalsVisibleTo("Roslyn.Compilers.CSharp.Test.Utilities")> <assembly: InternalsVisibleTo("Roslyn.Compilers.VisualBasic")> ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim assembly = m.ContainingSymbol Dim compilerServicesNS = GetSystemRuntimeCompilerServicesNamespace(m) Dim internalsVisibleToAttr As NamedTypeSymbol = compilerServicesNS.GetTypeMembers("InternalsVisibleToAttribute").First() Dim attrs = assembly.GetAttributes(internalsVisibleToAttr) Assert.Equal(5, attrs.Count) attrs(0).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.UnitTests") attrs(1).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp") attrs(2).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.UnitTests") attrs(3).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.Test.Utilities") attrs(4).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.VisualBasic") End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub Private Function GetSystemRuntimeCompilerServicesNamespace(m As ModuleSymbol) As NamespaceSymbol Dim compilation = m.DeclaringCompilation Dim globalNS = If(compilation Is Nothing, m.ContainingAssembly.CorLibrary.GlobalNamespace, compilation.GlobalNamespace) Return globalNS. GetMember(Of NamespaceSymbol)("System"). GetMember(Of NamespaceSymbol)("Runtime"). GetMember(Of NamespaceSymbol)("CompilerServices") End Function <Fact> Public Sub TestAssemblyAttributesReflection() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="attr.vb"><![CDATA[ Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices ' These are not pseudo attributes, but encoded as bits in metadata <assembly: AssemblyAlgorithmId(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)> <assembly: AssemblyCultureAttribute("")> <assembly: AssemblyDelaySign(true)> <assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)> <assembly: AssemblyKeyFile("MyKey.snk")> <assembly: AssemblyKeyName("Key Name")> <assembly: AssemblyVersion("1.2.*")> <assembly: AssemblyFileVersionAttribute("4.3.2.100")> ]]> </file> </compilation>) Dim attrs = compilation.Assembly.GetAttributes() Assert.Equal(8, attrs.Length) For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyAlgorithmIdAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(0, a.CommonNamedArguments.Length) Assert.Equal(TypedConstantKind.Enum, a.CommonConstructorArguments(0).Kind) Assert.Equal("System.Configuration.Assemblies.AssemblyHashAlgorithm", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal(Configuration.Assemblies.AssemblyHashAlgorithm.MD5, CType(a.CommonConstructorArguments(0).Value, Configuration.Assemblies.AssemblyHashAlgorithm)) Case "AssemblyCultureAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal(0, a.CommonNamedArguments.Length) Case "AssemblyDelaySignAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("Boolean", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal(True, a.CommonConstructorArguments(0).Value) Case "AssemblyFlagsAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Enum, a.CommonConstructorArguments(0).Kind) Assert.Equal("System.Reflection.AssemblyNameFlags", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal(AssemblyNameFlags.Retargetable, CType(a.CommonConstructorArguments(0).Value, AssemblyNameFlags)) Case "AssemblyKeyFileAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("MyKey.snk", a.CommonConstructorArguments(0).Value) Case "AssemblyKeyNameAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("Key Name", a.CommonConstructorArguments(0).Value) Case "AssemblyVersionAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("1.2.*", a.CommonConstructorArguments(0).Value) Case "AssemblyFileVersionAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("4.3.2.100", a.CommonConstructorArguments(0).Value) Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) End Select Next End Sub ' Verify that resolving an attribute defined within a class on a class does not cause infinite recursion <Fact> Public Sub TestAttributesOnClassDefinedInClass() Dim compilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices <A.X()> Public Class A <AttributeUsage(AttributeTargets.All, allowMultiple:=true)> Public Class XAttribute Inherits Attribute End Class End Class]]> </file> </compilation>) Dim attrs = compilation.SourceModule.GlobalNamespace.GetMember("A").GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("A.XAttribute", attrs(0).AttributeClass.ToDisplayString) End Sub <WorkItem(540506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540506")> <Fact> Public Sub TestAttributesOnClassWithConstantDefinedInClass() Dim compilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ <Attr(Goo.p)> Class Goo Friend Const p As Object = 2 + 2 End Class Friend Class AttrAttribute Inherits Attribute End Class ]]> </file> </compilation>) Dim attrs = compilation.SourceModule.GlobalNamespace.GetMember("Goo").GetAttributes() Assert.Equal(1, attrs.Length) attrs(0).VerifyValue(0, TypedConstantKind.Primitive, 4) End Sub <WorkItem(540407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540407")> <Fact> Public Sub TestAttributesOnProperty() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class A Inherits Attribute End Class Public Interface I <A> Property AP(<A()>a As Integer) As <A>Integer End Interface Public Class C <A> Public Property AP As <A>Integer <A> Public Property P(<A> a As Integer) As <A>Integer <A> Get Return 0 End Get <A> Set(<A>value As Integer) End Set End Property End Class ]]></file> </compilation> Dim attributeValidator = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) Dim i = DirectCast(m.GlobalNamespace.GetMember("I"), NamedTypeSymbol) Dim c = DirectCast(m.GlobalNamespace.GetMember("C"), NamedTypeSymbol) ' auto-property in interface Dim ap = i.GetMember("AP") Assert.Equal(1, ap.GetAttributes().Length) Dim get_AP = DirectCast(i.GetMember("get_AP"), MethodSymbol) Assert.Equal(0, get_AP.GetAttributes().Length) Assert.Equal(1, get_AP.GetReturnTypeAttributes().Length) Assert.Equal(1, get_AP.Parameters(0).GetAttributes().Length) Dim set_AP = DirectCast(i.GetMember("set_AP"), MethodSymbol) Assert.Equal(0, set_AP.GetAttributes().Length) Assert.Equal(0, set_AP.GetReturnTypeAttributes().Length) Assert.Equal(1, set_AP.Parameters(0).GetAttributes().Length) Assert.Equal(0, set_AP.Parameters(1).GetAttributes().Length) ' auto-property on class ap = c.GetMember("AP") Assert.Equal(1, ap.GetAttributes().Length) get_AP = DirectCast(c.GetMember("get_AP"), MethodSymbol) If isFromSource Then Assert.Equal(0, get_AP.GetAttributes().Length) Else AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(get_AP.GetAttributes())) End If Assert.Equal(1, get_AP.GetReturnTypeAttributes().Length) set_AP = DirectCast(c.GetMember("set_AP"), MethodSymbol) If isFromSource Then Assert.Equal(0, get_AP.GetAttributes().Length) Else AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(set_AP.GetAttributes())) End If Assert.Equal(0, set_AP.GetReturnTypeAttributes().Length) Assert.Equal(0, set_AP.Parameters(0).GetAttributes().Length) ' property Dim p = c.GetMember("P") Assert.Equal(1, p.GetAttributes().Length) Dim get_P = DirectCast(c.GetMember("get_P"), MethodSymbol) Assert.Equal(1, get_P.GetAttributes().Length) Assert.Equal(1, get_P.GetReturnTypeAttributes().Length) Assert.Equal(1, get_P.Parameters(0).GetAttributes().Length) Dim set_P = DirectCast(c.GetMember("set_P"), MethodSymbol) Assert.Equal(1, set_P.GetAttributes().Length) Assert.Equal(0, set_P.GetReturnTypeAttributes().Length) Assert.Equal(1, set_P.Parameters(0).GetAttributes().Length) Assert.Equal(1, set_P.Parameters(1).GetAttributes().Length) End Sub CompileAndVerify(source, sourceSymbolValidator:=attributeValidator(True), symbolValidator:=attributeValidator(False)) End Sub <WorkItem(540407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540407")> <Fact> Public Sub TestAttributesOnPropertyReturnType() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class A Inherits System.Attribute End Class Public Class B Inherits System.Attribute End Class Public Interface I Property Auto As <A> Integer ReadOnly Property AutoRO As <A> Integer WriteOnly Property AutoWO As <A> Integer ' warning End Interface Public Class C Property Auto As <A> Integer ReadOnly Property ROA As <A> Integer Get Return 0 End Get End Property WriteOnly Property WOA As <A> Integer ' warning Set(value As Integer) End Set End Property Property A As <A> Integer Get Return 0 End Get Set(value As Integer) End Set End Property Property AB As <A> Integer Get Return 0 End Get Set(<B()> value As Integer) End Set End Property End Class ]]></file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim i = DirectCast(m.GlobalNamespace.GetMember("I"), NamedTypeSymbol) Dim c = DirectCast(m.GlobalNamespace.GetMember("C"), NamedTypeSymbol) ' auto-property in interface Dim auto = DirectCast(i.GetMember("Auto"), PropertySymbol) Assert.Equal(1, auto.GetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.Parameters(0).GetAttributes().Length) Dim autoRO = DirectCast(i.GetMember("AutoRO"), PropertySymbol) Assert.Equal(1, autoRO.GetMethod.GetReturnTypeAttributes().Length) Assert.Null(autoRO.SetMethod) Dim autoWO = DirectCast(i.GetMember("AutoWO"), PropertySymbol) Assert.Null(autoWO.GetMethod) Assert.Equal(0, autoWO.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.Parameters(0).GetAttributes().Length) ' auto-property in class auto = DirectCast(c.GetMember("Auto"), PropertySymbol) Assert.Equal(1, auto.GetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.Parameters(0).GetAttributes().Length) ' custom property in class Dim roa = DirectCast(c.GetMember("ROA"), PropertySymbol) Assert.Equal(1, roa.GetMethod.GetReturnTypeAttributes().Length) Assert.Null(roa.SetMethod) Dim woa = DirectCast(c.GetMember("WOA"), PropertySymbol) Assert.Null(woa.GetMethod) Assert.Equal(0, woa.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, woa.SetMethod.Parameters(0).GetAttributes().Length) Dim a = DirectCast(c.GetMember("A"), PropertySymbol) Assert.Equal(1, a.GetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, a.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, a.SetMethod.Parameters(0).GetAttributes().Length) Dim ab = DirectCast(c.GetMember("AB"), PropertySymbol) Assert.Equal(1, ab.GetMethod.GetReturnTypeAttributes().Length) Assert.Equal("A", ab.GetMethod.GetReturnTypeAttributes()(0).AttributeClass.Name) Assert.Equal(0, ab.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(1, ab.SetMethod.Parameters(0).GetAttributes().Length) Assert.Equal("B", ab.SetMethod.Parameters(0).GetAttributes()(0).AttributeClass.Name) End Sub Dim verifier = CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) CompilationUtils.AssertTheseDiagnostics(verifier.Compilation, <errors><![CDATA[ BC42364: Attributes applied on a return type of a WriteOnly Property have no effect. WriteOnly Property AutoWO As <A> Integer ' warning ~ BC42364: Attributes applied on a return type of a WriteOnly Property have no effect. WriteOnly Property WOA As <A> Integer ' warning ~ ]]></errors>) End Sub <WorkItem(546779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546779")> <Fact> Public Sub TestAttributesOnPropertyReturnType_MarshalAs() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Interface I Property Auto As <MarshalAs(UnmanagedType.I4)> Integer End Interface ]]></file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim i = DirectCast(m.GlobalNamespace.GetMember("I"), NamedTypeSymbol) ' auto-property in interface Dim auto = DirectCast(i.GetMember("Auto"), PropertySymbol) Assert.Equal(UnmanagedType.I4, auto.GetMethod.ReturnTypeMarshallingInformation.UnmanagedType) Assert.Equal(1, auto.GetMethod.GetReturnTypeAttributes().Length) Assert.Null(auto.SetMethod.ReturnTypeMarshallingInformation) Assert.Equal(UnmanagedType.I4, auto.SetMethod.Parameters(0).MarshallingInformation.UnmanagedType) Assert.Equal(0, auto.SetMethod.Parameters(0).GetAttributes().Length) End Sub ' TODO (tomat): implement reading from PE: symbolValidator:=attributeValidator CompileAndVerify(source, sourceSymbolValidator:=attributeValidator) End Sub <WorkItem(540433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540433")> <Fact> Public Sub TestAttributesOnPropertyAndGetSet() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <AObject(GetType(Object), O:=A.obj)> Public Class A Public Const obj As Object = Nothing Public ReadOnly Property RProp As String <AObject(New Object() {GetType(String)})> Get Return Nothing End Get End Property <AObject(New Object() {1, "two", GetType(String), 3.1415926})> Public WriteOnly Property WProp <AObject(New Object() {New Object() {GetType(String)}})> Set(value) End Set End Property End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib.AsImmutableOrNull())}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim attrs = type.GetAttributes() Assert.Equal("AObjectAttribute", attrs(0).AttributeClass.ToDisplayString) attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Type, GetType(Object)) attrs(0).VerifyValue(Of Object)(0, "O", TypedConstantKind.Primitive, Nothing) Dim prop = type.GetMember(Of PropertySymbol)("RProp") attrs = prop.GetMethod.GetAttributes() attrs(0).VerifyValue(0, TypedConstantKind.Array, {GetType(String)}) prop = type.GetMember(Of PropertySymbol)("WProp") attrs = prop.GetAttributes() attrs(0).VerifyValue(Of Object())(0, TypedConstantKind.Array, {1, "two", GetType(String), 3.1415926}) attrs = prop.SetMethod.GetAttributes() attrs(0).VerifyValue(0, TypedConstantKind.Array, {New Object() {GetType(String)}}) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact> Public Sub TestAttributesOnPropertyParameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class A Inherits Attribute End Class Public Class X Public Property P(<A>a As Integer) As <A>Integer Get Return 0 End Get Set(<A>value As Integer) End Set End Property End Class ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("X"), NamedTypeSymbol) Dim getter = DirectCast(type.GetMember("get_P"), MethodSymbol) Dim setter = DirectCast(type.GetMember("set_P"), MethodSymbol) ' getter Assert.Equal(1, getter.Parameters.Length) Assert.Equal(1, getter.Parameters(0).GetAttributes().Length) Assert.Equal(1, getter.GetReturnTypeAttributes().Length) ' setter Assert.Equal(2, setter.Parameters.Length) Assert.Equal(1, setter.Parameters(0).GetAttributes().Length) Assert.Equal(1, setter.Parameters(1).GetAttributes().Length) End Sub CompileAndVerify(source, symbolValidator:=attributeValidator, sourceSymbolValidator:=attributeValidator) End Sub <Fact> Public Sub TestAttributesOnEnumField() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Option Strict On Imports System Imports system.Collections.Generic Imports System.Reflection Imports CustomAttribute Imports AN = CustomAttribute.AttrName ' Use AttrName without Attribute suffix <Assembly: AN(UShortField:=4321)> <Assembly: AN(UShortField:=1234)> <Module: AttrName(TypeField:=GetType(System.IO.FileStream))> Namespace AttributeTest Public Interface IGoo Class NestedClass ' enum as object <AllInheritMultiple(System.IO.FileMode.Open, BindingFlags.DeclaredOnly Or BindingFlags.Public, UIntField:=123 * Field)> Public Const Field As UInteger = 10 End Class <AllInheritMultiple(New Char() {"q"c, "c"c}, "")> <AllInheritMultiple()> Enum NestedEnum zero one = 1 <AllInheritMultiple(Nothing, 256, 0.0F, -1, AryField:=New ULong() {0, 1, 12345657})> <AllInheritMultipleAttribute(GetType(Dictionary(Of String, Integer)), 255 + NestedClass.Field, -0.0001F, 3 - CShort(NestedEnum.oneagain))> three = 3 oneagain = one End Enum End Interface End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim attributeValidator = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) Dim attrs = m.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("CustomAttribute.AttrNameAttribute", attrs(0).AttributeClass.ToDisplayString) attrs(0).VerifyValue(0, "TypeField", TypedConstantKind.Type, GetType(FileStream)) Dim assembly = m.ContainingSymbol attrs = assembly.GetAttributes() If isFromSource Then Assert.Equal(2, attrs.Length) Assert.Equal("CustomAttribute.AttrName", attrs(0).AttributeClass.ToDisplayString) attrs(1).VerifyValue(Of UShort)(0, "UShortField", TypedConstantKind.Primitive, 1234) Else Assert.Equal(5, attrs.Length) ' 3 synthesized assembly attributes Assert.Equal("CustomAttribute.AttrName", attrs(3).AttributeClass.ToDisplayString) attrs(4).VerifyValue(Of UShort)(0, "UShortField", TypedConstantKind.Primitive, 1234) End If Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim top = DirectCast(ns.GetMember("IGoo"), NamedTypeSymbol) Dim type = top.GetMember(Of NamedTypeSymbol)("NestedClass") Dim field = type.GetMember(Of FieldSymbol)("Field") attrs = field.GetAttributes() Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attrs(0).AttributeClass.ToDisplayString) attrs(0).VerifyValue(0, TypedConstantKind.Enum, CInt(FileMode.Open)) attrs(0).VerifyValue(1, TypedConstantKind.Enum, CInt(BindingFlags.DeclaredOnly Or BindingFlags.Public)) attrs(0).VerifyValue(0, "UIntField", TypedConstantKind.Primitive, 1230) Dim nenum = top.GetMember(Of TypeSymbol)("NestedEnum") attrs = nenum.GetAttributes() Assert.Equal(2, attrs.Length) attrs(0).VerifyValue(0, TypedConstantKind.Array, {"q"c, "c"c}) attrs = nenum.GetMember("three").GetAttributes() Assert.Equal(2, attrs.Length) attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, Nothing) attrs(0).VerifyValue(Of Long)(1, TypedConstantKind.Primitive, 256) attrs(0).VerifyValue(Of Single)(2, TypedConstantKind.Primitive, 0) attrs(0).VerifyValue(Of Short)(3, TypedConstantKind.Primitive, -1) attrs(0).VerifyValue(Of ULong())(0, "AryField", TypedConstantKind.Array, New ULong() {0, 1, 12345657}) attrs(1).VerifyValue(Of Object)(0, TypedConstantKind.Type, GetType(Dictionary(Of String, Integer))) attrs(1).VerifyValue(Of Long)(1, TypedConstantKind.Primitive, 265) attrs(1).VerifyValue(Of Single)(2, TypedConstantKind.Primitive, -0.0001F) attrs(1).VerifyValue(Of Short)(3, TypedConstantKind.Primitive, 2) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator(True), symbolValidator:=attributeValidator(False)) End Sub <Fact> Public Sub TestAttributesOnDelegate() Dim source = <compilation> <file name="TestAttributesOnDelegate.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports CustomAttribute Namespace AttributeTest Public Interface IGoo <AllInheritMultiple(New Object() {0, "", Nothing}, 255, -127 - 1, AryProp:=New Object() {New Object() {"", GetType(IList(Of String))}})> Delegate Sub NestedSubDele(<AllInheritMultiple()> <Derived(GetType(String(,,)))> p As String) End Interface End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim type = DirectCast(ns.GetMember("IGoo"), NamedTypeSymbol) Dim dele = DirectCast(type.GetTypeMember("NestedSubDele"), NamedTypeSymbol) Dim attrs = dele.GetAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Array, New Object() {0, "", Nothing}) attrs(0).VerifyValue(Of Byte)(1, TypedConstantKind.Primitive, 255) attrs(0).VerifyValue(Of SByte)(2, TypedConstantKind.Primitive, -128) attrs(0).VerifyValue(Of Object())(0, "AryProp", TypedConstantKind.Array, New Object() {New Object() {"", GetType(IList(Of String))}}) Dim mem = dele.GetMember(Of MethodSymbol)("Invoke") ' no attributes on the method: Assert.Equal(0, mem.GetAttributes().Length) ' attributes on parameters: attrs = mem.Parameters(0).GetAttributes() Assert.Equal(2, attrs.Length) attrs(1).VerifyValue(Of Object)(0, TypedConstantKind.Type, GetType(String(,,))) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(540600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540600")> <Fact> Public Sub TestAttributesUseBaseAttributeField() Dim source = <compilation> <file name="TestAttributesUseBaseAttributeField.vb"><![CDATA[ Imports System Namespace AttributeTest Public Interface IGoo <CustomAttribute.Derived(New Object() {1, Nothing, "Hi"}, ObjectField:=2)> Function F(p As Integer) As Integer End Interface End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim type = DirectCast(ns.GetMember("IGoo"), NamedTypeSymbol) Dim attrs = type.GetMember(Of MethodSymbol)("F").GetAttributes() Assert.Equal("CustomAttribute.DerivedAttribute", attrs(0).AttributeClass.ToDisplayString) attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Array, New Object() {1, Nothing, "Hi"}) attrs(0).VerifyValue(Of Object)(0, "ObjectField", TypedConstantKind.Primitive, 2) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact(), WorkItem(529421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529421")> Public Sub TestAttributesWithParamArrayInCtor() Dim source = <compilation> <file name="TestAttributesWithParamArrayInCtor.vb"><![CDATA[ Imports System Imports CustomAttribute Namespace AttributeTest <AllInheritMultiple(New Char() {" "c, Nothing}, "")> Public Interface IGoo End Interface End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim sourceAttributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim type = DirectCast(ns.GetMember("IGoo"), NamedTypeSymbol) Dim attrs = type.GetAttributes() attrs(0).VerifyValue(Of Char())(0, TypedConstantKind.Array, New Char() {" "c, Nothing}) attrs(0).VerifyValue(Of String())(1, TypedConstantKind.Array, New String() {""}) Dim attrCtor = attrs(0).AttributeConstructor Debug.Assert(attrCtor.Parameters.Last.IsParamArray) End Sub Dim mdAttributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim type = DirectCast(ns.GetMember("IGoo"), NamedTypeSymbol) Dim attrs = type.GetAttributes() attrs(0).VerifyValue(Of Char())(0, TypedConstantKind.Array, New Char() {" "c, Nothing}) attrs(0).VerifyValue(Of String())(1, TypedConstantKind.Array, New String() {""}) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=sourceAttributeValidator, symbolValidator:=mdAttributeValidator) End Sub <WorkItem(540605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540605")> <Fact> Public Sub TestAttributesOnReturnType() Dim source = <compilation> <file name="TestAttributesOnReturnType.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports CustomAttribute Namespace AttributeTest Class XAttribute inherits Attribute Sub New(s as string) End Sub End Class Public Interface IGoo Function F1(i as integer) as <X("f1 return type")> string Property P1 as <X("p1 return type")> string End Interface Class C1 Property P1 as <X("p1 return type")> string ReadOnly Property P2 as <X("p2 return type")> string Get return nothing End Get End Property Function F2(i as integer) As <X("f2 returns an integer")> integer return 0 end function End Class End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull())}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim iGoo = DirectCast(ns.GetMember("IGoo"), NamedTypeSymbol) Dim f1 = DirectCast(iGoo.GetMember("F1"), MethodSymbol) Dim attrs = f1.GetReturnTypeAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, "f1 return type") Dim p1 = DirectCast(iGoo.GetMember("P1"), PropertySymbol) attrs = p1.GetMethod.GetReturnTypeAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, "p1 return type") Dim c1 = DirectCast(ns.GetMember("C1"), NamedTypeSymbol) Dim p2 = DirectCast(c1.GetMember("P2"), PropertySymbol) attrs = p2.GetMethod.GetReturnTypeAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, "p2 return type") Dim f2 = DirectCast(c1.GetMember("F2"), MethodSymbol) attrs = f2.GetReturnTypeAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, "f2 returns an integer") End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact> Public Sub TestAttributesUsageCasing() Dim source = <compilation> <file name="TestAttributesOnReturnType.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports CustomAttribute Namespace AttributeTest <ATTributeUSageATTribute(AttributeTargets.ReturnValue, ALLowMulTiplE:=True, InHeRIteD:=false)> Class XAttribute Inherits Attribute Sub New() End Sub End Class End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim xAttributeClass = DirectCast(ns.GetMember("XAttribute"), NamedTypeSymbol) Dim attributeUsage = xAttributeClass.GetAttributeUsageInfo() Assert.Equal(AttributeTargets.ReturnValue, attributeUsage.ValidTargets) Assert.Equal(True, attributeUsage.AllowMultiple) Assert.Equal(False, attributeUsage.Inherited) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(540940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540940")> <Fact> Public Sub TestAttributeWithParamArray() Dim source = <compilation> <file name="TestAttributeWithParamArray.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Sub New(ParamArray x As Integer()) End Sub End Class <A> Module M Sub Main() End Sub End Module ]]></file> </compilation> CompileAndVerify(source) End Sub <WorkItem(528469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528469")> <Fact()> Public Sub TestAttributeWithAttributeTargets() Dim source = <compilation> <file name="TestAttributeWithParamArray.vb"><![CDATA[ Imports System <System.AttributeUsage(AttributeTargets.All)> _ Class ZAttribute Inherits Attribute End Class <Z()> _ Class scen1 End Class Module M1 Sub goo() <Z()> _ Static x1 As Object End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) CompileAndVerify(compilation) End Sub <WorkItem(541277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541277")> <Fact> Public Sub TestAttributeEmitObjectValue() Dim source = <compilation> <file name="TestAttributeEmitObjectValue.vb"><![CDATA[ Imports System <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class A Inherits Attribute Public Property X As Object Public Sub New() End Sub Public Sub New(o As Object) End Sub End Class <A(1)> <A(New String() {"a", "b"})> <A(X:=1), A(X:=New String() {"a", "b"})> Class B Shared Sub Main() Dim b As New B() Dim a As A = b.GetType().GetCustomAttributes(False)(0) Console.WriteLine(a.X) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim bClass = DirectCast(m.GlobalNamespace.GetMember("B"), NamedTypeSymbol) Dim attrs = bClass.GetAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, 1) attrs(1).VerifyValue(Of Object)(0, TypedConstantKind.Array, New String() {"a", "b"}) attrs(2).VerifyValue(Of Object)(0, "X", TypedConstantKind.Primitive, 1) attrs(3).VerifyValue(Of Object)(0, "X", TypedConstantKind.Array, New String() {"a", "b"}) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(541278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541278")> <Fact> Public Sub TestAttributeEmitGenericEnumValue() Dim source = <compilation> <file name="TestAttributeEmitObjectValue.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Sub New(x As Object) Y = x End Sub Public Property Y As Object End Class Class B(Of T) Class D End Class Enum E A = &HABCDEF End Enum End Class <A(B(Of Integer).E.A)> Class C End Class Module m1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim cClass = DirectCast(m.GlobalNamespace.GetMember("C"), NamedTypeSymbol) Dim attrs = cClass.GetAttributes() Dim tc = attrs(0).CommonConstructorArguments(0) Assert.Equal(tc.Kind, TypedConstantKind.Enum) Assert.Equal(CType(tc.Value, Int32), &HABCDEF) Assert.Equal(tc.Type.ToDisplayString, "B(Of Integer).E") End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")> <Fact()> Public Sub TestAttributeEmitOpenGeneric() Dim source = <compilation> <file name="TestAttributeEmitObjectValue.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Sub New(x As Object) Y = x End Sub Public Property Y As Object End Class <A(GetType(B(Of)))> Class B(Of T) End Class Module m1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim bClass = DirectCast(m.GlobalNamespace.GetMember("B"), NamedTypeSymbol) Dim attrs = bClass.GetAttributes() attrs(0).VerifyValue(0, TypedConstantKind.Type, bClass.ConstructUnboundGenericType()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(541278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541278")> <Fact> Public Sub TestAttributeToString() Dim source = <compilation> <file name="TestAttributeToString.vb"><![CDATA[ Imports System <AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=True)> Class A Inherits Attribute Public Property X As Object Public Property T As Type Public Sub New() End Sub Public Sub New(ByVal o As Object) End Sub Public Sub New(ByVal y As Y) End Sub End Class Public Enum Y One = 1 Two = 2 Three = 3 End Enum <A()> Class B1 Shared Sub Main() End Sub End Class <A(1)> Class B2 End Class <A(New String() {"a", "b"})> Class B3 End Class <A(X:=1)> Class B4 End Class <A(T:=GetType(String))> Class B5 End Class <A(1, X:=1, T:=GetType(String))> Class B6 End Class <A(Y.Three)> Class B7 End Class <A(DirectCast(5, Y))> Class B8 End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim aClass = DirectCast(m.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim attrs = aClass.GetAttributes() Assert.Equal("System.AttributeUsageAttribute(System.AttributeTargets.Class Or System.AttributeTargets.Struct, AllowMultiple:=True)", attrs(0).ToString()) Dim bClass = DirectCast(m.GlobalNamespace.GetMember("B1"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B2"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(1)", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B3"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A({""a"", ""b""})", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B4"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(X:=1)", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B5"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(T:=GetType(String))", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B6"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(1, X:=1, T:=GetType(String))", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B7"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(Y.Three)", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B8"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(5)", attrs(0).ToString()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(541687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541687")> <Fact> Public Sub Bug_8524_NullAttributeArrayArgument() Dim source = <compilation> <file><![CDATA[ Imports System Class A Inherits Attribute Public Property X As Object End Class <A(X:=CStr(Nothing))> Class B Shared Sub Main() Dim b As New B() Dim a As A = b.GetType().GetCustomAttributes(False)(0) Console.Write(a.X Is Nothing) End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, expectedOutput:="True") End Sub <WorkItem(541964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541964")> <Fact> Public Sub TestApplyNamedArgumentTwice() Dim source = <compilation> <file name="TestApplyNamedArgumentTwice.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, AllowMultiple:=False, AllowMultiple:=True), A, A> Class A Inherits Attribute End Class Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim aClass = DirectCast(m.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim attrs = aClass.GetAttributes() Assert.Equal("System.AttributeUsageAttribute(System.AttributeTargets.All, AllowMultiple:=False, AllowMultiple:=True)", attrs(0).ToString()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact> Public Sub TestApplyNamedArgumentCasing() Dim source = <compilation> <file name="TestApplyNamedArgumentTwice.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, ALLOWMULTIPLE:=True), A, A> Class A Inherits Attribute End Class Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim aClass = DirectCast(m.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim attrs = aClass.GetAttributes() Assert.Equal("System.AttributeUsageAttribute(System.AttributeTargets.All, AllowMultiple:=True)", attrs(0).ToString()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(542123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542123")> <Fact> Public Sub TestApplyNestedDerivedAttribute() Dim source = <compilation> <file name="TestApplyNestedDerivedAttribute.vb"><![CDATA[ Imports System <First.Second.Third()> Class First : Inherits Attribute Class Second : Inherits First End Class Class Third : Inherits Second End Class End Class Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.VerifyDiagnostics() End Sub <WorkItem(542269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542269")> <Fact> Public Sub TestApplyNestedDerivedAttributeOnTypeAndItsMember() Dim source = <compilation> <file name="TestApplyNestedDerivedAttributeOnTypeAndItsMember.vb"><![CDATA[ Imports System Public Class First : Inherits Attribute <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)> Friend Class Second Inherits First End Class End Class <First.Second()> Module Module1 <First.Second()> Function ToString(x As Integer, y As Integer) As String Return Nothing End Function Public Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.VerifyDiagnostics() End Sub <Fact> Public Sub AttributeTargets_Method() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.Method)> Class Attr Inherits Attribute End Class Public Class C <Attr()> Custom Event EvntWithAccessors As Action(Of Integer) <Attr()> AddHandler(value As Action(Of Integer)) End AddHandler <Attr()> RemoveHandler(value As Action(Of Integer)) End RemoveHandler <Attr()> RaiseEvent(obj As Integer) End RaiseEvent End Event <Attr()> Property PropertyWithAccessors As Integer <Attr()> Get Return 0 End Get <Attr()> Set(value As Integer) End Set End Property <Attr()> Shared Sub Sub1() End Sub <Attr()> Function Ftn2() As Integer Return 1 End Function <Attr()> Declare Function DeclareFtn Lib "bar" () As Integer <Attr()> Declare Sub DeclareSub Lib "bar" () <Attr()> Shared Operator -(a As C, b As C) As Integer Return 0 End Operator <Attr()> Shared Narrowing Operator CType(a As C) As Integer Return 0 End Operator <Attr()> Public Event Evnt As Action(Of Integer) <Attr()> Public Field As Integer <Attr()> Public WithEvents WE As NestedType <Attr()> Class NestedType End Class <Attr()> Interface Iface End Interface End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "PropertyWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Evnt"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Field"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "WE"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "NestedType"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Iface")) End Sub <Fact> Public Sub AttributeTargets_Field() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.Field)> Class Attr Inherits Attribute End Class Public Class C <Attr()> Custom Event EvntWithAccessors As Action(Of Integer) <Attr()> AddHandler(value As Action(Of Integer)) End AddHandler <Attr()> RemoveHandler(value As Action(Of Integer)) End RemoveHandler <Attr()> RaiseEvent(obj As Integer) End RaiseEvent End Event <Attr()> Property PropertyWithAccessors As Integer <Attr()> Get Return 0 End Get <Attr()> Set(value As Integer) End Set End Property <Attr()> Shared Sub Sub1() End Sub <Attr()> Function Ftn2() As Integer Return 1 End Function <Attr()> Declare Function DeclareFtn Lib "bar" () As Integer <Attr()> Declare Sub DeclareSub Lib "bar" () <Attr()> Shared Operator -(a As C, b As C) As Integer Return 0 End Operator <Attr()> Shared Narrowing Operator CType(a As C) As Integer Return 0 End Operator <Attr()> Public Event Evnt As Action(Of Integer) <Attr()> Public Field As Integer <Attr()> Public WithEvents WE As NestedType <Attr()> Class NestedType End Class <Attr()> Interface Iface End Interface End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "AddHandler", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "RemoveHandler", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "RaiseEvent", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "PropertyWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "Get", "PropertyWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "Set", "PropertyWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Sub1"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Ftn2"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "DeclareFtn"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "DeclareSub"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "-"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "CType"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Evnt"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "NestedType"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Iface")) End Sub <Fact> Public Sub AttributeTargets_WithEvents() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class A Inherits Attribute End Class Class D <A> Public WithEvents myButton As Button End Class Class Button Public Event OnClick() End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source) Dim d = DirectCast(c.GlobalNamespace.GetMembers("D").Single(), NamedTypeSymbol) Dim myButton = DirectCast(d.GetMembers("myButton").Single(), PropertySymbol) Assert.Equal(0, myButton.GetAttributes().Length) Dim attr = myButton.GetFieldAttributes().Single() Assert.Equal("A", attr.AttributeClass.Name) End Sub <Fact> Public Sub AttributeTargets_WithEventsGenericInstantiation() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class A Inherits Attribute End Class Class D(Of T As Button) <A> Public WithEvents myButton As T End Class Class Button Public Event OnClick() End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source) Dim d = DirectCast(c.GlobalNamespace.GetMembers("D").Single(), NamedTypeSymbol) Dim button = DirectCast(c.GlobalNamespace.GetMembers("Button").Single(), NamedTypeSymbol) Dim dOfButton = d.Construct(button) Dim myButton = DirectCast(dOfButton.GetMembers("myButton").Single(), PropertySymbol) Assert.Equal(0, myButton.GetAttributes().Length) Dim attr = myButton.GetFieldAttributes().Single() Assert.Equal("A", attr.AttributeClass.Name) End Sub <Fact> Public Sub AttributeTargets_Events() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class A Inherits Attribute End Class <Serializable> Class D <A, NonSerialized> Public Event OnClick As Action End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source) c.VerifyDiagnostics() Dim d = DirectCast(c.GlobalNamespace.GetMembers("D").Single(), NamedTypeSymbol) Dim onClick = DirectCast(d.GetMembers("OnClick").Single(), EventSymbol) ' TODO (tomat): move NonSerialized attribute onto the associated field Assert.Equal(2, onClick.GetAttributes().Length) ' should be 1 Assert.Equal(0, onClick.GetFieldAttributes().Length) ' should be 1 End Sub <Fact, WorkItem(546769, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546769"), WorkItem(546770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546770")> Public Sub DiagnosticsOnEventParameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class C Event E(<MarshalAs()> x As Integer) End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source) c.AssertTheseDiagnostics(<![CDATA[ BC30516: Overload resolution failed because no accessible 'New' accepts this number of arguments. Event E(<MarshalAs()> x As Integer) ~~~~~~~~~ ]]>) End Sub <Fact, WorkItem(528748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528748")> Public Sub TestNonPublicConstructor() Dim source = <compilation> <file name="TestNonPublicConstructor.vb"><![CDATA[ <Fred(1)> Class Class1 End Class Class FredAttribute : Inherits System.Attribute Public Sub New(x As Integer, Optional y As Integer = 1) End Sub Friend Sub New(x As Integer) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeNonPublicConstructor, "Fred")) End Sub <WorkItem(542223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542223")> <Fact> Public Sub AttributeArgumentAsEnumFromMetadata() Dim metadata1 = VisualBasicCompilation.Create("bar.dll", references:={MscorlibRef}, syntaxTrees:={Parse("Public Enum Bar : Baz : End Enum")}).EmitToArray(New EmitOptions(metadataOnly:=True)) Dim ref1 = MetadataReference.CreateFromImage(metadata1) Dim metadata2 = VisualBasicCompilation.Create( "goo.dll", references:={MscorlibRef, ref1}, syntaxTrees:={ VisualBasicSyntaxTree.ParseText(<![CDATA[ Public Class Ca : Inherits System.Attribute Public Sub New(o As Object) End Sub End Class <Ca(Bar.Baz)> Public Class Goo End Class]]>.Value)}).EmitToArray(options:=New EmitOptions(metadataOnly:=True)) Dim ref2 = MetadataReference.CreateFromImage(metadata2) Dim comp = VisualBasicCompilation.Create("moo.dll", references:={MscorlibRef, ref1, ref2}) Dim goo = comp.GetTypeByMetadataName("Goo") Dim ca = goo.GetAttributes().First().CommonConstructorArguments.First() Assert.Equal("Bar", ca.Type.Name) End Sub <Fact> Public Sub TestAttributeWithNestedUnboundGeneric() Dim library = <file name="Library.vb"><![CDATA[ Namespace ClassLibrary1 Public Class C1(Of T1) Public Class C2(Of T2, T3) End Class End Class End Namespace ]]> </file> Dim compilation1 = VisualBasicCompilation.Create("library.dll", {VisualBasicSyntaxTree.ParseText(library.Value)}, {MscorlibRef}, TestOptions.ReleaseDll) Dim classLibrary = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim source = <compilation> <file name="TestAttributeWithNestedUnboundGeneric.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class <A(GetType(ClassLibrary1.C1(Of )))> Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndReferences(source, {SystemRef, MsvbRef, classLibrary}) compilation2.VerifyDiagnostics() Dim a = compilation2.GetTypeByMetadataName("Module1") Dim gt = a.GetAttributes().First().CommonConstructorArguments.First() Assert.False(DirectCast(gt.Value, TypeSymbol).IsErrorType) Dim arg = DirectCast(gt.Value, UnboundGenericType) Assert.Equal("ClassLibrary1.C1(Of )", arg.ToDisplayString) End Sub <Fact> Public Sub TestAttributeWithAliasToUnboundGeneric() Dim library = <file name="Library.vb"><![CDATA[ Namespace ClassLibrary1 Public Class C1(Of T1) Public Class C2(Of T2, T3) End Class End Class End Namespace ]]> </file> Dim compilation1 = VisualBasicCompilation.Create("library.dll", {VisualBasicSyntaxTree.ParseText(library.Value)}, {MscorlibRef}, TestOptions.ReleaseDll) Dim classLibrary = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim source = <compilation> <file name="TestAttributeWithAliasToUnboundGeneric.vb"><![CDATA[ Imports System Imports x = ClassLibrary1 Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class <A(GetType(x.C1(Of )))> Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndReferences(source, {SystemRef, MsvbRef, classLibrary}) compilation2.VerifyDiagnostics() Dim a = compilation2.GetTypeByMetadataName("Module1") Dim gt = a.GetAttributes().First().CommonConstructorArguments.First() Assert.False(DirectCast(gt.Value, TypeSymbol).IsErrorType) Dim arg = DirectCast(gt.Value, UnboundGenericType) Assert.Equal("ClassLibrary1.C1(Of )", arg.ToDisplayString) End Sub <Fact> Public Sub TestAttributeWithArrayOfUnboundGeneric() Dim source = <compilation> <file name="TestAttributeWithArrayOfUnboundGeneric.vb"><![CDATA[ Imports System Class C1(of T) End Class Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class <A(GetType(C1(Of )()))> Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences(source, {SystemRef, MsvbRef}) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ArrayOfRawGenericInvalid, "()")) Dim a = compilation.GetTypeByMetadataName("Module1") Dim gt = a.GetAttributes().First().CommonConstructorArguments.First() Assert.False(DirectCast(gt.Value, TypeSymbol).IsErrorType) Dim arg = DirectCast(gt.Value, ArrayTypeSymbol) Assert.Equal("C1(Of ?)()", arg.ToDisplayString) End Sub <Fact> Public Sub TestAttributeWithNullableUnboundGeneric() Dim source = <compilation> <file name="TestAttributeWithNullableUnboundGeneric.vb"><![CDATA[ Imports System Class C1(of T) End Class Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class <A(GetType(C1(Of )?))> Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences(source, {SystemRef, MsvbRef}) CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[ BC33101: Type 'C1(Of ?)' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'. <A(GetType(C1(Of )?))> ~~~~~~~ BC30182: Type expected. <A(GetType(C1(Of )?))> ~ ]]> </errors>) Dim a = compilation.GetTypeByMetadataName("Module1") Dim gt = a.GetAttributes().First().CommonConstructorArguments.First() Assert.False(DirectCast(gt.Value, TypeSymbol).IsErrorType) Dim arg = DirectCast(gt.Value, SubstitutedNamedType) Assert.Equal("C1(Of ?)?", arg.ToDisplayString) End Sub <Fact()> Public Sub TestConstantValueInsideAttributes() Dim tree = VisualBasicSyntaxTree.ParseText(<![CDATA[ Class c1 const A as integer = 1; const B as integer = 2; class MyAttribute : inherits Attribute Sub New(i as integer) End Sub end class <MyAttribute(A + B + 3)> Sub Goo() End Sub End Class"]]>.Value) Dim expr = tree.GetRoot().DescendantNodes().OfType(Of BinaryExpressionSyntax).First() Dim comp = CreateCompilationWithMscorlib({tree}) Dim constantValue = comp.GetSemanticModel(tree).GetConstantValue(expr) Assert.True(constantValue.HasValue) Assert.Equal(constantValue.Value, 6) End Sub <Fact> Public Sub TestArrayTypeInAttributeArgument() Dim source = <compilation> <file name="TestArrayTypeInAttributeArgument.vb"><![CDATA[ Imports System Public Class W End Class Public Class Y(Of T) Public Class F End Class Public Class Z(Of U) End Class End Class Public Class XAttribute Inherits Attribute Public Sub New(y As Object) End Sub End Class <X(GetType(W()))> _ Public Class C1 End Class <X(GetType(W(,)))> _ Public Class C2 End Class <X(GetType(W(,)()))> _ Public Class C3 End Class <X(GetType(Y(Of W)()(,)))> _ Public Class C4 End Class <X(GetType(Y(Of Integer).F(,)()(,,)))> _ Public Class C5 End Class <X(GetType(Y(Of Integer).Z(Of W)(,)()))> _ Public Class C6 End Class ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim classW As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("W") Dim classY As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("Y") Dim classF As NamedTypeSymbol = classY.GetTypeMember("F") Dim classZ As NamedTypeSymbol = classY.GetTypeMember("Z") Dim classX As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("XAttribute") Dim classC1 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C1") Dim classC2 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C2") Dim classC3 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C3") Dim classC4 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C4") Dim classC5 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C5") Dim classC6 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C6") Dim attrs = classC1.GetAttributes() Assert.Equal(1, attrs.Length) Dim typeArg = ArrayTypeSymbol.CreateVBArray(classW, Nothing, 1, m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC2.GetAttributes() Assert.Equal(1, attrs.Length) typeArg = ArrayTypeSymbol.CreateVBArray(classW, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC3.GetAttributes() Assert.Equal(1, attrs.Length) typeArg = ArrayTypeSymbol.CreateVBArray(classW, Nothing, 1, m.ContainingAssembly) typeArg = ArrayTypeSymbol.CreateVBArray(typeArg, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC4.GetAttributes() Assert.Equal(1, attrs.Length) Dim classYOfW As NamedTypeSymbol = classY.Construct(ImmutableArray.Create(Of TypeSymbol)(classW)) typeArg = ArrayTypeSymbol.CreateVBArray(classYOfW, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) typeArg = ArrayTypeSymbol.CreateVBArray(typeArg, Nothing, 1, m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC5.GetAttributes() Assert.Equal(1, attrs.Length) Dim classYOfInt As NamedTypeSymbol = classY.Construct(ImmutableArray.Create(Of TypeSymbol)(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32))) Dim substNestedF As NamedTypeSymbol = classYOfInt.GetTypeMember("F") typeArg = ArrayTypeSymbol.CreateVBArray(substNestedF, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=3, declaringAssembly:=m.ContainingAssembly) typeArg = ArrayTypeSymbol.CreateVBArray(typeArg, Nothing, 1, m.ContainingAssembly) typeArg = ArrayTypeSymbol.CreateVBArray(typeArg, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC6.GetAttributes() Assert.Equal(1, attrs.Length) Dim substNestedZ As NamedTypeSymbol = classYOfInt.GetTypeMember("Z").Construct(ImmutableArray.Create(Of TypeSymbol)(classW)) typeArg = ArrayTypeSymbol.CreateVBArray(substNestedZ, Nothing, 1, m.ContainingAssembly) typeArg = ArrayTypeSymbol.CreateVBArray(typeArg, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) End Sub Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub #End Region #Region "Error Tests" <Fact> Public Sub AttributeConstructorErrors1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="AttributeConstructorErrors1.vb"> <![CDATA[ Imports System Module m Function NotAConstant() as integer return 9 End Function End Module Enum e1 a End Enum <AttributeUsage(AttributeTargets.All, allowMultiple:=True)> Class XAttribute Inherits Attribute Sub New() End Sub Sub New(ByVal d As Decimal) End Sub Sub New(ByRef i As Integer) End Sub Public Sub New(ByVal e As e1) End Sub End Class <XDoesNotExist> <X(1D)> <X(1)> <X(e1.a)> <X(NotAConstant() + 2)> Class A End Class ]]> </file> </compilation>) Dim expectedErrors = <errors><![CDATA[ BC30002: Type 'XDoesNotExist' is not defined. <XDoesNotExist> ~~~~~~~~~~~~~ BC30045: Attribute constructor has a parameter of type 'Decimal', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types. <X(1D)> ~ BC36006: Attribute constructor has a 'ByRef' parameter of type 'Integer'; cannot use constructors with byref parameters to apply the attribute. <X(1)> ~ BC31516: Type 'e1' cannot be used in an attribute because it is not declared 'Public'. <X(e1.a)> ~ BC36006: Attribute constructor has a 'ByRef' parameter of type 'Integer'; cannot use constructors with byref parameters to apply the attribute. <X(NotAConstant() + 2)> ~ BC30059: Constant expression is required. <X(NotAConstant() + 2)> ~~~~~~~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub AttributeConversionsErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="AttributeConversionsErrors.vb"> <![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, allowMultiple:=True)> Class XAttribute Inherits Attribute Sub New() End Sub Sub New(i As Integer) End Sub End Class <X("a")> Class A End Class ]]> </file> </compilation>) Dim expectedErrors = <errors><![CDATA[ BC30934: Conversion from 'String' to 'Integer' cannot occur in a constant expression used as an argument to an attribute. <X("a")> ~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub AttributeNamedArgumentErrors1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="AttributeNamedArgumentErrors1.vb"> <![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, allowMultiple:=True)> Class XAttribute Inherits Attribute Sub F1(i as integer) End Sub private PrivateField as integer shared Property SharedProperty as integer ReadOnly Property ReadOnlyProperty As Integer Get Return Nothing End Get End Property Property BadDecimalType as decimal Property BadDateType as date Property BadArrayType As Attribute() End Class <X(NotFound := nothing)> <X(F1 := nothing)> <X(PrivateField := nothing)> <X(SharedProperty := nothing)> <X(ReadOnlyProperty := nothing)> <X(BadDecimalType := nothing)> <X(BadDateType := nothing)> <X(BadArrayType:=Nothing)> Class A End Class ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30661: Field or property 'NotFound' is not found. <X(NotFound := nothing)> ~~~~~~~~ BC32010: 'F1' cannot be named as a parameter in an attribute specifier because it is not a field or property. <X(F1 := nothing)> ~~ BC30389: 'XAttribute.PrivateField' is not accessible in this context because it is 'Private'. <X(PrivateField := nothing)> ~~~~~~~~~~~~ BC31500: 'Shared' attribute property 'SharedProperty' cannot be the target of an assignment. <X(SharedProperty := nothing)> ~~~~~~~~~~~~~~ BC31501: 'ReadOnly' attribute property 'ReadOnlyProperty' cannot be the target of an assignment. <X(ReadOnlyProperty := nothing)> ~~~~~~~~~~~~~~~~ BC30659: Property or field 'BadDecimalType' does not have a valid attribute type. <X(BadDecimalType := nothing)> ~~~~~~~~~~~~~~ BC30659: Property or field 'BadDateType' does not have a valid attribute type. <X(BadDateType := nothing)> ~~~~~~~~~~~ BC30659: Property or field 'BadArrayType' does not have a valid attribute type. <X(BadArrayType:=Nothing)> ~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(540939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540939")> <Fact> Public Sub AttributeProtectedConstructorError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System <A()> Class A Inherits Attribute Protected Sub New() End Sub End Class <B("goo")> Class B Inherits Attribute Protected Sub New() End Sub End Class <C("goo")> Class C Inherits Attribute Protected Sub New() End Sub Protected Sub New(b as string) End Sub End Class <D(1S)> Class D Inherits Attribute Protected Sub New() End Sub protected Sub New(b as Integer) End Sub protected Sub New(b as Long) End Sub End Class ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30517: Overload resolution failed because no 'New' is accessible. <A()> ~~~ BC30517: Overload resolution failed because no 'New' is accessible. <B("goo")> ~~~~~~~~ BC30517: Overload resolution failed because no 'New' is accessible. <C("goo")> ~~~~~~~~ BC30517: Overload resolution failed because no 'New' is accessible. <D(1S)> ~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) ' TODO: after fixing LookupResults and changing the error handling for inaccessible attribute constructors, ' the error messages from above are expected to change to something like: ' Error BC30390 'A.Protected Sub New()' is not accessible in this context because it is 'Protected'. End Sub <WorkItem(540624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540624")> <Fact> Public Sub AttributeNoMultipleAndInvalidTarget() Dim source = <compilation> <file name="AttributeNoMultipleAndInvalidTarget.vb"><![CDATA[ Imports System Imports CustomAttribute <Base(1)> <Base("SOS")> Module AttributeMod <Derived("Q"c)> <Derived("C"c)> Public Class Goo End Class End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}) ' BC30663, BC30662 Dim expectedErrors = <errors> <![CDATA[ BC30663: Attribute 'BaseAttribute' cannot be applied multiple times. <Base("SOS")> ~~~~~~~~~~~ BC30662: Attribute 'DerivedAttribute' cannot be applied to 'Goo' because the attribute is not valid on this declaration type. <Derived("Q"c)> ~~~~~~~ BC30663: Attribute 'DerivedAttribute' cannot be applied multiple times. <Derived("C"c)> ~~~~~~~~~~~~~ ]]> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub AttributeNameScoping() Dim source = <compilation> <file name="AttributeNameScoping.vb"><![CDATA[ Imports System ' X1 should not be visible without qualification <clscompliant(x1)> Module m1 Const X1 as boolean = true ' C1 should not be visible without qualification <clscompliant(C1)> Public Class CGoo Public Const C1 as Boolean = true <clscompliant(c1)> public Sub s() end sub End Class ' C1 should not be visible without qualification <clscompliant(C1)> Public Structure SGoo Public Const C1 as Boolean = true <clscompliant(c1)> public Sub s() end sub End Structure ' s should not be visible without qualification <clscompliant(s.GetType() isnot nothing)> Public Interface IGoo Sub s() End Interface ' C1 should not be visible without qualification <clscompliant(a = 1)> Public Enum EGoo A = 1 End Enum End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_InaccessibleSymbol2, "x1").WithArguments("m1.X1", "Private"), Diagnostic(ERRID.ERR_NameNotDeclared1, "C1").WithArguments("C1"), Diagnostic(ERRID.ERR_NameNotDeclared1, "C1").WithArguments("C1"), Diagnostic(ERRID.ERR_NameNotDeclared1, "s").WithArguments("s"), Diagnostic(ERRID.ERR_RequiredConstExpr, "s.GetType() isnot nothing"), Diagnostic(ERRID.ERR_NameNotDeclared1, "a").WithArguments("a"), Diagnostic(ERRID.ERR_RequiredConstExpr, "a = 1")) End Sub <WorkItem(541279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541279")> <Fact> Public Sub AttributeArrayMissingInitializer() Dim source = <compilation> <file name="AttributeArrayMissingInitializer.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, AllowMultiple:=true)> Class A Inherits Attribute Public Sub New(x As Object()) End Sub End Class <A(New Object(5) {})> <A(New Object(5) {1})> Class B Shared Sub Main() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_MissingValuesForArraysInApplAttrs, "{}"), Diagnostic(ERRID.ERR_InitializerTooFewElements1, "{1}").WithArguments("5") ) End Sub <Fact> Public Sub Bug8642() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System <goo(Type.EmptyTypes)> Module Program Sub Main(args As String()) End Sub End Module ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30002: Type 'goo' is not defined. <goo(Type.EmptyTypes)> ~~~ BC30059: Constant expression is required. <goo(Type.EmptyTypes)> ~~~~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ErrorsInMultipleSyntaxTrees() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System <Module: A> <AttributeUsage(AttributeTargets.Class)> Class A Inherits Attribute End Class <AttributeUsage(AttributeTargets.Method)> Class B Inherits Attribute End Class ]]> </file> <file name="b.vb"> <![CDATA[ <Module: B> ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30549: Attribute 'A' cannot be applied to a module. <Module: A> ~ BC30549: Attribute 'B' cannot be applied to a module. <Module: B> ~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ErrorsInMultiplePartialDeclarations() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System <AttributeUsage(AttributeTargets.Class)> Class A1 Inherits Attribute End Class <AttributeUsage(AttributeTargets.Method)> Class A2 Inherits Attribute End Class <A1> Class B End Class ]]> </file> <file name="b.vb"> <![CDATA[ <A1, A2> Partial Class B End Class ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30663: Attribute 'A1' cannot be applied multiple times. <A1, A2> ~~ BC30662: Attribute 'A2' cannot be applied to 'B' because the attribute is not valid on this declaration type. <A1, A2> ~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub PartialMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class A Inherits Attribute End Class Public Class B Inherits Attribute End Class Partial Class C <A> Private Partial Sub Goo() End Sub <B> Private Sub Goo() End Sub End Class ]]> </file> </compilation>) CompileAndVerify(compilation, sourceSymbolValidator:= Sub(moduleSymbol) Dim c = DirectCast(moduleSymbol.GlobalNamespace.GetMembers("C").Single(), NamedTypeSymbol) Dim goo = DirectCast(c.GetMembers("Goo").Single(), MethodSymbol) Dim attrs = goo.GetAttributes() Assert.Equal(2, attrs.Length) Assert.Equal("A", attrs(0).AttributeClass.Name) Assert.Equal("B", attrs(1).AttributeClass.Name) End Sub) End Sub <WorkItem(542020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542020")> <Fact> Public Sub ErrorsAttributeNameResolutionWithNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System Class CAttribute Inherits Attribute End Class Namespace Y.CAttribute End Namespace Namespace Y Namespace X <C> Class C Inherits Attribute End Class End Namespace End Namespace ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30182: Type expected. <C> ~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(542170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542170")> <Fact> Public Sub GenericTypeParameterUsedAsAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Module M <T> Sub Goo(Of T) End Sub Class T : Inherits Attribute End Class End Module ]]> </file> </compilation>) 'BC32067: Type parameters, generic types or types contained in generic types cannot be used as attributes. compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_AttrCannotBeGenerics, "T").WithArguments("T")) End Sub <WorkItem(542273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542273")> <Fact()> Public Sub AnonymousTypeFieldAsAttributeNamedArgValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System <AttributeUsage(AttributeTargets.Class, AllowMultiple:=New With {.anonymousField = False}.anonymousField)> Class ExtensionAttribute Inherits Attribute End Class ]]> </file> </compilation>) 'BC30059: Constant expression is required. compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "New With {.anonymousField = False}.anonymousField")) End Sub <WorkItem(545073, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545073")> <Fact> Public Sub AttributeOnDelegateReturnTypeError() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class ReturnTypeAttribute Inherits System.Attribute End Class Class C Public Delegate Function D() As <ReturnTypeAttribute(0)> Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_TooManyArgs1, "0").WithArguments("Public Sub New()")) End Sub <Fact> Public Sub AttributeOnDelegateParameterError() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class ReturnTypeAttribute Inherits System.Attribute End Class Class C Public Delegate Function D(<ReturnTypeAttribute(0)>ByRef a As Integer) As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_TooManyArgs1, "0").WithArguments("Public Sub New()")) End Sub <WorkItem(545073, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545073")> <Fact> Public Sub AttributesOnDelegate() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Public Class A Inherits System.Attribute End Class Public Class B Inherits System.Attribute End Class Public Class C Inherits System.Attribute End Class <A> Public Delegate Function D(<C>a As Integer, <C>ByRef b As Integer) As <B> Integer ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim d = m.GlobalNamespace.GetTypeMember("D") Dim invoke = DirectCast(d.GetMember("Invoke"), MethodSymbol) Dim beginInvoke = DirectCast(d.GetMember("BeginInvoke"), MethodSymbol) Dim endInvoke = DirectCast(d.GetMember("EndInvoke"), MethodSymbol) Dim ctor = DirectCast(d.Constructors.Single(), MethodSymbol) Dim p As ParameterSymbol ' no attributes on methods: Assert.Equal(0, invoke.GetAttributes().Length) Assert.Equal(0, beginInvoke.GetAttributes().Length) Assert.Equal(0, endInvoke.GetAttributes().Length) Assert.Equal(0, ctor.GetAttributes().Length) ' attributes on return types: Assert.Equal(0, beginInvoke.GetReturnTypeAttributes().Length) Assert.Equal(0, endInvoke.GetReturnTypeAttributes().Length) Assert.Equal(0, ctor.GetReturnTypeAttributes().Length) Dim attrs = invoke.GetReturnTypeAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "B") ' ctor parameters: Assert.Equal(2, ctor.Parameters.Length) Assert.Equal(0, ctor.Parameters(0).GetAttributes().Length) Assert.Equal(0, ctor.Parameters(0).GetAttributes().Length) ' Invoke parameters: Assert.Equal(2, invoke.Parameters.Length) attrs = invoke.Parameters(0).GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") attrs = invoke.Parameters(1).GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") ' BeginInvoke parameters: Assert.Equal(4, beginInvoke.Parameters.Length) p = beginInvoke.Parameters(0) Assert.Equal("a", p.Name) attrs = p.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") Assert.Equal(1, p.GetAttributes(attrs(0).AttributeClass).Count) Assert.False(p.IsExplicitByRef) Assert.False(p.IsByRef) p = beginInvoke.Parameters(1) Assert.Equal("b", p.Name) attrs = p.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") Assert.Equal(1, p.GetAttributes(attrs(0).AttributeClass).Count) Assert.True(p.IsExplicitByRef) Assert.True(p.IsByRef) Assert.Equal(0, beginInvoke.Parameters(2).GetAttributes().Length) Assert.Equal(0, beginInvoke.Parameters(3).GetAttributes().Length) ' EndInvoke parameters: Assert.Equal(2, endInvoke.Parameters.Length) p = endInvoke.Parameters(0) Assert.Equal("b", p.Name) attrs = p.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") Assert.Equal(1, p.GetAttributes(attrs(0).AttributeClass).Count) Assert.True(p.IsExplicitByRef) Assert.True(p.IsByRef) p = endInvoke.Parameters(1) attrs = p.GetAttributes() Assert.Equal(0, attrs.Length) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub #End Region ''' <summary> ''' Verify that inaccessible friend AAttribute is preferred over accessible A ''' </summary> <Fact()> Public Sub TestAttributeLookupInaccessibleFriend() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Class A Inherits System.Attribute End Class <A()> Class C End Class Module Module1 Sub Main() End Sub End Module]]> </file> </compilation> Dim sourceWithAAttribute As XElement = <compilation> <file name="library.vb"> <![CDATA[ Class AAttribute End Class ]]></file> </compilation> Dim compWithAAttribute = VisualBasicCompilation.Create( "library.dll", {VisualBasicSyntaxTree.ParseText(sourceWithAAttribute.Value)}, {MsvbRef, MscorlibRef, SystemCoreRef}, TestOptions.ReleaseDll) Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {compWithAAttribute.ToMetadataReference()}) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_InaccessibleSymbol2, "A").WithArguments("AAttribute", "Friend")) End Sub ''' <summary> ''' Verify that inaccessible inherited private is preferred ''' </summary> <Fact()> Public Sub TestAttributeLookupInaccessibleInheritedPrivate() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Class C Private Class NSAttribute Inherits Attribute End Class End Class Class d Inherits C <NS()> Sub d() End Sub End Class Module Module1 Sub Main() End Sub End Module]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_InaccessibleSymbol2, "NS").WithArguments("C.NSAttribute", "Private")) End Sub ''' <summary> ''' Verify that ambiguous error is reported when A binds to two Attributes. ''' </summary> ''' <remarks>If this is run in the IDE make sure global namespace is empty or add ''' global namespace prefix to N1 and N2 or run test at command line.</remarks> <Fact()> Public Sub TestAttributeLookupAmbiguousAttributesWithPrefix() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports N1 Imports N2 Namespace N1 Class AAttribute End Class End Namespace Namespace N2 Class AAttribute End Class End Namespace Class A Inherits Attribute End Class <A()> Class C End Class]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_AmbiguousInImports2, "A").WithArguments("AAttribute", "N1, N2")) End Sub ''' <summary> ''' Verify that source attribute takes precedence over metadata attribute with the same name ''' </summary> <Fact()> Public Sub TestAttributeLookupSourceOverridesMetadata() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Public Class extensionattribute : Inherits Attribute End Class End Namespace Module m <System.Runtime.CompilerServices.extension()> Sub Test1(x As Integer) System.Console.WriteLine(x) End Sub Sub Main() Dim x = New System.Runtime.CompilerServices.extensionattribute() End Sub End Module]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source) comp.VerifyDiagnostics() End Sub <WorkItem(543855, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543855")> <Fact()> Public Sub VariantArrayConversionInAttribute() Dim vbCompilation = CreateVisualBasicCompilation("VariantArrayConversion", <![CDATA[ Imports System <Assembly: AObject(new Type() {GetType(string)})> <AttributeUsage(AttributeTargets.All)> Public Class AObjectAttribute Inherits Attribute Sub New(b As Object) End Sub Sub New(b As Object()) End Sub End Class ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) CompileAndVerify(vbCompilation).VerifyDiagnostics() End Sub <Fact(), WorkItem(544199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544199")> Public Sub EnumsAllowedToViolateAttributeUsage() CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.InteropServices &lt;ComVisible(True)&gt; _ &lt;Guid("6f4eb02b-3469-424c-bbcc-2672f653e646")&gt; _ &lt;BestFitMapping(False)&gt; _ &lt;StructLayout(LayoutKind.Auto)&gt; _ &lt;TypeLibType(TypeLibTypeFlags.FRestricted)&gt; _ &lt;Flags()&gt; _ Public Enum EnumHasAllSupportedAttributes ID1 ID2 End Enum </file> </compilation>).VerifyDiagnostics() End Sub <Fact, WorkItem(544367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544367")> Public Sub AttributeOnPropertyParameter() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim classAType As Type = GetType(A) Dim itemGetter = classAType.GetMethod("get_Item") ShowAttributes(itemGetter.GetParameters()(0)) Dim itemSetter = classAType.GetMethod("set_Item") ShowAttributes(itemSetter.GetParameters()(0)) End Sub Sub ShowAttributes(p As Reflection.ParameterInfo) Dim attrs = p.GetCustomAttributes(False) Console.WriteLine("param {1} in {0} has {2} attributes", p.Member, p.Name, attrs.Length) For Each a In attrs Console.WriteLine(" attribute of type {0}", a.GetType()) Next End Sub End Module Class A Default Public Property Item( &lt;MyAttr(A.C)&gt; index As Integer) As String Get Return "" End Get Set(value As String) End Set End Property Public Const C as Integer = 4 End Class Class MyAttr Inherits Attribute Public Sub New(x As Integer) End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(comp, <![CDATA[ param index in System.String get_Item(Int32) has 1 attributes attribute of type MyAttr param index in Void set_Item(Int32, System.String) has 1 attributes attribute of type MyAttr ]]>) End Sub <Fact, WorkItem(544367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544367")> Public Sub AttributeOnPropertyParameterWithError() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module Class A Default Public Property Item(<MyAttr> index As Integer) As String Get Return "" End Get Set(value As String) End Set End Property End Class Class MyAttr ' Does not inherit attribute End Class ]]> </file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31504: 'MyAttr' cannot be used as an attribute because it does not inherit from 'System.Attribute'. Default Public Property Item(&lt;MyAttr&gt; index As Integer) As String ~~~~~~ </expected>) End Sub <Fact, WorkItem(543810, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543810")> Public Sub AttributeNamedArgumentWithEvent() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Class Base Event myEvent End Class Class Program Inherits Base <MyAttribute(t:=myEvent)> Event MyEvent2 Sub Main(args As String()) End Sub End Class Class MyAttribute Inherits Attribute Public t As Object Sub New(t As Integer, Optional x As Integer = 1.0D, Optional y As String = Nothing) End Sub End Class Module m Sub Main() End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30455: Argument not specified for parameter 't' of 'Public Sub New(t As Integer, [x As Integer = 1], [y As String = Nothing])'. <MyAttribute(t:=myEvent)> ~~~~~~~~~~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. <MyAttribute(t:=myEvent)> ~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(543955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543955")> Public Sub StringParametersInDeclareMethods_1() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Reflection Module Module1 Declare Ansi Function GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, ByVal buffer As Integer) As Integer Declare Unicode Function GetWindowsDirectory2 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, ByVal buffer As Integer) As Integer Declare Auto Function GetWindowsDirectory3 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, ByVal buffer As Integer) As Integer Declare Ansi Function GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, ByVal buffer As Integer) As Integer Declare Unicode Function GetWindowsDirectory5 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, ByVal buffer As Integer) As Integer Declare Auto Function GetWindowsDirectory6 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, ByVal buffer As Integer) As Integer Delegate Function D(ByRef buffer As String, ByVal buffer As Integer) As Integer Sub Main() Dim t = GetType(Module1) Print(t.GetMethod("GetWindowsDirectory1")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory2")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory3")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory4")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory5")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory6")) System.Console.WriteLine() End Sub Private Sub Print(m As MethodInfo) System.Console.WriteLine(m.Name) For Each p In m.GetParameters() System.Console.WriteLine("{0} As {1}", p.Name, p.ParameterType) For Each marshal In p.GetCustomAttributes(GetType(Runtime.InteropServices.MarshalAsAttribute), False) System.Console.WriteLine(DirectCast(marshal, Runtime.InteropServices.MarshalAsAttribute).Value.ToString()) Next Next End Sub Sub Test1(ByRef x As String) GetWindowsDirectory1(x, 0) End Sub Sub Test2(ByRef x As String) GetWindowsDirectory2(x, 0) End Sub Sub Test3(ByRef x As String) GetWindowsDirectory3(x, 0) End Sub Sub Test4(ByRef x As String) GetWindowsDirectory4(x, 0) End Sub Sub Test5(ByRef x As String) GetWindowsDirectory5(x, 0) End Sub Sub Test6(ByRef x As String) GetWindowsDirectory6(x, 0) End Sub Function Test11() As D Return AddressOf GetWindowsDirectory1 End Function Function Test12() As D Return AddressOf GetWindowsDirectory2 End Function Function Test13() As D Return AddressOf GetWindowsDirectory3 End Function Function Test14() As D Return AddressOf GetWindowsDirectory4 End Function Function Test15() As D Return AddressOf GetWindowsDirectory5 End Function Function Test16() As D Return AddressOf GetWindowsDirectory6 End Function End Module ]]></file> </compilation>, TestOptions.ReleaseExe) Dim verifier = CompileAndVerify(comp, expectedOutput:= <![CDATA[ GetWindowsDirectory1 buffer As System.String& VBByRefStr buffer As System.Int32 GetWindowsDirectory2 buffer As System.String& VBByRefStr buffer As System.Int32 GetWindowsDirectory3 buffer As System.String& VBByRefStr buffer As System.Int32 GetWindowsDirectory4 buffer As System.String& AnsiBStr buffer As System.Int32 GetWindowsDirectory5 buffer As System.String& BStr buffer As System.Int32 GetWindowsDirectory6 buffer As System.String& TBStr buffer As System.Int32 ]]>) verifier.VerifyIL("Module1.Test1", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Ansi Function Module1.GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test2", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Unicode Function Module1.GetWindowsDirectory2 Lib "kernel32" Alias "GetWindowsDirectoryW" (String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test3", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Auto Function Module1.GetWindowsDirectory3 Lib "kernel32" Alias "GetWindowsDirectoryW" (String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test4", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Ansi Function Module1.GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test5", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Unicode Function Module1.GetWindowsDirectory5 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test6", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Auto Function Module1.GetWindowsDirectory6 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) End Sub <Fact, WorkItem(543955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543955")> Public Sub StringParametersInDeclareMethods_3() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Reflection Module Module1 Declare Ansi Function GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByVal buffer As String, ByVal buffer As Integer) As Integer Declare Ansi Function GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, ByVal buffer As Integer) As Integer Delegate Function D3(buffer As String, ByVal buffer As Integer) As Integer Delegate Function D4(buffer As Integer, ByVal buffer As Integer) As Integer Function Test19() As D3 Return AddressOf GetWindowsDirectory1 ' 1 End Function Function Test20() As D3 Return AddressOf GetWindowsDirectory4 ' 2 End Function Function Test21() As D4 Return AddressOf GetWindowsDirectory1 ' 3 End Function Function Test22() As D4 Return AddressOf GetWindowsDirectory4 ' 4 End Function Sub Main() End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) AssertTheseDiagnostics(comp, <expected> BC31143: Method 'Public Declare Ansi Function GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, buffer As Integer) As Integer' does not have a signature compatible with delegate 'Delegate Function Module1.D3(buffer As String, buffer As Integer) As Integer'. Return AddressOf GetWindowsDirectory1 ' 1 ~~~~~~~~~~~~~~~~~~~~ BC31143: Method 'Public Declare Ansi Function GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, buffer As Integer) As Integer' does not have a signature compatible with delegate 'Delegate Function Module1.D3(buffer As String, buffer As Integer) As Integer'. Return AddressOf GetWindowsDirectory4 ' 2 ~~~~~~~~~~~~~~~~~~~~ BC31143: Method 'Public Declare Ansi Function GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, buffer As Integer) As Integer' does not have a signature compatible with delegate 'Delegate Function Module1.D4(buffer As Integer, buffer As Integer) As Integer'. Return AddressOf GetWindowsDirectory1 ' 3 ~~~~~~~~~~~~~~~~~~~~ BC31143: Method 'Public Declare Ansi Function GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, buffer As Integer) As Integer' does not have a signature compatible with delegate 'Delegate Function Module1.D4(buffer As Integer, buffer As Integer) As Integer'. Return AddressOf GetWindowsDirectory4 ' 4 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(529620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529620")> <Fact()> Public Sub TestFriendEnumInAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ ' Friend Enum in an array in an attribute should be an error. Imports System Friend Enum e2 r g b End Enum Namespace Test2 <MyAttr1(New e2() {e2.g})> Class C End Class Class MyAttr1 Inherits Attribute Sub New(ByVal B As e2()) End Sub End Class End Namespace ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeNonPublicType1, "MyAttr1").WithArguments("e2()")) End Sub <WorkItem(545558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545558")> <Fact()> Public Sub TestUndefinedEnumInAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.ComponentModel Module Program <EditorBrowsable(EditorBrowsableState.n)> Sub Main(args As String()) End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotMember2, "EditorBrowsableState.n").WithArguments("n", "System.ComponentModel.EditorBrowsableState")) End Sub <WorkItem(545697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545697")> <Fact> Public Sub TestUnboundLambdaInNamedAttributeArgument() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Program <A(F:=Sub() Dim x = Mid("1", 1) End Sub)> Sub Main(args As String()) Dim a As Action = Sub() Dim x = Mid("1", 1) End Sub End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={SystemCoreRef}) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "A").WithArguments("A"), Diagnostic(ERRID.ERR_NameNotDeclared1, "Mid").WithArguments("Mid"), Diagnostic(ERRID.ERR_PropertyOrFieldNotDefined1, "F").WithArguments("F"), Diagnostic(ERRID.ERR_NameNotDeclared1, "Mid").WithArguments("Mid")) End Sub <Fact> Public Sub SpecialNameAttributeFromSource() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <SpecialName()> Public Structure S <SpecialName()> Friend Event E As Action(Of String) <SpecialName()> Default Property P(b As Byte) As Byte Get Return b End Get Set(value As Byte) End Set End Property End Structure ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source) Dim globalNS = comp.SourceAssembly.GlobalNamespace Dim typesym = DirectCast(globalNS.GetMember("S"), NamedTypeSymbol) Assert.NotNull(typesym) Assert.True(typesym.HasSpecialName) Dim e = DirectCast(typesym.GetMember("E"), EventSymbol) Assert.NotNull(e) Assert.True(e.HasSpecialName) Dim p = DirectCast(typesym.GetMember("P"), PropertySymbol) Assert.NotNull(p) Assert.True(p.HasSpecialName) Assert.True(e.HasSpecialName) Assert.Equal("Private EEvent As Action", e.AssociatedField.ToString) Assert.True(e.HasAssociatedField) Assert.Equal(ImmutableArray.Create(Of VisualBasicAttributeData)(), e.GetFieldAttributes) Assert.Null(e.OverriddenEvent) Assert.NotNull(p) Assert.True(p.HasSpecialName) Assert.Equal(ImmutableArray.Create(Of VisualBasicAttributeData)(), p.GetFieldAttributes) End Sub ''' <summary> ''' Verify that attributeusage from base class is used by derived class ''' </summary> <Fact()> Public Sub TestAttributeUsageInheritedBaseAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 <DerivedAllowsMultiple()> <DerivedAllowsMultiple()> ' Should allow multiple Sub Main() End Sub End Module]]> </file> </compilation> Dim sourceWithAttribute As XElement = <compilation> <file name="library.vb"> <![CDATA[ Imports System Public Class DerivedAllowsMultiple Inherits Base End Class <AttributeUsage(AttributeTargets.All, AllowMultiple:=True, Inherited:=true)> Public Class Base Inherits Attribute End Class ]]></file> </compilation> Dim compWithAttribute = VisualBasicCompilation.Create( "library.dll", {VisualBasicSyntaxTree.ParseText(sourceWithAttribute.Value)}, {MsvbRef, MscorlibRef, SystemCoreRef}, TestOptions.ReleaseDll) Dim sourceLibRef = compWithAttribute.ToMetadataReference() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {sourceLibRef}) comp.AssertNoDiagnostics() Dim metadataLibRef As MetadataReference = compWithAttribute.ToMetadataReference() comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {metadataLibRef}) comp.AssertNoDiagnostics() Dim attributesOnMain = comp.GlobalNamespace.GetModuleMembers("Module1").Single().GetMembers("Main").Single().GetAttributes() Assert.Equal(2, attributesOnMain.Length()) Assert.NotEqual(attributesOnMain(0).ApplicationSyntaxReference, attributesOnMain(1).ApplicationSyntaxReference) Assert.NotNull(attributesOnMain(0).ApplicationSyntaxReference) End Sub <Fact(), WorkItem(546490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546490")> Public Sub Bug15984() Dim customIL = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern FSharp.Core {} .assembly '<<GeneratedFileName>>' { } .class public abstract auto ansi sealed Library1.Goo extends [mscorlib]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 inc(int32 x) cil managed { // Code size 5 (0x5) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: add IL_0004: ret } // end of method Goo::inc } // end of class Library1.Goo ]]> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> </file> </compilation>, customIL.Value, appendDefaultHeader:=False) Dim type = compilation.GetTypeByMetadataName("Library1.Goo") Assert.Equal(0, type.GetAttributes()(0).ConstructorArguments.Count) End Sub <Fact> <WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089")> Public Sub NullArrays() Dim source = <compilation> <file><![CDATA[ Imports System Public Class A Inherits Attribute Public Sub New(a As Object(), b As Integer()) End Sub Public Property P As Object() Public F As Integer() End Class <A(Nothing, Nothing, P:=Nothing, F:=Nothing)> Class C End Class ]]></file> </compilation> CompileAndVerify(source, symbolValidator:= Sub(m) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim attr = c.GetAttributes().Single() Dim args = attr.ConstructorArguments.ToArray() Assert.True(args(0).IsNull) Assert.Equal("Object()", args(0).Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() args(0).Value) Assert.True(args(1).IsNull) Assert.Equal("Integer()", args(1).Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() args(1).Value) Dim named = attr.NamedArguments.ToDictionary(Function(e) e.Key, Function(e) e.Value) Assert.True(named("P").IsNull) Assert.Equal("Object()", named("P").Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() named("P").Value) Assert.True(named("F").IsNull) Assert.Equal("Integer()", named("F").Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() named("F").Value) End Sub) End Sub <Fact> <WorkItem(688268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688268")> Public Sub Bug688268() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports System.Security Public Interface I Sub _VtblGap1_30() Sub _VtblGaX1_30() End Interface ]]></file> </compilation> Dim metadataValidator As System.Action(Of ModuleSymbol) = Sub([module] As ModuleSymbol) Dim metadata = DirectCast([module], PEModuleSymbol).Module Dim typeI = DirectCast([module].GlobalNamespace.GetTypeMembers("I").Single(), PENamedTypeSymbol) Dim methods = metadata.GetMethodsOfTypeOrThrow(typeI.Handle) Assert.Equal(2, methods.Count) Dim e = methods.GetEnumerator() e.MoveNext() Dim flags = metadata.GetMethodDefFlagsOrThrow(e.Current) Assert.Equal( MethodAttributes.PrivateScope Or MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.VtableLayoutMask Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.Abstract Or MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName, flags) e.MoveNext() flags = metadata.GetMethodDefFlagsOrThrow(e.Current) Assert.Equal( MethodAttributes.PrivateScope Or MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.VtableLayoutMask Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.Abstract, flags) End Sub CompileAndVerify(source, symbolValidator:=metadataValidator) End Sub <Fact> Public Sub NullTypeAndString() Dim source = <compilation> <file><![CDATA[ Imports System Public Class A Inherits Attribute Public Sub New(t As Type, s As String) End Sub End Class <A(Nothing, Nothing)> Class C End Class ]]></file> </compilation> CompileAndVerify(source, symbolValidator:= Sub(m) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim attr = c.GetAttributes().Single() Dim args = attr.ConstructorArguments.ToArray() Assert.Null(args(0).Value) Assert.Equal("Type", args(0).Type.Name) Assert.Throws(Of InvalidOperationException)(Function() args(0).Values) Assert.Null(args(1).Value) Assert.Equal("String", args(1).Type.Name) Assert.Throws(Of InvalidOperationException)(Function() args(1).Values) End Sub) End Sub <Fact> <WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")> Public Sub Repro728865() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Reflection Imports Microsoft.Yeti Namespace PFxIntegration Public Class ProducerConsumerScenario Shared Sub Main() Dim program = GetType(ProducerConsumerScenario) Dim methodInfo = program.GetMethod("ProducerConsumer") Dim myAttributes = methodInfo.GetCustomAttributes(False) If myAttributes.Length > 0 Then Console.WriteLine() Console.WriteLine("The attributes for the method - {0} - are: ", methodInfo) Console.WriteLine() For j = 0 To myAttributes.Length - 1 Console.WriteLine("The type of the attribute is {0}", myAttributes(j)) Next End If End Sub Public Enum CollectionType [Default] Queue Stack Bag End Enum Public Sub New() End Sub <CartesianRowData({5, 100, 100000}, {CollectionType.Default, CollectionType.Queue, CollectionType.Stack, CollectionType.Bag})> Public Sub ProducerConsumer() Console.WriteLine("Hello") End Sub End Class End Namespace Namespace Microsoft.Yeti <AttributeUsage(AttributeTargets.Method, AllowMultiple:=True)> Public Class CartesianRowDataAttribute Inherits Attribute Public Sub New() End Sub Public Sub New(ParamArray data As Object()) Dim asEnum As IEnumerable(Of Object)() = New IEnumerable(Of Object)(data.Length) {} For i = 0 To data.Length - 1 WrapEnum(DirectCast(data(i), IEnumerable)) Next End Sub Shared Sub WrapEnum(x As IEnumerable) For Each a In x Console.WriteLine(" - {0} -", a) Next End Sub End Class End Namespace ]]></file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ - 5 - - 100 - - 100000 - - Default - - Queue - - Stack - - Bag - The attributes for the method - Void ProducerConsumer() - are: The type of the attribute is Microsoft.Yeti.CartesianRowDataAttribute]]>) End Sub <Fact> <WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")> Public Sub ParamArrayAttributeConstructor() Dim source = <compilation> <file><![CDATA[ Imports System Public Class MyAttribute Inherits Attribute Public Sub New(ParamArray array As Object()) End Sub End Class Public Class Test <My({1, 2, 3})> Sub M1() End Sub <My(1, 2, 3)> Sub M2() End Sub <My({"A", "B", "C"})> Sub M3() End Sub <My("A", "B", "C")> Sub M4() End Sub <My({{1, 2, 3}, {"A", "B", "C"}})> Sub M5() End Sub <My({1, 2, 3}, {"A", "B", "C"})> Sub M6() End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim methods = Enumerable.Range(1, 6).Select(Function(i) type.GetMember(Of MethodSymbol)("M" & i)).ToArray() methods(0).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Integer() {1, 2, 3}) methods(1).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Object() {1, 2, 3}) methods(2).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New String() {"A", "B", "C"}) methods(3).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Object() {"A", "B", "C"}) methods(4).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Object() {}) ' Value was invalid. methods(5).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Object() {DirectCast({1, 2, 3}, Object), DirectCast({"A", "B", "C"}, Object)}) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30934: Conversion from 'Object(*,*)' to 'Object' cannot occur in a constant expression used as an argument to an attribute. <My({{1, 2, 3}, {"A", "B", "C"}})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> <WorkItem(737021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737021")> Public Sub NothingVersusEmptyArray() Dim source = <compilation> <file><![CDATA[ Imports System Public Class ArrayAttribute Inherits Attribute Public field As Integer() Public Sub New(array As Integer()) End Sub End Class Public Class Test <Array(Nothing)> Sub M0() End Sub <Array({})> Sub M1() End Sub <Array(Nothing, field:=Nothing)> Sub M2() End Sub <Array({}, field:=Nothing)> Sub M3() End Sub <Array(Nothing, field:={})> Sub M4() End Sub <Array({}, field:={})> Sub M5() End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim methods = Enumerable.Range(0, 6).Select(Function(i) type.GetMember(Of MethodSymbol)("M" & i)) Dim attrs = methods.Select(Function(m) m.GetAttributes().Single()).ToArray() Const fieldName = "field" Dim nullArray As Integer() = Nothing Dim emptyArray As Integer() = {} Assert.NotEqual(nullArray, emptyArray) attrs(0).VerifyValue(0, TypedConstantKind.Array, nullArray) attrs(1).VerifyValue(0, TypedConstantKind.Array, emptyArray) attrs(2).VerifyValue(0, TypedConstantKind.Array, nullArray) attrs(2).VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray) attrs(3).VerifyValue(0, TypedConstantKind.Array, emptyArray) attrs(3).VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray) attrs(4).VerifyValue(0, TypedConstantKind.Array, nullArray) attrs(4).VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray) attrs(5).VerifyValue(0, TypedConstantKind.Array, emptyArray) attrs(5).VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray) End Sub <Fact> <WorkItem(530266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530266")> Public Sub UnboundGenericTypeInTypedConstant() Dim source = <compilation> <file><![CDATA[ Imports System Public Class TestAttribute Inherits Attribute Sub New(x as Type) End Sub End Class <TestAttribute(GetType(Target(Of )))> Class Target(Of T) End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib(source, TestOptions.ReleaseDll) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Target") Dim typeInAttribute = DirectCast(type.GetAttributes()(0).ConstructorArguments(0).Value, NamedTypeSymbol) Assert.True(typeInAttribute.IsUnboundGenericType) Assert.True(DirectCast(typeInAttribute, INamedTypeSymbol).IsUnboundGenericType) Assert.Equal("Target(Of )", typeInAttribute.ToTestDisplayString()) Dim comp2 = CreateCompilationWithMscorlibAndReferences(<compilation><file></file></compilation>, {comp.EmitToImageReference()}) type = comp2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Target") Assert.IsAssignableFrom(Of PENamedTypeSymbol)(type) typeInAttribute = DirectCast(type.GetAttributes()(0).ConstructorArguments(0).Value, NamedTypeSymbol) Assert.True(typeInAttribute.IsUnboundGenericType) Assert.True(DirectCast(typeInAttribute, INamedTypeSymbol).IsUnboundGenericType) Assert.Equal("Target(Of )", typeInAttribute.ToTestDisplayString()) End Sub <Fact, WorkItem(879792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879792")> Public Sub Bug879792() Dim source2 = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Z> Module Program Sub Main() End Sub End Module Interface ZatTribute(Of T) End Interface Class Z Inherits Attribute End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source2) CompilationUtils.AssertNoDiagnostics(comp) Dim program = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program") Assert.Equal("Z", program.GetAttributes()(0).AttributeClass.ToTestDisplayString()) End Sub <Fact, WorkItem(1020038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020038")> Public Sub Bug1020038() Dim source1 = <compilation name="Bug1020038"> <file name="a.vb"><![CDATA[ Public Class CTest End Class ]]> </file> </compilation> Dim validator = Sub(m As ModuleSymbol) Assert.Equal(2, m.ReferencedAssemblies.Length) Assert.Equal("Bug1020038", m.ReferencedAssemblies(1).Name) End Sub Dim compilation1 = CreateCompilationWithMscorlib(source1) Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class CAttr Inherits System.Attribute Sub New(x as System.Type) End Sub End Class <CAttr(GetType(CTest))> Class Test End Class ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndReferences(source2, {New VisualBasicCompilationReference(compilation1)}) CompileAndVerify(compilation2, symbolValidator:=validator) Dim source3 = <compilation> <file name="a.vb"><![CDATA[ Class CAttr Inherits System.Attribute Sub New(x as System.Type) End Sub End Class <CAttr(GetType(System.Func(Of System.Action(Of CTest))))> Class Test End Class ]]> </file> </compilation> Dim compilation3 = CreateCompilationWithMscorlibAndReferences(source3, {New VisualBasicCompilationReference(compilation1)}) CompileAndVerify(compilation3, symbolValidator:=validator) End Sub <Fact, WorkItem(1144603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1144603")> Public Sub EmitMetadataOnlyInPresenceOfErrors() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Public Class DiagnosticAnalyzerAttribute Inherits System.Attribute Public Sub New(firstLanguage As String, ParamArray additionalLanguages As String()) End Sub End Class Public Class LanguageNames Public Const CSharp As xyz = "C#" End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib(source1, options:=TestOptions.DebugDll) AssertTheseDiagnostics(compilation1, <![CDATA[ BC30002: Type 'xyz' is not defined. Public Const CSharp As xyz = "C#" ~~~ ]]>) Dim source2 = <compilation> <file name="a.vb"><![CDATA[ <DiagnosticAnalyzer(LanguageNames.CSharp)> Class CSharpCompilerDiagnosticAnalyzer End Class ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndReferences(source2, {New VisualBasicCompilationReference(compilation1)}, options:=TestOptions.DebugDll.WithModuleName("Test.dll")) Assert.Same(compilation1.Assembly, compilation2.SourceModule.ReferencedAssemblySymbols(1)) AssertTheseDiagnostics(compilation2) Dim emitResult2 = compilation2.Emit(peStream:=New MemoryStream(), options:=New EmitOptions(metadataOnly:=True)) Assert.False(emitResult2.Success) AssertTheseDiagnostics(emitResult2.Diagnostics, <![CDATA[ BC36970: Failed to emit module 'Test.dll'. ]]>) ' Use different mscorlib to test retargeting scenario Dim compilation3 = CreateCompilationWithMscorlib45AndVBRuntime(source2, {New VisualBasicCompilationReference(compilation1)}, options:=TestOptions.DebugDll) Assert.NotSame(compilation1.Assembly, compilation3.SourceModule.ReferencedAssemblySymbols(1)) AssertTheseDiagnostics(compilation3, <![CDATA[ BC30002: Type 'xyz' is not defined. <DiagnosticAnalyzer(LanguageNames.CSharp)> ~~~~~~~~~~~~~~~~~~~~ ]]>) Dim emitResult3 = compilation3.Emit(peStream:=New MemoryStream(), options:=New EmitOptions(metadataOnly:=True)) Assert.False(emitResult3.Success) AssertTheseDiagnostics(emitResult3.Diagnostics, <![CDATA[ BC30002: Type 'xyz' is not defined. <DiagnosticAnalyzer(LanguageNames.CSharp)> ~~~~~~~~~~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Internal() Dim reference = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("Source")> Namespace Microsoft.CodeAnalysis Friend Class EmbeddedAttribute Inherits System.Attribute End Class End Namespace Namespace TestReference <Microsoft.CodeAnalysis.Embedded> Friend Class TestType1 End Class <Microsoft.CodeAnalysis.EmbeddedAttribute> Friend Class TestType2 End Class Friend Class TestType3 End Class End Namespace ]]> </file> </compilation> Dim referenceCompilation = CreateCompilationWithMscorlib(reference).ToMetadataReference() Dim code = " Public Class Program Public Shared Sub Main() Dim obj1 = New TestReference.TestType1() Dim obj2 = New TestReference.TestType2() Dim obj3 = New TestReference.TestType3() ' This should be fine End Sub End Class" Dim compilation = CreateCompilationWithMscorlib(code, references:={referenceCompilation}, assemblyName:="Source") AssertTheseDiagnostics(compilation, <![CDATA[ BC30002: Type 'TestReference.TestType1' is not defined. Dim obj1 = New TestReference.TestType1() ~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'TestReference.TestType2' is not defined. Dim obj2 = New TestReference.TestType2() ~~~~~~~~~~~~~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Public() Dim reference = <compilation> <file name="a.vb"><![CDATA[ Namespace Microsoft.CodeAnalysis Friend Class EmbeddedAttribute Inherits System.Attribute End Class End Namespace Namespace TestReference <Microsoft.CodeAnalysis.Embedded> Public Class TestType1 End Class <Microsoft.CodeAnalysis.EmbeddedAttribute> Public Class TestType2 End Class Public Class TestType3 End Class End Namespace ]]> </file> </compilation> Dim referenceCompilation = CreateCompilationWithMscorlib(reference).ToMetadataReference() Dim code = " Public Class Program Public Shared Sub Main() Dim obj1 = New TestReference.TestType1() Dim obj2 = New TestReference.TestType2() Dim obj3 = New TestReference.TestType3() ' This should be fine End Sub End Class" Dim compilation = CreateCompilationWithMscorlib(code, references:={referenceCompilation}) AssertTheseDiagnostics(compilation, <![CDATA[ BC30002: Type 'TestReference.TestType1' is not defined. Dim obj1 = New TestReference.TestType1() ~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'TestReference.TestType2' is not defined. Dim obj2 = New TestReference.TestType2() ~~~~~~~~~~~~~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Module() Dim moduleCode = CreateCompilationWithMscorlib(options:=TestOptions.ReleaseModule, source:=" Namespace Microsoft.CodeAnalysis Friend Class EmbeddedAttribute Inherits System.Attribute End Class End Namespace Namespace TestReference <Microsoft.CodeAnalysis.Embedded> Public Class TestType1 End Class <Microsoft.CodeAnalysis.EmbeddedAttribute> Public Class TestType2 End Class Public Class TestType3 End Class End Namespace") Dim reference = ModuleMetadata.CreateFromImage(moduleCode.EmitToArray()).GetReference() Dim code = " Public Class Program Public Shared Sub Main() Dim obj1 = New TestReference.TestType1() Dim obj2 = New TestReference.TestType2() Dim obj3 = New TestReference.TestType3() ' This should be fine End Sub End Class" Dim compilation = CreateCompilationWithMscorlib(code, references:={reference}) AssertTheseDiagnostics(compilation, <![CDATA[ BC30002: Type 'TestReference.TestType1' is not defined. Dim obj1 = New TestReference.TestType1() ~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'TestReference.TestType2' is not defined. Dim obj2 = New TestReference.TestType2() ~~~~~~~~~~~~~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub ReferencingEmbeddedAttributesFromTheSameAssemblySucceeds() Dim compilation = CreateCompilationWithMscorlib(source:=" Namespace Microsoft.CodeAnalysis Friend Class EmbeddedAttribute Inherits System.Attribute End Class End Namespace Namespace TestReference <Microsoft.CodeAnalysis.Embedded> Public Class TestType1 End Class <Microsoft.CodeAnalysis.EmbeddedAttribute> Public Class TestType2 End Class Public Class TestType3 End Class End Namespace Public Class Program Public Shared Sub Main() Dim obj1 = New TestReference.TestType1() Dim obj2 = New TestReference.TestType2() Dim obj3 = New TestReference.TestType3() End Sub End Class") AssertTheseEmitDiagnostics(compilation) End Sub <Fact> Public Sub EmbeddedAttributeInSourceIsAllowedIfCompilerDoesNotNeedToGenerateOne() Dim compilation = CreateCompilationWithMscorlib(options:=TestOptions.ReleaseExe, sources:= <compilation> <file name="a.vb"><![CDATA[ Namespace Microsoft.CodeAnalysis Friend Class EmbeddedAttribute Inherits System.Attribute End Class End Namespace Namespace OtherNamespace <Microsoft.CodeAnalysis.Embedded> Public Class TestReference Public Shared Function GetValue() As Integer Return 3 End Function End Class End Namespace Public Class Program Public Shared Sub Main() ' This should be fine, as the compiler doesn't need to use an embedded attribute for this compilation System.Console.Write(OtherNamespace.TestReference.GetValue()) End Sub End Class ]]> </file> </compilation>) CompileAndVerify(compilation, expectedOutput:="3") End Sub <Fact> Public Sub EmbeddedTypesInAnAssemblyAreNotExposedExternally() Dim compilation1 = CreateCompilationWithMscorlib(options:=TestOptions.ReleaseDll, sources:= <compilation> <file name="a.vb"><![CDATA[ Namespace Microsoft.CodeAnalysis Friend Class EmbeddedAttribute Inherits System.Attribute End Class End Namespace <Microsoft.CodeAnalysis.Embedded> Public Class TestReference1 End Class Public Class TestReference2 End Class ]]> </file> </compilation>) Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference1")) Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference2")) Dim compilation2 = CreateCompilationWithMscorlib("", references:={compilation1.EmitToImageReference()}) Assert.Null(compilation2.GetTypeByMetadataName("TestReference1")) Assert.NotNull(compilation2.GetTypeByMetadataName("TestReference2")) End Sub End Class End Namespace
mmitche/roslyn
src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests.vb
Visual Basic
apache-2.0
162,935
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18010 ' ' 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.WPFParseStarterProject.My.MySettings Get Return Global.WPFParseStarterProject.My.MySettings.Default End Get End Property End Module End Namespace
kangkot/Parse-SDK-dotNET
Parse.StarterProjects/VB/WPFParseStarterProject/WPFParseStarterProject/My Project/Settings.Designer.vb
Visual Basic
bsd-3-clause
2,935
' 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 AutomaticBracketCompletionTests 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 TestBracket() As Task Using session = Await CreateSessionAsync("$$") Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestBracket2() As Task Using session = Await CreateSessionAsync("Imports System$$") Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_Bracket() 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 TestInvalidLocation_Comment_CloseBracket() As Task Dim code = <code>Class C Sub Method() Dim $$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) Type(session.Session, "'") CheckOverType(session.Session, allowOverType:=False) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_Comment_Tab() As Task Dim code = <code>Class C Sub Method() Dim $$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) Type(session.Session, "'") CheckTab(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 TestWorkspace.CreateVisualBasicAsync(code), BraceCompletionSessionProvider.Bracket.OpenCharacter, BraceCompletionSessionProvider.Bracket.CloseCharacter) End Function End Class End Namespace
ericfe-ms/roslyn
src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBracketCompletionTests.vb
Visual Basic
apache-2.0
4,466
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Structure FlowAnalysisInfo Public ReadOnly Compilation As VisualBasicCompilation Public ReadOnly Symbol As Symbol Public ReadOnly Node As BoundNode Public Sub New(_compilation As VisualBasicCompilation, _symbol As Symbol, _node As BoundNode) Debug.Assert(_compilation IsNot Nothing) Debug.Assert(_symbol IsNot Nothing) Debug.Assert(_node IsNot Nothing) Me.Compilation = _compilation Me.Symbol = _symbol Me.Node = _node End Sub End Structure Friend Structure FlowAnalysisRegionInfo ''' <summary> Region being analyzed: start node </summary> Public ReadOnly FirstInRegion As BoundNode ''' <summary> Region being analyzed: end node </summary> Public ReadOnly LastInRegion As BoundNode ''' <summary> Region itself </summary> Public ReadOnly Region As TextSpan Public Sub New(_firstInRegion As BoundNode, _lastInRegion As BoundNode, _region As TextSpan) Debug.Assert(_firstInRegion IsNot Nothing) Debug.Assert(_lastInRegion IsNot Nothing) Me.FirstInRegion = _firstInRegion Me.LastInRegion = _lastInRegion Me.Region = _region End Sub End Structure End Namespace
physhi/roslyn
src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/FlowAnalysisInfo.vb
Visual Basic
apache-2.0
1,834
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure.MetadataAsSource Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class PropertyDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of PropertyStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New MetadataPropertyDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Class C Property $$Goo As Integer End Class " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Class C {|hint:{|textspan:<Goo> |}Property $$Goo As Integer|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Property $$Goo As Integer|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Public Property $$Goo As Integer|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
OmarTawfik/roslyn
src/EditorFeatures/VisualBasicTest/Structure/MetadataAsSource/PropertyDeclarationStructureTests.vb
Visual Basic
apache-2.0
2,647
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.AddMissingReference Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.AddMissingReference <ExportCodeFixProviderAttribute(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.AddMissingReference), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.SimplifyNames)> Friend Class AddMissingReferenceCodeFixProvider Inherits AbstractAddMissingReferenceCodeFixProvider(Of IdentifierNameSyntax) Friend Const BC30005 As String = "BC30005" ' ERR_UnreferencedAssemblyEvent3 Friend Const BC30007 As String = "BC30007" ' ERR_UnreferencedAssemblyBase3 Friend Const BC30009 As String = "BC30009" ' ERR_UnreferencedAssemblyImplements3 Friend Const BC30652 As String = "BC30652" ' ERR_UnreferencedAssembly3 Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC30005, BC30007, BC30009, BC30652) End Get End Property End Class End Namespace
MatthieuMEZIL/roslyn
src/Features/VisualBasic/Portable/CodeFixes/AddMissingReference/AddMissingReferenceCodeFixProvider.vb
Visual Basic
apache-2.0
1,398
Imports MVVMCalc.Model Imports MVVMCalc.Common Namespace ViewModel Public Class MainViewModel : Inherits ViewModelBase Private _lhs As Double Private _rhs As Double Private _answer As Double Private _selectedCalculateType As CalculateTypeViewModel Private _calculateCommand As DelegateCommand Public Sub New() Me._CalculateTypes = CalculateTypeViewModel.Create() Me._selectedCalculateType = Me.CalculateTypes.First() End Sub Private _CalculateTypes As IEnumerable(Of CalculateTypeViewModel) Public ReadOnly Property CalculateTypes() As IEnumerable(Of CalculateTypeViewModel) Get Return _CalculateTypes End Get End Property Public Property SelectedCalculateType() As CalculateTypeViewModel Get Return _selectedCalculateType End Get Set(ByVal value As CalculateTypeViewModel) Me._selectedCalculateType = value Me.RaisePropertyChanged("SelectedCalculateType") End Set End Property Public Property Lhs() As Double Get Return _lhs End Get Set(ByVal value As Double) _lhs = value Me.RaisePropertyChanged("Lhs") End Set End Property Public Property Rhs() As Double Get Return _rhs End Get Set(ByVal value As Double) _rhs = value Me.RaisePropertyChanged("Rhs") End Set End Property Public Property Answer() As Double Get Return _answer End Get Set(ByVal value As Double) _answer = value Me.RaisePropertyChanged("Answer") End Set End Property Public ReadOnly Property CalculateCommand() As DelegateCommand Get If _calculateCommand Is Nothing Then _calculateCommand = New DelegateCommand(AddressOf CalculateExecute, AddressOf CanCalculateExecute) End If Return _calculateCommand End Get End Property Private Sub CalculateExecute() Dim calc As New Calculator Answer = calc.Execute(Lhs, Rhs, SelectedCalculateType.CalculateType) End Sub Private Function CanCalculateExecute() As Boolean Return SelectedCalculateType.CalculateType <> CalculateType.None End Function End Class End Namespace
takas-ho/MVVMClac.2008
MVVMCalc/ViewModel/MainViewModel.vb
Visual Basic
mit
2,667
' ' DotNetNuke® - http://www.dotnetnuke.com ' Copyright (c) 2002-2012 ' by DotNetNuke Corporation ' ' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ' documentation files (the "Software"), to deal in the Software without restriction, including without limitation ' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and ' to permit persons to whom the Software is furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all copies or substantial portions ' of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. Imports DotNetNuke.Services.Social.Notifications Imports DotNetNuke.Security.Roles Namespace Components.Integration Public Class Notifications Public Const ContentTypeName As String = "DNN_Feedback" Public Const NotificationModerationRequiredTypeName As String = "FeedbackModeration" ''' <summary> ''' Informs the core journal that the user that a feedback entry needs moderation ''' </summary> ''' <param name="sendToRoles"></param> ''' <remarks></remarks> Friend Function SendFeedbackModerationNotification(ByVal sendToRoles() As String, ByVal senderUserID As Integer, ByVal subject As String, ByVal body As String, _ ByVal portalID As Integer, ByVal tabID As Integer, ByVal moduleID As Integer, ByVal feedbackID As Integer) As String Dim notificationType As NotificationType = NotificationsController.Instance.GetNotificationType(NotificationModerationRequiredTypeName) If notificationType Is Nothing Then notificationType = CreateFeedbackNotificationTypes(portalID) End If Dim notificationKey As String = String.Format("{0}:{1}:{2}:{3}:{4}", ContentTypeName + NotificationModerationRequiredTypeName, portalID, tabID, moduleID, feedbackID) Dim objNotification As New Notification Dim objUserController As New UserController() Dim senderUser As UserInfo = objUserController.GetUser(portalID, senderUserID) objNotification.NotificationTypeID = notificationType.NotificationTypeId objNotification.Subject = subject objNotification.Body = body objNotification.IncludeDismissAction = True objNotification.SenderUserID = senderUserID objNotification.Context = notificationKey objNotification.From = senderUser.DisplayName Dim colRoles As New Generic.List(Of RoleInfo) Dim objRoleController As New RoleController Dim colUsers As New Generic.List(Of UserInfo) For Each roleName As String In sendToRoles If Left(roleName, 1) = "[" And Right(roleName, 1) = "]" Then Dim objUser As UserInfo = objUserController.GetUser(portalID, CInt(Mid(roleName, 2, Len(roleName) - 2))) colUsers.Add(objUser) Else Dim objRole As RoleInfo = objRoleController.GetRoleByName(portalID, roleName) colRoles.Add(objRole) End If Next NotificationsController.Instance.SendNotification(objNotification, portalID, colRoles, colUsers) Return notificationKey End Function Private Function CreateFeedbackNotificationTypes(ByVal portalID As Integer) As NotificationType Dim deskModuleId As Integer = Entities.Modules.DesktopModuleController.GetDesktopModuleByModuleName("DNN_Feedback", portalID).DesktopModuleID Dim objNotificationType As NotificationType = New NotificationType objNotificationType.Name = NotificationModerationRequiredTypeName objNotificationType.Description = "Feedback Moderation Required" objNotificationType.DesktopModuleId = deskModuleId NotificationsController.Instance.CreateNotificationType(objNotificationType) Dim actions As Generic.List(Of NotificationTypeAction) = New Generic.List(Of NotificationTypeAction) Dim objAction As New NotificationTypeAction objAction.NameResourceKey = "ApproveFeedback" objAction.DescriptionResourceKey = "ApproveFeedback_Desc" objAction.ConfirmResourceKey = "ApproveFeedback_Confirm" objAction.APICall = "DesktopModules/Feedback/API/NotificationService.ashx/ApproveFeedback" objAction.Order = 1 actions.Add(objAction) objAction = New NotificationTypeAction objAction.NameResourceKey = "PrivateFeedback" objAction.DescriptionResourceKey = "PrivateFeedback_Desc" objAction.ConfirmResourceKey = "PrivateFeedback_Confirm" objAction.APICall = "DesktopModules/Feedback/API/NotificationService.ashx/PrivateFeedback" objAction.Order = 2 actions.Add(objAction) objAction = New NotificationTypeAction objAction.NameResourceKey = "ArchiveFeedback" objAction.DescriptionResourceKey = "ArchiveFeedback_Desc" objAction.ConfirmResourceKey = "ArchiveFeedback_Confirm" objAction.APICall = "DesktopModules/Feedback/API/NotificationService.ashx/ArchiveFeedback" objAction.Order = 3 actions.Add(objAction) objAction = New NotificationTypeAction objAction.NameResourceKey = "DeleteFeedback" objAction.DescriptionResourceKey = "DeleteFeedback_Desc" objAction.ConfirmResourceKey = "DeleteFeedback_Confirm" objAction.APICall = "DesktopModules/Feedback/API/NotificationService.ashx/DeleteFeedback" objAction.Order = 4 actions.Add(objAction) NotificationsController.Instance.SetNotificationTypeActions(actions, objNotificationType.NotificationTypeId) Return objNotificationType End Function Public Sub DeleteNotification(ByVal contextKey As String, ByVal notificationId As Integer) If NotificationId = Nothing Then Dim notificationType As NotificationType = NotificationsController.Instance.GetNotificationType(NotificationModerationRequiredTypeName) Dim oNotifications As System.Collections.Generic.IList(Of Notification) = NotificationsController.Instance().GetNotificationByContext(notificationType.NotificationTypeId, contextKey) For Each oNotification As Notification In oNotifications NotificationsController.Instance().DeleteNotification(oNotification.NotificationID) Next Else NotificationsController.Instance().DeleteNotification(NotificationId) End If End Sub End Class End Namespace
DNNCommunity/DNN.Feedback
Components/Integration/Notifications.vb
Visual Basic
mit
7,414
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Partial Public Class CookieConsent '''<summary> '''ltlScript control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents ltlScript As Global.System.Web.UI.WebControls.Literal End Class
dnnconsulting/DnnC.CookieConsent
CookieConsent.ascx.designer.vb
Visual Basic
mit
722
'------------------------------------------------------------------------------ ' <auto-generated> ' Este código fue generado por una herramienta. ' Versión de runtime:4.0.30319.1008 ' ' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si ' se vuelve a generar el código. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "Funcionalidad para autoguardar de My.Settings" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property <Global.System.Configuration.ApplicationScopedSettingAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Configuration.SpecialSettingAttribute(Global.System.Configuration.SpecialSetting.ConnectionString), _ Global.System.Configuration.DefaultSettingValueAttribute("Data Source=SERVFONCREAGRO\SQL2008;Initial Catalog=SistIntFoncreagro;User ID=sa;P"& _ "assword=Sd84Dt-")> _ Public ReadOnly Property cnx() As String Get Return CType(Me("cnx"),String) End Get End Property <Global.System.Configuration.ApplicationScopedSettingAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Configuration.SpecialSettingAttribute(Global.System.Configuration.SpecialSetting.ConnectionString), _ Global.System.Configuration.DefaultSettingValueAttribute("Data Source=PCFONCRE02\MSSQLSERVER2008;Initial Catalog=SistIntFoncreagro;User ID="& _ "SA;Password=123")> _ Public ReadOnly Property SistIntFoncreagro() As String Get Return CType(Me("SistIntFoncreagro"),String) End Get End Property <Global.System.Configuration.ApplicationScopedSettingAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Configuration.SpecialSettingAttribute(Global.System.Configuration.SpecialSetting.ConnectionString), _ Global.System.Configuration.DefaultSettingValueAttribute("Data Source=localhost;Initial Catalog=SistIntFoncreagro;User ID=sa")> _ Public ReadOnly Property SistIntFoncreagro1() As String Get Return CType(Me("SistIntFoncreagro1"),String) End Get End Property <Global.System.Configuration.ApplicationScopedSettingAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Configuration.SpecialSettingAttribute(Global.System.Configuration.SpecialSetting.ConnectionString), _ Global.System.Configuration.DefaultSettingValueAttribute("Data Source=localhost;Initial Catalog=SistIntFoncreagro;Persist Security Info=Tru"& _ "e;User ID=sa;Password=Foncre@gro2012")> _ Public ReadOnly Property SistIntFoncreagro2() As String Get Return CType(Me("SistIntFoncreagro2"),String) End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.SistFoncreagro.Report.My.MySettings Get Return Global.SistFoncreagro.Report.My.MySettings.Default End Get End Property End Module End Namespace
crackper/SistFoncreagro
SistFoncreagro.Report/My Project/Settings.Designer.vb
Visual Basic
mit
5,541
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Option Strict Off Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Suppression Public MustInherit Class VisualBasicSuppressionTests Inherits AbstractSuppressionDiagnosticTest Private ReadOnly _compilationOptions As CompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True) Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overrides Function MassageActions(ByVal actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return actions(0).NestedCodeActions End Function Protected Overrides Function CreateWorkspaceFromFile(initialMarkup As String, parameters As TestParameters) As TestWorkspace Return TestWorkspace.CreateVisualBasic( initialMarkup, parameters.parseOptions, If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic End Function #Region "Pragma disable tests" Public MustInherit Class VisualBasicPragmaWarningDisableSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 0 End Get End Property Public Class CompilerDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirective() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() [|Dim x As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {WRN_UnusedLocal_Title} Dim x As Integer #Enable Warning BC42024 ' {WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable [|Dim x As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective1() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() [|Dim x _ As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {WRN_UnusedLocal_Title} Dim x _ As Integer #Enable Warning BC42024 ' {WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable [|Dim x _ As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective2() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) If i < [|j.MaxValue|] AndAlso i > 0 Then Console.WriteLine(i) End If End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title} If i < j.MaxValue AndAlso i > 0 Then #Enable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title} Console.WriteLine(i) End If End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance If i < [|j.MaxValue|] AndAlso i > 0 Then #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Console.WriteLine(i) End If End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective3() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) If i > 0 AndAlso i < [|j.MaxValue|] Then Console.WriteLine(i) End If End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title} If i > 0 AndAlso i < j.MaxValue Then #Enable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title} Console.WriteLine(i) End If End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance If i > 0 AndAlso i < [|j.MaxValue|] Then #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Console.WriteLine(i) End If End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective4() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim [|x As Integer|], y As Integer End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {WRN_UnusedLocal_Title} Dim x As Integer, y As Integer #Enable Warning BC42024 ' {WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable Dim [|x As Integer|], y As Integer #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective5() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim x As Integer, [|y As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {WRN_UnusedLocal_Title} Dim x As Integer, y As Integer #Enable Warning BC42024 ' {WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable Dim x As Integer, [|y As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective6() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) Dim x = <root> <condition value=<%= i < [|j.MaxValue|] %>/> </root> End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title} Dim x = <root> <condition value=<%= i < j.MaxValue %>/> </root> #Enable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Dim x = <root> <condition value=<%= i < [|j.MaxValue|] %>/> </root> #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective7() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(j As Short) Dim x = From i As Integer In {} Where i < [|j.MaxValue|] Select i End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(j As Short) #Disable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title} Dim x = From i As Integer In {{}} Where i < j.MaxValue Select i #Enable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Dim x = From i As Integer In {} Where i < [|j.MaxValue|] Select i #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveWithExistingTrivia() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() ' Trivia previous line [|Dim x As Integer|] ' Trivia same line ' Trivia next line End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() ' Trivia previous line #Disable Warning BC42024 ' {WRN_UnusedLocal_Title} Dim x As Integer ' Trivia same line #Enable Warning BC42024 ' {WRN_UnusedLocal_Title} ' Trivia next line End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() ' Trivia previous line #Disable Warning BC42024 ' Unused local variable [|Dim x As Integer|] ' Trivia same line #Enable Warning BC42024 ' Unused local variable ' Trivia next line End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(970129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionAroundSingleToken() As Task Dim source = <![CDATA[ Imports System <Obsolete> Class C End Class Module Module1 Sub Main [|C|] End Sub End Module]]> Dim expected = $" Imports System <Obsolete> Class C End Class Module Module1 Sub Main #Disable Warning BC40008 ' {WRN_UseOfObsoleteSymbolNoMessage1_Title} C #Enable Warning BC40008 ' {WRN_UseOfObsoleteSymbolNoMessage1_Title} End Sub End Module" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System <Obsolete> Class C End Class Module Module1 Sub Main #Disable Warning BC40008 ' Type or member is obsolete [|C|] #Enable Warning BC40008 ' Type or member is obsolete End Sub End Module]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia1() As Task Dim source = <![CDATA[ Class C ' Comment ' Comment ''' <summary><see [|cref="abc"|]/></summary> Sub M() ' Comment End Sub End Class]]> Dim expected = $" Class C ' Comment ' Comment #Disable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title} ''' <summary><see cref=""abc""/></summary> Sub M() ' Comment #Enable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title} End Sub End Class" Dim enableDocCommentProcessing = VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose) Await TestAsync(source.Value, expected, enableDocCommentProcessing) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = $" Class C ' Comment ' Comment #Disable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title} ''' <summary><see [|cref=""abc""|]/></summary> Sub M() ' Comment #Enable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title} End Sub End Class" Await TestMissingAsync(fixedSource, New TestParameters(enableDocCommentProcessing)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia2() As Task Dim source = <![CDATA['''[|<summary></summary>|]]]> Dim expected = $"#Disable Warning BC42312 ' {WRN_XMLDocWithoutLanguageElement_Title} '''<summary></summary> #Enable Warning BC42312 ' {WRN_XMLDocWithoutLanguageElement_Title}" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia3() As Task Dim source = <![CDATA[ '''[|<summary></summary>|] ]]> Dim expected = $"#Disable Warning BC42312 ' {WRN_XMLDocWithoutLanguageElement_Title} '''<summary></summary> #Enable Warning BC42312 ' {WRN_XMLDocWithoutLanguageElement_Title}" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia4() As Task Dim source = <![CDATA[ '''<summary><see [|cref="abc"|]/></summary> Class C : End Class ]]> Dim expected = $" #Disable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title} '''<summary><see cref=""abc""/></summary> Class C : End Class #Enable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title} " Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia5() As Task Dim source = <![CDATA[class C1 : End Class '''<summary><see [|cref="abc"|]/></summary> Class C2 : End Class Class C3 : End Class]]> Dim expected = $"class C1 : End Class #Disable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title} '''<summary><see cref=""abc""/></summary> Class C2 : End Class #Enable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title} Class C3 : End Class" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia6() As Task Dim source = <![CDATA[class C1 : End Class Class C2 : End Class [|'''|] Class C3 : End Class]]> Dim expected = $"class C1 : End Class #Disable Warning BC42302 ' {WRN_XMLDocNotFirstOnLine_Title} Class C2 : End Class ''' #Enable Warning BC42302 ' {WRN_XMLDocNotFirstOnLine_Title} Class C3 : End Class" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function End Class Public Class UserHiddenDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestHiddenDiagnosticCannotBeSuppressed() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim i as [|System.Int32|] = 0 Console.WriteLine(i) End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestInfoDiagnosticSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning InfoDiagnostic ' InfoDiagnostic Class C #Enable Warning InfoDiagnostic ' InfoDiagnostic Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning InfoDiagnostic ' InfoDiagnostic [|Class C|] #Enable Warning InfoDiagnostic ' InfoDiagnostic Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class Public Class DiagnosticWithBadIdSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Protected Overrides ReadOnly Property IncludeNoLocationDiagnostics As Boolean Get ' Analyzer driver generates a no-location analyzer exception diagnostic, which we don't intend to test here. Return False End Get End Property Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private _descriptor As New DiagnosticDescriptor("#$DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestDiagnosticWithBadIdSuppressed() As Task ' Diagnostics with bad/invalid ID are not reported. Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserWarningDiagnosticWithNameMatchingKeywordSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private _descriptor As New DiagnosticDescriptor("REm", "REm Title", "REm", "REm", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestWarningDiagnosticWithNameMatchingKeywordSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning [REm] ' REm Title Class C #Enable Warning [REm] ' REm Title Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning [REm] ' REm Title [|Class C|] #Enable Warning [REm] ' REm Title Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class Public Class UserErrorDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private _descriptor As New DiagnosticDescriptor("ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", DiagnosticSeverity.[Error], isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestErrorDiagnosticCanBeSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning ErrorDiagnostic ' ErrorDiagnostic Class C #Enable Warning ErrorDiagnostic ' ErrorDiagnostic Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning ErrorDiagnostic ' ErrorDiagnostic [|Class C|] #Enable Warning ErrorDiagnostic ' ErrorDiagnostic Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class End Class #End Region #Region "SuppressMessageAttribute tests" Public MustInherit Class VisualBasicGlobalSuppressMessageSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 1 End Get End Property Public Class CompilerDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestCompilerDiagnosticsCannotBeSuppressed() As Task Dim source = <![CDATA[ Class Class1 Sub Method() [|Dim x|] End Sub End Class]]> Await TestActionCountAsync(source.Value, 1) End Function End Class Public Class UserHiddenDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestHiddenDiagnosticsCannotBeSuppressed() As Task Dim source = <![CDATA[ Imports System Class Class1 Sub Method() [|Dim x As System.Int32 = 0|] End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Select Case context.Node.Kind() Case SyntaxKind.ClassStatement Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) Exit Select Case SyntaxKind.NamespaceStatement Dim ns = DirectCast(context.Node, NamespaceStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation())) Exit Select Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(context.Node, MethodStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation())) Exit Select Case SyntaxKind.PropertyStatement Dim p = DirectCast(context.Node, PropertyStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation())) Exit Select Case SyntaxKind.FieldDeclaration Dim f = DirectCast(context.Node, FieldDeclarationSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation())) Exit Select Case SyntaxKind.EventStatement Dim e = DirectCast(context.Node, EventStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation())) Exit Select End Select End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType() As Task Dim source = <![CDATA[ Imports System [|Class Class1|] Sub Method() Dim x End Sub End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")> [|Class Class1|] Sub Method() Dim x End Sub End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNamespace() As Task Dim source = <![CDATA[ Imports System [|Namespace N|] Class Class1 Sub Method() Dim x End Sub End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")> " Await TestInRegularAndScriptAsync(source.Value, expected, index:=1) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")> [|Namespace N|] Class Class1 Sub Method() Dim x End Sub End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnTypeInsideNamespace() As Task Dim source = <![CDATA[ Imports System Namespace N1 Namespace N2 [|Class Class1|] Sub Method() Dim x End Sub End Class End Namespace End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")> Namespace N1 Namespace N2 [|Class Class1|] Sub Method() Dim x End Sub End Class End Namespace End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNestedType() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) [|Class Class1|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")> Namespace N Class Generic(Of T) [|Class Class1|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method() Dim x End Sub|] End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method() Dim x End Sub|] End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnOverloadedMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method(y as Integer, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method(y as Integer, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnGenericMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method(Of U)(y as U, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method(Of U)(y as U, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnProperty() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic Private Class C [|Private ReadOnly Property P() As Integer|] Get Dim x As Integer = 0 End Get End Property End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")> Namespace N Class Generic Private Class C [|Private ReadOnly Property P() As Integer|] Get Dim x As Integer = 0 End Get End Property End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnField() As Task Dim source = <![CDATA[ Imports System Class C [|Private ReadOnly F As Integer|] End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")> Class C [|Private ReadOnly F As Integer|] End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnEvent() As Task Dim source = <![CDATA[ Imports System Public Class SampleEventArgs Public Sub New(s As String) Text = s End Sub Public Property Text() As [String] Get Return m_Text End Get Private Set m_Text = Value End Set End Property Private m_Text As [String] End Class Class C ' Declare the delegate (if using non-generic pattern). Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs) ' Declare the event. [|Public Custom Event SampleEvent As SampleEventHandler|] AddHandler(ByVal value As SampleEventHandler) End AddHandler RemoveHandler(ByVal value As SampleEventHandler) End RemoveHandler End Event End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")> Public Class SampleEventArgs Public Sub New(s As String) Text = s End Sub Public Property Text() As [String] Get Return m_Text End Get Private Set m_Text = Value End Set End Property Private m_Text As [String] End Class Class C ' Declare the delegate (if using non-generic pattern). Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs) ' Declare the event. [|Public Custom Event SampleEvent As SampleEventHandler|] AddHandler(ByVal value As SampleEventHandler) End AddHandler RemoveHandler(ByVal value As SampleEventHandler) End RemoveHandler End Event End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument() As Task Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument2() As Task ' Own custom file named GlobalSuppressions.cs Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ ' My own file named GlobalSuppressions.vb Class Class3 End Class ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument3() As Task ' Own custom file named GlobalSuppressions.vb + existing GlobalSuppressions2.vb with global suppressions Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ ' My own file named GlobalSuppressions.vb Class Class3 End Class ]]> </Document> <Document FilePath="GlobalSuppressions2.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() As Task Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $" Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function End Class End Class Public MustInherit Class VisualBasicLocalSuppressMessageSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 2 End Get End Property Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicLocalSuppressMessageSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Select Case context.Node.Kind() Case SyntaxKind.ClassStatement Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) Exit Select Case SyntaxKind.NamespaceStatement Dim ns = DirectCast(context.Node, NamespaceStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation())) Exit Select Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(context.Node, MethodStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation())) Exit Select Case SyntaxKind.PropertyStatement Dim p = DirectCast(context.Node, PropertyStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation())) Exit Select Case SyntaxKind.FieldDeclaration Dim f = DirectCast(context.Node, FieldDeclarationSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation())) Exit Select Case SyntaxKind.EventStatement Dim e = DirectCast(context.Node, EventStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation())) Exit Select End Select End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType() As Task Dim source = <![CDATA[ Imports System ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType2() As Task ' Type already has attributes. Dim source = <![CDATA[ Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType3() As Task ' Type has structured trivia. Dim source = <![CDATA[ Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType4() As Task ' Type has structured trivia and attributes. Dim source = <![CDATA[ Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnTypeInsideNamespace() As Task Dim source = <![CDATA[ Imports System Namespace N ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class End Namespace]]> Dim expected = $" Imports System Namespace N ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class End Namespace" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNestedType() As Task Dim source = <![CDATA[ Imports System Class Generic(Of T) ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class End Class]]> Dim expected = $" Imports System Class Generic(Of T) ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class End Class" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnMethod() As Task Dim source = <![CDATA[ Imports System Class Generic(Of T) Class C ' Some Trivia [|Sub Method() Dim x End Sub|] End Class End Class]]> Dim expected = $" Imports System Class Generic(Of T) Class C ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Sub Method() Dim x End Sub End Class End Class" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Sub Method()", "[|Sub Method()|]") Await TestMissingAsync(fixedSource) End Function End Class End Class #End Region End Class End Namespace
abock/roslyn
src/EditorFeatures/VisualBasicTest/Diagnostics/Suppression/SuppressionTests.vb
Visual Basic
mit
74,746
Imports SistFoncreagro.BussinessEntities Imports SistFoncreagro.DataAccess Public Class ProgramacionBL : Implements IProgramacionBL Dim factoryrepository As IProgramacionRepository Public Sub New() factoryrepository = New ProgramacionRepository End Sub Public Sub GenerarProgramacionPoaTecnico(ByVal anio As Integer, ByVal IdProyecto As Integer) Implements IProgramacionBL.GenerarProgramacionPoaTecnico factoryrepository.GenerarProgramacionPoaTecnico(anio, IdProyecto) End Sub Public Sub SavePROGRAMACION(ByVal _Programacion As BussinessEntities.Programacion) Implements IProgramacionBL.SavePROGRAMACION factoryrepository.SavePROGRAMACION(_Programacion) End Sub Public Sub SaveListaProgramacion(ByVal Programacion As System.Collections.Generic.List(Of BussinessEntities.Programacion)) Implements IProgramacionBL.SaveListaProgramacion factoryrepository.SaveListaProgramacion(Programacion) End Sub End Class
crackper/SistFoncreagro
SistFoncreagro.BussinesLogic/ProgramacionBL.vb
Visual Basic
mit
982
Option Infer On Imports System Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim partDocument As SolidEdgePart.PartDocument = Nothing Dim models As SolidEdgePart.Models = Nothing Dim model As SolidEdgePart.Model = Nothing Dim body As SolidEdgeGeometry.Body = Nothing Dim faces As SolidEdgeGeometry.Faces = Nothing Dim face As SolidEdgeGeometry.Face = Nothing Dim loops As SolidEdgeGeometry.Loops = Nothing Dim [loop] As SolidEdgeGeometry.Loop = Nothing Dim edgeUses As SolidEdgeGeometry.EdgeUses = Nothing Dim edgeUse As SolidEdgeGeometry.EdgeUse = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument) If partDocument IsNot Nothing Then models = partDocument.Models model = models.Item(1) body = CType(model.Body, SolidEdgeGeometry.Body) Dim FaceType = SolidEdgeGeometry.FeatureTopologyQueryTypeConstants.igQueryAll faces = CType(body.Faces(FaceType), SolidEdgeGeometry.Faces) For i As Integer = 1 To faces.Count face = CType(faces.Item(i), SolidEdgeGeometry.Face) loops = CType(face.Loops, SolidEdgeGeometry.Loops) For j As Integer = 1 To loops.Count [loop] = CType(loops.Item(j), SolidEdgeGeometry.Loop) edgeUses = CType([loop].EdgeUses, SolidEdgeGeometry.EdgeUses) For k As Integer = 1 To edgeUses.Count edgeUse = CType(edgeUses.Item(k), SolidEdgeGeometry.EdgeUse) Dim isClosed = edgeUse.IsClosed Next k Next j 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/SolidEdgeGeometry.EdgeUse.IsClosed.vb
Visual Basic
mit
2,701
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Partial Public Class JSFileUploader '''<summary> '''uploaderContainer control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> <System.ComponentModel.Description("uploaderContainer control.")> _ Protected WithEvents uploaderContainer As Global.System.Web.UI.HtmlControls.HtmlGenericControl '''<summary> '''uploaderOverlay control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> <System.ComponentModel.Description("uploaderOverlay control.")> _ Protected WithEvents uploaderOverlay As Global.System.Web.UI.HtmlControls.HtmlGenericControl '''<summary> '''selectFilesLink control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> <System.ComponentModel.Description("selectFilesLink control.")> _ Protected WithEvents selectFilesLink As Global.System.Web.UI.HtmlControls.HtmlGenericControl '''<summary> '''selectLink control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> <System.ComponentModel.Description("selectLink control.")> _ Protected WithEvents selectLink As Global.System.Web.UI.HtmlControls.HtmlInputButton '''<summary> '''dataTableContainer control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> <System.ComponentModel.Description("dataTableContainer control.")> _ Protected WithEvents dataTableContainer As Global.System.Web.UI.HtmlControls.HtmlGenericControl '''<summary> '''uploadLink control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> <System.ComponentModel.Description("uploadLink control.")> _ Protected WithEvents uploadLink As Global.System.Web.UI.HtmlControls.HtmlInputButton '''<summary> '''clearLink control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> <System.ComponentModel.Description("clearLink control.")> _ Protected WithEvents clearLink As Global.System.Web.UI.HtmlControls.HtmlInputButton End Class
Micmaz/DTIControls
DTIContentManagement/DTIUploader/JSFileUploader.ascx.designer.vb
Visual Basic
mit
3,081
Public Enum MagicClass Amateur = 1 Novice = 2 Student = 3 Apprentice = 4 Regular = 5 Journeyman = 6 Adept = 7 Scholar = 8 Mentor = 9 Expert = 10 Master = 11 GrandMaster = 12 End Enum
TeamEEDev/EECloud
EECloud.API/Enums/MagicClass.vb
Visual Basic
mit
236
Imports BVSoftware.Bvc5.Core Partial Class BVAdmin_Default Inherits BaseAdminPage Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If (WebAppSettings.LicenseData.Trim().Length > 0) Then Dim LicenseExpirationDate As DateTime = SessionManager.GetLicenseExpiration() Dim expireDays As Integer = Math.Floor((LicenseExpirationDate - DateTime.Now).TotalDays) If expireDays < 30 AndAlso expireDays > -1 Then MessageBox1.ShowWarning("Your license will expire in " & expireDays & " days. Please <a href=""http://www.bvcommerce.com/contactus.aspx"">contact BV Commerce</a> for an updated license.") End If End If If Not SessionManager.IsLicenseValid() Then MessageBox1.ShowInformation("No License Installed. Store is running in Lite mode and is limited to 10 products.") MessageBox1.ShowInformation("<a href=""" & TaskLoader.Brand.CompanyWebSite & """>Purchase a License</a>&nbsp;|&nbsp;<a href=""Configuration/License.aspx"">Install a Purchased License</a>.") End If End Sub Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit Me.PageTitle = "Dashboard" Me.CurrentTab = AdminTabType.Dashboard End Sub End Class
ajaydex/Scopelist_2015
BVAdmin/Default.aspx.vb
Visual Basic
apache-2.0
1,365
'Copyright 2019 Esri 'Licensed under the Apache License, Version 2.0 (the "License"); 'you may not use this file except in compliance with the License. 'You may obtain a copy of the License at ' http://www.apache.org/licenses/LICENSE-2.0 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. Imports System.Xml Imports ESRI.ArcGIS.Schematic Imports ESRI.ArcGIS.esriSystem Imports System.Windows.Forms ''' <summary> ''' Designer class of the dockable window add-in. It contains user interfaces that ''' make up the dockable window. ''' </summary> Public Class DigitDockableWindow Private m_digitCommand As DigitTool Dim m_dom As XmlDocument = Nothing Dim m_loading As Boolean = True Dim m_clickPanel As Boolean = False Dim m_curfrmWidth As Long Friend WithEvents m_Panel1 As System.Windows.Forms.SplitterPanel Friend WithEvents m_Panel2 As System.Windows.Forms.SplitterPanel Dim m_curPanel As System.Windows.Forms.SplitterPanel Dim m_mandatoryColor As System.Drawing.Color = Drawing.Color.White Private m_schematicLayer As ISchematicLayer Private m_schematicFeature1 As ISchematicFeature = Nothing Private m_schematicFeature2 As ISchematicFeature = Nothing Private m_createNode As Boolean = True 'update when click on panel and on new 'For button OK to retrieve the coordinate of the digit feature Private m_x As Integer Private m_y As Integer Private m_curLink As XmlElement = Nothing Private m_curNode As XmlElement = Nothing Private m_relations As XmlNodeList = Nothing Private m_schDataset As ISchematicDataset = Nothing Private m_schEltClassCont As ISchematicElementClassContainer = Nothing Private m_schEltClass As ISchematicElementClass = Nothing Private m_schematicInMemoryDiagram As ISchematicInMemoryDiagram = Nothing Private m_autoClear As Boolean = False Private m_schematicExtension As ESRI.ArcGIS.esriSystem.IExtension Public Sub New(ByVal hook As Object) ' This call is required by the Windows Form Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. Me.Hook = hook End Sub Private m_hook As Object ''' <summary> ''' Host object of the dockable window ''' </summary> Public Property Hook() As Object Get Return m_hook End Get Set(ByVal value As Object) m_hook = value End Set End Property ''' <summary> ''' Implementation class of the dockable window add-in. It is responsible for ''' creating and disposing the user interface class for the dockable window. ''' </summary> Public Class AddinImpl Inherits ESRI.ArcGIS.Desktop.AddIns.DockableWindow Private m_windowUI As DigitDockableWindow Protected Overrides Function OnCreateChild() As System.IntPtr m_windowUI = New DigitDockableWindow(Me.Hook) CurrentDigitTool.CurrentTool.digitDockableWindow = m_windowUI If (CurrentDigitTool.CurrentTool.currentDigit IsNot Nothing) Then m_windowUI.m_digitCommand = CurrentDigitTool.CurrentTool.currentDigit m_windowUI.m_digitCommand.m_dockableDigit = m_windowUI Else ' CurrentDigitTool.CurrentTool.CurrentDigit is null when we open ArcMap, but OnCreateChild ' is called if the dockable window was shown during the last ArcMap session. Dim windowID As UID = New UIDClass windowID.Value = "DigitTool_DockableWindowVB" CurrentDigitTool.CurrentTool.currentDockableWindow = My.ArcMap.DockableWindowManager.GetDockableWindow(windowID) End If Return m_windowUI.Handle End Function Protected Overrides Sub Dispose(ByVal Param As Boolean) If m_windowUI IsNot Nothing Then m_windowUI.Dispose(Param) End If MyBase.Dispose(Param) End Sub End Class Public Sub Init(ByVal schematicLayer As ISchematicLayer) ' CR229717: Lost the ElementClass if the dockable window is deactivate If (schematicLayer Is m_schematicLayer) Then If (m_schEltClass IsNot Nothing) Then Return End If End If Try If schematicLayer Is Nothing Then Return End If m_schematicLayer = schematicLayer Dim col As XmlNode = Nothing Dim myString As String = Nothing m_schDataset = schematicLayer.SchematicDiagram.SchematicDiagramClass.SchematicDataset m_schEltClassCont = m_schDataset m_schematicInMemoryDiagram = schematicLayer.SchematicInMemoryDiagram m_dom = New XmlDocument Dim schematicDiagram As ISchematicDiagram schematicDiagram = m_schematicInMemoryDiagram.SchematicDiagram ' get the path of the xml file that contains the definitions of the digitize dockable window Dim path As String Dim schematicDiagramClass As ISchematicDiagramClass = schematicDiagram.SchematicDiagramClass Dim schematicAttributeContainer As ISchematicAttributeContainer = schematicDiagramClass Dim schematicAttribute As ISchematicAttribute schematicAttribute = schematicAttributeContainer.GetSchematicAttribute("DigitizePropertiesLocation", True) If (schematicAttribute Is Nothing) Then MsgBox("Need an attribute named DigitizePropertiesLocation in the corresponding DiagramTemplate attributes") Return End If path = schematicAttribute.GetValue(schematicDiagram) If IsRelative(path) Then 'Concat the workspace's path with this path 'current workspace path Dim myDataset As ISchematicDataset = schematicDiagramClass.SchematicDataset If Not myDataset Is Nothing Then Dim mySchematicWorkspace As ISchematicWorkspace = myDataset.SchematicWorkspace If Not mySchematicWorkspace Is Nothing Then Dim myWorkspace As ESRI.ArcGIS.Geodatabase.IWorkspace = mySchematicWorkspace.Workspace If Not myWorkspace Is Nothing Then Dim workspacePath As String = myWorkspace.PathName 'add "..\" to path to step back one level... Dim stepBack As String = "..\" path = stepBack + path path = System.IO.Path.Combine(workspacePath, path) End If End If End If End If 'else keep the original hard path Dim reader As System.Xml.XmlReader = System.Xml.XmlReader.Create(path) m_dom.Load(reader) 'Load Nodes Dim nodes As XmlNodeList = Nothing nodes = m_dom.SelectNodes("descendant::NodeFeature") cboNodeType.Items.Clear() Dim node As XmlElement = Nothing For Each node In nodes Me.cboNodeType.Items.Add(node.GetAttribute("FeatureClassName").ToString) Next 'Load Links Dim links As XmlNodeList = Nothing links = m_dom.SelectNodes("descendant::LinkFeature") cboLinkType.Items.Clear() Dim link As XmlElement = Nothing For Each link In links Me.cboLinkType.Items.Add(link.GetAttribute("FeatureClassName").ToString) Next col = m_dom.SelectSingleNode("descendant::MandatoryColor") If Not col Is Nothing Then myString = "System.Drawing." myString = col.InnerText.ToString m_mandatoryColor = System.Drawing.Color.FromName(myString) End If col = m_dom.SelectSingleNode("descendant::FormName") If Not col Is Nothing Then myString = col.InnerText.ToString Me.Text = myString End If Dim rels As XmlNodeList = m_dom.SelectNodes("descendant::Relation") If rels.Count > 0 Then m_relations = rels End If col = m_dom.SelectSingleNode("descendant::AutoClearAfterCreate") If Not col Is Nothing Then If col.InnerText.ToString = "True" Then m_autoClear = True End If End If Catch ex As Exception End Try m_Panel1 = Splitter.Panel1 m_Panel2 = Splitter.Panel2 m_curPanel = Splitter.Panel1 lblMode.Text = "Create Node" m_loading = False m_clickPanel = False m_schEltClass = Nothing End Sub Public Function ValidateFields() As Boolean Dim blnValidated As Boolean = True Dim ctrl As Windows.Forms.Control = Nothing Dim mctrl As Windows.Forms.MaskedTextBox = Nothing Dim errors As String = "" Dim linkTypeChoice As String = "" Dim firstime As Boolean = True 'check all mandatory fields For Each ctrl In m_curPanel.Controls If TypeOf ctrl Is Windows.Forms.Label Then 'ignore labels Else If ctrl.Tag = "Mandatory" Then If TypeOf ctrl Is Windows.Forms.MaskedTextBox Then mctrl = ctrl If mctrl.MaskCompleted = False Then blnValidated = False If errors.Length > 0 Then errors = "Incomplete mandatory field" & Environment.NewLine + "Complete missing data and click on OK button" Else errors = errors & vbCrLf & "Incomplete mandatory field" & Environment.NewLine + "Complete missing data and click on OK button" End If End If Else If Not ctrl.Text.Length > 0 Then blnValidated = False If errors.Length > 0 Then errors = "Incomplete mandatory field" & Environment.NewLine + "Complete missing data and click on OK button" Else errors = errors & vbCrLf & "Incomplete mandatory field" & Environment.NewLine + "Complete missing data and click on OK button" End If End If End If End If 'check masked edit controls If TypeOf ctrl Is Windows.Forms.MaskedTextBox Then mctrl = ctrl 'if they typed something, but didn't complete it, then error 'if they typed nothing and it is not mandatory, then it is OK If mctrl.Text.Length > 0 Then If mctrl.Modified = True Then If mctrl.MaskCompleted = False Then blnValidated = False If errors.Length > 0 Then errors = "Invalid entry in a masked text field" Else errors = errors & vbCrLf & "Invalid entry in a masked text field" End If End If End If End If End If 'End If 'check link connections If m_curPanel Is Splitter.Panel2 Then 'make sure that the relation is correct if it exists Dim fields As XmlNodeList = m_curLink.SelectNodes("descendant::Field") Dim field As XmlElement = Nothing For Each field In fields 'find the field with a type of "Relation" If field.GetAttribute("Type") = "Relation" Then Dim rel As XmlElement = Nothing Dim dataset1 As ESRI.ArcGIS.Geodatabase.IDataset Dim dataset2 As ESRI.ArcGIS.Geodatabase.IDataset Dim FeatureClass1Name As String Dim FeatureClass2Name As String dataset1 = m_schematicFeature1.SchematicElementClass dataset2 = m_schematicFeature2.SchematicElementClass FeatureClass1Name = dataset1.Name FeatureClass2Name = dataset2.Name For Each rel In m_relations 'loop through the xml relations to match based on the from node and to node types If rel.GetAttribute("FromType") = FeatureClass1Name And rel.GetAttribute("ToType") = FeatureClass2Name Then 'find the control with the pick list for relationships Dim ctrls() As Windows.Forms.Control = m_curPanel.Controls.Find(field.GetAttribute("DBColumnName"), True) If ctrls.Length > 0 Then ctrl = ctrls(0) End If Dim vals As XmlNodeList = rel.SelectNodes("descendant::Value") Dim val As XmlElement = Nothing Dim myString As String = rel.GetAttribute("FromType") & "-" & rel.GetAttribute("ToType") Dim linkTypeClicking As String = myString 'validate that the current control string is correct 'if there are values, use them Dim blnfound As Boolean = False If vals.Count > 0 Then For Each val In vals linkTypeClicking = myString + "-" + val.InnerText.ToString() If myString & "-" & val.InnerText.ToString = ctrl.Text Then blnfound = True Exit For Else blnfound = False If firstime = True Then linkTypeChoice = ctrl.Text firstime = False End If End If Next If blnfound = False Then blnValidated = False If errors.Length > 0 Then errors = "Invalid link connection because :" errors = errors & vbCrLf & "Type's link clicked : " & linkTypeClicking errors = errors & vbCrLf & "Type's link chosen : " & linkTypeChoice Else errors = errors & vbCrLf & "Invalid link connection because :" errors = errors & vbCrLf & "Type's link clicked : " & linkTypeClicking errors = errors & vbCrLf & "Type's link chosen : " & linkTypeChoice End If End If Else If ctrl.Text <> myString Then If (firstime) Then linkTypeChoice = ctrl.Text firstime = False End If blnValidated = False If errors.Length > 0 Then errors = "Invalid link connection because :" errors = errors & vbCrLf & "Type's link clicked : " & linkTypeClicking errors = errors & vbCrLf & "Type's link chosen : " & linkTypeChoice Else errors = errors & vbCrLf & "Invalid link connection because :" errors = errors & vbCrLf & "Type's link clicked : " & linkTypeClicking errors = errors & vbCrLf & "Type's link chosen : " & linkTypeChoice End If Else blnfound = True End If End If If blnfound = False Then 'fix connection list Dim vlist As XmlNodeList = m_dom.SelectNodes("descendant::Relation") Dim v As XmlElement Dim rellist As XmlNodeList = Nothing Dim r As XmlElement = Nothing Dim cboconn As Windows.Forms.ComboBox = ctrl cboconn.Items.Clear() For Each v In vlist If v.GetAttribute("LinkType").ToString = m_curLink.GetAttribute("FeatureClassName").ToString Then 'make sure the node types are ok If v.GetAttribute("FromType").ToString() = FeatureClass1Name OrElse v.GetAttribute("ToType").ToString() = FeatureClass2Name Then rellist = v.SelectNodes("descendant::Value") If rellist.Count > 0 Then ' For Each r In rellist myString = v.GetAttribute("FromType").ToString() + "-" + v.GetAttribute("ToType").ToString() & "-" & r.InnerText.ToString cboconn.Items.Add(myString) Next Else 'assume they are not using subtypes cboconn.Items.Add(v.GetAttribute("FromType").ToString() & "-" & v.GetAttribute("ToType").ToString()) End If End If End If Next End If End If Next End If Next End If End If Next If errors.Length > 0 Then If m_curPanel Is Splitter.Panel1 Then btnOKPanel1.Visible = True ErrorProvider1.SetError(btnOKPanel1, errors) Else btnOKPanel2.Visible = True ErrorProvider1.SetError(btnOKPanel2, errors) End If End If Return blnValidated End Function Public Sub cboType_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboNodeType.SelectedValueChanged SelectionChanged() End Sub Public Sub SelectionChanged() Try Dim ctrl As System.Windows.Forms.Control = Nothing Dim ctrl2 As System.Windows.Forms.Control = Nothing Dim ctrls() As Object = Nothing Dim ctrlstoremove As Collection = New Collection Dim labelName As String = "" Dim featureClass As String = "" Dim cbo As Windows.Forms.ComboBox = Nothing Dim lblMain As Windows.Forms.Label = Nothing If m_digitCommand Is Nothing Then Return End If 'clear any current elements If Not m_schematicFeature1 Is Nothing Then m_schematicFeature1 = Nothing m_digitCommand.SchematicFeature1() = m_schematicFeature1 End If If Not m_schematicFeature2 Is Nothing Then m_schematicFeature2 = Nothing m_digitCommand.SchematicFeature2() = m_schematicFeature2 End If If m_curPanel Is Splitter.Panel1 Then labelName = "lblNodeLabel" featureClass = "descendant::NodeFeature" cbo = cboNodeType lblMain = lblNodeLabel Else labelName = "lblLinkLabel" featureClass = "descendant::LinkFeature" cbo = cboLinkType lblMain = lblLinkLabel End If For Each ctrl In m_curPanel.Controls If ctrl.Name.StartsWith("lbl") And ctrl.Name.ToString <> labelName Then ctrls = m_curPanel.Controls.Find(ctrl.Name.Substring(3), True) ctrl2 = ctrls(0) ctrlstoremove.Add(ctrl) ctrlstoremove.Add(ctrl2) End If Next If ctrlstoremove.Count > 0 Then Dim ctrol As System.Windows.Forms.Control For Each ctrol In ctrlstoremove m_curPanel.Controls.Remove(ctrol) ctrol = Nothing Next End If Dim elem As XmlElement = Nothing Dim elems As XmlNodeList = Nothing m_curfrmWidth = m_curPanel.Width elems = m_dom.SelectNodes(featureClass) Dim blnFound As Boolean = False For Each elem In elems If elem.GetAttribute("FeatureClassName").ToString = cbo.Text.ToString Then blnFound = True Exit For End If Next If blnFound = False Then ' CR229717: If this is deactivate, lost the Schematic ElementClass and can not retrieve it ' m_schEltClass = Nothing Exit Sub End If If m_curPanel Is Splitter.Panel1 Then m_curNode = elem Else m_curLink = elem End If 'set grid elems = elem.SelectNodes("descendant::Field") Dim f As XmlElement Dim x As Integer = Splitter.Location.X Dim y As Integer = lblMain.Location.Y + lblMain.Height + 5 Dim p As New System.Drawing.Point Dim rcount As Integer = 1 For Each f In elems Dim lbl As New System.Windows.Forms.Label lbl.Name = "lbl" & f.GetAttribute("DBColumnName").ToString lbl.Text = f.GetAttribute("DisplayName").ToString lbl.AutoSize = True m_curPanel.Controls.Add(lbl) p.X = 3 p.Y = y lbl.Location = p y = y + lbl.Height + 10 Select Case f.GetAttribute("Type").ToString Case "Text" Dim tx As New System.Windows.Forms.TextBox ctrl = tx tx.Name = f.GetAttribute("DBColumnName").ToString If f.GetAttribute("Length").Length > 0 Then tx.MaxLength = CInt(f.GetAttribute("Length")) End If If f.GetAttribute("Default").Length > 0 Then tx.Text = f.GetAttribute("Default") End If m_curPanel.Controls.Add(tx) Case "Combo" Dim cb As New System.Windows.Forms.ComboBox Dim defaulttext As String = "" ctrl = cb cb.DropDownStyle = Windows.Forms.ComboBoxStyle.DropDownList cb.Name = f.GetAttribute("DBColumnName").ToString Dim vlist As XmlNodeList = f.SelectNodes("descendant::Value") Dim v As XmlElement For Each v In vlist cb.Items.Add(v.InnerText.ToString) If v.GetAttribute("Default").Length > 0 Then defaulttext = v.InnerText End If Next If defaulttext.Length > 0 Then cb.Text = defaulttext End If m_curPanel.Controls.Add(cb) Case "MaskText" Dim MaskControl As New System.Windows.Forms.MaskedTextBox ctrl = MaskControl Dim mask As String = "" MaskControl.Name = f.GetAttribute("DBColumnName").ToString If f.GetAttribute("Mask").Length > 0 Then mask = f.GetAttribute("Mask") Else mask = "" End If MaskControl.Mask = mask If f.GetAttribute("Default").Length > 0 Then MaskControl.Text = f.GetAttribute("Default") End If MaskControl.Modified = False m_curPanel.Controls.Add(MaskControl) AddHandler MaskControl.TextChanged, AddressOf MaskedTextBox Case "Number" Dim MaskControl As New System.Windows.Forms.MaskedTextBox ctrl = MaskControl Dim mask As String = "" MaskControl.Name = f.GetAttribute("DBColumnName").ToString Dim i As Int16 = 1 If f.GetAttribute("Length").Length > 0 Then For i = 1 To CInt(f.GetAttribute("Length")) mask = mask & "9" Next Else If f.GetAttribute("Mask").Length > 0 Then mask = f.GetAttribute("Mask") Else mask = "" End If End If MaskControl.Mask = mask If f.GetAttribute("Default").Length > 0 Then MaskControl.Text = CInt(f.GetAttribute("Default")) End If MaskControl.Modified = False m_curPanel.Controls.Add(MaskControl) AddHandler MaskControl.TextChanged, AddressOf MaskedTextBox Case "Date" Dim dt As New System.Windows.Forms.DateTimePicker ctrl = dt dt.Name = f.GetAttribute("DBColumnName").ToString dt.Value = Now.Date dt.Format = Windows.Forms.DateTimePickerFormat.Short m_curPanel.Controls.Add(dt) Case "Relation" Dim cb As New System.Windows.Forms.ComboBox ctrl = cb cb.DropDownStyle = Windows.Forms.ComboBoxStyle.DropDownList cb.Name = f.GetAttribute("DBColumnName").ToString Dim vlist As XmlNodeList = m_dom.SelectNodes("descendant::Relation") Dim v As XmlElement Dim rellist As XmlNodeList = Nothing Dim r As XmlElement = Nothing Dim myString As String = Nothing For Each v In vlist If v.GetAttribute("LinkType").ToString = elem.GetAttribute("FeatureClassName").ToString Then rellist = v.SelectNodes("descendant::Value") If rellist.Count > 0 Then ' For Each r In rellist myString = v.GetAttribute("FromType").ToString & "-" & v.GetAttribute("ToType").ToString & "-" & r.InnerText.ToString cb.Items.Add(myString) Next Else 'assume they are not using subtypes cb.Items.Add(v.GetAttribute("FromType").ToString & "-" & v.GetAttribute("ToType").ToString) End If End If Next 'relations are always mandatory ctrl.BackColor = m_mandatoryColor ctrl.Tag = "Mandatory" m_curPanel.Controls.Add(cb) End Select If f.GetAttribute("Mandatory").ToString = "True" Then ctrl.BackColor = m_mandatoryColor ctrl.Tag = "Mandatory" End If Next ResizeForm() ' set m_schEltClass Dim schElement As ISchematicElement = Nothing Dim curElement As XmlElement = Nothing If m_curPanel Is Splitter.Panel1 Then curElement = m_curNode Else curElement = m_curLink End If If m_schEltClass Is Nothing Then m_schEltClass = m_schEltClassCont.GetSchematicElementClass(curElement.GetAttribute("FeatureClassName")) Else If m_schEltClass.Name <> curElement.GetAttribute("FeatureClassName") Then m_schEltClass = m_schEltClassCont.GetSchematicElementClass(curElement.GetAttribute("FeatureClassName")) End If End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub Public Function CheckValidFeature(ByVal blnFromNode As Boolean) As Boolean If m_curLink Is Nothing Then Return False End If ' CR229717: check if relation finish with the good kind of node Dim sRelation As String = "" Try ' If ComboBox does not exist, return an error sRelation = (CType(Me.Splitter.Panel2.Controls("Type"), ComboBox)).Text If (sRelation = "") Then Return False If (blnFromNode) Then sRelation = sRelation.Substring(0, sRelation.IndexOf("-")) Else sRelation = sRelation.Substring(sRelation.IndexOf("-") + 1) If (sRelation.IndexOf("-") > 0) Then sRelation = sRelation.Substring(0, sRelation.IndexOf("-")) End If Catch End Try Dim fields As XmlNodeList = m_curLink.SelectNodes("descendant::Field") Dim field As XmlElement = Nothing For Each field In fields If field.GetAttribute("Type") = "Relation" Then Dim rel As XmlElement = Nothing For Each rel In m_relations ' CR229717: check if relation is for this kind of link If (rel.GetAttribute("LinkType") <> Me.cboLinkType.Text) Then Continue For If blnFromNode Then If m_schematicFeature1 Is Nothing Then Return False End If ' CR229717: check if relation start with the good kind of node If (sRelation <> rel.GetAttribute("FromType")) Then Continue For If rel.GetAttribute("FromType") = m_schematicFeature1.SchematicElementClass.Name Then Return True End If Else If m_schematicFeature2 Is Nothing Then Return False End If ' CR229717: check if relation finish with the good kind of node If (sRelation <> rel.GetAttribute("ToType")) Then Continue For If rel.GetAttribute("ToType") = m_schematicFeature2.SchematicElementClass.Name Then Return True End If End If Next Return False End If Next Return True End Function Private Sub frmDigitize_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize If m_loading = False Then ResizeForm() End If End Sub Private Sub ResizeForm() Try Dim ctr As System.Windows.Forms.Control Dim ctr2 As System.Windows.Forms.Control Dim ctrls() As Object Dim p As System.Drawing.Point 'handle panel 1 For Each ctr In Splitter.Panel1.Controls If ctr.Name.StartsWith("lbl") And ctr.Name.ToString <> "lblNodeLabel" Then 'ctr.Width = Splitter.panel1.Width / 3 'MsgBox(ctr.Name.Substring(3)) ctrls = Splitter.Panel1.Controls.Find(ctr.Name.Substring(3), True) If ctrls.GetLength(0) > 0 Then ctr2 = ctrls(0) p.Y = ctr.Location.Y p.X = ctr.Width + 3 ctr2.Location = p ctr2.Width = Splitter.Panel1.Width - ctr.Width - 5 End If End If Next Splitter.Panel1.Refresh() 'handle panel 2 For Each ctr In Splitter.Panel2.Controls If ctr.Name.StartsWith("lbl") And ctr.Name.ToString <> "lblLinkLabel" Then 'ctr.Width = Splitter.panel1.Width / 3 'MsgBox(ctr.Name.Substring(3)) ctrls = Splitter.Panel2.Controls.Find(ctr.Name.Substring(3), True) If ctrls.GetLength(0) > 0 Then ctr2 = ctrls(0) p.Y = ctr.Location.Y p.X = ctr.Width + 3 ctr2.Location = p ctr2.Width = Splitter.Panel2.Width - ctr.Width - 5 End If End If Next Splitter.Panel2.Refresh() Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub cboLinkType_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboLinkType.SelectedValueChanged SelectionChanged() End Sub Public Sub FillValue(ByRef schFeature As ISchematicFeature) Try If m_schEltClass Is Nothing Then Err.Raise(513, "CreateNewFeature", "Error getting Feature Class") End If Dim fldIndex As Int16 = Nothing Dim ctrl As Windows.Forms.Control = Nothing For Each ctrl In m_curPanel.Controls If TypeOf ctrl Is Windows.Forms.Label Or ctrl.Name = "cboNodeType" Then 'do nothing Else If TypeOf ctrl Is Windows.Forms.TextBox Or TypeOf ctrl Is Windows.Forms.ComboBox Then If ctrl.Text.Length > 0 Then 'insert in DB fldIndex = schFeature.Fields.FindField(ctrl.Name) If (fldIndex > -1) Then schFeature.Value(fldIndex) = ctrl.Text schFeature.Store() End If End If ElseIf TypeOf ctrl Is Windows.Forms.DateTimePicker Then fldIndex = schFeature.Fields.FindField(ctrl.Name) If (fldIndex > -1) Then schFeature.Value(fldIndex) = ctrl.Text schFeature.Store() End If ElseIf TypeOf ctrl Is Windows.Forms.MaskedTextBox Then Dim mctrl As Windows.Forms.MaskedTextBox = ctrl If mctrl.Text.Length > 0 Then If mctrl.Modified = True Then If mctrl.MaskCompleted = True Then fldIndex = schFeature.Fields.FindField(ctrl.Name) If (fldIndex > -1) Then schFeature.Value(fldIndex) = ctrl.Text schFeature.Store() End If End If End If End If End If End If Next Return Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub btnOKPanel1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOKPanel1.Click 'try to create the node at the original point If Not m_digitCommand Is Nothing Then m_digitCommand.MyMouseUp(m_x, m_y) End If ErrorProvider1.SetError(btnOKPanel1, "") btnOKPanel1.Visible = False End Sub Private Sub btnOKPanel2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOKPanel2.Click 'try to create the link with the original points m_digitCommand.MyMouseUp(m_x, m_y) ErrorProvider1.SetError(btnOKPanel1, "") btnOKPanel1.Visible = False End Sub Private Sub MaskedTextBox(ByVal sender As Object, ByVal e As EventArgs) Dim mctrl As Windows.Forms.MaskedTextBox = sender mctrl.Modified = True End Sub Private Sub WindowVisibleChange() Handles Me.VisibleChanged If (m_digitCommand Is Nothing) Then m_digitCommand = CurrentDigitTool.CurrentTool.currentDigit End If If (m_digitCommand Is Nothing) Then Return End If If Me.Visible = True And CurrentDigitTool.CurrentTool.currentDockableWindow.IsVisible() = False Then If m_digitCommand.FromDeactivate = False Then m_digitCommand.DeactivatedFromDock = True Dim app As ESRI.ArcGIS.Framework.IApplication = Me.Hook app.CurrentTool = Nothing End If End If m_digitCommand.EndFeedBack() m_digitCommand.FromDeactivate = False End Sub Friend ReadOnly Property CreateNode() As Boolean Get Return m_createNode End Get End Property Friend ReadOnly Property AutoClear() As Boolean Get Return m_autoClear End Get End Property Friend ReadOnly Property FeatureClass() As ISchematicElementClass Get Return m_schEltClass End Get End Property Public WriteOnly Property x() As Integer Set(ByVal Value As Integer) m_x = Value End Set End Property Public WriteOnly Property y() As Integer Set(ByVal Value As Integer) m_y = Value End Set End Property Public WriteOnly Property SchematicFeature1() As ISchematicFeature Set(ByVal Value As ISchematicFeature) m_schematicFeature1 = Value End Set End Property Public WriteOnly Property SchematicFeature2() As ISchematicFeature Set(ByVal Value As ISchematicFeature) m_schematicFeature2 = Value End Set End Property 'IsRelative return true when the path start with "." Private Function IsRelative(ByVal path As String) As Boolean If path(0) = "." Then Return True Else Return False End If End Function Private Sub cboNodeType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboNodeType.SelectedIndexChanged SelectionChanged() End Sub Private Sub Splitter_Panel1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Splitter.Panel1.Click If (m_digitCommand Is Nothing) Then m_digitCommand = CurrentDigitTool.CurrentTool.currentDigit End If If Not m_digitCommand Is Nothing Then m_digitCommand.EndFeedBack() End If m_createNode = True If (Not m_curPanel Is Splitter.Panel1) Or (m_clickPanel = False) Then m_clickPanel = True Dim ctrl As Windows.Forms.Control m_curPanel = Splitter.Panel1 For Each ctrl In Splitter.Panel2.Controls ctrl.Enabled = False Next For Each ctrl In Splitter.Panel1.Controls ctrl.Enabled = True Next lblMode.Text = "Create Node" If m_curPanel Is Splitter.Panel1 Then btnOKPanel1.Visible = False ErrorProvider1.SetError(btnOKPanel1, "") Else btnOKPanel2.Visible = False ErrorProvider1.SetError(btnOKPanel2, "") End If Dim e2 As New System.EventArgs cboType_SelectedValueChanged(sender, e2) End If End Sub Private Sub Splitter_Panel2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Splitter.Panel2.Click If (m_digitCommand Is Nothing) Then m_digitCommand = CurrentDigitTool.CurrentTool.currentDigit End If If m_digitCommand Is Nothing Then Return End If m_createNode = False If Not m_curPanel Is Splitter.Panel2 Then Dim ctrl As Windows.Forms.Control m_curPanel = Splitter.Panel2 For Each ctrl In Splitter.Panel1.Controls ctrl.Enabled = False Next For Each ctrl In Splitter.Panel2.Controls ctrl.Enabled = True Next lblMode.Text = "Create Link" If Not m_schematicFeature1 Is Nothing Then m_schematicFeature1 = Nothing m_digitCommand.SchematicFeature1() = m_schematicFeature1 End If If Not m_schematicFeature2 Is Nothing Then m_schematicFeature2 = Nothing m_digitCommand.SchematicFeature2() = m_schematicFeature2 End If If m_curPanel Is Splitter.Panel1 Then btnOKPanel1.Visible = False ErrorProvider1.SetError(btnOKPanel1, "") Else btnOKPanel2.Visible = False ErrorProvider1.SetError(btnOKPanel2, "") End If Dim e2 As New System.EventArgs cboLinkType_SelectedValueChanged(sender, e2) End If End Sub End Class
Esri/arcobjects-sdk-community-samples
Net/Schematics/SchematicDigitizingTools/VBNet/DockableDigit.vb
Visual Basic
apache-2.0
32,794
' 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.Semantics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub NoInitializers() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Shared s1 As Integer Private i1 As Integer Private Property P1 As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.Regular) Dim tree = compilation.SyntaxTrees.Single() Dim nodes = tree.GetRoot().DescendantNodes().Where(Function(n) TryCast(n, VariableDeclaratorSyntax) IsNot Nothing OrElse TryCast(n, PropertyStatementSyntax) IsNot Nothing).ToArray() Assert.Equal(3, nodes.Length) Dim semanticModel = compilation.GetSemanticModel(tree) For Each node In nodes Assert.Null(semanticModel.GetOperationInternal(node)) Next End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub ConstantInitializers_StaticField() Dim source = <![CDATA[ Class C Shared s1 As Integer = 1'BIND:"= 1" End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializer (Field: C.s1 As System.Int32) (OperationKind.FieldInitializerAtDeclaration) (Syntax: '= 1') ILiteralExpression (Text: 1) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub ConstantInitializers_InstanceField() Dim source = <![CDATA[ Class C Private i1 As Integer = 1, i2 As Integer = 2'BIND:"= 2" End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializer (Field: C.i2 As System.Int32) (OperationKind.FieldInitializerAtDeclaration) (Syntax: '= 2') ILiteralExpression (Text: 2) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub ConstantInitializers_Property() Dim source = <![CDATA[ Class C Private Property P1 As Integer = 1'BIND:"= 1" End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyInitializer (Property: Property C.P1 As System.Int32) (OperationKind.PropertyInitializerAtDeclaration) (Syntax: '= 1') ILiteralExpression (Text: 1) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub ConstantInitializers_DefaultValueParameter() Dim source = <![CDATA[ Class C Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IParameterInitializer (Parameter: [p1 As System.Int32 = 0]) (OperationKind.ParameterInitializerAtDeclaration) (Syntax: '= 0') ILiteralExpression (Text: 0) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30642: 'Optional' and 'ParamArray' cannot be combined. Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0" ~~~~~~~~~~ BC30046: Method cannot have both a ParamArray and Optional parameters. Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub ConstantInitializers_DefaultValueParamsArray() Dim source = <![CDATA[ Class C Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IParameterInitializer (Parameter: [ParamArray p2 As System.Int32() = Nothing]) (OperationKind.ParameterInitializerAtDeclaration) (Syntax: '= Nothing') IConversionExpression (ConversionKind.Basic, Implicit) (OperationKind.ConversionExpression, Type: System.Int32(), Constant: null) (Syntax: 'Nothing') ILiteralExpression (OperationKind.LiteralExpression, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30642: 'Optional' and 'ParamArray' cannot be combined. Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing" ~~~~~~~~~~ BC30046: Method cannot have both a ParamArray and Optional parameters. Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/17813"), WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")> Public Sub MultipleFieldInitializers() Dim source = <![CDATA[ Class C Dim x, y As New Object'BIND:"As New Object" End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializer (2 initialized fields) (OperationKind.FieldInitializerAtDeclaration) (Syntax: 'As New Object') Field_1: C.x As System.Object Field_2: C.y As System.Object IObjectCreationExpression (Constructor: Sub System.Object..ctor()) (OperationKind.ObjectCreationExpression, Type: System.Object) (Syntax: 'New Object') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub ExpressionInitializers_StaticField() Dim source = <![CDATA[ Class C Shared s1 As Integer = 1 + F()'BIND:"= 1 + F()" Private Shared Function F() As Integer Return 1 End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializer (Field: C.s1 As System.Int32) (OperationKind.FieldInitializerAtDeclaration) (Syntax: '= 1 + F()') IBinaryOperatorExpression (BinaryOperationKind.IntegerAdd) (OperationKind.BinaryOperatorExpression, Type: System.Int32) (Syntax: '1 + F()') Left: ILiteralExpression (Text: 1) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: IInvocationExpression (static Function C.F() As System.Int32) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'F()') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub ExpressionInitializers_InstanceField() Dim source = <![CDATA[ Class C Private i1 As Integer = 1 + F()'BIND:"= 1 + F()" Private Shared Function F() As Integer Return 1 End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializer (Field: C.i1 As System.Int32) (OperationKind.FieldInitializerAtDeclaration) (Syntax: '= 1 + F()') IBinaryOperatorExpression (BinaryOperationKind.IntegerAdd) (OperationKind.BinaryOperatorExpression, Type: System.Int32) (Syntax: '1 + F()') Left: ILiteralExpression (Text: 1) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: IInvocationExpression (static Function C.F() As System.Int32) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'F()') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub ExpressionInitializers_Property() Dim source = <![CDATA[ Class C Private Property P1 As Integer = 1 + F()'BIND:"= 1 + F()" Private Shared Function F() As Integer Return 1 End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyInitializer (Property: Property C.P1 As System.Int32) (OperationKind.PropertyInitializerAtDeclaration) (Syntax: '= 1 + F()') IBinaryOperatorExpression (BinaryOperationKind.IntegerAdd) (OperationKind.BinaryOperatorExpression, Type: System.Int32) (Syntax: '1 + F()') Left: ILiteralExpression (Text: 1) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: IInvocationExpression (static Function C.F() As System.Int32) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'F()') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub PartialClasses_StaticField() Dim source = <![CDATA[ Partial Class C Shared s1 As Integer = 1'BIND:"= 1" Private i1 As Integer = 1 End Class Partial Class C Shared s2 As Integer = 2 Private i2 As Integer = 2 End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializer (Field: C.s1 As System.Int32) (OperationKind.FieldInitializerAtDeclaration) (Syntax: '= 1') ILiteralExpression (Text: 1) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub PartialClasses_InstanceField() Dim source = <![CDATA[ Partial Class C Shared s1 As Integer = 1 Private i1 As Integer = 1 End Class Partial Class C Shared s2 As Integer = 2 Private i2 As Integer = 2'BIND:"= 2" End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializer (Field: C.i2 As System.Int32) (OperationKind.FieldInitializerAtDeclaration) (Syntax: '= 2') ILiteralExpression (Text: 2) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")> Public Sub MemberInitializer() Dim source = <![CDATA[ Structure B Public Field As Boolean End Structure Class F Public Field As Integer Public Property Property1() As String Public Property Property2() As B End Class Class C Public Sub M1()'BIND:"Public Sub M1()" Dim x1 = New F() Dim x2 = New F() With {.Field = 2} Dim x3 = New F() With {.Property1 = ""} Dim x4 = New F() With {.Property1 = "", .Field = 2} Dim x5 = New F() With {.Property2 = New B() With {.Field = True}} Dim e1 = New F() With {.Property2 = 1} Dim e2 = New F() From {""} End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockStatement (9 statements, 7 locals) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'Public Sub ... End Sub') Locals: Local_1: x1 As F Local_2: x2 As F Local_3: x3 As F Local_4: x4 As F Local_5: x5 As F Local_6: e1 As F Local_7: e2 As F IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim x1 = New F()') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'x1') Variables: Local_1: x1 As F Initializer: IObjectCreationExpression (Constructor: Sub F..ctor()) (OperationKind.ObjectCreationExpression, Type: F) (Syntax: 'New F()') IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim x2 = Ne ... .Field = 2}') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'x2') Variables: Local_1: x2 As F Initializer: IObjectCreationExpression (Constructor: Sub F..ctor()) (OperationKind.ObjectCreationExpression, Type: F) (Syntax: 'New F() Wit ... .Field = 2}') Member Initializers(1): IFieldInitializer (Field: F.Field As System.Int32) (OperationKind.FieldInitializerInCreation) (Syntax: '.Field = 2') ILiteralExpression (Text: 2) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim x3 = Ne ... erty1 = ""}') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'x3') Variables: Local_1: x3 As F Initializer: IObjectCreationExpression (Constructor: Sub F..ctor()) (OperationKind.ObjectCreationExpression, Type: F) (Syntax: 'New F() Wit ... erty1 = ""}') Member Initializers(1): IPropertyInitializer (Property: Property F.Property1 As System.String) (OperationKind.PropertyInitializerInCreation) (Syntax: '.Property1 = ""') ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "") (Syntax: '""') IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim x4 = Ne ... .Field = 2}') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'x4') Variables: Local_1: x4 As F Initializer: IObjectCreationExpression (Constructor: Sub F..ctor()) (OperationKind.ObjectCreationExpression, Type: F) (Syntax: 'New F() Wit ... .Field = 2}') Member Initializers(2): IPropertyInitializer (Property: Property F.Property1 As System.String) (OperationKind.PropertyInitializerInCreation) (Syntax: '.Property1 = ""') ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "") (Syntax: '""') IFieldInitializer (Field: F.Field As System.Int32) (OperationKind.FieldInitializerInCreation) (Syntax: '.Field = 2') ILiteralExpression (Text: 2) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim x5 = Ne ... ld = True}}') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'x5') Variables: Local_1: x5 As F Initializer: IObjectCreationExpression (Constructor: Sub F..ctor()) (OperationKind.ObjectCreationExpression, Type: F) (Syntax: 'New F() Wit ... ld = True}}') Member Initializers(1): IPropertyInitializer (Property: Property F.Property2 As B) (OperationKind.PropertyInitializerInCreation) (Syntax: '.Property2 ... eld = True}') IObjectCreationExpression (Constructor: Sub B..ctor()) (OperationKind.ObjectCreationExpression, Type: B) (Syntax: 'New B() Wit ... eld = True}') Member Initializers(1): IFieldInitializer (Field: B.Field As System.Boolean) (OperationKind.FieldInitializerInCreation) (Syntax: '.Field = True') ILiteralExpression (Text: True) (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'True') IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Dim e1 = Ne ... perty2 = 1}') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'e1') Variables: Local_1: e1 As F Initializer: IObjectCreationExpression (Constructor: Sub F..ctor()) (OperationKind.ObjectCreationExpression, Type: F, IsInvalid) (Syntax: 'New F() Wit ... perty2 = 1}') Member Initializers(1): IPropertyInitializer (Property: Property F.Property2 As B) (OperationKind.PropertyInitializerInCreation, IsInvalid) (Syntax: '.Property2 = 1') IConversionExpression (ConversionKind.Basic, Implicit) (OperationKind.ConversionExpression, Type: B, IsInvalid) (Syntax: '1') ILiteralExpression (Text: 1) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Dim e2 = Ne ... ) From {""}') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'e2') Variables: Local_1: e2 As F Initializer: IObjectCreationExpression (Constructor: Sub F..ctor()) (OperationKind.ObjectCreationExpression, Type: F, IsInvalid) (Syntax: 'New F() From {""}') ILabelStatement (Label: exit) (OperationKind.LabelStatement) (Syntax: 'End Sub') IReturnStatement (OperationKind.ReturnStatement) (Syntax: 'End Sub') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'Integer' cannot be converted to 'B'. Dim e1 = New F() With {.Property2 = 1} ~ BC36718: Cannot initialize the type 'F' with a collection initializer because it is not a collection type. Dim e2 = New F() From {""} ~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub End Class End Namespace
akrisiun/roslyn
src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_ISymbolInitializer.vb
Visual Basic
apache-2.0
19,421
' 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 Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Partial Friend Class VisualBasicMethodExtractor Partial Private Class VisualBasicCodeGenerator Private Class ExpressionCodeGenerator Inherits VisualBasicCodeGenerator Public Sub New(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult) MyBase.New(insertionPoint, selectionResult, analyzerResult) End Sub Public Shared Function IsExtractMethodOnExpression(code As SelectionResult) As Boolean Return code.SelectionInExpression End Function Protected Overrides Function CreateMethodName() As SyntaxToken Dim methodName = "NewMethod" Dim containingScope = CType(VBSelectionResult.GetContainingScope(), SyntaxNode) methodName = GetMethodNameBasedOnExpression(methodName, containingScope) Dim semanticModel = CType(SemanticDocument.SemanticModel, SemanticModel) Dim nameGenerator = New UniqueNameGenerator(semanticModel) Return SyntaxFactory.Identifier( nameGenerator.CreateUniqueMethodName(containingScope, methodName)) End Function Private Shared Function GetMethodNameBasedOnExpression(methodName As String, expression As SyntaxNode) As String If expression.IsParentKind(SyntaxKind.EqualsValue) AndAlso expression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then Dim varDecl = DirectCast(expression.Parent.Parent, VariableDeclaratorSyntax) If varDecl.Names.Count <> 1 Then Return methodName End If Dim identifierNode = varDecl.Names(0) If identifierNode Is Nothing Then Return methodName End If Dim name = identifierNode.Identifier.ValueText Return If(name IsNot Nothing AndAlso name.Length > 0, MakeMethodName("Get", name, camelCase:=False), methodName) End If If TypeOf expression Is MemberAccessExpressionSyntax Then expression = CType(expression, MemberAccessExpressionSyntax).Name End If If TypeOf expression Is NameSyntax Then Dim lastDottedName = CType(expression, NameSyntax).GetLastDottedName() Dim plainName = CType(lastDottedName, SimpleNameSyntax).Identifier.ValueText Return If(plainName IsNot Nothing AndAlso plainName.Length > 0, MakeMethodName("Get", plainName, camelCase:=False), methodName) End If Return methodName End Function Protected Overrides Function GetInitialStatementsForMethodDefinitions() As IEnumerable(Of StatementSyntax) Contract.ThrowIfFalse(IsExtractMethodOnExpression(VBSelectionResult)) Dim expression = DirectCast(VBSelectionResult.GetContainingScope(), ExpressionSyntax) Dim statement As StatementSyntax If Me.AnalyzerResult.HasReturnType Then statement = SyntaxFactory.ReturnStatement(expression:=expression) Else ' we have expression for void method (Sub). make the expression as call ' statement if possible we can create call statement only from invocation ' and member access expression. otherwise, it is not a valid expression. ' return error code If expression.Kind <> SyntaxKind.InvocationExpression AndAlso expression.Kind <> SyntaxKind.SimpleMemberAccessExpression Then Return SpecializedCollections.EmptyEnumerable(Of StatementSyntax)() End If statement = SyntaxFactory.ExpressionStatement(expression:=expression) End If Return SpecializedCollections.SingletonEnumerable(Of StatementSyntax)(statement) End Function Protected Overrides Function GetOutermostCallSiteContainerToProcess(cancellationToken As CancellationToken) As SyntaxNode Dim callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken) Return If(callSiteContainer, (GetCallSiteContainerFromExpression())) End Function Private Function GetCallSiteContainerFromExpression() As SyntaxNode Dim container = VBSelectionResult.InnermostStatementContainer() Contract.ThrowIfNull(container) Contract.ThrowIfFalse(container.IsStatementContainerNode() OrElse TypeOf container Is TypeBlockSyntax OrElse TypeOf container Is CompilationUnitSyntax) Return container End Function Protected Overrides Function GetFirstStatementOrInitializerSelectedAtCallSite() As StatementSyntax Return VBSelectionResult.GetContainingScopeOf(Of StatementSyntax)() End Function Protected Overrides Function GetLastStatementOrInitializerSelectedAtCallSite() As StatementSyntax Return GetFirstStatementOrInitializerSelectedAtCallSite() End Function Protected Overrides Async Function GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(callSiteAnnotation As SyntaxAnnotation, cancellationToken As CancellationToken) As Task(Of StatementSyntax) Dim enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite() Dim callSignature = CreateCallSignature().WithAdditionalAnnotations(callSiteAnnotation) Dim invocation = If(TypeOf callSignature Is AwaitExpressionSyntax, DirectCast(callSignature, AwaitExpressionSyntax).Expression, callSignature) Dim sourceNode = DirectCast(VBSelectionResult.GetContainingScope(), SyntaxNode) Contract.ThrowIfTrue( sourceNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso DirectCast(sourceNode.Parent, MemberAccessExpressionSyntax).Name Is sourceNode, "invalid scope. scope is not an expression") ' To lower the chances that replacing sourceNode with callSignature will break the user's ' code, we make the enclosing statement semantically explicit. This ends up being a little ' bit more work because we need to annotate the sourceNode so that we can get back to it ' after rewriting the enclosing statement. Dim sourceNodeAnnotation = New SyntaxAnnotation() Dim enclosingStatementAnnotation = New SyntaxAnnotation() Dim newEnclosingStatement = enclosingStatement _ .ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation)) _ .WithAdditionalAnnotations(enclosingStatementAnnotation) Dim updatedDocument = Await Me.SemanticDocument.Document.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(False) Dim updatedRoot = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) newEnclosingStatement = DirectCast(updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode(), StatementSyntax) ' because of the complexification we cannot guarantee that there is only one annotation. ' however complexification of names is prepended, so the last annotation should be the original one. sourceNode = DirectCast(updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode(), SyntaxNode) ' we want to replace the old identifier with a invocation expression, but because of MakeExplicit we might have ' a member access now instead of the identifier. So more syntax fiddling is needed. If sourceNode.Parent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso DirectCast(sourceNode, ExpressionSyntax).IsRightSideOfDot() Then Dim explicitMemberAccess = DirectCast(sourceNode.Parent, MemberAccessExpressionSyntax) Dim replacementMemberAccess = SyntaxFactory.MemberAccessExpression( sourceNode.Parent.Kind(), explicitMemberAccess.Expression, SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(DirectCast(invocation, InvocationExpressionSyntax).Expression, SimpleNameSyntax)) replacementMemberAccess = explicitMemberAccess.CopyAnnotationsTo(replacementMemberAccess) Dim newInvocation = SyntaxFactory.InvocationExpression( replacementMemberAccess, DirectCast(invocation, InvocationExpressionSyntax).ArgumentList) _ .WithTrailingTrivia(sourceNode.GetTrailingTrivia()) Dim newCallSignature = If(callSignature IsNot invocation, callSignature.ReplaceNode(invocation, newInvocation), invocation.CopyAnnotationsTo(newInvocation)) sourceNode = sourceNode.Parent callSignature = newCallSignature End If Return newEnclosingStatement.ReplaceNode(sourceNode, callSignature) End Function End Class End Class End Class End Namespace
davkean/roslyn
src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.ExpressionCodeGenerator.vb
Visual Basic
apache-2.0
10,849
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class XmlCDataHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function CreateHighlighter() As IHighlighter Return New XmlCDataHighlighter() End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample6_1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> <phone type="home">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> {|Cursor:[|<![CDATA[|]|}Be wary of this guy![|]]>]]<![CDATA[>|] </contact> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample6_2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> <phone type="home">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> [|<![CDATA[|]Be wary of this guy!{|Cursor:[|]]>]]<![CDATA[>|]|} </contact> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample6_3() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> <phone type="home">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[B{|Cursor:e wary of this guy|}!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function End Class End Namespace
reaction1989/roslyn
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/XmlCDataHighligherTests.vb
Visual Basic
apache-2.0
2,212
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class Binder #Region "Get All Attributes" ' Method to bind attributes types early for all attributes to enable early decoding of some well-known attributes used within the binder. ' Note: attributesToBind contains merged attributes from all the different syntax locations (e.g. for named types, partial methods, etc.). Friend Shared Function BindAttributeTypes(binders As ImmutableArray(Of Binder), attributesToBind As ImmutableArray(Of AttributeSyntax), ownerSymbol As Symbol, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Debug.Assert(binders.Any()) Debug.Assert(attributesToBind.Any()) Debug.Assert(ownerSymbol IsNot Nothing) Debug.Assert(binders.Length = attributesToBind.Length) Dim totalAttributesCount As Integer = attributesToBind.Length Dim boundAttributeTypes = New NamedTypeSymbol(totalAttributesCount - 1) {} For i = 0 To totalAttributesCount - 1 boundAttributeTypes(i) = BindAttributeType(binders(i), attributesToBind(i), ownerSymbol, diagnostics) Next Return boundAttributeTypes.AsImmutableOrNull() End Function ' Method to bind attributes types early for all attributes to enable early decoding of some well-known attributes used within the binder. Friend Shared Function BindAttributeType(binder As Binder, attribute As AttributeSyntax, ownerSymbol As Symbol, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol binder = New LocationSpecificBinder(VisualBasic.BindingLocation.Attribute, ownerSymbol, binder) Return DirectCast(binder.BindTypeSyntax(attribute.Name, diagnostics), NamedTypeSymbol) End Function ''' <summary> ''' Gets but does not fully validate a symbol's attributes. Returns binding errors but not attribute usage and attribute specific errors. ''' </summary> Friend Shared Sub GetAttributes(binders As ImmutableArray(Of Binder), attributesToBind As ImmutableArray(Of AttributeSyntax), boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol), attributeBuilder As VisualBasicAttributeData(), ownerSymbol As Symbol, diagnostics As BindingDiagnosticBag) Debug.Assert(Not binders.IsEmpty) Debug.Assert(Not attributesToBind.IsEmpty) Debug.Assert(binders.Length = attributesToBind.Length) For index = 0 To attributesToBind.Length - 1 If attributeBuilder(index) Is Nothing Then Dim binder = binders(index) binder = New LocationSpecificBinder(VisualBasic.BindingLocation.Attribute, ownerSymbol, binder) attributeBuilder(index) = binder.GetAttribute(attributesToBind(index), boundAttributeTypes(index), diagnostics) End If Next End Sub #End Region #Region "Get Single Attribute" Friend Function GetAttribute(node As AttributeSyntax, boundAttributeType As NamedTypeSymbol, diagnostics As BindingDiagnosticBag) As SourceAttributeData Dim boundAttribute As boundAttribute = BindAttribute(node, boundAttributeType, diagnostics) Dim visitor As New AttributeExpressionVisitor(Me, boundAttribute.HasErrors) Dim args As ImmutableArray(Of TypedConstant) = visitor.VisitPositionalArguments(boundAttribute.ConstructorArguments, diagnostics) Dim namedArgs As ImmutableArray(Of KeyValuePair(Of String, TypedConstant)) = visitor.VisitNamedArguments(boundAttribute.NamedArguments, diagnostics) Dim isConditionallyOmitted As Boolean = Not visitor.HasErrors AndAlso IsAttributeConditionallyOmitted(boundAttributeType, node, boundAttribute.SyntaxTree) Return New SourceAttributeData(node.GetReference(), DirectCast(boundAttribute.Type, NamedTypeSymbol), boundAttribute.Constructor, args, namedArgs, isConditionallyOmitted, hasErrors:=visitor.HasErrors) End Function Protected Function IsAttributeConditionallyOmitted(attributeType As NamedTypeSymbol, node As AttributeSyntax, syntaxTree As SyntaxTree) As Boolean If IsEarlyAttributeBinder Then Return False End If Debug.Assert(attributeType IsNot Nothing) Debug.Assert(Not attributeType.IsErrorType()) ' Source attribute is conditionally omitted if the attribute type is conditional and none of the conditional symbols are true at the attribute source location. If attributeType.IsConditional Then Dim conditionalSymbols As IEnumerable(Of String) = attributeType.GetAppliedConditionalSymbols() Debug.Assert(conditionalSymbols IsNot Nothing) Debug.Assert(conditionalSymbols.Any()) If syntaxTree.IsAnyPreprocessorSymbolDefined(conditionalSymbols, node) Then Return False End If ' NOTE: Conditional symbols on base type must be inherited by derived type, but the native VB compiler doesn't do so. We will maintain compatibility. Return True Else Return False End If End Function #End Region #Region "Bind Single Attribute" Friend Function BindAttribute(node As AttributeSyntax, diagnostics As BindingDiagnosticBag) As BoundAttribute Dim namedType As NamedTypeSymbol = DirectCast(BindTypeSyntax(node.Name, diagnostics), NamedTypeSymbol) Return BindAttribute(node, namedType, diagnostics) End Function Friend Sub LookupAttributeType(lookupResult As LookupResult, container As NamespaceOrTypeSymbol, name As String, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Debug.Assert(options.IsValid()) Debug.Assert(options.IsAttributeTypeLookup()) ' Per 5.2.1 When the compiler resolves an attribute name, it appends "Attribute" to the name and tries the ' lookup. If that lookup fails, the compiler tries the lookup without the suffix. options = options Or LookupOptions.IgnoreExtensionMethods Lookup(lookupResult, container, name & "Attribute", options, useSiteInfo) ' If no result is found then do a second lookup without the attribute suffix. ' The result is that namespace symbols or inaccessible symbols with the attribute ' suffix will be returned from the first lookup. If lookupResult.IsClear OrElse lookupResult.IsWrongArity Then lookupResult.Clear() Lookup(lookupResult, container, name, options, useSiteInfo) End If If Not lookupResult.IsGood Then ' Didn't find a viable symbol just return Return End If ' Found a good symbol, now check that it is appropriate to use as an attribute. CheckAttributeTypeViability(lookupResult, useSiteInfo) End Sub Private Sub Lookup(lookupResult As LookupResult, container As NamespaceOrTypeSymbol, name As String, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) If container IsNot Nothing Then LookupMember(lookupResult, container, name, 0, options, useSiteInfo) Else Lookup(lookupResult, name, 0, options, useSiteInfo) End If End Sub Private Sub CheckAttributeTypeViability(lookupResult As LookupResult, ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.HasSingleSymbol AndAlso lookupResult.IsGood) ' For error reporting, check the unwrapped symbol. However, return the unwrapped alias symbol if it is an alias. ' BindTypeOrNamespace will do the final unwrap. Dim symbol = UnwrapAlias(lookupResult.SingleSymbol) Dim diagInfo As DiagnosticInfo = Nothing Dim errorId As ERRID Dim resultKind As LookupResultKind If symbol.Kind = SymbolKind.Namespace Then errorId = ERRID.ERR_UnrecognizedType ElseIf symbol.Kind = SymbolKind.TypeParameter Then errorId = ERRID.ERR_AttrCannotBeGenerics ElseIf symbol.Kind <> SymbolKind.NamedType Then errorId = ERRID.ERR_UnrecognizedType resultKind = LookupResultKind.NotATypeOrNamespace Else Dim namedType = DirectCast(symbol, NamedTypeSymbol) Dim localUseSiteInfo = If(useSiteInfo.AccumulatesDependencies, New CompoundUseSiteInfo(Of AssemblySymbol)(Compilation.Assembly), CompoundUseSiteInfo(Of AssemblySymbol).DiscardedDependecies) ' type cannot be generic If namedType.IsGenericType Then errorId = ERRID.ERR_AttrCannotBeGenerics ' type must be a class ElseIf namedType.IsStructureType Then errorId = ERRID.ERR_AttributeMustBeClassNotStruct1 ' type must inherit from System.Attribute ElseIf Not Compilation.GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(namedType, localUseSiteInfo) Then errorId = ERRID.ERR_AttributeMustInheritSysAttr If Not localUseSiteInfo.Diagnostics.IsNullOrEmpty() Then diagInfo = localUseSiteInfo.Diagnostics.First() End If ' type can not be "mustinherit" ElseIf namedType.IsMustInherit Then errorId = ERRID.ERR_AttributeCannotBeAbstract Else ' Return the symbol from the lookup result. In the case of an alias, it will be the alias symbol not ' the unwrapped symbol. This is the convention for lookup methods. useSiteInfo.MergeAndClear(localUseSiteInfo) Return End If End If If diagInfo Is Nothing Then diagInfo = New BadSymbolDiagnostic(symbol, errorId) End If lookupResult.Clear() lookupResult.SetFrom(SingleLookupResult.NotAnAttributeType(symbol, diagInfo)) Return End Sub Friend Function BindAttribute(node As AttributeSyntax, type As NamedTypeSymbol, diagnostics As BindingDiagnosticBag) As BoundAttribute ' If attribute name bound to an error type with a single named type ' candidate symbol, we want to bind the attribute constructor ' and arguments with that named type to generate better semantic info. ' CONSIDER: Do we need separate code paths for IDE and ' CONSIDER: batch compilation scenarios? Above mentioned scenario ' CONSIDER: is not useful for batch compilation. Dim attributeTypeForBinding As NamedTypeSymbol = type Dim resultKind = LookupResultKind.Good If type.IsErrorType() Then Dim errorType = DirectCast(type, ErrorTypeSymbol) resultKind = errorType.ResultKind If errorType.CandidateSymbols.Length = 1 AndAlso errorType.CandidateSymbols(0).Kind = SymbolKind.NamedType Then attributeTypeForBinding = DirectCast(errorType.CandidateSymbols(0), NamedTypeSymbol) End If End If ' Get the bound arguments and the argument names. Dim argumentListOpt = node.ArgumentList Dim methodSym As MethodSymbol = Nothing Dim analyzedArguments = BindAttributeArguments(attributeTypeForBinding, argumentListOpt, diagnostics) Dim boundArguments As ImmutableArray(Of BoundExpression) = analyzedArguments.positionalArguments Dim boundNamedArguments As ImmutableArray(Of BoundExpression) = analyzedArguments.namedArguments If Not attributeTypeForBinding.IsErrorType() Then ' Filter out inaccessible constructors Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim accessibleConstructors = GetAccessibleConstructors(attributeTypeForBinding, useSiteInfo) If accessibleConstructors.Length = 0 Then ' TODO: we may want to fix the behavior of the Lookup result to contain more than one e.g. inaccessible symbol. ' Then we could display which method was inaccessible here. Until then, we're giving a generic diagnostic ' which is a little deviation from Dev10 which reports: ' "'C.Protected Sub New()' is not accessible in this context because it is 'Protected'. ' Having multiple bad symbols in a LookupResult was tried already by acasey, but getting this right is pretty ' complicated and a performance hit (multiple diagnostics, ...). diagnostics.Add(node, useSiteInfo) ' Avoid cascading diagnostics If Not type.IsErrorType() Then ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_NoViableOverloadCandidates1, "New")) End If If attributeTypeForBinding.InstanceConstructors.IsEmpty Then resultKind = LookupResult.WorseResultKind(resultKind, LookupResultKind.Empty) Else resultKind = LookupResult.WorseResultKind(resultKind, LookupResultKind.Inaccessible) End If Else Dim constructorsGroup = New BoundMethodGroup(node.Name, Nothing, accessibleConstructors, LookupResultKind.Good, Nothing, QualificationKind.QualifiedViaTypeName) Dim results As OverloadResolution.OverloadResolutionResult = OverloadResolution.MethodInvocationOverloadResolution(constructorsGroup, boundArguments, Nothing, Me, callerInfoOpt:=node.Name, useSiteInfo:=useSiteInfo) If diagnostics.Add(node.Name, useSiteInfo) Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If If Not results.BestResult.HasValue Then resultKind = LookupResult.WorseResultKind(resultKind, LookupResultKind.OverloadResolutionFailure) ' Avoid cascading diagnostics If Not type.IsErrorType() Then ' Create and report the diagnostic. If results.Candidates.Length = 0 Then results = OverloadResolution.MethodInvocationOverloadResolution(constructorsGroup, boundArguments, Nothing, Me, includeEliminatedCandidates:=True, callerInfoOpt:=node.Name, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) End If ' Report overload resolution but do not use the bound node result. We always want to return a ' SourceAttributeData not a BadBoundExpression. ' TODO - Split ReportOverloadResolutionFailureAndProduceBoundNode into two methods. One that does error reporting and one that ' builds the bound node. We only need the error reporting here. ReportOverloadResolutionFailureAndProduceBoundNode(node, constructorsGroup, boundArguments, Nothing, results, diagnostics, callerInfoOpt:=node.Name) End If Else Dim methodResult = results.BestResult.Value methodSym = DirectCast(methodResult.Candidate.UnderlyingSymbol, MethodSymbol) Dim errorsReported As Boolean = False ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, methodSym, node) ' Check that all formal parameters have attribute-compatible types and are public For Each param In methodSym.Parameters If Not IsValidTypeForAttributeArgument(param.Type) Then errorsReported = True ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_BadAttributeConstructor1, param.Type) ElseIf param.IsByRef Then errorsReported = True ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_BadAttributeConstructor2, param.Type) End If ' Check that the type is public. If DigThroughArrayType(param.Type).DeclaredAccessibility <> Accessibility.Public Then errorsReported = True ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_BadAttributeNonPublicType1, param.Type) Else ' Check all containers. Dim container = param.Type.ContainingType While container IsNot Nothing If DigThroughArrayType(container).DeclaredAccessibility <> Accessibility.Public Then errorsReported = True ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_BadAttributeNonPublicContType2, param.Type, container) End If container = container.ContainingType End While End If Next If Not errorsReported Then ' There should not be any used temporaries or copy back expressions because arguments must ' be constants and they cannot be passed byref. Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) = PassArguments(node.Name, methodResult, boundArguments, diagnostics) ' We don't do anything with the default parameter info currently, as we don't expose IOperations for ' Attributes. If that changes, we can add this info to the BoundAttribute node. boundArguments = argumentInfo.Arguments Debug.Assert(Not boundArguments.Any(Function(a) a.Kind = BoundKind.ByRefArgumentWithCopyBack)) If methodSym.DeclaredAccessibility <> Accessibility.Public Then ReportDiagnostic(diagnostics, node.Name, ERRID.ERR_BadAttributeNonPublicConstructor) End If End If End If End If End If Return New BoundAttribute(node, methodSym, boundArguments, boundNamedArguments, resultKind, type, hasErrors:=resultKind <> LookupResultKind.Good) End Function ' Given a list of arguments, create arrays of the bound arguments and pairs of names and expression syntax. Attribute arguments are bound but ' named arguments are not yet bound. Assumption is that the parser enforces that named arguments come after arguments. Private Function BindAttributeArguments( type As NamedTypeSymbol, argumentListOpt As ArgumentListSyntax, diagnostics As BindingDiagnosticBag ) As AnalyzedAttributeArguments Dim boundArguments As ImmutableArray(Of BoundExpression) Dim namedArguments As ImmutableArray(Of BoundExpression) If (argumentListOpt Is Nothing) Then boundArguments = s_noArguments namedArguments = s_noArguments Else Dim arguments As SeparatedSyntaxList(Of ArgumentSyntax) = argumentListOpt.Arguments Dim boundArgumentsBuilder As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance Dim namedArgumentsBuilder As ArrayBuilder(Of BoundExpression) = Nothing Dim argCount As Integer = 0 Dim argumentSyntax As ArgumentSyntax Try For Each argumentSyntax In arguments Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument Dim simpleArgument = DirectCast(argumentSyntax, SimpleArgumentSyntax) If Not simpleArgument.IsNamed Then ' Validating the expression is done when the bound expression is converted to a TypedConstant Dim expression As BoundExpression = BindValue(simpleArgument.Expression, diagnostics) MarkEmbeddedTypeReferenceIfNeeded(expression) boundArgumentsBuilder.Add(expression) Else If namedArgumentsBuilder Is Nothing Then namedArgumentsBuilder = ArrayBuilder(Of BoundExpression).GetInstance() End If namedArgumentsBuilder.Add(BindAttributeNamedArgument(type, simpleArgument, diagnostics)) End If Case SyntaxKind.OmittedArgument boundArgumentsBuilder.Add(New BoundOmittedArgument(argumentSyntax, Nothing)) End Select argCount += 1 Next Finally boundArguments = boundArgumentsBuilder.ToImmutableAndFree namedArguments = If(namedArgumentsBuilder Is Nothing, s_noArguments, namedArgumentsBuilder.ToImmutableAndFree) End Try End If Return New AnalyzedAttributeArguments(boundArguments, namedArguments) End Function Private Function BindAttributeNamedArgument(container As TypeSymbol, namedArg As SimpleArgumentSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression Debug.Assert(namedArg.IsNamed) ' Bind the named argument Dim result As LookupResult = LookupResult.GetInstance() Dim identifierName As IdentifierNameSyntax = namedArg.NameColonEquals.Name Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) LookupMember(result, container, identifierName.Identifier.ValueText, 0, LookupOptions.IgnoreExtensionMethods, useSiteInfo) ' Validating the expression is done when the bound expression is converted to a TypedConstant Dim rValue As BoundExpression = Me.BindValue(namedArg.Expression, diagnostics) MarkEmbeddedTypeReferenceIfNeeded(rValue) Dim lValue As BoundExpression = Nothing If result.IsGood Then Dim sym As Symbol = GetBestAttributeFieldOrProperty(result) Dim fieldSym As FieldSymbol = Nothing Dim propertySym As PropertySymbol = Nothing Dim fieldOrPropType As TypeSymbol = Nothing Dim isReadOnly As Boolean = False Dim hasErrors As Boolean = False ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, sym, namedArg) Select Case sym.Kind Case SymbolKind.Field fieldSym = DirectCast(sym, FieldSymbol) fieldOrPropType = fieldSym.Type isReadOnly = fieldSym.IsReadOnly ReportUseSite(diagnostics, identifierName.Identifier, sym) Case SymbolKind.Property propertySym = DirectCast(sym, PropertySymbol) fieldOrPropType = propertySym.GetTypeFromSetMethod() ' NOTE: to match Dev10/VB behavior we intentionally do NOT check propertySym.IsWritable, ' but instead rely on presence of Set method in this particular property symbol Dim setMethod = propertySym.SetMethod isReadOnly = setMethod Is Nothing If setMethod IsNot Nothing Then ReportUseSite(diagnostics, identifierName.Identifier, setMethod) If setMethod.ParameterCount <> 1 Then ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_NoNonIndexProperty1, sym.Name) hasErrors = True End If If Not IsAccessible(setMethod, useSiteInfo) Then ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_InaccessibleMember3, propertySym.ContainingSymbol, propertySym, AccessCheck.GetAccessibilityForErrorMessage(setMethod, Me.Compilation.Assembly)) hasErrors = True End If If setMethod.IsInitOnly Then InternalSyntax.Parser.CheckFeatureAvailability(diagnostics, identifierName.Location, DirectCast(identifierName.SyntaxTree.Options, VisualBasicParseOptions).LanguageVersion, InternalSyntax.Feature.InitOnlySettersUsage) End If End If Case Else ' Must be a field or a property symbol ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_AttrAssignmentNotFieldOrProp1, identifierName.Identifier.ValueText) hasErrors = True End Select If sym.DeclaredAccessibility <> Accessibility.Public Then ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_BadAttributeNonPublicProperty1, sym.Name) hasErrors = True End If If sym.IsShared Then ' Shared attribute property cannot be the target ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_BadAttributeSharedProperty1, sym.Name) hasErrors = True End If If isReadOnly Then ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_BadAttributeReadOnlyProperty1, sym.Name) hasErrors = True End If If fieldOrPropType IsNot Nothing Then If Not IsValidTypeForAttributeArgument(fieldOrPropType) Then ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_BadAttributePropertyType1, sym.Name) hasErrors = True End If ' Convert the value to the field or property type rValue = ApplyImplicitConversion(namedArg.Expression, fieldOrPropType, rValue, diagnostics) Else rValue = MakeRValue(rValue, diagnostics) End If If propertySym IsNot Nothing Then lValue = New BoundPropertyAccess(identifierName, propertySym, Nothing, PropertyAccessKind.Set, Not isReadOnly, Nothing, ImmutableArray(Of BoundExpression).Empty, defaultArguments:=BitVector.Null, hasErrors) Debug.Assert(TypeSymbol.Equals(lValue.Type, fieldOrPropType, TypeCompareKind.ConsiderEverything)) ElseIf fieldSym IsNot Nothing Then lValue = New BoundFieldAccess(identifierName, Nothing, fieldSym, True, fieldOrPropType, hasErrors) Else lValue = BadExpression(identifierName, ErrorTypeSymbol.UnknownResultType) End If Else ' Did not find anything with that name. If result.HasDiagnostic Then ReportDiagnostic(diagnostics, identifierName, result.Diagnostic) Else ReportDiagnostic(diagnostics, identifierName, ERRID.ERR_PropertyOrFieldNotDefined1, identifierName.Identifier.ValueText) End If lValue = BadExpression(identifierName, ErrorTypeSymbol.UnknownResultType) rValue = MakeRValue(rValue, diagnostics) End If diagnostics.Add(namedArg, useSiteInfo) result.Free() Dim namedArgExpr = New BoundAssignmentOperator(namedArg, lValue, rValue, True) Return namedArgExpr End Function Private Sub MarkEmbeddedTypeReferenceIfNeeded(expression As BoundExpression) ' If we are embedding code and also there are no errors If (Me.Compilation.EmbeddedSymbolManager.Embedded <> 0) AndAlso Not expression.HasErrors Then ' And also is the expression comes from compilation syntax trees If expression.Syntax.SyntaxTree IsNot Nothing AndAlso Me.Compilation.ContainsSyntaxTree(expression.Syntax.SyntaxTree) Then ' Mark type if it is referenced in expression like 'GetType(Microsoft.VisualBasic.Strings)' If expression.Kind = BoundKind.GetType Then MarkEmbeddedTypeReferencedFromGetTypeExpression(DirectCast(expression, BoundGetType)) ElseIf expression.Kind = BoundKind.ArrayCreation Then Dim arrayCreation = DirectCast(expression, BoundArrayCreation) Dim arrayInitialization As BoundArrayInitialization = arrayCreation.InitializerOpt If arrayInitialization IsNot Nothing Then For Each initializer In arrayInitialization.Initializers MarkEmbeddedTypeReferenceIfNeeded(initializer) Next End If End If End If End If End Sub Private Sub MarkEmbeddedTypeReferencedFromGetTypeExpression(expression As BoundGetType) Dim sourceType As TypeSymbol = expression.SourceType.Type If sourceType.IsEmbedded Then ' We assume that none of embedded types references ' other embedded types in attribute values Debug.Assert(Not expression.Syntax.SyntaxTree.IsEmbeddedSyntaxTree) ' Note that none of the embedded symbols from referenced ' assemblies or compilations should be found/referenced Debug.Assert(sourceType.ContainingAssembly Is Me.Compilation.Assembly) Me.Compilation.EmbeddedSymbolManager.MarkSymbolAsReferenced(sourceType) End If End Sub ' Find the first field or property with a Set method in the result. Private Shared Function GetBestAttributeFieldOrProperty(result As LookupResult) As Symbol If result.HasSingleSymbol Then Return result.SingleSymbol End If Dim bestSym As Symbol = Nothing Dim symbols = result.Symbols For Each sym In symbols Select Case sym.Kind Case SymbolKind.Field Return sym Case SymbolKind.Property ' WARNING: This code seems to rely on an assumption that result.Symbols collection have ' symbols sorted by containing type (symbols from most-derived type first, ' then symbols from base types in order of inheritance). Thus, if we have the ' following inheritance of attribute types: ' ' D Inherits B Inherits Attribute ' ' where B defines a virtual property PROP and D overrides it, 'result.Symbols' ' will have both symbols {D.PROP, B.PROP} and we should always grab D.PROP ' ' TODO: revise bestSym = sym Dim propSym = DirectCast(sym, PropertySymbol) Dim setMethod = propSym.GetMostDerivedSetMethod() ' NOTE: Dev10 seems to grab the first property and report error in case the ' property is ReadOnly (actually, does not have Set method) ' ' TODO: check/revise If setMethod IsNot Nothing AndAlso setMethod.ParameterCount = 1 Then Return propSym End If End Select Next If bestSym Is Nothing Then Return symbols(0) End If Return bestSym End Function ' Determines if the type is a valid type for a custom attribute argument The only valid types are ' 1. primitive types except date and decimal, ' 2. object, system.type, public enumerated types ' 3. one dimensional arrays of (1) and (2) above Private Function IsValidTypeForAttributeArgument(type As TypeSymbol) As Boolean Return type.IsValidTypeForAttributeArgument(Me.Compilation) End Function #End Region #Region "AttributeExpressionVisitor" ''' <summary> ''' Walk a custom attribute argument bound node and return a TypedConstant. Verify that the expression is a constant expression. ''' </summary> ''' <remarks></remarks> Friend Structure AttributeExpressionVisitor Private ReadOnly _binder As Binder Private _hasErrors As Boolean Public Sub New(binder As Binder, hasErrors As Boolean) Me._binder = binder Me._hasErrors = hasErrors End Sub Public ReadOnly Property HasErrors As Boolean Get Return Me._hasErrors End Get End Property Public Function VisitPositionalArguments(arguments As ImmutableArray(Of BoundExpression), diag As BindingDiagnosticBag) As ImmutableArray(Of TypedConstant) Return VisitArguments(arguments, diag) End Function Private Function VisitArguments(arguments As ImmutableArray(Of BoundExpression), diag As BindingDiagnosticBag) As ImmutableArray(Of TypedConstant) Dim builder As ArrayBuilder(Of TypedConstant) = Nothing For Each exp In arguments If builder Is Nothing Then builder = ArrayBuilder(Of TypedConstant).GetInstance() End If builder.Add(VisitExpression(exp, diag)) Next If builder Is Nothing Then Return ImmutableArray(Of TypedConstant).Empty End If Return builder.ToImmutableAndFree End Function Public Function VisitNamedArguments(arguments As ImmutableArray(Of BoundExpression), diag As BindingDiagnosticBag) As ImmutableArray(Of KeyValuePair(Of String, TypedConstant)) Dim builder As ArrayBuilder(Of KeyValuePair(Of String, TypedConstant)) = Nothing For Each namedArg In arguments Dim kv = VisitNamedArgument(namedArg, diag) If kv.HasValue Then If builder Is Nothing Then builder = ArrayBuilder(Of KeyValuePair(Of String, TypedConstant)).GetInstance() End If builder.Add(kv.Value) End If Next If builder Is Nothing Then Return ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty End If Return builder.ToImmutableAndFree End Function Private Function VisitNamedArgument(argument As BoundExpression, diag As BindingDiagnosticBag) As Nullable(Of KeyValuePair(Of String, TypedConstant)) Select Case argument.Kind Case BoundKind.AssignmentOperator Dim assignment = DirectCast(argument, BoundAssignmentOperator) Select Case assignment.Left.Kind Case BoundKind.FieldAccess Dim left = DirectCast(assignment.Left, BoundFieldAccess) Return New KeyValuePair(Of String, TypedConstant)(left.FieldSymbol.Name, VisitExpression(assignment.Right, diag)) Case BoundKind.PropertyAccess Dim left = DirectCast(assignment.Left, BoundPropertyAccess) Return New KeyValuePair(Of String, TypedConstant)(left.PropertySymbol.Name, VisitExpression(assignment.Right, diag)) End Select End Select Return Nothing End Function Public Function VisitExpression(node As BoundExpression, diagBag As BindingDiagnosticBag) As TypedConstant Do If node.IsConstant Then If _binder.IsValidTypeForAttributeArgument(node.Type) Then Return CreateTypedConstant(node.Type, node.ConstantValueOpt.Value) Else Return CreateErrorTypedConstant(node.Type) End If Else Select Case node.Kind Case BoundKind.GetType Return VisitGetType(DirectCast(node, BoundGetType), diagBag) Case BoundKind.ArrayCreation Return VisitArrayCreation(DirectCast(node, BoundArrayCreation), diagBag) Case BoundKind.DirectCast Dim conv = DirectCast(node, BoundDirectCast) If conv.HasErrors OrElse Not Conversions.IsWideningConversion(conv.ConversionKind) OrElse Not _binder.IsValidTypeForAttributeArgument(conv.Operand.Type) Then If Not conv.HasErrors Then ReportDiagnostic(diagBag, conv.Operand.Syntax, ERRID.ERR_RequiredAttributeConstConversion2, conv.Operand.Type, conv.Type) End If Return CreateErrorTypedConstant(node.Type) Else node = conv.Operand End If Case BoundKind.TryCast Dim conv = DirectCast(node, BoundTryCast) If conv.HasErrors OrElse Not Conversions.IsWideningConversion(conv.ConversionKind) OrElse Not _binder.IsValidTypeForAttributeArgument(conv.Operand.Type) Then If Not conv.HasErrors Then ReportDiagnostic(diagBag, conv.Operand.Syntax, ERRID.ERR_RequiredAttributeConstConversion2, conv.Operand.Type, conv.Type) End If Return CreateErrorTypedConstant(node.Type) Else node = conv.Operand End If Case BoundKind.Conversion Dim conv = DirectCast(node, BoundConversion) If conv.HasErrors OrElse Not Conversions.IsWideningConversion(conv.ConversionKind) OrElse Not _binder.IsValidTypeForAttributeArgument(conv.Operand.Type) Then If Not conv.HasErrors Then ReportDiagnostic(diagBag, conv.Operand.Syntax, ERRID.ERR_RequiredAttributeConstConversion2, conv.Operand.Type, conv.Type) End If Return CreateErrorTypedConstant(node.Type) Else If node.Syntax.Kind = SyntaxKind.PredefinedCastExpression Then Dim cast = DirectCast(node.Syntax, PredefinedCastExpressionSyntax) If cast.Keyword.Kind = SyntaxKind.CObjKeyword Then InternalSyntax.Parser.CheckFeatureAvailability(diagBag, cast.Keyword.GetLocation(), DirectCast(cast.SyntaxTree, VisualBasicSyntaxTree).Options.LanguageVersion, InternalSyntax.Feature.CObjInAttributeArguments) End If End If node = conv.Operand End If Case BoundKind.Parenthesized node = DirectCast(node, BoundParenthesized).Expression Case BoundKind.BadExpression Return CreateErrorTypedConstant(node.Type) Case Else ReportDiagnostic(diagBag, node.Syntax, ERRID.ERR_RequiredConstExpr) Return CreateErrorTypedConstant(node.Type) End Select End If Loop End Function Private Function VisitGetType(node As BoundGetType, diagBag As BindingDiagnosticBag) As TypedConstant Dim sourceType = node.SourceType Dim getTypeArgument = sourceType.Type ' GetType argument is allowed to be: ' (a) an unbound type ' (b) a closed constructed type ' It can not be an open type. i.e. either all type arguments are missing or all type arguments do not contain any type parameter symbols. If getTypeArgument IsNot Nothing Then Dim isValidArgument = getTypeArgument.IsUnboundGenericType OrElse Not getTypeArgument.IsOrRefersToTypeParameter If Not isValidArgument Then Dim diagInfo = New BadSymbolDiagnostic(getTypeArgument, ERRID.ERR_OpenTypeDisallowed) ReportDiagnostic(diagBag, sourceType.Syntax, diagInfo) Return CreateErrorTypedConstant(node.Type) End If End If Return CreateTypedConstant(node.Type, getTypeArgument) End Function Private Function VisitArrayCreation(node As BoundArrayCreation, diag As BindingDiagnosticBag) As TypedConstant Dim type = DirectCast(node.Type, ArrayTypeSymbol) Dim values As ImmutableArray(Of TypedConstant) = Nothing Dim initializerOpt = node.InitializerOpt If initializerOpt Is Nothing OrElse initializerOpt.Initializers.Length = 0 Then If node.Bounds.Length = 1 Then Dim lastIndex = node.Bounds(0) If lastIndex.IsConstant AndAlso Not lastIndex.ConstantValueOpt.IsDefaultValue Then ' Arrays used as attribute arguments require explicitly specifying the ' values for all the elements. Note that we check this only for 1-D ' arrays because only 1-D arrays are allowed as attribute arguments. ' For all other array arguments, a more general error is given during ' normal array initializer binding. ReportDiagnostic(diag, initializerOpt.Syntax, ERRID.ERR_MissingValuesForArraysInApplAttrs) _hasErrors = True End If End If End If If initializerOpt IsNot Nothing Then values = VisitArguments(initializerOpt.Initializers, diag) End If Return CreateTypedConstant(type, values) End Function Private Shared Function CreateTypedConstant(type As ArrayTypeSymbol, array As ImmutableArray(Of TypedConstant)) As TypedConstant Return New TypedConstant(type, array) End Function Private Function CreateTypedConstant(type As TypeSymbol, value As Object) As TypedConstant Dim kind = TypedConstant.GetTypedConstantKind(type, _binder.Compilation) If kind = TypedConstantKind.Array Then Debug.Assert(value Is Nothing) Return New TypedConstant(type, Nothing) End If Return New TypedConstant(type, kind, value) End Function Private Function CreateErrorTypedConstant(type As TypeSymbol) As TypedConstant _hasErrors = True Return New TypedConstant(type, TypedConstantKind.Error, Nothing) End Function End Structure #End Region #Region "AnalyzedAttributeArguments" Private Structure AnalyzedAttributeArguments Public positionalArguments As ImmutableArray(Of BoundExpression) Public namedArguments As ImmutableArray(Of BoundExpression) Public Sub New(positionalArguments As ImmutableArray(Of BoundExpression), namedArguments As ImmutableArray(Of BoundExpression)) Me.positionalArguments = positionalArguments Me.namedArguments = namedArguments End Sub End Structure #End Region End Class End Namespace
ErikSchierboom/roslyn
src/Compilers/VisualBasic/Portable/Binding/Binder_Attributes.vb
Visual Basic
apache-2.0
49,173
' 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.Diagnostics Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Partial Friend Class TriviaDataFactory Private MustInherit Class AbstractLineBreakTrivia Inherits Whitespace Protected ReadOnly _original As String Protected ReadOnly _newString As String Public Sub New(optionSet As OptionSet, original As String, lineBreaks As Integer, indentation As Integer, elastic As Boolean) MyBase.New(optionSet, lineBreaks, indentation, elastic, LanguageNames.VisualBasic) Me._original = original Me._newString = CreateStringFromState() End Sub Protected MustOverride Function CreateStringFromState() As String Public Overrides Function WithSpace(space As Integer, context As FormattingContext, formattingRules As ChainedFormattingRules) As TriviaData Return Contract.FailWithReturn(Of TriviaData)("Should never happen") End Function Public Overrides Function WithLine(line As Integer, indentation As Integer, context As FormattingContext, formattingRules As ChainedFormattingRules, cancellationToken As CancellationToken) As TriviaData Return Contract.FailWithReturn(Of TriviaData)("Should never happen") End Function Public Overrides ReadOnly Property ContainsChanges As Boolean Get Return Not Me._original.Equals(Me._newString) OrElse Me.TreatAsElastic End Get End Property Public Overrides Function GetTextChanges(textSpan As TextSpan) As IEnumerable(Of TextChange) Return SpecializedCollections.SingletonEnumerable(New TextChange(textSpan, Me._newString)) End Function Public Overrides Sub Format(context As FormattingContext, formattingRules As ChainedFormattingRules, formattingResultApplier As Action(Of Integer, TokenStream, TriviaData), cancellationToken As CancellationToken, Optional tokenPairIndex As Integer = TokenPairIndexNotNeeded) If Me.ContainsChanges Then formattingResultApplier(tokenPairIndex, context.TokenStream, Me) End If End Sub End Class End Class End Namespace
nguerrera/roslyn
src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.AbstractLineBreakTrivia.vb
Visual Basic
apache-2.0
3,278
' 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.VisualStudio.GraphModel Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Public Class GraphNodeIdTests Private Sub AssertMarkedNodeIdIs(code As String, expectedId As String, Optional language As String = "C#", Optional symbolTransform As Func(Of ISymbol, ISymbol) = Nothing) Using testState = New ProgressionTestState( <Workspace> <Project Language=<%= language %> CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> <%= code %> </Document> </Project> </Workspace>) Dim graph = testState.GetGraphWithMarkedSymbolNode(symbolTransform) Dim node = graph.Nodes.Single() Assert.Equal(expectedId, node.Id.ToString()) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub SimpleType() AssertMarkedNodeIdIs("namespace N { class $$C { } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C)") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub NestedType() AssertMarkedNodeIdIs("namespace N { class C { class $$E { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=E ParentType=C))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub MemberWithSimpleArrayType() AssertMarkedNodeIdIs( "namespace N { class C { void $$M(int[] p) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Int32 ArrayRank=1 ParentType=Int32))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub MemberWithNestedArrayType() AssertMarkedNodeIdIs( "namespace N { class C { void $$M(int[][,] p) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Int32 ArrayRank=1 ParentType=(Name=Int32 ArrayRank=2 ParentType=Int32)))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub MemberWithPointerType() AssertMarkedNodeIdIs( "namespace N { class C { struct S { } unsafe void $$M(S** p) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=S Indirection=2 ParentType=C))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub MemberWithVoidPointerType() AssertMarkedNodeIdIs( "namespace N { class C { unsafe void $$M(void* p) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Void Indirection=1))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub MemberWithGenericTypeParameters() AssertMarkedNodeIdIs( "namespace N { class C<T> { void $$M<U>(T t, U u) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0),(ParameterIdentifier=0)]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(547263)> Sub MemberWithParameterTypeConstructedWithMemberTypeParameter() AssertMarkedNodeIdIs( "namespace N { class C { void $$M<T>(T t, System.Func<T, int> u) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(ParameterIdentifier=0),(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Func GenericParameterCount=2 GenericArguments=[(ParameterIdentifier=0),(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=Int32)]))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub MemberWithArraysOfGenericTypeParameters() AssertMarkedNodeIdIs( "namespace N { class C<T> { void $$M<U>(T[] t, U[] u) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0))),(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ParameterIdentifier=0)))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub MemberWithArraysOfGenericTypeParameters2() AssertMarkedNodeIdIs( "namespace N { class C<T> { void $$M<U>(T[][,] t, U[][,] u) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ArrayRank=2 ParentType=(Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0)))),(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ArrayRank=2 ParentType=(ParameterIdentifier=0))))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Sub MemberWithGenericType() AssertMarkedNodeIdIs( "namespace N { class C { void $$M(System.Collections.Generic.List<int> p) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System.Collections.Generic Type=(Name=List GenericParameterCount=1 GenericArguments=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=Int32)]))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(616549)> Sub MemberWithDynamicType() AssertMarkedNodeIdIs( "namespace N { class C { void $$M(dynamic d) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Namespace=System Type=Object)]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(616549)> Sub MemberWithGenericTypeOfDynamicType() AssertMarkedNodeIdIs( "namespace N { class C { void $$M(System.Collections.Generic.List<dynamic> p) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System.Collections.Generic Type=(Name=List GenericParameterCount=1 GenericArguments=[(Namespace=System Type=Object)]))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(616549)> Sub MemberWithArrayOfDynamicType() AssertMarkedNodeIdIs( "namespace N { class C { void $$M(dynamic[] d) { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Namespace=System Type=(Name=Object ArrayRank=1 ParentType=Object))]))") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(547234)> Sub ErrorType() AssertMarkedNodeIdIs( "Class $$C : Inherits D : End Class", "Type=D", LanguageNames.VisualBasic, Function(s) DirectCast(s, INamedTypeSymbol).BaseType) End Sub End Class End Namespace
DavidKarlas/roslyn
src/VisualStudio/Core/Test/Progression/GraphNodeIdTests.vb
Visual Basic
apache-2.0
8,596
' 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.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Roslyn.Diagnostics.Analyzers.VisualBasic <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Public Class BasicSymbolDeclaredEventAnalyzer Inherits SymbolDeclaredEventAnalyzer(Of SyntaxKind) Private Shared ReadOnly sourceModuleTypeFullName As String = "Microsoft.CodeAnalysis.VisualBasic.Symbols.SourceModuleSymbol" Protected Overrides Function GetCompilationAnalyzer(compilation As Compilation, symbolType As INamedTypeSymbol) As CompilationAnalyzer Dim compilationType = compilation.GetTypeByMetadataName(GetType(VisualBasicCompilation).FullName) If compilationType Is Nothing Then Return Nothing End If Dim sourceModuleType = compilation.GetTypeByMetadataName(sourceModuleTypeFullName) If sourceModuleType Is Nothing Then Return Nothing End If Return New BasicCompilationAnalyzer(symbolType, compilationType, sourceModuleType) End Function Protected Overrides ReadOnly Property InvocationExpressionSyntaxKind As SyntaxKind Get Return SyntaxKind.InvocationExpression End Get End Property Private NotInheritable Class BasicCompilationAnalyzer Inherits CompilationAnalyzer Private ReadOnly sourceModuleType As INamedTypeSymbol Private Shared ReadOnly _symbolTypesWithExpectedSymbolDeclaredEvent As HashSet(Of String) = New HashSet(Of String) From {"SourceNamespaceSymbol", "SourceNamedTypeSymbol", "SourceEventSymbol", "SourceFieldSymbol", "SourceMethodSymbol", "SourcePropertySymbol"} Private Const AtomicSetFlagAndRaiseSymbolDeclaredEventName As String = "AtomicSetFlagAndRaiseSymbolDeclaredEvent" Public Sub New(symbolType As INamedTypeSymbol, compilationType As INamedTypeSymbol, sourceModuleSymbol As INamedTypeSymbol) MyBase.New(symbolType, compilationType) Me.sourceModuleType = sourceModuleSymbol End Sub Protected Overrides ReadOnly Property SymbolTypesWithExpectedSymbolDeclaredEvent As HashSet(Of String) Get Return _symbolTypesWithExpectedSymbolDeclaredEvent End Get End Property Protected Overrides Function GetFirstArgumentOfInvocation(node As SyntaxNode) As SyntaxNode Dim invocation = DirectCast(node, InvocationExpressionSyntax) If invocation.ArgumentList IsNot Nothing Then Dim argument = invocation.ArgumentList.Arguments.FirstOrDefault() If argument IsNot Nothing Then Return argument.GetExpression End If End If Return Nothing End Function Friend Overrides Sub AnalyzeMethodInvocation(invocationSymbol As IMethodSymbol, context As SyntaxNodeAnalysisContext) If invocationSymbol.Name.Equals(AtomicSetFlagAndRaiseSymbolDeclaredEventName, StringComparison.OrdinalIgnoreCase) AndAlso sourceModuleType.Equals(invocationSymbol.ContainingType) Then Dim argumentOpt As SyntaxNode = Nothing Dim invocationExp = DirectCast(context.Node, InvocationExpressionSyntax) If invocationExp.ArgumentList IsNot Nothing Then For Each argument In invocationExp.ArgumentList.Arguments If AnalyzeSymbolDeclaredEventInvocation(argument.GetExpression, context) Then Exit For End If Next End If End If MyBase.AnalyzeMethodInvocation(invocationSymbol, context) End Sub End Class End Class End Namespace
JohnHamby/roslyn
src/Diagnostics/Roslyn/VisualBasic/Reliability/BasicSymbolDeclaredEventAnalyzer.vb
Visual Basic
apache-2.0
4,257
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Imports Microsoft.CodeAnalysis.Snippets Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion Public Class CSharpCompletionSnippetNoteTests Private _markup As XElement = <document> <![CDATA[using System; class C { $$ void M() { } }]]></document> <WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SnippetExpansionNoteAddedToDescription_ExactMatch() As Task Using state = CreateCSharpSnippetExpansionNoteTestState(_markup, "interface") state.SendTypeChars("interfac") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem(description:="title" & vbCrLf & "description" & vbCrLf & String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "interface")) End Using End Function <WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SnippetExpansionNoteAddedToDescription_DifferentSnippetShortcutCasing() As Task Using state = CreateCSharpSnippetExpansionNoteTestState(_markup, "intErfaCE") state.SendTypeChars("interfac") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem(description:=$"{String.Format(FeaturesResources._0_Keyword, "interface")} {String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "interface")}") End Using End Function <WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Sub SnippetExpansionNoteNotAddedToDescription_ShortcutIsProperSubstringOfInsertedText() Using state = CreateCSharpSnippetExpansionNoteTestState(_markup, "interfac") state.SendTypeChars("interfac") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem(description:="title" & vbCrLf & "description" & vbCrLf & String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "interfac")) End Using End Sub <WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Sub SnippetExpansionNoteNotAddedToDescription_ShortcutIsProperSuperstringOfInsertedText() Using state = CreateCSharpSnippetExpansionNoteTestState(_markup, "interfaces") state.SendTypeChars("interfac") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources._0_Keyword, "interface")) End Using End Sub <WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Sub SnippetExpansionNoteAddedToDescription_DisplayTextDoesNotMatchShortcutButInsertionTextDoes() Using state = CreateCSharpSnippetExpansionNoteTestState(_markup, "InsertionText") state.SendTypeChars("DisplayTex") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "InsertionText")) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.Interactive)> Public Async Function SnippetExpansionNoteNotAddedToDescription_Interactive() As Task Dim workspaceXml = <Workspace> <Submission Language="C#" CommonReferences="true"> $$ </Submission> </Workspace> Using state = TestState.CreateTestStateFromWorkspace( workspaceXml, New CompletionProvider() {New MockCompletionProvider()}, Nothing, New List(Of Type) From {GetType(TestCSharpSnippetInfoService)}, WorkspaceKind.Interactive) Dim testSnippetInfoService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService(Of ISnippetInfoService)(), TestCSharpSnippetInfoService) testSnippetInfoService.SetSnippetShortcuts({"for"}) state.Workspace.Options = state.Workspace.Options.WithChangedOption(InternalFeatureOnOffOptions.Snippets, False) state.SendTypeChars("for") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources._0_Keyword, "for")) End Using End Function Private Function CreateCSharpSnippetExpansionNoteTestState(xElement As XElement, ParamArray snippetShortcuts As String()) As TestState Dim state = TestState.CreateCSharpTestState( xElement, New CompletionProvider() {New MockCompletionProvider()}, Nothing, New List(Of Type) From {GetType(TestCSharpSnippetInfoService)}) Dim testSnippetInfoService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService(Of ISnippetInfoService)(), TestCSharpSnippetInfoService) testSnippetInfoService.SetSnippetShortcuts(snippetShortcuts) Return state End Function End Class End Namespace
MatthieuMEZIL/roslyn
src/VisualStudio/Core/Test/Completion/CSharpCompletionSnippetNoteTests.vb
Visual Basic
apache-2.0
6,440
' 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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the ByVal, ByRef, etc keywords. ''' </summary> Friend Class ParameterModifiersKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End If Dim targetToken = context.TargetToken Dim methodDeclaration = targetToken.GetAncestor(Of MethodBaseSyntax)() If methodDeclaration Is Nothing OrElse methodDeclaration.ParameterList Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End If Dim parameterAlreadyHasByValOrByRef = False If targetToken.GetAncestor(Of ParameterSyntax)() IsNot Nothing Then parameterAlreadyHasByValOrByRef = targetToken.GetAncestor(Of ParameterSyntax)().Modifiers.Any(Function(m) m.IsKind(SyntaxKind.ByValKeyword, SyntaxKind.ByRefKeyword)) End If ' Compute some basic properties of what is allowed at all in this context Dim byRefAllowed = Not TypeOf methodDeclaration Is AccessorStatementSyntax AndAlso methodDeclaration.Kind <> SyntaxKind.PropertyStatement AndAlso methodDeclaration.Kind <> SyntaxKind.OperatorStatement Dim optionalAndParamArrayAllowed = Not TypeOf methodDeclaration Is DelegateStatementSyntax AndAlso Not TypeOf methodDeclaration Is LambdaHeaderSyntax AndAlso Not TypeOf methodDeclaration Is AccessorStatementSyntax AndAlso methodDeclaration.Kind <> SyntaxKind.EventStatement AndAlso methodDeclaration.Kind <> SyntaxKind.OperatorStatement ' Compute a simple list of the "standard" recommendations assuming nothing special is going on Dim defaultRecommendations As New List(Of RecommendedKeyword) defaultRecommendations.Add(New RecommendedKeyword("ByVal", VBFeaturesResources.Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code)) If byRefAllowed Then defaultRecommendations.Add(New RecommendedKeyword("ByRef", VBFeaturesResources.Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code)) End If If optionalAndParamArrayAllowed Then defaultRecommendations.Add(New RecommendedKeyword("Optional", VBFeaturesResources.Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called)) defaultRecommendations.Add(New RecommendedKeyword("ParamArray", VBFeaturesResources.Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type)) End If If methodDeclaration.ParameterList.OpenParenToken = targetToken Then Return defaultRecommendations ElseIf targetToken.Kind = SyntaxKind.CommaToken AndAlso targetToken.Parent.Kind = SyntaxKind.ParameterList Then ' Now we get to look at previous declarations and see what might still be valid For Each parameter In methodDeclaration.ParameterList.Parameters.Where(Function(p) p.FullSpan.End < context.Position) ' If a previous one had a ParamArray, then nothing is valid anymore, since the ParamArray must ' always be the last parameter If parameter.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.ParamArrayKeyword) Then Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End If ' If a previous one had an Optional, then all following must be optional. Following Dev10 behavior, ' we recommend just Optional as a first recommendation If parameter.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.OptionalKeyword) AndAlso optionalAndParamArrayAllowed Then Return defaultRecommendations.Where(Function(k) k.Keyword = "Optional") End If Next ' We had no special requirements, so return the default set Return defaultRecommendations ElseIf targetToken.Kind = SyntaxKind.OptionalKeyword AndAlso Not parameterAlreadyHasByValOrByRef Then Return defaultRecommendations.Where(Function(k) k.Keyword.StartsWith("By", StringComparison.Ordinal)) ElseIf targetToken.Kind = SyntaxKind.ParamArrayKeyword AndAlso Not parameterAlreadyHasByValOrByRef Then Return defaultRecommendations.Where(Function(k) k.Keyword = "ByVal") End If Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End Function End Class End Namespace
panopticoncentral/roslyn
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/ParameterModifiersKeywordRecommender.vb
Visual Basic
mit
5,842
Imports FluentAssertions Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports System.Collections.Immutable Imports Xunit Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports CodeCracker.VisualBasic Public Class GeneratedCodeAnalysisExtensionsTests Private Const baseProjectPath = "D:\ClassLibrary11\" <Theory> <InlineData(baseProjectPath + "A.g.VB")> <InlineData(baseProjectPath + "A.g.vb")> <InlineData(baseProjectPath + "B.g.vb")> <InlineData(baseProjectPath + "A.g.i.vb")> <InlineData(baseProjectPath + "B.g.i.vb")> <InlineData(baseProjectPath + "A.designer.vb")> <InlineData(baseProjectPath + "A.generated.vb")> <InlineData(baseProjectPath + "B.generated.vb")> <InlineData(baseProjectPath + "AssemblyInfo.vb")> <InlineData(baseProjectPath + "A.AssemblyAttributes.vb")> <InlineData(baseProjectPath + "B.AssemblyAttributes.vb")> <InlineData(baseProjectPath + "AssemblyAttributes.vb")> <InlineData(baseProjectPath + "Service.vb")> <InlineData(baseProjectPath + "TemporaryGeneratedFile_.vb")> <InlineData(baseProjectPath + "TemporaryGeneratedFile_A.vb")> <InlineData(baseProjectPath + "TemporaryGeneratedFile_B.vb")> Public Sub IsOnGeneratedFile(fileName As String) fileName.IsOnGeneratedFile().Should().BeTrue() End Sub <Theory> <InlineData(baseProjectPath + "TheAssemblyInfo.vb")> <InlineData(baseProjectPath + "A.vb")> <InlineData(baseProjectPath + "TheTemporaryGeneratedFile_A.vb")> <InlineData(baseProjectPath + "TheService.vb")> <InlineData(baseProjectPath + "TheAssemblyAttributes.vb")> Public Sub IsNotOnGeneratedFile(fileName As String) fileName.IsOnGeneratedFile().Should().BeFalse() End Sub <Fact> Public Sub IsContextOnGeneratedFile() Dim context As SyntaxNodeAnalysisContext = GetContext( "Class TypeName End Class", baseProjectPath + "TemporaryGeneratedFile_.vb") context.IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData("<System.Diagnostics.DebuggerNonUserCode> Class TypeName End Class")> <InlineData("<System.Diagnostics.DebuggerNonUserCodeAttribute> Class TypeName End Class")> Public Sub HasDebuggerNonUserCodeAttributeOnAClass(source As String) GetContext(Of ClassBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData("<System.Diagnostics.DebuggerNonUserCode> Module TypeName End Module")> <InlineData("<System.Diagnostics.DebuggerNonUserCodeAttribute> Module TypeName End Module")> Public Sub HasDebuggerNonUserCodeAttributeOnAModule(source As String) GetContext(Of ModuleBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName <System.Diagnostics.DebuggerNonUserCode> Sub Foo() End Sub End Class")> <InlineData( "Class TypeName <System.Diagnostics.DebuggerNonUserCodeAttribute> Sub Foo() End Sub End Class")> Public Sub HasDebuggerNonUserCodeAttributeOnAMethod(source As String) GetContext(Of MethodBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName <System.Diagnostics.DebuggerNonUserCode> Sub Foo() System.Console.WriteLine(1) End Sub End Class")> <InlineData( "Class TypeName <System.Diagnostics.DebuggerNonUserCodeAttribute> Sub Foo() System.Console.WriteLine(1) End Sub End Class")> Public Sub HasDebuggerNonUserCodeAttributeOnAStatementWithinAMethod(source As String) GetContext(Of InvocationExpressionSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName <System.Diagnostics.DebuggerNonUserCode> Property Foo As Integer End Class")> <InlineData( "Class TypeName <System.Diagnostics.DebuggerNonUserCodeAttribute> Property Foo As Integer End Class")> Public Sub HasDebuggerNonUserCodeAttributeOnAProperty(source As String) GetContext(Of PropertyStatementSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName Private _foo As Integer <System.Diagnostics.DebuggerNonUserCode> Public ReadOnly Property Foo() As Integer Get Return _foo End Get End Property End Class")> <InlineData( "Class TypeName Private _foo As Integer <System.Diagnostics.DebuggerNonUserCodeAttribute> Public ReadOnly Property Foo() As Integer Get Return _foo End Get End Property End Class")> Public Sub HasDebuggerNonUserCodeAttributeOnAPropertyCheckingTheGet(source As String) GetContext(Of AccessorBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName Private _foo As Integer Public ReadOnly Property Foo() As Integer <System.Diagnostics.DebuggerNonUserCode> Get Return _foo End Get End Property End Class")> <InlineData( "Class TypeName Private _foo As Integer Public ReadOnly Property Foo() As Integer <System.Diagnostics.DebuggerNonUserCodeAttribute> Get Return _foo End Get End Property End Class")> Public Sub HasDebuggerNonUserCodeAttributeOnAPropertyGet(source As String) GetContext(Of AccessorBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName Private _foo As Integer Public WriteOnly Property Foo() As Integer <System.Diagnostics.DebuggerNonUserCode> Set(ByVal value As Integer) _foo = value End Set End Property End Class")> <InlineData( "Class TypeName Private _foo As Integer Public WriteOnly Property Foo() As Integer <System.Diagnostics.DebuggerNonUserCodeAttribute> Set(ByVal value As Integer) _foo = value End Set End Property End Class")> Public Sub HasDebuggerNonUserCodeAttributeOnAPropertySet(source As String) GetContext(Of AccessorBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData("<System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> Class TypeName End Class")> <InlineData("<System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> Class TypeName End Class")> Public Sub HasGeneratedCodeAttributeOnAClass(source As String) GetContext(Of ClassBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData("<System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> Interface ITypeName End Interface")> <InlineData("<System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> Interface ITypeName End Interface")> Public Sub HasGeneratedCodeAttributeOnAnInterface(source As String) GetContext(Of InterfaceBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "<System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> Enum A a End Enum")> <InlineData( "<System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> Enum A a End Enum")> Public Sub HasGeneratedCodeAttributeOnEnum(source As String) GetContext(Of EnumBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName <System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> private i as Integer End Class")> <InlineData( "Class TypeName <System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> private i as Integer End Class")> Public Sub HasGeneratedCodeAttributeOnAField(source As String) GetContext(Of FieldDeclarationSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName <System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> Event a As Action End Class")> <InlineData( "Class TypeName <System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> Event a As Action End Class")> Public Sub HasGeneratedCodeAttributeOnAnEvent(source As String) GetContext(Of EventStatementSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName public Sub Foo(<System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> i as Integer) End Sub End Class")> <InlineData( "Class TypeName public Sub Foo(<System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> i as Integer) End Sub End Class")> Public Sub HasGeneratedCodeAttributeOnParameter(source As String) GetContext(Of ParameterSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName <System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> Delegate Sub A() End Class")> <InlineData( "Class TypeName <System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> Delegate Sub A() End Class")> Public Sub HasGeneratedCodeAttributeOnDelegate(source As String) GetContext(Of DelegateStatementSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "<System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> Class TypeName Structure Nested End Structure End Class")> <InlineData( "<System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> Class TypeName Structure Nested End Structure End Class")> Public Sub HasGeneratedCodeAttributeOnNestedClass(source As String) GetContext(Of StructureBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList <System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> Public Custom Event Click As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class")> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList <System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> Public Custom Event Click As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class")> Public Sub HasGeneratedCodeAttributeOnCustomEvent(source As String) GetContext(Of EventStatementSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList <System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> Public Custom Event Click As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class")> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList <System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> Public Custom Event Click As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class")> Public Sub HasGeneratedCodeAttributeOnCustomEventInsideAccessor(source As String) GetContext(Of AccessorBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList Public Custom Event Click As EventHandler <System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class")> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList Public Custom Event Click As EventHandler <System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class")> Public Sub HasGeneratedCodeAttributeOnCustomEventAdd(source As String) GetContext(Of AccessorBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList Public Custom Event Click As EventHandler <System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> RemoveHandler(ByVal value As EventHandler) End RemoveHandler AddHandler(ByVal value As EventHandler) End AddHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class")> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList Public Custom Event Click As EventHandler <System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> RemoveHandler(ByVal value As EventHandler) End RemoveHandler AddHandler(ByVal value As EventHandler) End AddHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class")> Public Sub HasGeneratedCodeAttributeOnCustomEventRemove(source As String) GetContext(Of AccessorBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Theory> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList Public Custom Event Click As EventHandler <System.CodeDom.Compiler.GeneratedCode(Nothing, Nothing)> RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler End Event End Class")> <InlineData( "Class TypeName Private Events As New System.ComponentModel.EventHandlerList Public Custom Event Click As EventHandler <System.CodeDom.Compiler.GeneratedCodeAttribute(Nothing, Nothing)> RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler End Event End Class")> Public Sub HasGeneratedCodeAttributeOnCustomEventRaise(source As String) GetContext(Of AccessorBlockSyntax)(source).IsGenerated().Should().BeTrue() End Sub <Fact> Public Sub WithAutoGeneratedCommentBasedOnWebForms() GetContext(Of ClassBlockSyntax)( "'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Partial Public Class _Default End Class").IsGenerated().Should().BeTrue() End Sub <Fact> Public Sub WithAutoGeneratedCommentEmpty() GetContext( "'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------").IsGenerated().Should().BeTrue() End Sub Private Shared Function GetContext(code As String, Optional fileName As String = baseProjectPath + "a.vb") As SyntaxNodeAnalysisContext Return GetContext(Of CompilationUnitSyntax)(code, fileName) End Function Private Shared Function GetContext(Of T As SyntaxNode)(code As String, Optional fileName As String = baseProjectPath + "a.vb") As SyntaxNodeAnalysisContext Dim tree = SyntaxFactory.ParseSyntaxTree(code, path:=fileName) Dim compilation = VisualBasicCompilation.Create("comp.dll", New SyntaxTree() {tree}) Dim root = tree.GetRoot() Dim semanticModel = compilation.GetSemanticModel(tree) Dim analyzerOptions = New AnalyzerOptions(ImmutableArray(Of AdditionalText).Empty) Dim node = root.DescendantNodesAndSelf().OfType(Of T)().First() Dim context = New SyntaxNodeAnalysisContext(node, semanticModel, analyzerOptions, Sub(diag) End Sub, Function(diag) Return True End Function, Nothing) Return context End Function End Class
ElemarJR/code-cracker
test/VisualBasic/CodeCracker.Test/GeneratedCodeAnalysisExtensionsTests.vb
Visual Basic
apache-2.0
18,711
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo Imports Microsoft.CodeAnalysis.Test.Utilities.QuickInfo Imports Microsoft.VisualStudio.Core.Imaging Imports Microsoft.VisualStudio.Imaging Imports Microsoft.VisualStudio.Text.Adornments Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Public Class IntellisenseQuickInfoBuilderTests_Links Inherits AbstractIntellisenseQuickInfoBuilderTests <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)> <InlineData("see")> <InlineData("a")> Public Async Function QuickInfoForPlainHyperlink(tag As String) As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// This contains a link to &lt;<%= tag %> href="https://github.com/dotnet/roslyn"/&gt;. /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "This contains a link to"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "https://github.com/dotnet/roslyn", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(New Uri("https://github.com/dotnet/roslyn", UriKind.Absolute)), "https://github.com/dotnet/roslyn"), New ClassifiedTextRun(ClassificationTypeNames.Text, ".")))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)> <InlineData("see")> <InlineData("a")> Public Async Function QuickInfoForHyperlinkWithText(tag As String) As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// This contains a link to &lt;<%= tag %> href="https://github.com/dotnet/roslyn"&gt;dotnet/roslyn&lt;/<%= tag %>&gt;. /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "This contains a link to"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "dotnet/roslyn", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(New Uri("https://github.com/dotnet/roslyn", UriKind.Absolute)), "https://github.com/dotnet/roslyn"), New ClassifiedTextRun(ClassificationTypeNames.Text, ".")))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function End Class End Namespace
physhi/roslyn
src/EditorFeatures/Test2/IntelliSense/IntellisenseQuickInfoBuilderTests_Links.vb
Visual Basic
apache-2.0
6,719
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class TryCastExpressionDocumentation Inherits AbstractCastExpressionDocumentation Public Overrides ReadOnly Property DocumentationText As String Get Return VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return { New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "TryCast"), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(") } End Get End Property End Class End Namespace
sharwell/roslyn
src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/TryCastExpressionDocumentation.vb
Visual Basic
mit
1,128
' 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.ImportsKeywordRecommender Public Class OptionKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsInBlankFile() VerifyRecommendationsContain(<File>|</File>, "Imports") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsAfterAnotherImportsStatement() VerifyRecommendationsContain(<File> Imports Bar |</File>, "Imports") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsAfterXmlImports() VerifyRecommendationsContain(<File> Imports &lt;xmlns:test="http://tempuri.org"&gt; |</File>, "Imports") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsAfterBlankLineAfterImports() VerifyRecommendationsContain(<File> Imports Bar |</File>, "Imports") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsAfterBlankLineAfterXmlImports() VerifyRecommendationsContain(<File> Imports &lt;xmlns:test="http://tempuri.org"&gt; |</File>, "Imports") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsAfterOptionStatement() VerifyRecommendationsContain(<File> Option Strict On |</File>, "Imports") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsAfterBlankLineAfterOptionStatement() VerifyRecommendationsContain(<File> Option Strict On |</File>, "Imports") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsNotBeforeOptionStatement() VerifyRecommendationsMissing(<File> | Option Strict On </File>, "Imports") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ImportsNotAfterType() VerifyRecommendationsMissing(<File> Class Foo End Class |</File>, "Imports") End Sub End Class End Namespace
droyad/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ImportsKeywordRecommenderTests.vb
Visual Basic
apache-2.0
2,748
' Written by Michael Kellar ' 10/8/2015 Option Strict On Option Explicit On Public Class Form1 ' Class-level constants Const dblMONTHS_YEAR As Double = 12 ' Months per year Const dblNEW_RATE As Double = 0.05 ' Interest rate, new cars Const dblUSED_RATE As Double = 0.08 ' Interest rate, used cars ' Class-level variable to hold the annual interest rate Dim dblAnnualRate As Double = dblNEW_RATE Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click Dim dblVehicleCost As Double ' Vehicle cost Dim dblDownPayment As Double ' Down payment Dim intMonths As Integer ' Number of months for the loan Dim dblLoan As Double ' Amount of the loan Dim dblMonthlyPayment As Double ' Monthly payment Dim dblInterest As Double ' Interest paid for the period Dim dblPrincipal As Double ' Principal paid for the period Dim intCount As Integer ' Counter for the loop Dim strOut As String ' Used to hold a line of output Dim blnInputOk As Boolean = True ' Get the vehicle cost, validating at the same time.- If Not Double.TryParse(txtCost.Text, dblVehicleCost) Then lblMessage.Text = "Vehicle cost must be a number" blnInputOk = False End If ' Get the down payment, validating at the same time. If Not Double.TryParse(txtDownPayment.Text, dblDownPayment) Then lblMessage.Text = "Down Payment must be a number" blnInputOk = False End If ' Get the number of months, validating at the same time. If Not Integer.TryParse(txtMonths.Text, intMonths) Then lblMessage.Text = "Months must be an integer" blnInputOk = False End If If blnInputOk = True Then ' Calculate the loan amount and monthly payment. dblLoan = dblVehicleCost - dblDownPayment dblMonthlyPayment = Pmt(dblAnnualRate / dblMONTHS_YEAR, intMonths, -dblLoan) ' Clear the list box and message label. lstOutput.Items.Clear() lblMessage.Text = String.Empty For intCount = 1 To intMonths ' Calculate the interest for this period. dblInterest = IPmt(dblAnnualRate / dblMONTHS_YEAR, intCount, intMonths, -dblLoan) ' Calculate the principal for this period. dblPrincipal = PPmt(dblAnnualRate / dblMONTHS_YEAR, intCount, intMonths, -dblLoan) ' Start building the output string strOut = "Month " & intCount.ToString("d2") ' Add the payment amount to the output string. strOut &= ": payment = " & dblMonthlyPayment.ToString("n2") ' Add the interest amount to the output string. strOut &= ", interest = " & dblInterest.ToString("n2") ' Add the principal for the period. strOut &= ", principal = " & dblPrincipal.ToString("n2") ' Add the output string to the list box lstOutput.Items.Add(strOut) Next End If End Sub Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click ' Reset the interest rate, clear the text boxes, the ' list box, and the message label. Set default interest ' rate for our new car loans. radNew.Checked = True dblAnnualRate = dblNEW_RATE lblAnnualRate.Text = dblNEW_RATE.ToString("p") txtCost.Clear() txtDownPayment.Clear() txtMonths.Clear() lstOutput.Items.Clear() lblMessage.Text = String.Empty ' Reset the focus to txtCost. txtCost.Focus() End Sub Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click ' Close the form. Me.Close() End Sub Private Sub radNew_CheckedChanged(sender As Object, e As EventArgs) Handles radNew.CheckedChanged ' If the New radio button is checked, then ' the user has selected a new car loan. If radNew.Checked = True Then dblAnnualRate = dblNEW_RATE lblAnnualRate.Text = dblNEW_RATE.ToString("p") lstOutput.Items.Clear() End If End Sub Private Sub radUsed_CheckedChanged(sender As Object, e As EventArgs) Handles radUsed.CheckedChanged ' If the New radio button is checked, then ' the user has selected a new car loan. If radUsed.Checked = True Then dblAnnualRate = dblUSED_RATE lblAnnualRate.Text = dblUSED_RATE.ToString("p") lstOutput.Items.Clear() End If End Sub End Class
Shadorunce/MiniProjects
Vehicle Loan/VehicleLoanFiles/Form1.vb
Visual Basic
mit
4,978
'------------------------------------------------------------------------------ ' <auto-generated> ' 此代码由工具生成。 ' 运行时版本:4.0.30319.42000 ' ' 对此文件的更改可能会导致不正确的行为,并且如果 ' 重新生成代码,这些更改将会丢失。 ' </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()> _ Public 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)> _ Public 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("ballance_tools.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)> _ Public Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
yyc12345/ballance_tools
ballance_tools/My Project/Resources.Designer.vb
Visual Basic
mit
2,732
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "fTarjetas" '-------------------------------------------------------------------------------------------' Partial Class fTarjetas Inherits vis2Formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine("SELECT Tarjetas.Cod_Tar,") loComandoSeleccionar.AppendLine(" (CASE Tarjetas.status") loComandoSeleccionar.AppendLine(" WHEN 'A' THEN 'ACTIVO'") loComandoSeleccionar.AppendLine(" WHEN 'I' THEN 'INACTIVO'") loComandoSeleccionar.AppendLine(" WHEN 'S' THEN 'SUSPENDIDO'") loComandoSeleccionar.AppendLine(" END) AS status,") loComandoSeleccionar.AppendLine(" Tarjetas.nom_tar,") loComandoSeleccionar.AppendLine(" Tarjetas.telefonos,") loComandoSeleccionar.AppendLine(" Tarjetas.cod_tip AS tip_cod,") loComandoSeleccionar.AppendLine(" Tipos_Tarjetas.nom_tip AS tip_nom,") loComandoSeleccionar.AppendLine(" (CASE Tarjetas.tip_tar") loComandoSeleccionar.AppendLine(" WHEN 'C' THEN 'CREDITO'") loComandoSeleccionar.AppendLine(" WHEN 'D' THEN 'DEBITO'") loComandoSeleccionar.AppendLine(" END) AS tip_tar,") loComandoSeleccionar.AppendLine(" Tarjetas.cod_ban,") loComandoSeleccionar.AppendLine(" Bancos.nom_ban,") loComandoSeleccionar.AppendLine(" Tarjetas.cod_cue,") loComandoSeleccionar.AppendLine(" Cuentas_Bancarias.nom_cue,") loComandoSeleccionar.AppendLine(" Tarjetas.Clave,") loComandoSeleccionar.AppendLine(" Tarjetas.dep_dir,") loComandoSeleccionar.AppendLine(" Tarjetas.por_rec,") loComandoSeleccionar.AppendLine(" Tarjetas.mon_rec,") loComandoSeleccionar.AppendLine(" Tarjetas.por_com,") loComandoSeleccionar.AppendLine(" Tarjetas.mon_com,") loComandoSeleccionar.AppendLine(" Tarjetas.por_imp,") loComandoSeleccionar.AppendLine(" Tarjetas.por_ret,") loComandoSeleccionar.AppendLine(" Tarjetas.comentario") loComandoSeleccionar.AppendLine("FROM Tarjetas") loComandoSeleccionar.AppendLine(" JOIN Tipos_Tarjetas ON Tipos_Tarjetas.cod_tip = Tarjetas.cod_tip") loComandoSeleccionar.AppendLine(" JOIN bancos ON Bancos.cod_ban = Tarjetas.cod_ban") loComandoSeleccionar.AppendLine(" JOIN Cuentas_Bancarias ON Cuentas_Bancarias.cod_cue = Tarjetas.cod_cue ") loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) 'Me.mEscribirConsulta(loComandoSeleccionar.ToString()) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") '--------------------------------------------------' ' Carga la imagen del logo en cusReportes ' '--------------------------------------------------' Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa") '------------------------------------------------------------------------------------------------------- ' Verificando si el select (tabla nº0) trae registros '------------------------------------------------------------------------------------------------------- If (laDatosReporte.Tables(0).Rows.Count <= 0) Then Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _ "No se Encontraron Registros para los Parámetros Especificados. ", _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _ "350px", _ "200px") End If loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fTarjetas", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvfTarjetas.ReportSource = loObjetoReporte Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload Try loObjetoReporte.Close() Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo '-------------------------------------------------------------------------------------------' ' EAG: 31/08/2015 : Codigo inicial '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
fTarjetas.aspx.vb
Visual Basic
mit
6,144
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class OverviewForm Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(OverviewForm)) Me.RefreshTimer = New System.Windows.Forms.Timer(Me.components) Me.BackgroundPanel = New System.Windows.Forms.Panel() Me.WindowsUserListView = New System.Windows.Forms.ListView() Me.UsernameColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.DrivesListView = New System.Windows.Forms.ListView() Me.PartitionColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.TypeColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.FileSystemColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.TotalSpaceColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.FreeSpaceColumnHeader = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.NetworkGroupBox = New System.Windows.Forms.GroupBox() Me.InternalIPLabel = New System.Windows.Forms.Label() Me.ExternalIPLabel = New System.Windows.Forms.Label() Me.InternalIPLabelText = New System.Windows.Forms.Label() Me.ExternalIPLabelText = New System.Windows.Forms.Label() Me.BasicGroupBox = New System.Windows.Forms.GroupBox() Me.CPUUsageLabel = New System.Windows.Forms.Label() Me.CPUUsageLabelText = New System.Windows.Forms.Label() Me.AvailableMemoryLabel = New System.Windows.Forms.Label() Me.OperatingSystemLabel = New System.Windows.Forms.Label() Me.AvailableMemoryLabelText = New System.Windows.Forms.Label() Me.ComputerNameLabel = New System.Windows.Forms.Label() Me.OperatingSystemLabelText = New System.Windows.Forms.Label() Me.ComputerNameLabelText = New System.Windows.Forms.Label() Me.BottomPanel = New System.Windows.Forms.Panel() Me.CloseButton = New System.Windows.Forms.Button() Me.ExitButton = New System.Windows.Forms.Button() Me.FormTitleLabel = New System.Windows.Forms.Label() Me.BackgroundPanel.SuspendLayout() Me.NetworkGroupBox.SuspendLayout() Me.BasicGroupBox.SuspendLayout() Me.BottomPanel.SuspendLayout() Me.SuspendLayout() ' 'RefreshTimer ' Me.RefreshTimer.Enabled = True Me.RefreshTimer.Interval = 1000 ' 'BackgroundPanel ' Me.BackgroundPanel.BackColor = System.Drawing.Color.White Me.BackgroundPanel.Controls.Add(Me.WindowsUserListView) Me.BackgroundPanel.Controls.Add(Me.DrivesListView) Me.BackgroundPanel.Controls.Add(Me.NetworkGroupBox) Me.BackgroundPanel.Controls.Add(Me.BasicGroupBox) Me.BackgroundPanel.Controls.Add(Me.BottomPanel) Me.BackgroundPanel.Location = New System.Drawing.Point(5, 34) Me.BackgroundPanel.Margin = New System.Windows.Forms.Padding(0) Me.BackgroundPanel.Name = "BackgroundPanel" Me.BackgroundPanel.Size = New System.Drawing.Size(605, 335) Me.BackgroundPanel.TabIndex = 7 ' 'WindowsUserListView ' Me.WindowsUserListView.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.UsernameColumnHeader}) Me.WindowsUserListView.Location = New System.Drawing.Point(423, 116) Me.WindowsUserListView.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.WindowsUserListView.Name = "WindowsUserListView" Me.WindowsUserListView.Size = New System.Drawing.Size(175, 172) Me.WindowsUserListView.TabIndex = 10 Me.WindowsUserListView.UseCompatibleStateImageBehavior = False Me.WindowsUserListView.View = System.Windows.Forms.View.Details ' 'UsernameColumnHeader ' Me.UsernameColumnHeader.Text = "Username" Me.UsernameColumnHeader.Width = 150 ' 'DrivesListView ' Me.DrivesListView.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.PartitionColumnHeader, Me.TypeColumnHeader, Me.FileSystemColumnHeader, Me.TotalSpaceColumnHeader, Me.FreeSpaceColumnHeader}) Me.DrivesListView.FullRowSelect = True Me.DrivesListView.Location = New System.Drawing.Point(7, 116) Me.DrivesListView.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.DrivesListView.MultiSelect = False Me.DrivesListView.Name = "DrivesListView" Me.DrivesListView.Size = New System.Drawing.Size(414, 172) Me.DrivesListView.TabIndex = 9 Me.DrivesListView.UseCompatibleStateImageBehavior = False Me.DrivesListView.View = System.Windows.Forms.View.Details ' 'PartitionColumnHeader ' Me.PartitionColumnHeader.Text = "Partition" Me.PartitionColumnHeader.Width = 80 ' 'TypeColumnHeader ' Me.TypeColumnHeader.Text = "Drive Type" Me.TypeColumnHeader.Width = 80 ' 'FileSystemColumnHeader ' Me.FileSystemColumnHeader.Text = "Filesystem" Me.FileSystemColumnHeader.Width = 80 ' 'TotalSpaceColumnHeader ' Me.TotalSpaceColumnHeader.Text = "Drive Size" Me.TotalSpaceColumnHeader.TextAlign = System.Windows.Forms.HorizontalAlignment.Right Me.TotalSpaceColumnHeader.Width = 80 ' 'FreeSpaceColumnHeader ' Me.FreeSpaceColumnHeader.Text = "Free Space" Me.FreeSpaceColumnHeader.TextAlign = System.Windows.Forms.HorizontalAlignment.Right Me.FreeSpaceColumnHeader.Width = 80 ' 'NetworkGroupBox ' Me.NetworkGroupBox.Controls.Add(Me.InternalIPLabel) Me.NetworkGroupBox.Controls.Add(Me.ExternalIPLabel) Me.NetworkGroupBox.Controls.Add(Me.InternalIPLabelText) Me.NetworkGroupBox.Controls.Add(Me.ExternalIPLabelText) Me.NetworkGroupBox.Font = New System.Drawing.Font("Tahoma", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.NetworkGroupBox.Location = New System.Drawing.Point(367, 3) Me.NetworkGroupBox.Name = "NetworkGroupBox" Me.NetworkGroupBox.Size = New System.Drawing.Size(231, 107) Me.NetworkGroupBox.TabIndex = 8 Me.NetworkGroupBox.TabStop = False Me.NetworkGroupBox.Text = "Network Information" ' 'InternalIPLabel ' Me.InternalIPLabel.AutoSize = True Me.InternalIPLabel.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.InternalIPLabel.ForeColor = System.Drawing.Color.FromArgb(CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer)) Me.InternalIPLabel.Location = New System.Drawing.Point(5, 42) Me.InternalIPLabel.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.InternalIPLabel.Name = "InternalIPLabel" Me.InternalIPLabel.Size = New System.Drawing.Size(72, 16) Me.InternalIPLabel.TabIndex = 2 Me.InternalIPLabel.Text = "Internal IP:" ' 'ExternalIPLabel ' Me.ExternalIPLabel.AutoSize = True Me.ExternalIPLabel.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ExternalIPLabel.ForeColor = System.Drawing.Color.FromArgb(CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer)) Me.ExternalIPLabel.Location = New System.Drawing.Point(5, 23) Me.ExternalIPLabel.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.ExternalIPLabel.Name = "ExternalIPLabel" Me.ExternalIPLabel.Size = New System.Drawing.Size(74, 16) Me.ExternalIPLabel.TabIndex = 0 Me.ExternalIPLabel.Text = "External IP:" ' 'InternalIPLabelText ' Me.InternalIPLabelText.AutoSize = True Me.InternalIPLabelText.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.InternalIPLabelText.ForeColor = System.Drawing.Color.OliveDrab Me.InternalIPLabelText.Location = New System.Drawing.Point(132, 42) Me.InternalIPLabelText.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.InternalIPLabelText.Name = "InternalIPLabelText" Me.InternalIPLabelText.Size = New System.Drawing.Size(83, 16) Me.InternalIPLabelText.TabIndex = 3 Me.InternalIPLabelText.Text = "{ InternalIP }" ' 'ExternalIPLabelText ' Me.ExternalIPLabelText.AutoSize = True Me.ExternalIPLabelText.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ExternalIPLabelText.ForeColor = System.Drawing.Color.OliveDrab Me.ExternalIPLabelText.Location = New System.Drawing.Point(132, 23) Me.ExternalIPLabelText.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.ExternalIPLabelText.Name = "ExternalIPLabelText" Me.ExternalIPLabelText.Size = New System.Drawing.Size(85, 16) Me.ExternalIPLabelText.TabIndex = 1 Me.ExternalIPLabelText.Text = "{ ExternalIP }" ' 'BasicGroupBox ' Me.BasicGroupBox.Controls.Add(Me.CPUUsageLabel) Me.BasicGroupBox.Controls.Add(Me.CPUUsageLabelText) Me.BasicGroupBox.Controls.Add(Me.AvailableMemoryLabel) Me.BasicGroupBox.Controls.Add(Me.OperatingSystemLabel) Me.BasicGroupBox.Controls.Add(Me.AvailableMemoryLabelText) Me.BasicGroupBox.Controls.Add(Me.ComputerNameLabel) Me.BasicGroupBox.Controls.Add(Me.OperatingSystemLabelText) Me.BasicGroupBox.Controls.Add(Me.ComputerNameLabelText) Me.BasicGroupBox.Font = New System.Drawing.Font("Tahoma", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.BasicGroupBox.Location = New System.Drawing.Point(7, 3) Me.BasicGroupBox.Name = "BasicGroupBox" Me.BasicGroupBox.Size = New System.Drawing.Size(355, 107) Me.BasicGroupBox.TabIndex = 7 Me.BasicGroupBox.TabStop = False Me.BasicGroupBox.Text = "Basic Information" ' 'CPUUsageLabel ' Me.CPUUsageLabel.AutoSize = True Me.CPUUsageLabel.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.CPUUsageLabel.ForeColor = System.Drawing.Color.FromArgb(CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer)) Me.CPUUsageLabel.Location = New System.Drawing.Point(5, 80) Me.CPUUsageLabel.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.CPUUsageLabel.Name = "CPUUsageLabel" Me.CPUUsageLabel.Size = New System.Drawing.Size(75, 16) Me.CPUUsageLabel.TabIndex = 6 Me.CPUUsageLabel.Text = "CPU Usage:" ' 'CPUUsageLabelText ' Me.CPUUsageLabelText.AutoSize = True Me.CPUUsageLabelText.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.CPUUsageLabelText.ForeColor = System.Drawing.Color.OliveDrab Me.CPUUsageLabelText.Location = New System.Drawing.Point(132, 80) Me.CPUUsageLabelText.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.CPUUsageLabelText.Name = "CPUUsageLabelText" Me.CPUUsageLabelText.Size = New System.Drawing.Size(90, 16) Me.CPUUsageLabelText.TabIndex = 7 Me.CPUUsageLabelText.Text = "{ CPU Usage }" ' 'AvailableMemoryLabel ' Me.AvailableMemoryLabel.AutoSize = True Me.AvailableMemoryLabel.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.AvailableMemoryLabel.ForeColor = System.Drawing.Color.FromArgb(CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer)) Me.AvailableMemoryLabel.Location = New System.Drawing.Point(5, 61) Me.AvailableMemoryLabel.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.AvailableMemoryLabel.Name = "AvailableMemoryLabel" Me.AvailableMemoryLabel.Size = New System.Drawing.Size(114, 16) Me.AvailableMemoryLabel.TabIndex = 4 Me.AvailableMemoryLabel.Text = "Available Memory:" ' 'OperatingSystemLabel ' Me.OperatingSystemLabel.AutoSize = True Me.OperatingSystemLabel.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.OperatingSystemLabel.ForeColor = System.Drawing.Color.FromArgb(CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer)) Me.OperatingSystemLabel.Location = New System.Drawing.Point(5, 42) Me.OperatingSystemLabel.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.OperatingSystemLabel.Name = "OperatingSystemLabel" Me.OperatingSystemLabel.Size = New System.Drawing.Size(119, 16) Me.OperatingSystemLabel.TabIndex = 2 Me.OperatingSystemLabel.Text = "Operating System: " ' 'AvailableMemoryLabelText ' Me.AvailableMemoryLabelText.AutoSize = True Me.AvailableMemoryLabelText.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.AvailableMemoryLabelText.ForeColor = System.Drawing.Color.OliveDrab Me.AvailableMemoryLabelText.Location = New System.Drawing.Point(132, 61) Me.AvailableMemoryLabelText.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.AvailableMemoryLabelText.Name = "AvailableMemoryLabelText" Me.AvailableMemoryLabelText.Size = New System.Drawing.Size(155, 16) Me.AvailableMemoryLabelText.TabIndex = 5 Me.AvailableMemoryLabelText.Text = "{ AvailableMemoryLabel }" ' 'ComputerNameLabel ' Me.ComputerNameLabel.AutoSize = True Me.ComputerNameLabel.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ComputerNameLabel.ForeColor = System.Drawing.Color.FromArgb(CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer), CType(CType(51, Byte), Integer)) Me.ComputerNameLabel.Location = New System.Drawing.Point(5, 23) Me.ComputerNameLabel.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.ComputerNameLabel.Name = "ComputerNameLabel" Me.ComputerNameLabel.Size = New System.Drawing.Size(96, 16) Me.ComputerNameLabel.TabIndex = 0 Me.ComputerNameLabel.Text = "System Name: " ' 'OperatingSystemLabelText ' Me.OperatingSystemLabelText.AutoSize = True Me.OperatingSystemLabelText.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.OperatingSystemLabelText.ForeColor = System.Drawing.Color.OliveDrab Me.OperatingSystemLabelText.Location = New System.Drawing.Point(132, 42) Me.OperatingSystemLabelText.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.OperatingSystemLabelText.Name = "OperatingSystemLabelText" Me.OperatingSystemLabelText.Size = New System.Drawing.Size(156, 16) Me.OperatingSystemLabelText.TabIndex = 3 Me.OperatingSystemLabelText.Text = "{ OperatingSystemLabel }" ' 'ComputerNameLabelText ' Me.ComputerNameLabelText.AutoSize = True Me.ComputerNameLabelText.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ComputerNameLabelText.ForeColor = System.Drawing.Color.OliveDrab Me.ComputerNameLabelText.Location = New System.Drawing.Point(132, 23) Me.ComputerNameLabelText.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0) Me.ComputerNameLabelText.Name = "ComputerNameLabelText" Me.ComputerNameLabelText.Size = New System.Drawing.Size(147, 16) Me.ComputerNameLabelText.TabIndex = 1 Me.ComputerNameLabelText.Text = "{ ComputerNameLabel }" ' 'BottomPanel ' Me.BottomPanel.BackColor = System.Drawing.Color.FromArgb(CType(CType(221, Byte), Integer), CType(CType(221, Byte), Integer), CType(CType(221, Byte), Integer)) Me.BottomPanel.Controls.Add(Me.CloseButton) Me.BottomPanel.Dock = System.Windows.Forms.DockStyle.Bottom Me.BottomPanel.Location = New System.Drawing.Point(0, 295) Me.BottomPanel.Name = "BottomPanel" Me.BottomPanel.Size = New System.Drawing.Size(605, 40) Me.BottomPanel.TabIndex = 6 ' 'CloseButton ' Me.CloseButton.BackColor = System.Drawing.Color.WhiteSmoke Me.CloseButton.FlatAppearance.BorderColor = System.Drawing.Color.Silver Me.CloseButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.CloseButton.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.CloseButton.Location = New System.Drawing.Point(539, 3) Me.CloseButton.Name = "CloseButton" Me.CloseButton.Size = New System.Drawing.Size(61, 31) Me.CloseButton.TabIndex = 0 Me.CloseButton.Text = "Exit" Me.CloseButton.UseVisualStyleBackColor = False ' 'ExitButton ' Me.ExitButton.BackColor = System.Drawing.Color.FromArgb(CType(CType(200, Byte), Integer), CType(CType(80, Byte), Integer), CType(CType(80, Byte), Integer)) Me.ExitButton.FlatAppearance.BorderSize = 0 Me.ExitButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.ExitButton.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ExitButton.ForeColor = System.Drawing.Color.White Me.ExitButton.Location = New System.Drawing.Point(567, 3) Me.ExitButton.Name = "ExitButton" Me.ExitButton.Size = New System.Drawing.Size(43, 29) Me.ExitButton.TabIndex = 8 Me.ExitButton.Text = "X" Me.ExitButton.UseVisualStyleBackColor = False ' 'FormTitleLabel ' Me.FormTitleLabel.Font = New System.Drawing.Font("Tahoma", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.FormTitleLabel.Location = New System.Drawing.Point(5, 5) Me.FormTitleLabel.Name = "FormTitleLabel" Me.FormTitleLabel.Size = New System.Drawing.Size(615, 23) Me.FormTitleLabel.TabIndex = 9 Me.FormTitleLabel.Text = "{ Form Title }" Me.FormTitleLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'OverviewForm ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(52, Byte), Integer), CType(CType(131, Byte), Integer), CType(CType(211, Byte), Integer)) Me.ClientSize = New System.Drawing.Size(615, 375) Me.Controls.Add(Me.ExitButton) Me.Controls.Add(Me.BackgroundPanel) Me.Controls.Add(Me.FormTitleLabel) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Margin = New System.Windows.Forms.Padding(2, 2, 2, 2) Me.Name = "OverviewForm" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Overview" Me.BackgroundPanel.ResumeLayout(False) Me.NetworkGroupBox.ResumeLayout(False) Me.NetworkGroupBox.PerformLayout() Me.BasicGroupBox.ResumeLayout(False) Me.BasicGroupBox.PerformLayout() Me.BottomPanel.ResumeLayout(False) Me.ResumeLayout(False) End Sub Friend WithEvents RefreshTimer As System.Windows.Forms.Timer Friend WithEvents BackgroundPanel As System.Windows.Forms.Panel Friend WithEvents DrivesListView As System.Windows.Forms.ListView Friend WithEvents PartitionColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents TypeColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents FileSystemColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents TotalSpaceColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents FreeSpaceColumnHeader As System.Windows.Forms.ColumnHeader Friend WithEvents NetworkGroupBox As System.Windows.Forms.GroupBox Friend WithEvents InternalIPLabel As System.Windows.Forms.Label Friend WithEvents ExternalIPLabel As System.Windows.Forms.Label Friend WithEvents InternalIPLabelText As System.Windows.Forms.Label Friend WithEvents ExternalIPLabelText As System.Windows.Forms.Label Friend WithEvents BasicGroupBox As System.Windows.Forms.GroupBox Friend WithEvents CPUUsageLabel As System.Windows.Forms.Label Friend WithEvents CPUUsageLabelText As System.Windows.Forms.Label Friend WithEvents AvailableMemoryLabel As System.Windows.Forms.Label Friend WithEvents OperatingSystemLabel As System.Windows.Forms.Label Friend WithEvents AvailableMemoryLabelText As System.Windows.Forms.Label Friend WithEvents ComputerNameLabel As System.Windows.Forms.Label Friend WithEvents OperatingSystemLabelText As System.Windows.Forms.Label Friend WithEvents ComputerNameLabelText As System.Windows.Forms.Label Friend WithEvents BottomPanel As System.Windows.Forms.Panel Friend WithEvents CloseButton As System.Windows.Forms.Button Friend WithEvents ExitButton As System.Windows.Forms.Button Friend WithEvents FormTitleLabel As System.Windows.Forms.Label Friend WithEvents WindowsUserListView As System.Windows.Forms.ListView Friend WithEvents UsernameColumnHeader As System.Windows.Forms.ColumnHeader End Class
richardmountain/ComputerSpecInformation
trunk/SystemInformation.UI/OverviewForm.Designer.vb
Visual Basic
mit
23,659