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
|
|---|---|---|---|---|---|
'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.
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class FrmTextView
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.txtContents = New System.Windows.Forms.TextBox
Me.SuspendLayout()
'
'txtContents
'
Me.txtContents.BackColor = System.Drawing.Color.White
Me.txtContents.Location = New System.Drawing.Point(11, 9)
Me.txtContents.Multiline = True
Me.txtContents.Name = "txtContents"
Me.txtContents.ReadOnly = True
Me.txtContents.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.txtContents.Size = New System.Drawing.Size(423, 411)
Me.txtContents.TabIndex = 0
'
'FrmTextView
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(442, 425)
Me.Controls.Add(Me.txtContents)
Me.Name = "FrmTextView"
Me.Text = "Form2"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents txtContents As System.Windows.Forms.TextBox
End Class
|
Esri/arcobjects-sdk-community-samples
|
Net/Catalog/TextTab/VBNET/FrmTextView.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,485
|
Imports bwl.Graphics._3D.CatRender
Public Class TestForm
Private Sub TestForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler CatRender1.Display.DisplayPicturebox.MouseDown, AddressOf TestHandler
CatRender1.Render.SceneDraw.defaults.lighting = LightingMode.full
CatRender1.Render.SceneDraw.settings.drawLines = True
CatRender1.Render.SceneDraw.settings.drawTriangles = True
CatRender1.RenderScene.AddObject(Object3D.CreateAmbientLightObject(Color.DarkGray))
CatRender1.RenderScene.AddObject(Object3D.CreatePointLightObject(Color.White, 100, 50, 100, -50))
CatRender1.RenderScene.AddObject(Object3D.CreateModelObject(
ModelGen.CreateBoxModel(10, 5, 20,
Material.CreateMaterial(Color.Red)),
0, 0, 0, 0, 0, 0))
CatRender1.RenderScene.AddObject(Object3D.CreateSpriteObject(
Sprite.CreateSprite("..\..\point.bmp"),
0, 0, 0))
CatRender1.RenderScene.AddObject(Object3D.CreateSpriteObject(
Sprite.CreateSprite("..\..\point.bmp"),
10, 10, -10, Color.Red))
CatRender1.RenderDrawingEnabled = True
CatRender1.RenderWorkingEnabled = True
CatRender1.RenderAutoMove = True
CatRender1.RenderMouseLocking = False
End Sub
Private Sub CatRender1_RenderWorkCycle() Handles CatRender1.RenderWorkCycle
Dim sprites = CatRender1.RenderSceneDraw.DebugSpritesList
Debug.WriteLine(sprites.Count)
If sprites.Count > 0 Then
Debug.WriteLine("uid, " + sprites(0).UID.ToString + " px, " + sprites(0).px.ToString)
End If
End Sub
Private Sub TestHandler(sender As Object, e As MouseEventArgs)
'если была правая кнопка - блокируем
If e.Button = Windows.Forms.MouseButtons.Right Then
CatRender1.Display.MouseLocked = True
Else
MsgBox(e.X.ToString + ", " + e.Y.ToString)
End If
End Sub
End Class
|
Lifemotion/Bwl.Graphics3D.CatRender
|
Bwl.Graphics3D.CatRender.Test/TestForm.vb
|
Visual Basic
|
apache-2.0
| 2,280
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
Friend Class ImportsClauseComparer
Implements IComparer(Of ImportsClauseSyntax)
Public Shared ReadOnly NormalInstance As IComparer(Of ImportsClauseSyntax) = New ImportsClauseComparer()
Private ReadOnly _nameComparer As IComparer(Of NameSyntax)
Private ReadOnly _tokenComparer As IComparer(Of SyntaxToken)
Private Sub New()
_nameComparer = NameSyntaxComparer.Create(TokenComparer.NormalInstance)
_tokenComparer = TokenComparer.NormalInstance
End Sub
Public Sub New(tokenComparer As IComparer(Of SyntaxToken))
_nameComparer = NameSyntaxComparer.Create(tokenComparer)
_tokenComparer = tokenComparer
End Sub
Friend Function Compare(x As ImportsClauseSyntax, y As ImportsClauseSyntax) As Integer Implements IComparer(Of ImportsClauseSyntax).Compare
Dim imports1 = TryCast(x, SimpleImportsClauseSyntax)
Dim imports2 = TryCast(y, SimpleImportsClauseSyntax)
Dim xml1 = TryCast(x, XmlNamespaceImportsClauseSyntax)
Dim xml2 = TryCast(y, XmlNamespaceImportsClauseSyntax)
If xml1 IsNot Nothing AndAlso xml2 Is Nothing Then
Return 1
ElseIf xml1 Is Nothing AndAlso xml2 IsNot Nothing Then
Return -1
ElseIf xml1 IsNot Nothing AndAlso xml2 IsNot Nothing Then
Return CompareXmlNames(
DirectCast(xml1.XmlNamespace.Name, XmlNameSyntax),
DirectCast(xml2.XmlNamespace.Name, XmlNameSyntax))
ElseIf imports1 IsNot Nothing AndAlso imports2 IsNot Nothing Then
If imports1.Alias IsNot Nothing AndAlso imports2.Alias Is Nothing Then
Return 1
ElseIf imports1.Alias Is Nothing AndAlso imports2.Alias IsNot Nothing Then
Return -1
ElseIf imports1.Alias IsNot Nothing AndAlso imports2.Alias IsNot Nothing Then
Return _tokenComparer.Compare(imports1.Alias.Identifier, imports2.Alias.Identifier)
Else
Return _nameComparer.Compare(imports1.Name, imports2.Name)
End If
End If
Return 0
End Function
Private Function CompareXmlNames(xmlName1 As XmlNameSyntax, xmlName2 As XmlNameSyntax) As Integer
Dim tokens1 = xmlName1.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
Dim tokens2 = xmlName2.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
For i = 0 To Math.Min(tokens1.Count - 1, tokens2.Count - 1)
Dim compare = _tokenComparer.Compare(tokens1(i), tokens2(i))
If compare <> 0 Then
Return compare
End If
Next
Return tokens1.Count - tokens2.Count
End Function
End Class
End Namespace
|
abock/roslyn
|
src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Utilities/ImportsClauseComparer.vb
|
Visual Basic
|
mit
| 3,413
|
' 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_199
''' <summary>
''' A Double extension method that converts the @this to a money.
''' </summary>
''' <param name="this">The @this to act on.</param>
''' <returns>@this as a Double.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function ToMoney(this As [Double]) As [Double]
Return Math.Round(this, 2)
End Function
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Double/Double.ToMoney.vb
|
Visual Basic
|
mit
| 767
|
' 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.CSharp
Imports Microsoft.CodeAnalysis.Editor.Options
Imports Microsoft.CodeAnalysis.Options
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
<[UseExportProvider]>
Public Class CSharpSignatureHelpCommandHandlerTests
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestCreateAndDismiss(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class C
{
void Goo()
{
Goo$$
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()")
state.SendTypeChars(")")
Await state.AssertNoSignatureHelpSession()
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TypingUpdatesParameters(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class C
{
void Goo(int i, string j)
{
Goo$$
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="int i")
state.SendTypeChars("1,")
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TypingChangeParameterByNavigating(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class C
{
void Goo(int i, string j)
{
Goo(1$$
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars(",")
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j")
state.SendLeftKey()
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="int i")
state.SendRightKey()
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function NavigatingOutOfSpanDismissesSignatureHelp(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class C
{
void Goo()
{
Goo($$)
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeSignatureHelp()
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()")
state.SendRightKey()
Await state.AssertNoSignatureHelpSession()
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestNestedCalls(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class C
{
void Bar() { }
void Goo()
{
Goo$$
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()")
state.SendTypeChars("Bar(")
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Bar()")
state.SendTypeChars(")")
Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()")
End Using
End Function
<WorkItem(544547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544547")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestNoSigHelpOnGenericNamespace(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
namespace global::F$$
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertNoSignatureHelpSession()
End Using
End Function
<WorkItem(544547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544547")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestSigHelpOnExtraSpace(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class G<S, T> { };
class C
{
void Goo()
{
G<int, $$
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeSignatureHelp()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WorkItem(6713, "https://github.com/dotnet/roslyn/issues/6713")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestOnIncompleteInvocation(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
static void Main(string[] args)
{
F$$
}
static void F(int i, int j) { }
static void F(string s, int j, int k) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
' We don't have a definite symbol, so default to first
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Assert.Equal({"void Program.F(int i, int j)", "void Program.F(string s, int j, int k)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
Await state.AssertSelectedSignatureHelpItem("void Program.F(int i, int j)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
' We have a definite guess (the string overload)
state.SendTypeChars("""""")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s, int j, int k)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
state.SendTypeChars(", 2")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s, int j, int k)")
state.SendTypeChars(", 3")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s, int j, int k)")
' Selection becomes invalid
state.SendTypeChars(", 4")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s, int j, int k)")
End Using
End Function
<WorkItem(6713, "https://github.com/dotnet/roslyn/issues/6713")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestOnIncompleteInvocation_CommaMatters(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
static void Main(string[] args)
{
F$$
}
static void F(int i) { }
static void F(string s, int j) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
' We don't have a definite symbol, so default to first
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Assert.Equal({"void Program.F(int i)", "void Program.F(string s, int j)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
' We have a definite guess (the first acceptable overload)
state.SendTypeChars("default")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
state.SendTypeChars(",")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s, int j)")
state.SendBackspace()
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)")
End Using
End Function
<WorkItem(6713, "https://github.com/dotnet/roslyn/issues/6713")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestOnIncompleteInvocation_WithRef(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
static void Main(string args)
{
F$$
}
static void F(ref int i, int j) { }
static void F(double d) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
' We don't have a definite symbol, so default to first
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Assert.Equal({"void Program.F(double d)", "void Program.F(ref int i, int j)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
Await state.AssertSelectedSignatureHelpItem("void Program.F(double d)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
' We have a definite guess (the overload with ref)
state.SendTypeChars("ref args")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(ref int i, int j)")
' Selection becomes invalid
state.SendTypeChars(", 2, 3")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(ref int i, int j)")
End Using
End Function
<WorkItem(6713, "https://github.com/dotnet/roslyn/issues/6713")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestOnIncompleteInvocation_WithArgumentName(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
static void Main(string args)
{
F$$
}
static void F(int i, int j) { }
static void F(string name) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(name: 1")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string name)")
Assert.Equal({"void Program.F(string name)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
End Using
End Function
<WorkItem(6713, "https://github.com/dotnet/roslyn/issues/6713")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestOnIncompleteInvocation_WithExtension(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
void M()
{
this.F$$
}
}
public static class ProgramExtension
{
public static void F(this Program p, int i, int j) { }
public static void F(this Program p, string name) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Assert.Equal({$"({CSharpFeaturesResources.extension}) void Program.F(string name)", $"({CSharpFeaturesResources.extension}) void Program.F(int i, int j)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) void Program.F(string name)")
state.SendTypeChars("1")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) void Program.F(int i, int j)")
End Using
End Function
<WorkItem(6713, "https://github.com/dotnet/roslyn/issues/6713")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestOnIncompleteObjectConstruction(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
void M()
{
new Program$$
}
Program(int i, int j) { }
Program(string name) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("Program(string name)")
Assert.Equal({"Program(string name)", "Program(int i, int j)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
state.SendTypeChars("1")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("Program(int i, int j)")
End Using
End Function
<WorkItem(6713, "https://github.com/dotnet/roslyn/issues/6713")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestOnIncompleteConstructorInitializer(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
Program() : this$$
{
}
Program(int i, int j) { }
Program(string name) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("Program(string name)")
Assert.Equal({"Program(string name)", "Program(int i, int j)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
state.SendTypeChars("1")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("Program(int i, int j)")
state.SendBackspace()
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("Program(int i, int j)")
state.SendTypeChars("""""")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("Program(string name)")
End Using
End Function
<WorkItem(545488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545488")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestUseBestOverload(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
static void Main()
{
F$$
}
static void F(int i) { }
static void F(string s) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
' We don't have a definite symbol, so default to first
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
Assert.Equal({"void Program.F(int i)", "void Program.F(string s)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
' We now have a definite symbol (the string overload)
state.SendTypeChars("""""")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
' We stick with the last selection after deleting
state.SendBackspace()
state.SendBackspace()
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
' We now have a definite symbol (the int overload)
state.SendTypeChars("1")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
End Using
End Function
<WorkItem(545488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545488")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestForgetSelectedItemWhenNoneAreViable(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
static void Main(string[] args)
{
F$$
}
static void F(int i) { }
static void F(string s) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
' We don't have a definite symbol, so default to first
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
Assert.Equal({"void Program.F(int i)", "void Program.F(string s)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
' We now have a definite symbol (the string overload)
state.SendTypeChars("""""")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
' We don't have a definite symbol again, so we stick with last selection
state.SendTypeChars(",")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)")
Assert.Equal(2, state.GetSignatureHelpItems().Count)
End Using
End Function
<WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestKeepUserSelectedItem(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void M()
{
M$$
}
void M(int i) { }
void M(int i, int j) { }
void M(int i, int j, int k) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void C.M()")
Assert.Equal(4, state.GetSignatureHelpItems().Count)
If showCompletionInArgumentLists Then
Await state.AssertCompletionSession()
state.SendEscape()
End If
state.SendUpKey()
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)")
state.SendTypeChars("1")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)")
state.SendTypeChars(",")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)")
state.SendTypeChars("2,")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)")
End Using
End Function
<WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")>
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestKeepUserSelectedItem2(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void M()
{
M$$
}
void M(int i) { }
void M(int i, int j) { }
void M(int i, string x) { }
void M(int i, int j, int k) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void C.M()")
Assert.Equal(5, state.GetSignatureHelpItems().Count)
state.SendTypeChars("1, ")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)")
If showCompletionInArgumentLists Then
Await state.AssertCompletionSession()
state.SendEscape()
End If
state.SendDownKey()
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)")
state.SendTypeChars("1")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)")
End Using
End Function
<WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestKeepUserSelectedItem3(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void M()
{
M$$
}
void M(int i) { }
void M(int i, int j) { }
void M(int i, string x) { }
void M(int i, int j, int k) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void C.M()")
Assert.Equal(5, state.GetSignatureHelpItems().Count)
state.SendTypeChars("1, """" ")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)")
state.SendUpKey()
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)")
state.SendTypeChars(",")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)")
state.SendBackspace()
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)")
End Using
End Function
<WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestPathIndependent(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void M()
{
M$$
}
void M(int i) { }
void M(int i, int j) { }
void M(int i, string x) { }
void M(int i, int j, int k) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void C.M()")
Assert.Equal(5, state.GetSignatureHelpItems().Count)
Assert.Equal({"void C.M()", "void C.M(int i)", "void C.M(int i, int j)", "void C.M(int i, string x)", "void C.M(int i, int j, int k)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
state.SendTypeChars("1")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i)")
state.SendTypeChars(",")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)")
state.SendTypeChars(" ""a"" ")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)")
End Using
End Function
<WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestPathIndependent2(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void M()
{
M$$
}
void M(int i) { }
void M(int i, int j) { }
void M(int i, string x) { }
void M(int i, int j, int k) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void C.M()")
Assert.Equal(5, state.GetSignatureHelpItems().Count)
Assert.Equal({"void C.M()", "void C.M(int i)", "void C.M(int i, int j)", "void C.M(int i, string x)", "void C.M(int i, int j, int k)"},
state.GetSignatureHelpItems().Select(Function(i) i.ToString()))
state.SendTypeChars("1, ""a"" ")
Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)")
End Using
End Function
<WorkItem(819063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819063")>
<WorkItem(843508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843508")>
<WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestSessionMaintainedDuringIndexerErrorToleranceTransition(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class Program
{
void M(int x)
{
string s = "Test";
s$$
}
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("[")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("char string[int index]")
state.SendTypeChars("x")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("char string[int index]")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestSigHelpInLinkedFiles(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs">
class C
{
void M()
{
M2($$);
}
#if Proj1
void M2(int x) { }
#endif
#if Proj2
void M2(string x) { }
#endif
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
Dim documents = state.Workspace.Documents
Dim linkDocument = documents.Single(Function(d) d.IsLinkFile)
state.SendInvokeSignatureHelp()
Await state.AssertSelectedSignatureHelpItem("void C.M2(int x)")
state.SendEscape()
state.Workspace.SetDocumentContext(linkDocument.Id)
state.SendInvokeSignatureHelp()
Await state.AssertSelectedSignatureHelpItem("void C.M2(string x)")
End Using
End Function
<WorkItem(1060850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1060850")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestSigHelpNotDismissedAfterQuote(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void M()
{
}
void M(string s)
{
M($$);
}
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeSignatureHelp()
Await state.AssertSelectedSignatureHelpItem("void C.M()")
state.SendTypeChars("""")
Await state.AssertSignatureHelpSession()
Await state.AssertSelectedSignatureHelpItem("void C.M(string s)")
End Using
End Function
<WorkItem(1060850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1060850")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestSigHelpDismissedAfterComment(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
void M()
{
}
void M(string s)
{
M($$);
}
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeSignatureHelp()
Await state.AssertSelectedSignatureHelpItem("void C.M()")
state.SendTypeChars("//")
Await state.AssertNoSignatureHelpSession()
End Using
End Function
<WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestGenericNameSigHelpInTypeParameterListAfterConditionalAccess(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(object[] args)
{
var x = args?.OfType$$
}
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()")
End Using
End Function
<WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestGenericNameSigHelpInTypeParameterListAfterMultipleConditionalAccess(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(object[] args)
{
var x = args?.Select(a => a)?.OfType$$
}
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()")
End Using
End Function
<WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestGenericNameSigHelpInTypeParameterListMuchAfterConditionalAccess(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(object[] args)
{
var x = args?.Select(a => a).Where(_ => true).OfType$$
}
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()")
End Using
End Function
<WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestGenericNameSigHelpInTypeParameterListAfterConditionalAccessAndNullCoalesce(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(object[] args)
{
var x = (args ?? args)?.OfType$$
}
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()")
End Using
End Function
<WorkItem(5174, "https://github.com/dotnet/roslyn/issues/5174")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function DontShowSignatureHelpIfOptionIsTurnedOffUnlessExplicitlyInvoked(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class C
{
void M(int i)
{
M$$
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
' disable implicit sig help then type a trigger character -> no session should be available
state.Workspace.GetService(Of IGlobalOptionService).SetGlobalOption(New OptionKey(SignatureHelpViewOptions.ShowSignatureHelp, LanguageNames.CSharp), False)
state.SendTypeChars("(")
Await state.AssertNoSignatureHelpSession()
' force-invoke -> session should be available
state.SendInvokeSignatureHelp()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function MixedTupleNaming(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class C
{
void Goo()
{
(int, int x) t = (5$$
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars(",")
Await state.AssertSelectedSignatureHelpItem(displayText:="(int, int x)", selectedParameter:="int x")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function ParameterSelectionWhileParsedAsParenthesizedExpression(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document>
class C
{
void Goo()
{
(int a, string b) x = (b$$
}
}
</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeSignatureHelp()
Await state.AssertSelectedSignatureHelpItem(displayText:="(int a, string b)", selectedParameter:="int a")
End Using
End Function
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/Test2/IntelliSense/CSharpSignatureHelpCommandHandlerTests.vb
|
Visual Basic
|
mit
| 39,475
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_ObjectLock_FieldReference()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Dim o As New Object
Public Sub M1()
SyncLock o'BIND:"SyncLock o"
End SyncLock
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement) (Syntax: 'SyncLock o' ... nd SyncLock')
Expression:
IFieldReferenceExpression: C1.o As System.Object (OperationKind.FieldReferenceExpression, Type: System.Object) (Syntax: 'o')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C1, IsImplicit) (Syntax: 'o')
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement) (Syntax: 'SyncLock o' ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_ObjectLock_LocalReference()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
Dim o As New Object
SyncLock o'BIND:"SyncLock o"
End SyncLock
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement) (Syntax: 'SyncLock o' ... nd SyncLock')
Expression:
ILocalReferenceExpression: o (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'o')
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement) (Syntax: 'SyncLock o' ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_ObjectLock_Nothing()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
Dim o As New Object
SyncLock o'BIND:"SyncLock o"
End SyncLock
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement) (Syntax: 'SyncLock o' ... nd SyncLock')
Expression:
ILocalReferenceExpression: o (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'o')
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement) (Syntax: 'SyncLock o' ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_ObjectLock_NonReferenceType()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
Dim i As Integer = 1
SyncLock i'BIND:"SyncLock i"
End SyncLock
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement, IsInvalid) (Syntax: 'SyncLock i' ... nd SyncLock')
Expression:
ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32, IsInvalid) (Syntax: 'i')
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'SyncLock i' ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30582: 'SyncLock' operand cannot be of type 'Integer' because 'Integer' is not a reference type.
SyncLock i'BIND:"SyncLock i"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_MissingLockExpression()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
SyncLock'BIND:"SyncLock"
End SyncLock
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement, IsInvalid) (Syntax: 'SyncLock'BI ... nd SyncLock')
Expression:
IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '')
Children(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'SyncLock'BI ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
SyncLock'BIND:"SyncLock"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_InvalidLockExpression()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
SyncLock InvalidReference'BIND:"SyncLock InvalidReference"
End SyncLock
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement, IsInvalid) (Syntax: 'SyncLock In ... nd SyncLock')
Expression:
IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: 'InvalidReference')
Children(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'SyncLock In ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30451: 'InvalidReference' is not declared. It may be inaccessible due to its protection level.
SyncLock InvalidReference'BIND:"SyncLock InvalidReference"
~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_MissingEndLock()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
Dim o As New Object
SyncLock o'BIND:"SyncLock o"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement, IsInvalid) (Syntax: 'SyncLock o' ... SyncLock o"')
Expression:
ILocalReferenceExpression: o (OperationKind.LocalReferenceExpression, Type: System.Object, IsInvalid) (Syntax: 'o')
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'SyncLock o' ... SyncLock o"')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30675: 'SyncLock' statement must end with a matching 'End SyncLock'.
SyncLock o'BIND:"SyncLock o"
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_ExpressionBody_ObjectCall()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
Dim o As New Object
SyncLock o.ToString()'BIND:"SyncLock o.ToString()"
End SyncLock
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement) (Syntax: 'SyncLock o. ... nd SyncLock')
Expression:
IInvocationExpression (virtual Function System.Object.ToString() As System.String) (OperationKind.InvocationExpression, Type: System.String) (Syntax: 'o.ToString()')
Instance Receiver:
ILocalReferenceExpression: o (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'o')
Arguments(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement) (Syntax: 'SyncLock o. ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_ExpressionLock_ClassMethodCall()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
SyncLock M2()'BIND:"SyncLock M2()"
End SyncLock
End Sub
Public Function M2() As Object
Return New Object
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement) (Syntax: 'SyncLock M2 ... nd SyncLock')
Expression:
IInvocationExpression ( Function C1.M2() As System.Object) (OperationKind.InvocationExpression, Type: System.Object) (Syntax: 'M2()')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C1, IsImplicit) (Syntax: 'M2')
Arguments(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement) (Syntax: 'SyncLock M2 ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_ExpressionBody_SubMethod()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
SyncLock M2()'BIND:"SyncLock M2()"
End SyncLock
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement, IsInvalid) (Syntax: 'SyncLock M2 ... nd SyncLock')
Expression:
IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M2()')
Children(1):
IInvocationExpression ( Sub C1.M2()) (OperationKind.InvocationExpression, Type: System.Void, IsInvalid) (Syntax: 'M2()')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C1, IsInvalid, IsImplicit) (Syntax: 'M2')
Arguments(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'SyncLock M2 ... nd SyncLock')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30491: Expression does not produce a value.
SyncLock M2()'BIND:"SyncLock M2()"
~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ILockStatement_NonEmptyBody()
Dim source = <![CDATA[
Option Strict On
Imports System
Public Class C1
Public Sub M1()
Dim o As New Object
SyncLock o'BIND:"SyncLock o"
Console.WriteLine("Hello World!")
End SyncLock
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILockStatement (OperationKind.LockStatement) (Syntax: 'SyncLock o' ... nd SyncLock')
Expression:
ILocalReferenceExpression: o (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'o')
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: 'SyncLock o' ... nd SyncLock')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.Wri ... lo World!")')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.String)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.Wri ... lo World!")')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: '"Hello World!"')
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of SyncLockBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
End Class
End Namespace
|
CaptainHayashi/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_ILockStatement.vb
|
Visual Basic
|
apache-2.0
| 13,386
|
' 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.SymbolDisplay
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
'Imports SemanticModel = Microsoft.CodeAnalysis.VisualBasic.Semantics.SemanticModel
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class SymbolDisplayVisitor
Inherits AbstractSymbolDisplayVisitor
Private ReadOnly _escapeKeywordIdentifiers As Boolean
' A Symbol in VB might be a PENamedSymbolWithEmittedNamespaceName and in that case the
' casing of the contained types and namespaces might differ because of merged classes/namespaces.
' To maintain the original spelling an emittedNamespaceName with the correct spelling is passed to
' this visitor.
Friend Sub New(
builder As ArrayBuilder(Of SymbolDisplayPart),
format As SymbolDisplayFormat,
semanticModelOpt As SemanticModel,
positionOpt As Integer)
MyBase.New(builder, format, True, semanticModelOpt, positionOpt)
Debug.Assert(format IsNot Nothing, "Format must not be null")
Me._escapeKeywordIdentifiers = format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)
End Sub
Private Sub New(
builder As ArrayBuilder(Of SymbolDisplayPart),
format As SymbolDisplayFormat,
semanticModelOpt As SemanticModel,
positionOpt As Integer,
escapeKeywordIdentifiers As Boolean,
isFirstSymbolVisited As Boolean,
Optional inNamespaceOrType As Boolean = False)
MyBase.New(builder, format, isFirstSymbolVisited, semanticModelOpt, positionOpt, inNamespaceOrType)
Me._escapeKeywordIdentifiers = escapeKeywordIdentifiers
End Sub
' in case the display of a symbol is different for a type that acts as a container, use this visitor
Protected Overrides Function MakeNotFirstVisitor(Optional inNamespaceOrType As Boolean = False) As AbstractSymbolDisplayVisitor
Return New SymbolDisplayVisitor(
Me.builder,
Me.format,
Me.semanticModelOpt,
Me.positionOpt,
Me._escapeKeywordIdentifiers,
isFirstSymbolVisited:=False,
inNamespaceOrType:=inNamespaceOrType)
End Function
Friend Function CreatePart(kind As SymbolDisplayPartKind,
symbol As ISymbol,
text As String,
noEscaping As Boolean) As SymbolDisplayPart
Dim escape = (AlwaysEscape(kind, text) OrElse Not noEscaping) AndAlso _escapeKeywordIdentifiers AndAlso IsEscapable(kind)
Return New SymbolDisplayPart(kind, symbol, If(escape, EscapeIdentifier(text), text))
End Function
Private Shared Function AlwaysEscape(kind As SymbolDisplayPartKind, text As String) As Boolean
If kind <> SymbolDisplayPartKind.Keyword Then
' We must always escape "Rem" and "New" when they are being used in an identifier context.
' For constructors, (say C.New) we emit New as a Keyword kind if it's a constructor, or
' as an appropriate name kind if it's an identifier.
If CaseInsensitiveComparison.Equals(SyntaxFacts.GetText(SyntaxKind.REMKeyword), text) OrElse
CaseInsensitiveComparison.Equals(SyntaxFacts.GetText(SyntaxKind.NewKeyword), text) Then
Return True
End If
End If
Return False
End Function
Private Shared Function IsEscapable(kind As SymbolDisplayPartKind) As Boolean
Select Case kind
Case SymbolDisplayPartKind.ModuleName,
SymbolDisplayPartKind.ClassName,
SymbolDisplayPartKind.StructName,
SymbolDisplayPartKind.InterfaceName,
SymbolDisplayPartKind.EnumName,
SymbolDisplayPartKind.DelegateName,
SymbolDisplayPartKind.TypeParameterName,
SymbolDisplayPartKind.MethodName,
SymbolDisplayPartKind.PropertyName,
SymbolDisplayPartKind.FieldName,
SymbolDisplayPartKind.LocalName,
SymbolDisplayPartKind.NamespaceName,
SymbolDisplayPartKind.ParameterName,
SymbolDisplayPartKind.AliasName,
SymbolDisplayPartKind.ErrorTypeName,
SymbolDisplayPartKind.LabelName,
SymbolDisplayPartKind.EventName,
SymbolDisplayPartKind.RangeVariableName
Return True
Case Else
Return False
End Select
End Function
Private Function EscapeIdentifier(identifier As String) As String
' always escape keywords,
If SyntaxFacts.GetKeywordKind(identifier) <> SyntaxKind.None Then
Return String.Format("[{0}]", identifier)
End If
' The minimal flag is e.g. used by the service layer when generating code (example: simplify name).
' Unfortunately we do not know in what context the identifier is used and we need to assume the worst case here
' to avoid ambiguities while parsing the resulting code.
If Me.IsMinimizing Then
Dim contextualKeywordKind As SyntaxKind = SyntaxFacts.GetContextualKeywordKind(identifier)
' Leading implicit line continuation is allowed before query operators (Aggregate, Distinct, From, Group By,
' Group Join, Join, Let, Order By, Select, Skip, Skip While, Take, Take While, Where, In, Into, On, Ascending,
' and Descending).
' If the current identifier is one of these keywords, we need to escape them to avoid parsing issues if the
' previous line was a query expression.
'
' In addition to the query operators, we need to escape the identifier "preserve" to avoid ambiguities
' inside of a dim statement (dim [preserve].ArrayName(1))
Select Case contextualKeywordKind
Case SyntaxKind.AggregateKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.GroupKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.SelectKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.InKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.AscendingKeyword,
SyntaxKind.DescendingKeyword,
SyntaxKind.PreserveKeyword
Return String.Format("[{0}]", identifier)
End Select
End If
Return identifier
End Function
Public Overrides Sub VisitAssembly(symbol As IAssemblySymbol)
Dim text = If((format.TypeQualificationStyle = SymbolDisplayTypeQualificationStyle.NameOnly), symbol.Identity.Name, symbol.Identity.GetDisplayName())
builder.Add(CreatePart(SymbolDisplayPartKind.AssemblyName, symbol, text, False))
End Sub
Public Overrides Sub VisitLabel(symbol As ILabelSymbol)
builder.Add(CreatePart(SymbolDisplayPartKind.LabelName, symbol, symbol.Name, False))
End Sub
Public Overrides Sub VisitAlias(symbol As IAliasSymbol)
builder.Add(CreatePart(SymbolDisplayPartKind.LocalName, symbol, symbol.Name, False))
If format.LocalOptions.IncludesOption(SymbolDisplayLocalOptions.IncludeType) Then
AddPunctuation(SyntaxKind.EqualsToken)
symbol.Target.Accept(Me)
End If
End Sub
Public Overrides Sub VisitModule(symbol As IModuleSymbol)
builder.Add(CreatePart(SymbolDisplayPartKind.ModuleName, symbol, symbol.Name, False))
End Sub
Public Overloads Overrides Sub VisitNamespace(symbol As INamespaceSymbol)
If isFirstSymbolVisited AndAlso format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeNamespaceKeyword) Then
AddKeyword(SyntaxKind.NamespaceKeyword)
AddSpace()
End If
VisitNamespace(symbol, String.Empty)
End Sub
Private Overloads Sub VisitNamespace(symbol As INamespaceSymbol, emittedName As String)
Dim myCaseCorrectedNSName As String = symbol.Name
Dim myCaseCorrectedParentNSName As String = String.Empty
If Not emittedName.IsEmpty Then
Dim nsIdx = emittedName.LastIndexOf("."c)
If nsIdx > -1 Then
myCaseCorrectedNSName = emittedName.Substring(nsIdx + 1)
myCaseCorrectedParentNSName = emittedName.Substring(0, nsIdx)
Else
myCaseCorrectedNSName = emittedName
End If
End If
If Me.IsMinimizing Then
If TryAddAlias(symbol, builder) Then
Return
End If
MinimallyQualify(symbol, myCaseCorrectedNSName, myCaseCorrectedParentNSName)
Return
End If
Dim visitedParents As Boolean = False
If format.TypeQualificationStyle = SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces Then
Dim containingNamespace = symbol.ContainingNamespace
' add "Namespace " if SymbolDisplayKindOptions.IncludeKind is set
' this is not handled in AddTypeKind in AddTypeKind()
If containingNamespace Is Nothing AndAlso format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeNamespaceKeyword) Then
AddKeyword(SyntaxKind.NamespaceKeyword)
AddSpace()
End If
If ShouldVisitNamespace(containingNamespace) Then
VisitNamespace(containingNamespace, myCaseCorrectedParentNSName)
AddOperator(SyntaxKind.DotToken)
visitedParents = True
End If
End If
If symbol.IsGlobalNamespace Then
AddGlobalNamespace(symbol)
Else
builder.Add(CreatePart(SymbolDisplayPartKind.NamespaceName, symbol, myCaseCorrectedNSName, visitedParents))
End If
End Sub
Private Sub AddGlobalNamespace(symbol As INamespaceSymbol)
Select Case format.GlobalNamespaceStyle
Case SymbolDisplayGlobalNamespaceStyle.Omitted
Case SymbolDisplayGlobalNamespaceStyle.Included
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, symbol, SyntaxFacts.GetText(SyntaxKind.GlobalKeyword), True))
Case SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining
Debug.Assert(Me.isFirstSymbolVisited, "Don't call with IsFirstSymbolVisited = false if OmittedAsContaining")
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, symbol, SyntaxFacts.GetText(SyntaxKind.GlobalKeyword), True))
Case Else
Throw ExceptionUtilities.UnexpectedValue(format.GlobalNamespaceStyle)
End Select
End Sub
Public Overrides Sub VisitLocal(symbol As ILocalSymbol)
' Locals can be synthesized by the compiler in many cases (for example the implicit
' local in a function that has the same name as the containing function). In some
' cases the locals are anonymous (for example, a similar local in an operator).
'
' These anonymous locals should not be exposed through public APIs. However, for
' testing purposes we occasionally may print them out. In this case, give them
' a reasonable name so that tests can clearly describe what these are.
Dim name = If(symbol.Name, "<anonymous local>")
builder.Add(CreatePart(SymbolDisplayPartKind.LocalName, symbol, name, noEscaping:=False))
If format.LocalOptions.IncludesOption(SymbolDisplayLocalOptions.IncludeType) Then
AddSpace()
AddKeyword(SyntaxKind.AsKeyword)
AddSpace()
symbol.Type.Accept(Me)
End If
If symbol.IsConst AndAlso symbol.HasConstantValue AndAlso format.LocalOptions.IncludesOption(SymbolDisplayLocalOptions.IncludeConstantValue) Then
AddSpace()
AddPunctuation(SyntaxKind.EqualsToken)
AddSpace()
AddConstantValue(symbol.Type, symbol.ConstantValue)
End If
End Sub
Public Overrides Sub VisitRangeVariable(symbol As IRangeVariableSymbol)
builder.Add(CreatePart(SymbolDisplayPartKind.RangeVariableName, symbol, symbol.Name, False))
If format.LocalOptions.IncludesOption(SymbolDisplayLocalOptions.IncludeType) Then
Dim vbRangeVariable = TryCast(symbol, RangeVariableSymbol)
If vbRangeVariable IsNot Nothing Then
AddSpace()
AddKeyword(SyntaxKind.AsKeyword)
AddSpace()
DirectCast(vbRangeVariable.Type, ITypeSymbol).Accept(Me)
End If
End If
End Sub
Protected Overrides Sub AddSpace()
builder.Add(CreatePart(SymbolDisplayPartKind.Space, Nothing, " ", False))
End Sub
Private Sub AddOperator(operatorKind As SyntaxKind)
builder.Add(CreatePart(SymbolDisplayPartKind.Operator, Nothing, SyntaxFacts.GetText(operatorKind), False))
End Sub
Private Sub AddPunctuation(punctuationKind As SyntaxKind)
builder.Add(CreatePart(SymbolDisplayPartKind.Punctuation, Nothing, SyntaxFacts.GetText(punctuationKind), False))
End Sub
Private Sub AddPseudoPunctuation(text As String)
builder.Add(CreatePart(SymbolDisplayPartKind.Punctuation, Nothing, text, False))
End Sub
Private Sub AddKeyword(keywordKind As SyntaxKind)
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, Nothing, SyntaxFacts.GetText(keywordKind), False))
End Sub
Private Sub AddAccessibilityIfRequired(symbol As ISymbol)
AssertContainingSymbol(symbol)
Dim containingType = symbol.ContainingType
If format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeAccessibility) AndAlso
(containingType Is Nothing OrElse
(containingType.TypeKind <> TypeKind.Interface AndAlso Not IsEnumMember(symbol))) Then
Select Case symbol.DeclaredAccessibility
Case Accessibility.Private
AddKeyword(SyntaxKind.PrivateKeyword)
Case Accessibility.Internal
AddKeyword(SyntaxKind.FriendKeyword)
Case Accessibility.Protected
AddKeyword(SyntaxKind.ProtectedKeyword)
Case Accessibility.ProtectedAndInternal
AddKeyword(SyntaxKind.PrivateKeyword)
AddSpace()
AddKeyword(SyntaxKind.ProtectedKeyword)
Case Accessibility.ProtectedOrInternal
AddKeyword(SyntaxKind.ProtectedKeyword)
AddSpace()
AddKeyword(SyntaxKind.FriendKeyword)
Case Accessibility.Public
AddKeyword(SyntaxKind.PublicKeyword)
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility)
End Select
AddSpace()
End If
End Sub
Private Function ShouldVisitNamespace(containingSymbol As ISymbol) As Boolean
Return _
containingSymbol IsNot Nothing AndAlso
containingSymbol.Kind = SymbolKind.Namespace AndAlso
format.TypeQualificationStyle = SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces AndAlso
(Not (DirectCast(containingSymbol, INamespaceSymbol)).IsGlobalNamespace OrElse
format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Included)
End Function
Private Function IncludeNamedType(namedType As INamedTypeSymbol) As Boolean
Return _
namedType IsNot Nothing AndAlso
(Not namedType.IsScriptClass OrElse format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeScriptType))
End Function
Private Shared Function IsEnumMember(symbol As ISymbol) As Boolean
Return _
symbol IsNot Nothing AndAlso
symbol.Kind = SymbolKind.Field AndAlso
symbol.ContainingType IsNot Nothing AndAlso
symbol.ContainingType.TypeKind = TypeKind.Enum AndAlso
symbol.Name <> WellKnownMemberNames.EnumBackingFieldName
End Function
End Class
End Namespace
|
paulvanbrenk/roslyn
|
src/Compilers/VisualBasic/Portable/SymbolDisplay/SymbolDisplayVisitor.vb
|
Visual Basic
|
apache-2.0
| 18,044
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Generic
Imports System.Diagnostics
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a compiler generated field used to implement static locals.
''' There are two kind of fields: the one, that holds the value, and the one, that holds initialization "flag".
''' </summary>
Friend NotInheritable Class SynthesizedStaticLocalBackingField
Inherits SynthesizedFieldSymbol
Public ReadOnly IsValueField As Boolean
Private ReadOnly _reportErrorForLongNames As Boolean
Public Sub New(
implicitlyDefinedBy As LocalSymbol,
isValueField As Boolean,
reportErrorForLongNames As Boolean
)
MyBase.New(implicitlyDefinedBy.ContainingType,
implicitlyDefinedBy,
If(isValueField,
implicitlyDefinedBy.Type,
implicitlyDefinedBy.DeclaringCompilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag)),
If(isValueField, implicitlyDefinedBy.Name, implicitlyDefinedBy.Name & "$Init"),
isShared:=implicitlyDefinedBy.ContainingSymbol.IsShared,
isSpecialNameAndRuntimeSpecial:=True)
Debug.Assert(implicitlyDefinedBy.IsStatic)
Me.IsValueField = isValueField
Me._reportErrorForLongNames = reportErrorForLongNames
End Sub
Friend Overloads ReadOnly Property ImplicitlyDefinedBy As LocalSymbol
Get
Return DirectCast(_implicitlyDefinedBy, LocalSymbol)
End Get
End Property
Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean
Get
Return False
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
' no attributes on static backing fields - Dev12 behavior
End Sub
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedStaticLocalBackingField.vb
|
Visual Basic
|
apache-2.0
| 2,461
|
Imports System.Data.Linq.Mapping
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.ValueTypes
Imports r = System.Text.RegularExpressions.Regex
Namespace ASCII.MSL
Public Module FileReader
Private Function dataBlockParser(path As String) As IEnumerable(Of String())
Dim raw As String() = path.ReadAllText _
.Trim(" "c, CChar(vbTab), CChar(vbCr), CChar(vbLf)) _
.LineTokens
If raw.Any(Function(l) l.StringEmpty) Then
Return raw.Split(Function(s) s.StringEmpty, DelimiterLocation.NotIncludes)
Else
Return raw _
.Split(Function(s) InStr(s, "NAME:") = 1, DelimiterLocation.NextFirst) _
.Where(Function(b) Not b.IsNullOrEmpty)
End If
End Function
Public Iterator Function Load(path$, Optional unit As TimeScales = TimeScales.Second) As IEnumerable(Of MSLIon)
Dim properties = DataFramework.Schema(Of MSLIon)(PropertyAccess.Readable, True)
' property name => column name
Dim schema As Dictionary(Of String, String) = properties.Values _
.ToDictionary(Function(field) field.Name,
Function(field)
Dim map As ColumnAttribute = field.GetCustomAttribute(GetType(ColumnAttribute))
If map Is Nothing Then
Return LCase(field.Name)
Else
Return LCase(map.Name)
End If
End Function)
Dim chemicals = dataBlockParser(path).ToArray
Call schema.Remove(NameOf(MSLIon.Peaks))
For Each lines In chemicals
Dim data = lines.Split(Function(s) InStr(s, "NUM PEAKS:", CompareMethod.Text) = 1, DelimiterLocation.NotIncludes).ToArray
Dim meta As String() = data(Scan0)
Dim peaks As String() = data.ElementAtOrDefault(1)
Dim metaTable = meta _
.Select(Function(s) s.GetTagValue(":", trim:=True)) _
.ToDictionary(Function(tuple)
Return tuple.Name.ToLower
End Function)
Dim o As Object = Activator.CreateInstance(GetType(MSLIon))
For Each prop In schema
Dim write As PropertyInfo = properties(prop.Key)
Dim value As Object = Scripting.CTypeDynamic(metaTable.TryGetValue(prop.Value).Value, write.PropertyType)
If write.Name = NameOf(MSLIon.RT) Then
If unit = TimeScales.Minute Then
value = CDbl(value) * 60
End If
End If
Call write.SetValue(o, value)
Next
Yield DirectCast(o, MSLIon).With(Sub(msl) msl.Peaks = peaks.ParseMs2Peaks)
Next
End Function
Const fragment$ = "\(\s*\d+(\.\d+)?\s*\d+(\.\d+)?\s*\)"
<Extension>
Private Function ParseMs2Peaks(peaks As String()) As ms2()
Return peaks _
.Select(Function(s)
Return r.Matches(s, fragment).ToArray
End Function) _
.IteratesALL _
.Select(Function(s)
Dim p As String() = s _
.GetStackValue("(", ")") _
.Trim _
.StringSplit("\s+")
Return New ms2 With {
.intensity = Val(p(1)),
.quantity = .intensity,
.mz = Val(p(0))
}
End Function) _
.ToArray
End Function
End Module
End Namespace
|
xieguigang/spectrum
|
src/assembly/assembly/ASCII/MSL/FileReader.vb
|
Visual Basic
|
mit
| 4,254
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18034
'
' 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("HuxoTools.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 resource of type System.Drawing.Bitmap.
'''</summary>
Friend ReadOnly Property bg() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("bg", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Drawing.Bitmap.
'''</summary>
Friend ReadOnly Property HuxoTools() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("HuxoTools", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
End Module
End Namespace
|
Wovaki/huxotools
|
HuxoTools/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 3,503
|
Imports System.Windows.Forms
Public Class frmSelectPicture
Public Property Hintergrundbild As String
Public Property HintergrundThumbnail As String
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
End Sub
Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
Private Sub btnHintergrundbild_Click(sender As Object, e As EventArgs) Handles btnHintergrundbild.Click
Dim openFileDialog1 As New OpenFileDialog()
Dim Filterstring As String
Filterstring = "Vorgabe (" & My.Settings.setBackgroundImageFileFormat & ")|*." & (My.Settings.setBackgroundImageFileFormat.ToUpper) & "|Photoline (*.PLD)|*.PLD|Photoshop (*.PSD)|*.PSD|Alle Dateien (*.*)|*.*"
openFileDialog1.InitialDirectory = My.Settings.setBackgroundImagePath ' '"C:\Program Files"
openFileDialog1.Filter = Filterstring
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
txtHintergrundbild.Text = openFileDialog1.FileName
Hintergrundbild = openFileDialog1.FileName
' picPicture.ImageLocation = openFileDialog1.FileName
picPicture.Image = Image.FromFile(openFileDialog1.FileName)
Create_Thumbnail()
Catch Ex As Exception
MessageBox.Show(Err.Number & " - " & Err.Description, "Es Ist Ein Fehler Aufgetreten! btnHintergrundbild_Click")
Finally
End Try
End If
End Sub
Private Sub Create_Thumbnail()
Dim imgThumb As Image = Nothing
Try
Dim image As Image = Nothing
'Hoch oder querformat
If picPicture.Image.Size.Width > picPicture.Image.Size.Height Then
imgThumb = picPicture.Image.GetThumbnailImage(200, 141, Nothing, New IntPtr())
Else
imgThumb = picPicture.Image.GetThumbnailImage(141, 200, Nothing, New IntPtr())
End If
' Check if image exists
' If Not image Is Nothing Then
Me.Refresh()
' End If
picThumbnail.Image = imgThumb
' Button1.Image = imgThumb
picThumbnail.Image.Save(Trim(txtHintergrundbild.Text) & My.Settings.setThumbnailImageSuffix, System.Drawing.Imaging.ImageFormat.Jpeg)
txtHintergrundThumbnail.Text = Trim(txtHintergrundbild.Text) & My.Settings.setThumbnailImageSuffix
HintergrundThumbnail = txtHintergrundThumbnail.Text
Catch
MessageBox.Show(Err.Number & " - " & Err.Description, "Es Ist Ein Fehler Aufgetreten! btnHintergrundbild_Click")
End Try
End Sub
Private Sub btnHintergrundThumbnail_Click(sender As Object, e As EventArgs) Handles btnHintergrundThumbnail.Click
Dim openFileDialog1 As New OpenFileDialog()
Dim Filterstring As String
Filterstring = "Vorgabe (" & My.Settings.setBackgroundImageFileFormat & ")|*." & (My.Settings.setBackgroundImageFileFormat.ToUpper) & "|Photoline (*.PLD)|*.PLD|Photoshop (*.PSD)|*.PSD|Alle Dateien (*.*)|*.*"
openFileDialog1.InitialDirectory = My.Settings.setBackgroundImagePath ' '"C:\Program Files"
openFileDialog1.Filter = Filterstring
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
txtHintergrundThumbnail.Text = openFileDialog1.FileName
HintergrundThumbnail = openFileDialog1.FileName
Catch Ex As Exception
MessageBox.Show(Err.Number & " - " & Err.Description, "Es Ist Ein Fehler Aufgetreten! btnHintergrundbild_Click")
Finally
End Try
End If
End Sub
End Class
|
FrankGITDeveloper/Landsknecht_GreenScreen
|
Landsknecht_GreenScreen/frmSelectPicture.vb
|
Visual Basic
|
mit
| 4,217
|
Partial Class RepContabilizacionFondoFijo
'NOTE: The following procedure is required by the telerik Reporting Designer
'It can be modified using the telerik Reporting Designer.
'Do not modify it using the code editor.
Private Sub InitializeComponent()
Dim ReportParameter1 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter()
Dim StyleRule1 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule2 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule3 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule4 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Me.DSRepContabilizacionFondoFijo = New Telerik.Reporting.SqlDataSource()
Me.reportFooter = New Telerik.Reporting.ReportFooterSection()
Me.montoSumFunctionTextBox = New Telerik.Reporting.TextBox()
Me.TextBox14 = New Telerik.Reporting.TextBox()
Me.labelsGroupHeader = New Telerik.Reporting.GroupHeaderSection()
Me.registroCaptionTextBox = New Telerik.Reporting.TextBox()
Me.montoCaptionTextBox = New Telerik.Reporting.TextBox()
Me.cuentaCaptionTextBox = New Telerik.Reporting.TextBox()
Me.cCostoCaptionTextBox = New Telerik.Reporting.TextBox()
Me.glosaCaptionTextBox = New Telerik.Reporting.TextBox()
Me.TextBox12 = New Telerik.Reporting.TextBox()
Me.labelsGroupFooter = New Telerik.Reporting.GroupFooterSection()
Me.labelsGroup = New Telerik.Reporting.Group()
Me.responsableCaptionTextBox = New Telerik.Reporting.TextBox()
Me.mesCaptionTextBox = New Telerik.Reporting.TextBox()
Me.pageHeader = New Telerik.Reporting.PageHeaderSection()
Me.TextBox3 = New Telerik.Reporting.TextBox()
Me.TextBox2 = New Telerik.Reporting.TextBox()
Me.reportNameTextBox = New Telerik.Reporting.TextBox()
Me.TextBox39 = New Telerik.Reporting.TextBox()
Me.TextBox38 = New Telerik.Reporting.TextBox()
Me.TextBox9 = New Telerik.Reporting.TextBox()
Me.TextBox8 = New Telerik.Reporting.TextBox()
Me.TextBox7 = New Telerik.Reporting.TextBox()
Me.TextBox4 = New Telerik.Reporting.TextBox()
Me.pageFooter = New Telerik.Reporting.PageFooterSection()
Me.reportHeader = New Telerik.Reporting.ReportHeaderSection()
Me.titleTextBox = New Telerik.Reporting.TextBox()
Me.TextBox1 = New Telerik.Reporting.TextBox()
Me.TextBox5 = New Telerik.Reporting.TextBox()
Me.TextBox6 = New Telerik.Reporting.TextBox()
Me.TextBox10 = New Telerik.Reporting.TextBox()
Me.responsableDataTextBox = New Telerik.Reporting.TextBox()
Me.ejercicioDataTextBox = New Telerik.Reporting.TextBox()
Me.mesDataTextBox = New Telerik.Reporting.TextBox()
Me.nroLiqDataTextBox = New Telerik.Reporting.TextBox()
Me.TextBox11 = New Telerik.Reporting.TextBox()
Me.detail = New Telerik.Reporting.DetailSection()
Me.registroDataTextBox = New Telerik.Reporting.TextBox()
Me.montoDataTextBox = New Telerik.Reporting.TextBox()
Me.cuentaDataTextBox = New Telerik.Reporting.TextBox()
Me.cCostoDataTextBox = New Telerik.Reporting.TextBox()
Me.glosaDataTextBox = New Telerik.Reporting.TextBox()
Me.TextBox13 = New Telerik.Reporting.TextBox()
CType(Me, System.ComponentModel.ISupportInitialize).BeginInit()
'
'DSRepContabilizacionFondoFijo
'
Me.DSRepContabilizacionFondoFijo.ConnectionString = "cnx"
Me.DSRepContabilizacionFondoFijo.Name = "DSRepContabilizacionFondoFijo"
Me.DSRepContabilizacionFondoFijo.Parameters.AddRange(New Telerik.Reporting.SqlDataSourceParameter() {New Telerik.Reporting.SqlDataSourceParameter("@idRendicion", System.Data.DbType.Int32, "=Parameters.idRendicion.Value")})
Me.DSRepContabilizacionFondoFijo.SelectCommand = "dbo.RepContabilizacionFondoFijo"
Me.DSRepContabilizacionFondoFijo.SelectCommandType = Telerik.Reporting.SqlDataSourceCommandType.StoredProcedure
'
'reportFooter
'
Me.reportFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.reportFooter.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.montoSumFunctionTextBox, Me.TextBox14})
Me.reportFooter.Name = "reportFooter"
Me.reportFooter.Style.Visible = True
'
'montoSumFunctionTextBox
'
Me.montoSumFunctionTextBox.CanGrow = True
Me.montoSumFunctionTextBox.Format = "{0:N2}"
Me.montoSumFunctionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(7.9997997283935547R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoSumFunctionTextBox.Name = "montoSumFunctionTextBox"
Me.montoSumFunctionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoSumFunctionTextBox.Style.BorderStyle.Top = Telerik.Reporting.Drawing.BorderType.Solid
Me.montoSumFunctionTextBox.Style.Font.Bold = True
Me.montoSumFunctionTextBox.Style.Font.Name = "Arial"
Me.montoSumFunctionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.montoSumFunctionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.montoSumFunctionTextBox.StyleName = "Data"
Me.montoSumFunctionTextBox.Value = "=Sum(Fields.Monto)"
'
'TextBox14
'
Me.TextBox14.CanGrow = True
Me.TextBox14.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(5.4998002052307129R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox14.Name = "TextBox14"
Me.TextBox14.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.4997992515563965R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox14.Style.Font.Bold = True
Me.TextBox14.Style.Font.Name = "Arial"
Me.TextBox14.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox14.StyleName = "Caption"
Me.TextBox14.Value = "TOTAL GENERAL:"
'
'labelsGroupHeader
'
Me.labelsGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.labelsGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.registroCaptionTextBox, Me.montoCaptionTextBox, Me.cuentaCaptionTextBox, Me.cCostoCaptionTextBox, Me.glosaCaptionTextBox, Me.TextBox12})
Me.labelsGroupHeader.Name = "labelsGroupHeader"
Me.labelsGroupHeader.PrintOnEveryPage = True
Me.labelsGroupHeader.Style.BorderStyle.Bottom = Telerik.Reporting.Drawing.BorderType.Dashed
Me.labelsGroupHeader.Style.BorderStyle.Top = Telerik.Reporting.Drawing.BorderType.Dashed
'
'registroCaptionTextBox
'
Me.registroCaptionTextBox.CanGrow = True
Me.registroCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(5.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.registroCaptionTextBox.Name = "registroCaptionTextBox"
Me.registroCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.9995989799499512R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.registroCaptionTextBox.Style.Font.Name = "Arial"
Me.registroCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.registroCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.registroCaptionTextBox.StyleName = "Caption"
Me.registroCaptionTextBox.Value = "Registro"
'
'montoCaptionTextBox
'
Me.montoCaptionTextBox.CanGrow = True
Me.montoCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(7.9997997283935547R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoCaptionTextBox.Name = "montoCaptionTextBox"
Me.montoCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoCaptionTextBox.Style.Font.Name = "Arial"
Me.montoCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.montoCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.montoCaptionTextBox.StyleName = "Caption"
Me.montoCaptionTextBox.Value = "Monto"
'
'cuentaCaptionTextBox
'
Me.cuentaCaptionTextBox.CanGrow = True
Me.cuentaCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.99999988079071045R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cuentaCaptionTextBox.Name = "cuentaCaptionTextBox"
Me.cuentaCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cuentaCaptionTextBox.Style.Font.Name = "Arial"
Me.cuentaCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cuentaCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.cuentaCaptionTextBox.StyleName = "Caption"
Me.cuentaCaptionTextBox.Value = "Cuenta"
'
'cCostoCaptionTextBox
'
Me.cCostoCaptionTextBox.CanGrow = True
Me.cCostoCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(3.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cCostoCaptionTextBox.Name = "cCostoCaptionTextBox"
Me.cCostoCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cCostoCaptionTextBox.Style.Font.Name = "Arial"
Me.cCostoCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cCostoCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.cCostoCaptionTextBox.StyleName = "Caption"
Me.cCostoCaptionTextBox.Value = "CCosto"
'
'glosaCaptionTextBox
'
Me.glosaCaptionTextBox.CanGrow = True
Me.glosaCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(10.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.00010012308484874666R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.glosaCaptionTextBox.Name = "glosaCaptionTextBox"
Me.glosaCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(8.5000009536743164R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.glosaCaptionTextBox.Style.Font.Name = "Arial"
Me.glosaCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.glosaCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.glosaCaptionTextBox.StyleName = "Caption"
Me.glosaCaptionTextBox.Value = "Glosa"
'
'TextBox12
'
Me.TextBox12.CanGrow = True
Me.TextBox12.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.00010012308484874666R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox12.Name = "TextBox12"
Me.TextBox12.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox12.Style.Font.Name = "Arial"
Me.TextBox12.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox12.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.TextBox12.StyleName = "Caption"
Me.TextBox12.Value = "Item"
'
'labelsGroupFooter
'
Me.labelsGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.labelsGroupFooter.Name = "labelsGroupFooter"
Me.labelsGroupFooter.Style.Visible = False
'
'labelsGroup
'
Me.labelsGroup.GroupFooter = Me.labelsGroupFooter
Me.labelsGroup.GroupHeader = Me.labelsGroupHeader
Me.labelsGroup.Name = "labelsGroup"
'
'responsableCaptionTextBox
'
Me.responsableCaptionTextBox.CanGrow = True
Me.responsableCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.00010012308484874666R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(2.5000002384185791R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.responsableCaptionTextBox.Name = "responsableCaptionTextBox"
Me.responsableCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.responsableCaptionTextBox.Style.Font.Name = "Arial"
Me.responsableCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.responsableCaptionTextBox.StyleName = "Caption"
Me.responsableCaptionTextBox.Value = "Responsable"
'
'mesCaptionTextBox
'
Me.mesCaptionTextBox.CanGrow = True
Me.mesCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(5.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.9999996423721313R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.mesCaptionTextBox.Name = "mesCaptionTextBox"
Me.mesCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.4999005794525146R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.mesCaptionTextBox.Style.Font.Name = "Arial"
Me.mesCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.mesCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.mesCaptionTextBox.StyleName = "Caption"
Me.mesCaptionTextBox.Value = "Mes"
'
'pageHeader
'
Me.pageHeader.Height = New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.pageHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox3, Me.TextBox2, Me.reportNameTextBox, Me.TextBox39, Me.TextBox38, Me.TextBox9, Me.TextBox8, Me.TextBox7, Me.TextBox4})
Me.pageHeader.Name = "pageHeader"
'
'TextBox3
'
Me.TextBox3.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox3.Name = "TextBox3"
Me.TextBox3.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(14.999799728393555R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox3.Style.Font.Bold = True
Me.TextBox3.Style.Font.Name = "Arial"
Me.TextBox3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(8.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox3.StyleName = "PageInfo"
Me.TextBox3.Value = "Jr. Ciro Alegría N° 296 - Cajamarca"
'
'TextBox2
'
Me.TextBox2.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(14.999799728393555R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox2.Style.Font.Bold = True
Me.TextBox2.Style.Font.Name = "Arial"
Me.TextBox2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(8.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox2.StyleName = "PageInfo"
Me.TextBox2.Value = "RUC: 20453262767"
'
'reportNameTextBox
'
Me.reportNameTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.000099921220680698752R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.reportNameTextBox.Name = "reportNameTextBox"
Me.reportNameTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(14.999799728393555R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.reportNameTextBox.Style.Font.Bold = True
Me.reportNameTextBox.Style.Font.Name = "Arial"
Me.reportNameTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(8.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.reportNameTextBox.StyleName = "PageInfo"
Me.reportNameTextBox.Value = "FONCREAGRO"
'
'TextBox39
'
Me.TextBox39.Format = "{0:d}"
Me.TextBox39.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99999982118606567R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox39.Name = "TextBox39"
Me.TextBox39.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.4997981786727905R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox39.Style.Font.Name = "Arial"
Me.TextBox39.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox39.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.TextBox39.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox39.StyleName = "PageInfo"
Me.TextBox39.Value = "Hora:"
'
'TextBox38
'
Me.TextBox38.Format = "{0:t}"
Me.TextBox38.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(16.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99999982118606567R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox38.Name = "TextBox38"
Me.TextBox38.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox38.Style.Font.Name = "Arial"
Me.TextBox38.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox38.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox38.StyleName = "PageInfo"
Me.TextBox38.Value = "= Now()"
'
'TextBox9
'
Me.TextBox9.Format = "{0:d}"
Me.TextBox9.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(16.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.50000005960464478R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox9.Name = "TextBox9"
Me.TextBox9.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox9.Style.Font.Name = "Arial"
Me.TextBox9.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox9.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox9.StyleName = "PageInfo"
Me.TextBox9.Value = "= Now()"
'
'TextBox8
'
Me.TextBox8.Format = "{0:d}"
Me.TextBox8.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.50000005960464478R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox8.Name = "TextBox8"
Me.TextBox8.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.4997981786727905R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox8.Style.Font.Name = "Arial"
Me.TextBox8.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox8.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.TextBox8.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox8.StyleName = "PageInfo"
Me.TextBox8.Value = "Fecha:"
'
'TextBox7
'
Me.TextBox7.Format = "{0:d}"
Me.TextBox7.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox7.Name = "TextBox7"
Me.TextBox7.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.4997981786727905R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox7.Style.Font.Name = "Arial"
Me.TextBox7.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox7.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.TextBox7.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox7.StyleName = "PageInfo"
Me.TextBox7.Value = "Página:"
'
'TextBox4
'
Me.TextBox4.Format = "{0:g}"
Me.TextBox4.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(16.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox4.Name = "TextBox4"
Me.TextBox4.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox4.Style.Font.Name = "Arial"
Me.TextBox4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox4.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.TextBox4.StyleName = "PageInfo"
Me.TextBox4.Value = "=PageNumber"
'
'pageFooter
'
Me.pageFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.pageFooter.Name = "pageFooter"
'
'reportHeader
'
Me.reportHeader.Height = New Telerik.Reporting.Drawing.Unit(3.5000002384185791R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.reportHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.titleTextBox, Me.TextBox1, Me.TextBox5, Me.TextBox6, Me.TextBox10, Me.responsableCaptionTextBox, Me.responsableDataTextBox, Me.ejercicioDataTextBox, Me.mesCaptionTextBox, Me.mesDataTextBox, Me.nroLiqDataTextBox, Me.TextBox11})
Me.reportHeader.Name = "reportHeader"
'
'titleTextBox
'
Me.titleTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.000099921220680698752R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.titleTextBox.Name = "titleTextBox"
Me.titleTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(18.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.titleTextBox.Style.Color = System.Drawing.Color.Black
Me.titleTextBox.Style.Font.Bold = True
Me.titleTextBox.Style.Font.Name = "Arial"
Me.titleTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(10.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.titleTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.titleTextBox.StyleName = "Title"
Me.titleTextBox.Value = "PARTE DE CONTABILIZACION DEL FONDO FIJO"
'
'TextBox1
'
Me.TextBox1.CanGrow = True
Me.TextBox1.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.4999997615814209R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(16.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox1.Style.Font.Name = "Arial"
Me.TextBox1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox1.StyleName = "Data"
Me.TextBox1.Value = ": {Fields.Proyecto}"
'
'TextBox5
'
Me.TextBox5.CanGrow = True
Me.TextBox5.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.4999997615814209R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox5.Name = "TextBox5"
Me.TextBox5.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox5.Style.Font.Name = "Arial"
Me.TextBox5.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox5.StyleName = "Caption"
Me.TextBox5.Value = "Proyecto"
'
'TextBox6
'
Me.TextBox6.CanGrow = True
Me.TextBox6.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(2.0002002716064453R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox6.Name = "TextBox6"
Me.TextBox6.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox6.Style.Font.Name = "Arial"
Me.TextBox6.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox6.StyleName = "Caption"
Me.TextBox6.Value = "Ejercicio"
'
'TextBox10
'
Me.TextBox10.CanGrow = True
Me.TextBox10.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.00010012308484874666R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0000001192092896R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox10.Name = "TextBox10"
Me.TextBox10.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox10.Style.Font.Name = "Arial"
Me.TextBox10.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox10.StyleName = "Caption"
Me.TextBox10.Value = "N° Liquidación"
'
'responsableDataTextBox
'
Me.responsableDataTextBox.CanGrow = True
Me.responsableDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.0000002384185791R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(2.5000004768371582R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.responsableDataTextBox.Name = "responsableDataTextBox"
Me.responsableDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(16.999496459960937R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.responsableDataTextBox.Style.Font.Name = "Arial"
Me.responsableDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.responsableDataTextBox.StyleName = "Data"
Me.responsableDataTextBox.Value = ": {Fields.Responsable}"
'
'ejercicioDataTextBox
'
Me.ejercicioDataTextBox.CanGrow = True
Me.ejercicioDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.9999996423721313R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.ejercicioDataTextBox.Name = "ejercicioDataTextBox"
Me.ejercicioDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(3.0002000331878662R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.ejercicioDataTextBox.Style.Font.Name = "Arial"
Me.ejercicioDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.ejercicioDataTextBox.StyleName = "Data"
Me.ejercicioDataTextBox.Value = ": {Fields.Ejercicio}"
'
'mesDataTextBox
'
Me.mesDataTextBox.CanGrow = True
Me.mesDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(6.5000004768371582R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.9999996423721313R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.mesDataTextBox.Name = "mesDataTextBox"
Me.mesDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9997000694274902R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.mesDataTextBox.Style.Font.Name = "Arial"
Me.mesDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.mesDataTextBox.StyleName = "Data"
Me.mesDataTextBox.Value = ": {Fields.Mes}"
'
'nroLiqDataTextBox
'
Me.nroLiqDataTextBox.CanGrow = True
Me.nroLiqDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99979943037033081R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.nroLiqDataTextBox.Name = "nroLiqDataTextBox"
Me.nroLiqDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(3.0004997253417969R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.nroLiqDataTextBox.Style.Font.Name = "Arial"
Me.nroLiqDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.nroLiqDataTextBox.StyleName = "Data"
Me.nroLiqDataTextBox.Value = ": {Fields.NroLiq}"
'
'TextBox11
'
Me.TextBox11.CanGrow = True
Me.TextBox11.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(10.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.9999996423721313R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox11.Name = "TextBox11"
Me.TextBox11.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(8.5000009536743164R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox11.Style.Font.Name = "Arial"
Me.TextBox11.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox11.StyleName = "Caption"
Me.TextBox11.Value = "Moneda : 01 Nuevos Soles"
'
'detail
'
Me.detail.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.detail.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.registroDataTextBox, Me.montoDataTextBox, Me.cuentaDataTextBox, Me.cCostoDataTextBox, Me.glosaDataTextBox, Me.TextBox13})
Me.detail.Name = "detail"
'
'registroDataTextBox
'
Me.registroDataTextBox.CanGrow = True
Me.registroDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(5.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.registroDataTextBox.Name = "registroDataTextBox"
Me.registroDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.9995989799499512R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.registroDataTextBox.Style.Font.Name = "Arial"
Me.registroDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.registroDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left
Me.registroDataTextBox.StyleName = "Data"
Me.registroDataTextBox.Value = "=Fields.Registro"
'
'montoDataTextBox
'
Me.montoDataTextBox.CanGrow = True
Me.montoDataTextBox.Format = "{0:N2}"
Me.montoDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(7.9997997283935547R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoDataTextBox.Name = "montoDataTextBox"
Me.montoDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoDataTextBox.Style.Font.Name = "Arial"
Me.montoDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.montoDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.montoDataTextBox.StyleName = "Data"
Me.montoDataTextBox.Value = "=Fields.Monto"
'
'cuentaDataTextBox
'
Me.cuentaDataTextBox.CanGrow = True
Me.cuentaDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.99999988079071045R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cuentaDataTextBox.Name = "cuentaDataTextBox"
Me.cuentaDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cuentaDataTextBox.Style.Font.Name = "Arial"
Me.cuentaDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cuentaDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.cuentaDataTextBox.StyleName = "Data"
Me.cuentaDataTextBox.Value = "=Fields.Cuenta"
'
'cCostoDataTextBox
'
Me.cCostoDataTextBox.CanGrow = True
Me.cCostoDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(3.0000002384185791R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cCostoDataTextBox.Name = "cCostoDataTextBox"
Me.cCostoDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cCostoDataTextBox.Style.Font.Name = "Arial"
Me.cCostoDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cCostoDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.cCostoDataTextBox.StyleName = "Data"
Me.cCostoDataTextBox.Value = "=Fields.CCosto"
'
'glosaDataTextBox
'
Me.glosaDataTextBox.CanGrow = True
Me.glosaDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(10.000000953674316R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.glosaDataTextBox.Name = "glosaDataTextBox"
Me.glosaDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(8.5000009536743164R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.glosaDataTextBox.Style.Font.Name = "Arial"
Me.glosaDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.glosaDataTextBox.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.30000001192092896R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.glosaDataTextBox.StyleName = "Data"
Me.glosaDataTextBox.Value = "=Fields.Glosa"
'
'TextBox13
'
Me.TextBox13.CanGrow = True
Me.TextBox13.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.00010012308484874666R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox13.Name = "TextBox13"
Me.TextBox13.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox13.Style.Font.Name = "Arial"
Me.TextBox13.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(7.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox13.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.TextBox13.StyleName = "Caption"
Me.TextBox13.Value = "= RowNumber()"
'
'RepContabilizacionFondoFijo
'
Me.DataSource = Me.DSRepContabilizacionFondoFijo
Me.Groups.AddRange(New Telerik.Reporting.Group() {Me.labelsGroup})
Me.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.labelsGroupHeader, Me.labelsGroupFooter, Me.reportFooter, Me.pageHeader, Me.pageFooter, Me.reportHeader, Me.detail})
Me.PageSettings.Landscape = False
Me.PageSettings.Margins.Bottom = New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Left = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Right = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Top = New Telerik.Reporting.Drawing.Unit(1.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.PaperKind = System.Drawing.Printing.PaperKind.A4
ReportParameter1.Name = "idRendicion"
ReportParameter1.Text = "idRendicion"
ReportParameter1.Type = Telerik.Reporting.ReportParameterType.[Integer]
ReportParameter1.Visible = True
Me.ReportParameters.Add(ReportParameter1)
Me.Style.BackgroundColor = System.Drawing.Color.White
StyleRule1.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Title")})
StyleRule1.Style.Color = System.Drawing.Color.Black
StyleRule1.Style.Font.Bold = True
StyleRule1.Style.Font.Italic = False
StyleRule1.Style.Font.Name = "Tahoma"
StyleRule1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(20.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule1.Style.Font.Strikeout = False
StyleRule1.Style.Font.Underline = False
StyleRule2.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Caption")})
StyleRule2.Style.Color = System.Drawing.Color.Black
StyleRule2.Style.Font.Name = "Tahoma"
StyleRule2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule2.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
StyleRule3.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Data")})
StyleRule3.Style.Font.Name = "Tahoma"
StyleRule3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule3.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
StyleRule4.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("PageInfo")})
StyleRule4.Style.Font.Name = "Tahoma"
StyleRule4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule4.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
Me.StyleSheet.AddRange(New Telerik.Reporting.Drawing.StyleRule() {StyleRule1, StyleRule2, StyleRule3, StyleRule4})
Me.Width = New Telerik.Reporting.Drawing.Unit(18.5R, Telerik.Reporting.Drawing.UnitType.Cm)
CType(Me, System.ComponentModel.ISupportInitialize).EndInit()
End Sub
Friend WithEvents DSRepContabilizacionFondoFijo As Telerik.Reporting.SqlDataSource
Friend WithEvents reportFooter As Telerik.Reporting.ReportFooterSection
Friend WithEvents montoSumFunctionTextBox As Telerik.Reporting.TextBox
Friend WithEvents labelsGroupHeader As Telerik.Reporting.GroupHeaderSection
Friend WithEvents responsableCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents registroCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents montoCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents cuentaCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents mesCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents cCostoCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents glosaCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents labelsGroupFooter As Telerik.Reporting.GroupFooterSection
Friend WithEvents labelsGroup As Telerik.Reporting.Group
Friend WithEvents pageHeader As Telerik.Reporting.PageHeaderSection
Friend WithEvents pageFooter As Telerik.Reporting.PageFooterSection
Friend WithEvents reportHeader As Telerik.Reporting.ReportHeaderSection
Friend WithEvents detail As Telerik.Reporting.DetailSection
Friend WithEvents nroLiqDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents responsableDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents registroDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents montoDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents cuentaDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents mesDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents ejercicioDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents cCostoDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents glosaDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox3 As Telerik.Reporting.TextBox
Friend WithEvents TextBox2 As Telerik.Reporting.TextBox
Friend WithEvents reportNameTextBox As Telerik.Reporting.TextBox
Friend WithEvents titleTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox1 As Telerik.Reporting.TextBox
Friend WithEvents TextBox5 As Telerik.Reporting.TextBox
Friend WithEvents TextBox6 As Telerik.Reporting.TextBox
Friend WithEvents TextBox10 As Telerik.Reporting.TextBox
Friend WithEvents TextBox11 As Telerik.Reporting.TextBox
Friend WithEvents TextBox12 As Telerik.Reporting.TextBox
Friend WithEvents TextBox13 As Telerik.Reporting.TextBox
Friend WithEvents TextBox14 As Telerik.Reporting.TextBox
Friend WithEvents TextBox39 As Telerik.Reporting.TextBox
Friend WithEvents TextBox38 As Telerik.Reporting.TextBox
Friend WithEvents TextBox9 As Telerik.Reporting.TextBox
Friend WithEvents TextBox8 As Telerik.Reporting.TextBox
Friend WithEvents TextBox7 As Telerik.Reporting.TextBox
Friend WithEvents TextBox4 As Telerik.Reporting.TextBox
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.Report/RepContabilizacionFondoFijo.Designer.vb
|
Visual Basic
|
mit
| 47,895
|
Namespace RowsAndColumns
Public Class HandleColumnFilterEvents
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
' If first visit, load GridWeb data
If Not Page.IsPostBack AndAlso Not GridWeb1.IsPostBack Then
LoadData()
Else
Label1.Text = ""
End If
End Sub
Private Sub LoadData()
' Gets the web application's path.
Dim path As String = TryCast(Me.Master, Site).GetDataDir()
Dim fileName As String = path + "\RowsAndColumns\Products.xlsx"
' Imports from an excel file.
GridWeb1.ImportExcelFile(fileName)
GridWeb1.ActiveCell = GridWeb1.WorkSheets(0).Cells("A1")
' Access active worksheet
Dim sheet = GridWeb1.WorkSheets(Me.GridWeb1.ActiveSheetIndex)
' Enable GridWeb's auto-filter.
sheet.AddAutoFilter(0, 0, sheet.Cells.MaxDataColumn)
sheet.RefreshFilter()
End Sub
' ExStart:BeforeColumnFilter
Protected Sub GridWeb1_BeforeColumnFilter(sender As Object, e As RowColumnEventArgs)
' Display the column index and filter applied
Dim msg As String = "[Column Index]: " & (e.Num) & ", [Filter Value]: " & e.Argument
Label1.Text = msg
End Sub
' ExEnd:BeforeColumnFilter
' ExStart:AfterColumnFilter
Protected Sub GridWeb1_AfterColumnFilter(sender As Object, e As RowColumnEventArgs)
Dim hidden As String = ""
Dim headrow As Integer = 0
Dim maxrow As Integer = GridWeb1.WorkSheets(0).Cells.MaxRow
Dim count As Integer = 0
' Iterate all worksheet rows to find out filtered rows
Dim i As Integer = headrow + 1
While i <= maxrow
If GridWeb1.WorkSheets(0).Cells.Rows(i).Hidden Then
hidden += "-" + (i + 1)
Else
count += 1
End If
i += 1
End While
' Display hidden rows and visible rows count
Dim msg As String = "[Hidden Rows]: " & hidden & " [Visible Rows]: " & count
Label1.Text = msg
End Sub
' ExEnd:AfterColumnFilter
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples.GridWeb/VisualBasic/RowsAndColumns/HandleColumnFilterEvents.aspx.vb
|
Visual Basic
|
mit
| 2,394
|
Imports System.Text
Imports HomeSeerAPI
Friend Module Util
#Region "No Longer Needed"
#If NoLongerNeeded Then
Public Function AddLink(ByVal ref As String, ByVal label As String, Optional ByVal image As String = "", Optional ByVal w As Integer = 0, Optional ByVal h As Integer = 0) As String
Dim st As String = ""
On Error Resume Next
If image = "" Then
st = "<a href=""" + ref + """>" + label + "</a>" + vbCrLf
Else
st = "<a href=""" + ref + """>" + label + "<img src=""" + image + """ width=""" + Str(w) + """ height=""" + Str(h) + """ border=""0""></a>" + vbCrLf
End If
AddLink = st
End Function
Public Function HTML_StartCell(ByVal SClass As String, ByVal colspan As Integer, Optional ByVal align As Integer = 0, Optional ByVal nowrap As Boolean = False) As String
Dim st As String = ""
Dim stalign As String = ""
Dim wrap As String = ""
On Error Resume Next
If nowrap Then
wrap = " nowrap"
Else
wrap = ""
End If
If align = 0 Then
stalign = ""
Else
If align = ALIGN_RIGHT Then
stalign = " align=""right"""
ElseIf align = ALIGN_LEFT Then
stalign = " align=""left"""
ElseIf align = ALIGN_CENTER Then
stalign = " align=""center"""
End If
End If
If SClass = "" Then
st = "<td" + wrap + stalign + " colspan=""" + Trim(Str(colspan)) + """>"
Else
st = "<td" + wrap + stalign + " colspan=""" + Trim(Str(colspan)) + """ class=""" + SClass + """>"
End If
HTML_StartCell = st
End Function
Public Function HTML_StartTable(ByVal border As Integer, Optional ByVal spacing As Integer = 0, Optional ByVal width As String = "") As String
Dim st As String = ""
Dim w As String
On Error Resume Next
If width = "" Then
w = ""
Else
w = "width=""" & width & """"
End If
If spacing = 0 Then
st = "<table border=""" + Trim(Str(border)) + """ cellpadding=""0"" cellspacing=""0"" " + w + ">" + vbCrLf
Else
st = "<table border=""" + Trim(Str(border)) + """ cellpadding=""0"" cellspacing=""" + Trim(Str(spacing)) + """" + " " + w + "> " + vbCrLf
End If
HTML_StartTable = st
End Function
Public Function AddHidden(ByVal name As String, ByVal Value As String) As String
Dim st As String = ""
On Error Resume Next
st = "<input type=""hidden"" name=""" + name + """ value=""" + Value + """>"
AddHidden = st
End Function
Public Function FormButton(ByVal name As String, ByVal Value As String, Optional ByVal style As String = "") As String
Dim st As String = ""
On Error Resume Next
st = st + "<input " & style & " class=""formbutton"" type=""submit"" name=""" + name + """ value=""" + Value + """>" + vbCrLf
FormButton = st
End Function
Public Function FormTextArea(ByRef label As String, ByRef name As String, ByRef value As String, ByRef rows As Integer, ByRef cols As Integer) As String
Dim st As String = ""
st = label & "<textarea rows=""" & rows.ToString & """ cols=""" & cols.ToString & """ name=""" & name & """>" & value & "</textarea>" & vbCrLf
FormTextArea = st
End Function
Public Function FormTextBox(ByRef label As String, ByRef Name As String, ByRef Value As String, ByRef fieldsize As Integer) As String
Dim st As New StringBuilder
Dim newline As String = ""
Dim v As String = ""
On Error Resume Next
If Value Is Nothing Then
v = ""
Else
v = Value
End If
If label <> "" Then
newline = "<br>"
End If
st.Append(label)
st.Append(newline)
st.Append("<input class=""formtext"" type=""text"" size=""" & fieldsize.ToString & """ name=""")
st.Append(Name)
st.Append(""" value=""")
st.Append(v)
st.Append(""">" & vbCrLf)
Return st.ToString
End Function
Public Function FormDropDown(ByRef label As String, ByRef Name_Renamed As String, ByRef options() As pair, ByRef option_count As Short, ByRef selected As Short, Optional ByRef OnChange As Boolean = False) As String
Dim st As New StringBuilder
Dim i As Short
Dim sel As String = ""
Dim newline As String = ""
On Error Resume Next
If label <> "" Then
newline = "<br>"
End If
st.Append(label & newline)
If OnChange Then
st.Append("<select class=""formdropdown"" name=""" & Name_Renamed & """ size=""1"" onchange=""submit();"">" & vbCrLf)
Else
st.Append("<select class=""formdropdown"" name=""" & Name_Renamed & """ size=""1"">" & vbCrLf)
End If
For i = 0 To option_count - 1
If i = selected Then
sel = "selected "
Else
sel = ""
End If
st.Append("<option " & sel & "value=""" & options(i).value & """>" & options(i).name & "</option>" & vbCrLf)
Next
st.Append("</select>" & vbCrLf)
FormDropDown = st.ToString
End Function
Sub GetFormData(ByVal sFormData As String)
'================================================
' Get the CGI data from STDIN or from QueryString
' Store name/value pairs
'================================================
Dim sBuff As String ' buffer to receive POST method data
Dim sname As String ' temp string to hold a form item name
Dim sValue As String ' temp string to hold a form item value
Dim lBytesRead As Integer ' actual bytes read by POST method
Dim rc As Integer ' return code
Dim pointer As Integer ' sFormData position pointer
Dim n As Integer ' name/value pair counter
Dim delim1 As Integer ' position of "="
Dim delim2 As Integer ' position of "&"
On Error Resume Next
'=========================================
' Parse and decode form data
'=========================================
' Data is received from browser as "name=value&name=value&...name=value"
' Names and values are URL-encoded
'
' Store name/value pairs in array tPair(), and decode the values
'
' redim tPair() based on the number of pairs found in sFormData
pointer = 1
lPairs = 0
Do
delim1 = InStr(pointer, sFormData, "=")
If delim1 = 0 Then Exit Do
pointer = delim1 + 1
lPairs = lPairs + 1
Loop
ReDim tPair(lPairs)
' assign values to tPair().name and tPair().value
pointer = 1
For n = 0 To (lPairs - 1)
delim1 = InStr(pointer, sFormData, "=") ' find next equal sign
If delim1 = 0 Then Exit For ' parse complete
tPair(n).name = UrlDecode(Mid$(sFormData, pointer, delim1 - pointer))
delim2 = InStr(delim1, sFormData, "&")
' if no trailing ampersand, we are at the end of data
If delim2 = 0 Then delim2 = Len(sFormData) + 1
' value is between the "=" and the "&"
tPair(n).value = UrlDecode(Mid$(sFormData, delim1 + 1, delim2 - delim1 - 1))
pointer = delim2 + 1
Next n
End Sub
Public Function UrlDecode(ByRef sEncoded As String) As String
'========================================================
' Accept url-encoded string
' Return decoded string
'========================================================
Dim x As Integer ' sEncoded position pointer
Dim pos As Integer ' position of InStr target
On Error Resume Next
UrlDecode = sEncoded
If sEncoded = "" Then Exit Function
' convert "+" to space
x = 1
Do
pos = InStr(x, sEncoded, "+")
If pos = 0 Then Exit Do
Mid(sEncoded, pos, 1) = " "
x = pos + 1
Loop
x = 1
' convert "%xx" to character
Do
pos = InStr(x, sEncoded, "%")
If pos = 0 Then Exit Do
Mid(sEncoded, pos, 1) = Chr(CInt("&H" & (Mid(sEncoded, pos + 1, 2))))
sEncoded = Microsoft.VisualBasic.Left(sEncoded, pos) & Mid(sEncoded, pos + 3)
x = pos + 1
Loop
UrlDecode = sEncoded
End Function
#End If
#End Region
End Module
|
HomeSeer/HSPI_MEDIAPLAYER
|
util.vb
|
Visual Basic
|
mit
| 8,798
|
Imports System.Drawing
Friend NotInheritable Class GraphicHelper
''' <summary>
''' Convert value from specified unit to pixel on horizontal resolution
''' </summary>
Public Shared Function ToPixelX(graph As Graphics,
value As Double,
scale As GraphicsUnit) As Integer
Select Case scale
Case GraphicsUnit.Millimeter
Return CInt(Math.Truncate(graph.DpiX * value / 25.4))
Case GraphicsUnit.Inch
Return CInt(Math.Truncate(graph.DpiX * value))
Case GraphicsUnit.Point
Return CInt(Math.Truncate(graph.DpiX * value / 72))
Case GraphicsUnit.Document
Return CInt(Math.Truncate(graph.DpiX * value / 300))
End Select
Return CInt(value)
End Function
''' <summary>
''' Convert value from specified unit to pixel on vertical resolution
''' </summary>
Public Shared Function ToPixelY(graph As Graphics,
value As Double,
scale As GraphicsUnit) As Integer
Select Case scale
Case GraphicsUnit.Millimeter
Return CInt(Math.Truncate(graph.DpiY * value / 25.4))
Case GraphicsUnit.Inch
Return CInt(Math.Truncate(graph.DpiY * value))
Case GraphicsUnit.Point
Return CInt(Math.Truncate(graph.DpiY * value / 72))
Case GraphicsUnit.Document
Return CInt(Math.Truncate(graph.DpiY * value / 300))
End Select
Return CInt(value)
End Function
End Class
|
pagotti/vrx
|
Core/Drawing/GraphicHelper.vb
|
Visual Basic
|
mit
| 1,698
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim 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 holes2d As SolidEdgePart.Holes2d = Nothing
Dim hole2d As SolidEdgePart.Hole2d = 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
If partDocument IsNot Nothing Then
profileSets = partDocument.ProfileSets
profileSet = profileSets.Add()
profiles = profileSet.Profiles
profile = profiles.Add(refPlanes.Item(1))
holes2d = profile.Holes2d
hole2d = holes2d.Add(0, 0)
For i As Integer = 1 To holes2d.Count
hole2d = holes2d.Item(i)
hole2d.Select()
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.Hole2d.Select.vb
|
Visual Basic
|
mit
| 2,206
|
Imports Microsoft.Win32
Class Application
' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
' can be handled in this file.
Private repository As SpielerRepository
Private Sub Application_Exit(sender As Object, e As ExitEventArgs) Handles Me.[Exit]
repository?.Deregister()
End Sub
Private Sub Application_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
AddHandler AppDomain.CurrentDomain.UnhandledException, Sub(sender2 As Object, args As UnhandledExceptionEventArgs)
Dim f As New Fehler
f.ExceptionText.Text = args.ExceptionObject.ToString
f.ShowDialog()
End Sub
ShutdownMode = ShutdownMode.OnExplicitShutdown
Dim d = New ProgrammStart
If Not d.ShowDialog Then
Shutdown()
Return
End If
Dim pfad As String
If d.NeuesTurnier Then
With New NeuesTurnierDialog
If Not .ShowDialog() Then
Shutdown()
Return
End If
pfad = .NeuesTurnierKontext.Dateiname
SpeichereTurnier(.NeuesTurnierKontext)
End With
Else
pfad = ÖffneDialog()
End If
Dim dateiSystem = New Dateisystem(pfad)
Dim speicher As New Speicher(dateiSystem)
Dim cache As New SpeicherCache(speicher)
Dim observable = New StartlistenController(speicher.LeseSpieler())
repository = New SpielerRepository(cache, observable, observable)
Dim mainWindow As New MainWindow(observable,
cache.KlassementNamen, AddressOf cache.SpeichereAlles)
mainWindow.Show()
ShutdownMode = ShutdownMode.OnLastWindowClose
End Sub
Private Sub SpeichereTurnier(neuesTurnierKontext As NeuesTurnierKontext)
With neuesTurnierKontext
Dim doc = New XDocument(<tournament
end-date=<%= .Turnierende.ToString("yyyy-MM-dd") %>
start-date=<%= .Turnierbeginn.ToString("yyyy-MM-dd") %>
name=<%= .Turniername %>
tournament-id=<%= Guid.NewGuid %>>
<%= From x In .Klassements Select <competition start-date=<%= x.KlassementStart.ToString("yyyy-MM-dd H:mm") %>
ttr-remarks=<%= x.TTRHinweis %>
age-group=<%= x.KlassementName %>
type=<%= x.Typ %>>
<players/>
</competition> %>
</tournament>)
doc.Save(neuesTurnierKontext.Dateiname)
End With
End Sub
Private Function ÖffneDialog() As String
With New OpenFileDialog
.Filter = "Click-TT Turnierdaten|*.xml"
If Not .ShowDialog Then
Shutdown()
Return ""
End If
Return .FileName
End With
End Function
End Class
|
GoppeltM/PPC-Manager
|
Trunk/PPC Manager/StartlistenEditor/Application.xaml.vb
|
Visual Basic
|
mit
| 3,641
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace Pages
Partial Public Class Index
'''<summary>
'''litDisplayName control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents litDisplayName As Global.System.Web.UI.WebControls.Literal
End Class
End Namespace
|
lurienanofab/labscheduler
|
LabScheduler/index.aspx.designer.vb
|
Visual Basic
|
mit
| 806
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2018 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Public Class SocketDataEventArgs
Inherits System.EventArgs
Public ReadOnly Property Data As String
Public Sub New(data As String)
Me.Data = data
End Sub
End Class
|
tradewright/tradewright-twsapi
|
src/IBAPI/EventArgs/SocketDataEventArgs.vb
|
Visual Basic
|
mit
| 1,379
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Sonne_Mond
Inherits System.Windows.Forms.Form
'Das Formular überschreibt den Löschvorgang, um die Komponentenliste zu bereinigen.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Wird vom Windows Form-Designer benötigt.
Private components As System.ComponentModel.IContainer
'Hinweis: Die folgende Prozedur ist für den Windows Form-Designer erforderlich.
'Das Bearbeiten ist mit dem Windows Form-Designer möglich.
'Das Bearbeiten mit dem Code-Editor ist nicht möglich.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Sonne_Mond))
Me.cmd_back = New System.Windows.Forms.Button
Me.cmd_sun = New System.Windows.Forms.Button
Me.cmd_moon = New System.Windows.Forms.Button
Me.pb_Sun = New System.Windows.Forms.PictureBox
Me.pb_moon = New System.Windows.Forms.PictureBox
CType(Me.pb_Sun, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.pb_moon, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'cmd_back
'
Me.cmd_back.Location = New System.Drawing.Point(362, 481)
Me.cmd_back.Name = "cmd_back"
Me.cmd_back.Size = New System.Drawing.Size(75, 23)
Me.cmd_back.TabIndex = 0
Me.cmd_back.Text = "Zurück"
Me.cmd_back.UseVisualStyleBackColor = True
'
'cmd_sun
'
Me.cmd_sun.Location = New System.Drawing.Point(175, 413)
Me.cmd_sun.Name = "cmd_sun"
Me.cmd_sun.Size = New System.Drawing.Size(75, 23)
Me.cmd_sun.TabIndex = 1
Me.cmd_sun.Text = "Sonne"
Me.cmd_sun.UseVisualStyleBackColor = True
'
'cmd_moon
'
Me.cmd_moon.Location = New System.Drawing.Point(550, 413)
Me.cmd_moon.Name = "cmd_moon"
Me.cmd_moon.Size = New System.Drawing.Size(75, 23)
Me.cmd_moon.TabIndex = 2
Me.cmd_moon.Text = "Mond"
Me.cmd_moon.UseVisualStyleBackColor = True
'
'pb_Sun
'
Me.pb_Sun.Image = CType(resources.GetObject("pb_Sun.Image"), System.Drawing.Image)
Me.pb_Sun.Location = New System.Drawing.Point(59, 84)
Me.pb_Sun.Name = "pb_Sun"
Me.pb_Sun.Size = New System.Drawing.Size(300, 300)
Me.pb_Sun.TabIndex = 3
Me.pb_Sun.TabStop = False
'
'pb_moon
'
Me.pb_moon.Image = CType(resources.GetObject("pb_moon.Image"), System.Drawing.Image)
Me.pb_moon.Location = New System.Drawing.Point(433, 84)
Me.pb_moon.Name = "pb_moon"
Me.pb_moon.Size = New System.Drawing.Size(300, 300)
Me.pb_moon.TabIndex = 4
Me.pb_moon.TabStop = False
'
'Sonne_Mond
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(810, 546)
Me.Controls.Add(Me.pb_moon)
Me.Controls.Add(Me.pb_Sun)
Me.Controls.Add(Me.cmd_moon)
Me.Controls.Add(Me.cmd_sun)
Me.Controls.Add(Me.cmd_back)
Me.Name = "Sonne_Mond"
Me.Text = "Sonne_Mond"
CType(Me.pb_Sun, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.pb_moon, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents cmd_back As System.Windows.Forms.Button
Friend WithEvents cmd_sun As System.Windows.Forms.Button
Friend WithEvents cmd_moon As System.Windows.Forms.Button
Friend WithEvents pb_Sun As System.Windows.Forms.PictureBox
Friend WithEvents pb_moon As System.Windows.Forms.PictureBox
End Class
|
KingJosy/ProjektD
|
Programmier Sammlung/Projektsammlung/Sonne_Mond.Designer.vb
|
Visual Basic
|
mit
| 4,327
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.CheckersSolitaire.Main
End Sub
End Class
End Namespace
|
DualBrain/CheckersSolitaire
|
My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,482
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Public MustInherit Class AbstractCodeFunctionTests
Inherits AbstractCodeElementTests(Of EnvDTE80.CodeFunction2)
Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeFunction2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetStartPoint(part)
End Function
Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeFunction2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetEndPoint(part)
End Function
Protected Overrides Function GetAccess(codeElement As EnvDTE80.CodeFunction2) As EnvDTE.vsCMAccess
Return codeElement.Access
End Function
Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeFunction2) As String
Return codeElement.Comment
End Function
Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeFunction2) As String
Return codeElement.DocComment
End Function
Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeFunction2) As String
Return codeElement.FullName
End Function
Protected Function GetFunctionKind(codeElement As EnvDTE80.CodeFunction2) As EnvDTE.vsCMFunction
Return codeElement.FunctionKind
End Function
Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeFunction2) As EnvDTE.vsCMElement
Return codeElement.Kind
End Function
Protected Overrides Function GetMustImplement(codeElement As EnvDTE80.CodeFunction2) As Boolean
Return codeElement.MustImplement
End Function
Protected Overrides Function GetName(codeElement As EnvDTE80.CodeFunction2) As String
Return codeElement.Name
End Function
Protected Overridable Function GetIsOverloaded(codeElement As EnvDTE80.CodeFunction2) As Boolean
Return codeElement.IsOverloaded
End Function
Protected Overridable Function GetOverloads(codeElement As EnvDTE80.CodeFunction2) As EnvDTE.CodeElements
Return codeElement.Overloads
End Function
Protected Overrides Function GetOverrideKind(codeElement As EnvDTE80.CodeFunction2) As EnvDTE80.vsCMOverrideKind
Return codeElement.OverrideKind
End Function
Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeFunction2) As Object
Return codeElement.Parent
End Function
Protected Overrides Function GetPrototype(codeElement As EnvDTE80.CodeFunction2, flags As EnvDTE.vsCMPrototype) As String
Return codeElement.Prototype(flags)
End Function
Protected Overrides Function GetAccessSetter(codeElement As EnvDTE80.CodeFunction2) As Action(Of EnvDTE.vsCMAccess)
Return Sub(access) codeElement.Access = access
End Function
Protected Overrides Function GetIsSharedSetter(codeElement As EnvDTE80.CodeFunction2) As Action(Of Boolean)
Return Sub(value) codeElement.IsShared = value
End Function
Protected Overrides Function GetMustImplementSetter(codeElement As EnvDTE80.CodeFunction2) As Action(Of Boolean)
Return Sub(value) codeElement.MustImplement = value
End Function
Protected Overrides Function GetOverrideKindSetter(codeElement As EnvDTE80.CodeFunction2) As Action(Of EnvDTE80.vsCMOverrideKind)
Return Sub(value) codeElement.OverrideKind = value
End Function
Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeFunction2) As Action(Of String)
Return Sub(name) codeElement.Name = name
End Function
Protected Overrides Function GetTypeProp(codeElement As EnvDTE80.CodeFunction2) As EnvDTE.CodeTypeRef
Return codeElement.Type
End Function
Protected Overrides Function GetTypePropSetter(codeElement As EnvDTE80.CodeFunction2) As Action(Of EnvDTE.CodeTypeRef)
Return Sub(value) codeElement.Type = value
End Function
Protected Overrides Function AddParameter(codeElement As EnvDTE80.CodeFunction2, data As ParameterData) As EnvDTE.CodeParameter
Return codeElement.AddParameter(data.Name, data.Type, data.Position)
End Function
Protected Overrides Sub RemoveChild(codeElement As EnvDTE80.CodeFunction2, child As Object)
codeElement.RemoveParameter(child)
End Sub
Protected Overridable Function ExtensionMethodExtender_GetIsExtension(codeElement As EnvDTE80.CodeFunction2) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function PartialMethodExtender_GetIsPartial(codeElement As EnvDTE80.CodeFunction2) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function PartialMethodExtender_GetIsDeclaration(codeElement As EnvDTE80.CodeFunction2) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function PartialMethodExtender_GetHasOtherPart(codeElement As EnvDTE80.CodeFunction2) As Boolean
Throw New NotSupportedException
End Function
Protected Sub TestCanOverride(code As XElement, expected As Boolean)
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Assert.Equal(expected, codeElement.CanOverride)
End Using
End Sub
Protected Sub TestSetCanOverride(code As XElement, expectedCode As XElement, value As Boolean)
TestSetCanOverride(code, expectedCode, value, NoThrow(Of Boolean)())
End Sub
Protected Sub TestSetCanOverride(code As XElement, expectedCode As XElement, value As Boolean, action As SetterAction(Of Boolean))
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
action(value, Sub(v) codeElement.CanOverride = v)
Dim text = state.GetDocumentAtCursor().GetTextAsync().Result.ToString()
Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim())
End Using
End Sub
Protected Sub TestIsOverloaded(code As XElement, expectedOverloaded As Boolean)
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Dim overloaded = GetIsOverloaded(codeElement)
Assert.Equal(expectedOverloaded, overloaded)
End Using
End Sub
Protected Sub TestOverloadsUniqueSignatures(code As XElement, ParamArray expectedOverloadNames As String())
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Dim actualOverloads = GetOverloads(codeElement)
Assert.Equal(expectedOverloadNames.Count, actualOverloads.Count)
For index = 1 To actualOverloads.Count
Dim codeFunction = CType(actualOverloads.Item(index), EnvDTE80.CodeFunction2)
Dim signature = GetPrototype(codeFunction, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature)
Assert.True(expectedOverloadNames.Contains(signature))
Next
End Using
End Sub
Protected Sub TestFunctionKind(code As XElement, expected As EnvDTE.vsCMFunction)
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Assert.Equal(expected, codeElement.FunctionKind)
End Using
End Sub
Protected Sub TestFunctionKind(code As XElement, expected As EnvDTE80.vsCMFunction2)
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Assert.Equal(expected, CType(codeElement.FunctionKind, EnvDTE80.vsCMFunction2))
End Using
End Sub
Protected Sub TestExtensionMethodExtender_IsExtension(code As XElement, expected As Boolean)
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Assert.Equal(expected, ExtensionMethodExtender_GetIsExtension(codeElement))
End Using
End Sub
Protected Sub TestPartialMethodExtender_IsPartial(code As XElement, expected As Boolean)
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Assert.Equal(expected, PartialMethodExtender_GetIsPartial(codeElement))
End Using
End Sub
Protected Sub TestPartialMethodExtender_IsDeclaration(code As XElement, expected As Boolean)
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Assert.Equal(expected, PartialMethodExtender_GetIsDeclaration(codeElement))
End Using
End Sub
Protected Sub TestPartialMethodExtender_HasOtherPart(code As XElement, expected As Boolean)
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim codeElement = state.GetCodeElementAtCursor(Of EnvDTE80.CodeFunction2)()
Assert.NotNull(codeElement)
Assert.Equal(expected, PartialMethodExtender_GetHasOtherPart(codeElement))
End Using
End Sub
End Class
End Namespace
|
mono/roslyn
|
src/VisualStudio/Core/Test/CodeModel/AbstractCodeFunctionTests.vb
|
Visual Basic
|
apache-2.0
| 10,885
|
' 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.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class ImplementsTests
Inherits BasicTestBase
<Fact>
Public Sub SimpleImplementation()
CompileAndVerify(
<compilation name="SimpleImplementation">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal style As String)
Sub SayItWithStyle(ByVal answer As Integer)
End Interface
Class Foo
Implements IFoo
Public Sub X(ByVal style As String) Implements IFoo.SayItWithStyle
System.Console.WriteLine("I said: {0}", style)
End Sub
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
Class Bar
Inherits Foo
Public Overrides Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.SayItWithStyle("Eric Clapton rocks!")
f.SayItWithStyle(42)
Dim g As IFoo = New Bar
g.SayItWithStyle("Lady Gaga rules!")
g.SayItWithStyle(13)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
I said: Eric Clapton rocks!
The answer is: 42
I said: Lady Gaga rules!
The answer is: 13
]]>)
End Sub
<Fact>
Public Sub SimpleImplementationProperties()
CompileAndVerify(
<compilation name="SimpleImplementationProperties">
<file name="a.vb">
Option Strict On
Interface IFoo
Property MyString As String
Property MyInt As Integer
End Interface
Class Foo
Implements IFoo
Private s As String
Public Property IGotYourInt As Integer Implements IFoo.MyInt
Public Property IGotYourString As String Implements IFoo.MyString
Get
Return "You got: " + s
End Get
Set(value As String)
s = value
End Set
End Property
Public Overridable Property MyString As String
End Class
Class Bar
Inherits Foo
Private s As String
Public Overrides Property MyString As String
Get
Return "I got: " + s
End Get
Set(value As String)
s = value + " and then some"
End Set
End Property
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.MyInt = 178
f.MyString = "Lady Gaga"
System.Console.WriteLine(f.MyInt)
System.Console.WriteLine(f.MyString)
Dim g As IFoo = New Bar
g.MyInt = 12
g.MyString = "Eric Clapton"
System.Console.WriteLine(g.MyInt)
System.Console.WriteLine(g.MyString)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
178
You got: Lady Gaga
12
You got: Eric Clapton
]]>)
End Sub
<Fact>
Public Sub SimpleImplementationOverloadedProperties()
CompileAndVerify(
<compilation name="SimpleImplementationOverloadedProperties">
<file name="a.vb">
Option Strict On
Interface IFoo
Property MyString As String
Property MyString(x As Integer) As String
Property MyString(x As String) As String
Property MyInt As Integer
End Interface
Class Foo
Implements IFoo
Private s, t, u As String
Public Property IGotYourInt As Integer Implements IFoo.MyInt
Public Property IGotYourString As String Implements IFoo.MyString
Get
Return "You got: " + s
End Get
Set(value As String)
s = value
End Set
End Property
Public Property IGotYourString2(x As Integer) As String Implements IFoo.MyString
Get
Return "You got: " & t & " and " & x
End Get
Set(value As String)
t = value + "2"
End Set
End Property
Public Property IGotYourString3(x As String) As String Implements IFoo.MyString
Get
Return "You used to have: " & u & " and " & x
End Get
Set(value As String)
u = value + "3"
End Set
End Property
Public Overridable Property MyString As String
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.MyInt = 178
f.MyString = "Lady Gaga"
f.MyString(8) = "Eric Clapton"
f.MyString("foo") = "Katy Perry"
System.Console.WriteLine(f.MyInt)
System.Console.WriteLine(f.MyString)
System.Console.WriteLine(f.MyString(4))
System.Console.WriteLine(f.MyString("Bob Marley"))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
178
You got: Lady Gaga
You got: Eric Clapton2 and 4
You used to have: Katy Perry3 and Bob Marley
]]>)
End Sub
<Fact>
Public Sub ReImplementation()
CompileAndVerify(
<compilation name="ReImplementation">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal style As String)
Sub SayItWithStyle(ByVal answer As Integer)
End Interface
Class Foo
Implements IFoo
Public Sub X(ByVal style As String) Implements IFoo.SayItWithStyle
System.Console.WriteLine("I said: {0}", style)
End Sub
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
Class Bar
Inherits Foo
Implements IFoo
Private Sub Z(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The question is: {0}", a)
End Sub
Public Overrides Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("I don't say: {0}", style)
End Sub
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.SayItWithStyle("Eric Clapton rocks!")
f.SayItWithStyle(42)
Dim g As IFoo = New Bar
g.SayItWithStyle("Lady Gaga rules!")
g.SayItWithStyle(13)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
I said: Eric Clapton rocks!
The answer is: 42
I said: Lady Gaga rules!
The question is: 13
]]>)
End Sub
<Fact>
Public Sub ReImplementationProperties()
CompileAndVerify(
<compilation name="ReImplementationProperties">
<file name="a.vb">
Option Strict On
Interface IFoo
Property MyString As String
Property MyInt As Integer
End Interface
Class Foo
Implements IFoo
Private s As String
Public Property IGotYourInt As Integer Implements IFoo.MyInt
Public Property IGotYourString As String Implements IFoo.MyString
Get
Return "You got: " + s
End Get
Set(value As String)
s = value
End Set
End Property
Public Overridable Property MyString As String
End Class
Class Bar
Inherits Foo
Implements IFoo
Private s As String
Public Property AnotherString As String Implements IFoo.MyString
Get
Return "I got your: " + s
End Get
Set(value As String)
s = value + " right here"
End Set
End Property
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.MyInt = 178
f.MyString = "Lady Gaga"
System.Console.WriteLine(f.MyInt)
System.Console.WriteLine(f.MyString)
Dim g As IFoo = New Bar
g.MyInt = 12
g.MyString = "Eric Clapton"
System.Console.WriteLine(g.MyInt)
System.Console.WriteLine(g.MyString)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
178
You got: Lady Gaga
12
I got your: Eric Clapton right here
]]>)
End Sub
<Fact>
Public Sub ImplementationOfGenericMethod()
CompileAndVerify(
<compilation name="ImplementationOfGenericMethod">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Interface IFoo
Sub SayItWithStyle(Of T)(ByVal style As T)
Sub SayItWithStyle(Of T)(ByVal style As IList(Of T))
End Interface
Class Foo
Implements IFoo
Public Sub SayItWithStyle(Of U)(ByVal style As System.Collections.Generic.IList(Of U)) Implements IFoo.SayItWithStyle
System.Console.WriteLine("style is IList(Of U)")
End Sub
Public Sub SayItWithStyle(Of V)(ByVal style As V) Implements IFoo.SayItWithStyle
System.Console.WriteLine("style is V")
End Sub
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
Dim g As List(Of Integer) = New List(Of Integer)
g.Add(42)
g.Add(13)
g.Add(14)
f.SayItWithStyle(Of String)("Eric Clapton rocks!")
f.SayItWithStyle(Of Integer)(g)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
style is V
style is IList(Of U)
]]>)
End Sub
<Fact>
Public Sub ImplementationOfGenericMethod2()
CompileAndVerify(
<compilation name="ImplementationOfGenericMethod2">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Interface IFoo(Of K, L)
Sub SayItWithStyle(Of T)(ByVal style As T, ByVal a As K, ByVal b As Dictionary(Of L, K))
Sub SayItWithStyle(Of T)(ByVal style As IList(Of T), ByVal a As L, ByVal b As Dictionary(Of K, L))
End Interface
Class Foo(Of M)
Implements IFoo(Of M, ULong)
Public Sub SayItWithStyle(Of T)(ByVal style As T, ByVal a As M, ByVal b As Dictionary(Of ULong, M)) Implements IFoo(Of M, ULong).SayItWithStyle
Console.WriteLine("first")
End Sub
Public Sub SayItWithStyle(Of T)(ByVal style As System.Collections.Generic.IList(Of T), ByVal a As ULong, ByVal b As Dictionary(Of M, ULong)) Implements IFoo(Of M, ULong).SayItWithStyle
Console.WriteLine("second")
End Sub
End Class
Module Module1
Sub Main()
Dim f As IFoo(Of String, ULong) = New Foo(Of String)()
Dim g As List(Of Integer) = New List(Of Integer)
g.Add(42)
g.Add(13)
g.Add(14)
Dim h As Dictionary(Of String, ULong) = Nothing
Dim i As Dictionary(Of ULong, String) = Nothing
f.SayItWithStyle(Of String)("Eric Clapton rocks!", "hi", i)
f.SayItWithStyle(Of Integer)(g, 17, h)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
first
second
]]>)
End Sub
<Fact>
Public Sub ImplementationOfGenericMethod3()
CompileAndVerify(
<compilation name="ImplementationOfGenericMethod3">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1(Of T)
Sub Foo(ByVal i As T, ByVal j As String)
End Interface
Interface I2
Inherits I1(Of String)
End Interface
Public Class Class1
Implements I2
Public Sub A2(ByVal i As String, ByVal j As String) Implements I1(Of String).Foo
System.Console.WriteLine("{0} {1}", i, j)
End Sub
End Class
End Namespace
Module Module1
Sub Main()
Dim x As MyNS.I2 = New MyNS.Class1()
x.Foo("hello", "world")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello world")
End Sub
<Fact>
Public Sub ImplementNonInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementNonInterface">
<file name="a.vb">
Option Strict On
Public Structure S1
Public Sub foo()
End Sub
Public Property Zip As Integer
End Structure
Public Enum E1
Red
green
End Enum
Public Delegate Sub D1(ByVal x As Integer)
Public Class Class1
Public Sub foo() Implements S1.foo
End Sub
Public Property zap As Integer Implements S1.Zip
Get
return 3
End Get
Set
End Set
End Property
Public Sub bar() Implements E1.Red
End Sub
Public Sub baz() Implements System.Object.GetHashCode
End Sub
Public Sub quux() Implements D1.Invoke
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30232: Implemented type must be an interface.
Public Sub foo() Implements S1.foo
~~
BC30232: Implemented type must be an interface.
Public Property zap As Integer Implements S1.Zip
~~
BC30232: Implemented type must be an interface.
Public Sub bar() Implements E1.Red
~~
BC30232: Implemented type must be an interface.
Public Sub baz() Implements System.Object.GetHashCode
~~~~~~~~~~~~~
BC30232: Implemented type must be an interface.
Public Sub quux() Implements D1.Invoke
~~
</expected>)
End Sub
<WorkItem(531308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531308")>
<Fact>
Public Sub ImplementsClauseAndObsoleteAttribute()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementsClauseAndObsoleteAttribute">
<file name="a.vb">
Imports System
Interface i1
<Obsolete("", True)> Sub foo()
<Obsolete("", True)> Property moo()
<Obsolete("", True)> Event goo()
End Interface
Class c1
Implements i1
'COMPILEERROR: BC30668, "i1.foo"
Public Sub foo() Implements i1.foo
End Sub
'COMPILEERROR: BC30668, "i1.moo"
Public Property moo() As Object Implements i1.moo
Get
Return Nothing
End Get
Set(ByVal Value As Object)
End Set
End Property
'COMPILEERROR: BC30668, "i1.goo"
Public Event goo() Implements i1.goo
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31075: 'Sub foo()' is obsolete.
Public Sub foo() Implements i1.foo
~~~~~~~~~~~~~~~~~
BC31075: 'Property moo As Object' is obsolete.
Public Property moo() As Object Implements i1.moo
~~~~~~~~~~~~~~~~~
BC31075: 'Event goo()' is obsolete.
Public Event goo() Implements i1.goo
~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub UnimplementedInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedInterface">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Bar(ByVal x As String)
Property Zap As Integer
End Interface
Public Class Class1
Public Sub Foo(ByVal x As String) Implements I1.Bar
End Sub
Public Property Quuz As Integer Implements I1.Zap
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC31035: Interface 'I1' is not implemented by this class.
Public Sub Foo(ByVal x As String) Implements I1.Bar
~~
BC31035: Interface 'I1' is not implemented by this class.
Public Property Quuz As Integer Implements I1.Zap
~~
</expected>)
End Sub
<Fact>
Public Sub UnimplementedInterface2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedInterface2">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Bar(ByVal x As String)
Property Zap As Integer
End Interface
Public Class Class1
Implements I1
Public Sub Foo(ByVal x As String) Implements I1.Bar
End Sub
Public Property Quuz As Integer Implements I1.Zap
End Class
Public Class Class2
Inherits Class1
Public Sub Quux(ByVal x As String) Implements I1.Bar
End Sub
Public Property Dingo As Integer Implements I1.Zap
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC31035: Interface 'I1' is not implemented by this class.
Public Sub Quux(ByVal x As String) Implements I1.Bar
~~
BC31035: Interface 'I1' is not implemented by this class.
Public Property Dingo As Integer Implements I1.Zap
~~
</expected>)
End Sub
<Fact>
Public Sub ImplementUnknownType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementUnknownType">
<file name="a.vb">
Option Strict On
Public Class Class1
Public Sub foo() Implements UnknownType.foo
End Sub
Public Sub bar() Implements System.UnknownType(Of String).bar
End Sub
Public Property quux As Integer Implements UnknownType.foo
Public Property quuz As String Implements System.UnknownType(Of String).bar
Get
return ""
End Get
Set
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30002: Type 'UnknownType' is not defined.
Public Sub foo() Implements UnknownType.foo
~~~~~~~~~~~
BC30002: Type 'System.UnknownType' is not defined.
Public Sub bar() Implements System.UnknownType(Of String).bar
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'UnknownType' is not defined.
Public Property quux As Integer Implements UnknownType.foo
~~~~~~~~~~~
BC30002: Type 'System.UnknownType' is not defined.
Public Property quuz As String Implements System.UnknownType(Of String).bar
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_01()
' Somewhat surprisingly, perhaps, I3.Foo is considered ambiguous between I1.Foo(String, String) and
' I2.Foo(Integer), even though only I2.Foo(String, String) matches the method arguments provided. This
' matches Dev10 behavior.
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Interface I2
Sub Foo(ByVal x As Integer)
End Interface
Interface I3
Inherits I1, I2
End Interface
Public Class Class1
Implements I3
Public Sub Foo(ByVal i As String, ByVal j As String) Implements I3.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(x As Integer)' for interface 'I2'.
Implements I3
~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Interface I2
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Interface I3
Inherits I1, I2
End Interface
Public Class Class1
Implements I3
Public Sub Foo(ByVal i As String, ByVal j As String) Implements I3.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(i As String, j As String)' for interface 'I2'.
Implements I3
~~
BC31040: 'Foo' exists in multiple base interfaces. Use the name of the interface that declares 'Foo' in the 'Implements' clause instead of the name of the derived interface.
Public Sub Foo(ByVal i As String, ByVal j As String) Implements I3.Foo
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_03()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1(Of T, S)
Sub Foo(ByVal i As T, ByVal j As S)
Sub Foo(ByVal i As S, ByVal j As T)
End Interface
Interface I3
Inherits I1(Of Integer, Short), I1(Of Short, Integer)
End Interface
Public Class Class1
Implements I3
Public Sub Foo(ByVal i As Integer, ByVal j As Short) Implements I3.Foo
End Sub
Public Sub Foo(ByVal i As Short, ByVal j As Integer) Implements I3.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(i As Integer, j As Short)' for interface 'I1(Of Short, Integer)'.
Implements I3
~~
BC30149: Class 'Class1' must implement 'Sub Foo(i As Short, j As Integer)' for interface 'I1(Of Short, Integer)'.
Implements I3
~~
BC31040: 'Foo' exists in multiple base interfaces. Use the name of the interface that declares 'Foo' in the 'Implements' clause instead of the name of the derived interface.
Public Sub Foo(ByVal i As Integer, ByVal j As Short) Implements I3.Foo
~~~~~~
BC31040: 'Foo' exists in multiple base interfaces. Use the name of the interface that declares 'Foo' in the 'Implements' clause instead of the name of the derived interface.
Public Sub Foo(ByVal i As Short, ByVal j As Integer) Implements I3.Foo
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_04()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1(Of T, S)
Sub Foo(ByVal i As T)
Sub Foo(ByVal i As S)
End Interface
Public Class Class1
Implements I1(Of Integer, Integer)
Public Sub Foo(ByVal i As Integer) Implements I1(Of Integer, Integer).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(i As Integer)' for interface 'I1(Of Integer, Integer)'.
Implements I1(Of Integer, Integer)
~~~~~~~~~~~~~~~~~~~~~~~
BC30937: Member 'I1(Of Integer, Integer).Foo' that matches this signature cannot be implemented because the interface 'I1(Of Integer, Integer)' contains multiple members with this same name and signature:
'Sub Foo(i As Integer)'
'Sub Foo(i As Integer)'
Public Sub Foo(ByVal i As Integer) Implements I1(Of Integer, Integer).Foo
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_05()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1
Sub Foo(ByVal i As String)
End Interface
Interface I2
Inherits I1
Overloads Sub Foo(ByVal i As String)
End Interface
Interface I3
Inherits I1, I2
End Interface
Interface I4
Inherits I2, I1
End Interface
Public Class Class1
Implements I3
Public Sub Foo(ByVal i As String) Implements I3.Foo
End Sub
End Class
Public Class Class2
Implements I4
Public Sub Foo(ByVal i As String) Implements I4.Foo
End Sub
End Class
Public Class Class3
Implements I3
Public Sub Foo1(ByVal i As String) Implements I3.Foo
End Sub
Public Sub Foo2(ByVal i As String) Implements I1.Foo
End Sub
End Class
Public Class Class4
Implements I4
Public Sub Foo1(ByVal i As String) Implements I4.Foo
End Sub
Public Sub Foo2(ByVal i As String) Implements I1.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(i As String)' for interface 'I1'.
Implements I3
~~
BC30149: Class 'Class2' must implement 'Sub Foo(i As String)' for interface 'I1'.
Implements I4
~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterfaceProperty()
' Somewhat surprisingly, perhaps, I3.Foo is considered ambiguous between I1.Foo(String, String) and
' I2.Foo(Integer), even though only I2.Foo(String, String) matches the method arguments provided. This
' matches Dev10 behavior.
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterfaceProperty">
<file name="a.vb">
Option Strict On
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Interface I2
Property Foo As Integer
End Interface
Interface I3
Inherits I1, I2
End Interface
Public Class Class1
Implements I3
Public Property Bar As Integer Implements I3.Foo
Get
Return 3
End Get
Set(value As Integer)
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Property Foo As Integer' for interface 'I2'.
Implements I3
~~
BC30149: Class 'Class1' must implement 'Sub Foo(i As String, j As String)' for interface 'I1'.
Implements I3
~~
BC31040: 'Foo' exists in multiple base interfaces. Use the name of the interface that declares 'Foo' in the 'Implements' clause instead of the name of the derived interface.
Public Property Bar As Integer Implements I3.Foo
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NoMethodOfSig()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NoMethodOfSig">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
Function Foo(ByVal i As Long) As Integer
Property P(i As Long) As Integer
End Interface
Public Class Class1
Implements I1
Public Sub X(ByVal i As Long) Implements I1.Foo
End Sub
Public Sub Y(ByRef i As String, ByVal j As String) Implements I1.Foo
End Sub
Public Property Z1 As Integer Implements I1.P
Public Property Z2(i as Integer) As Integer Implements I1.P
Get
return 3
End Get
Set
End Set
End Property
Public Property Z3 As Integer Implements I1.Foo
End Class
End Namespace</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Function Foo(i As Long) As Integer' for interface 'I1'.
Implements I1
~~
BC30149: Class 'Class1' must implement 'Property P(i As Long) As Integer' for interface 'I1'.
Implements I1
~~
BC30149: Class 'Class1' must implement 'Sub Foo(i As String, j As String)' for interface 'I1'.
Implements I1
~~
BC30401: 'X' cannot implement 'Foo' because there is no matching sub on interface 'I1'.
Public Sub X(ByVal i As Long) Implements I1.Foo
~~~~~~
BC30401: 'Y' cannot implement 'Foo' because there is no matching sub on interface 'I1'.
Public Sub Y(ByRef i As String, ByVal j As String) Implements I1.Foo
~~~~~~
BC30401: 'Z1' cannot implement 'P' because there is no matching property on interface 'I1'.
Public Property Z1 As Integer Implements I1.P
~~~~
BC30401: 'Z2' cannot implement 'P' because there is no matching property on interface 'I1'.
Public Property Z2(i as Integer) As Integer Implements I1.P
~~~~
BC30401: 'Z3' cannot implement 'Foo' because there is no matching property on interface 'I1'.
Public Property Z3 As Integer Implements I1.Foo
~~~~~~
</expected>)
End Sub
<WorkItem(577934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577934")>
<Fact>
Public Sub Bug577934a()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Of T)(Optional x As T = CType(Nothing, T))
End Interface
Class C
Implements I
Public Sub Foo(Of T)(Optional x As T = Nothing) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(577934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577934")>
<Fact>
Public Sub Bug577934b()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Of T)(Optional x As T = DirectCast(Nothing, T))
End Interface
Class C
Implements I
Public Sub Foo(Of T)(Optional x As T = Nothing) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(577934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577934")>
<Fact>
Public Sub Bug577934c()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Of T As Class)(Optional x As T = TryCast(Nothing, T))
End Interface
Class C
Implements I
Public Sub Foo(Of T As Class)(Optional x As T = Nothing) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact>
Public Sub NoMethodOfName()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NoMethodOfName">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Public Class Class1
Implements I1
Public Sub Foo(ByVal i As String, ByVal j As String) Implements I1.Foo
End Sub
Public Sub Bar() Implements MyNS.I1.Quux
End Sub
Public Function Zap() As Integer Implements I1.GetHashCode
Return 0
End Function
Public Property Zip As Integer Implements I1.GetHashCode
Public ReadOnly Property Zing(x As String) As String Implements I1.Zing, I1.Foo
Get
return ""
End Get
End Property
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30401: 'Bar' cannot implement 'Quux' because there is no matching sub on interface 'I1'.
Public Sub Bar() Implements MyNS.I1.Quux
~~~~~~~~~~~~
BC30401: 'Zap' cannot implement 'GetHashCode' because there is no matching function on interface 'I1'.
Public Function Zap() As Integer Implements I1.GetHashCode
~~~~~~~~~~~~~~
BC30401: 'Zip' cannot implement 'GetHashCode' because there is no matching property on interface 'I1'.
Public Property Zip As Integer Implements I1.GetHashCode
~~~~~~~~~~~~~~
BC30401: 'Zing' cannot implement 'Zing' because there is no matching property on interface 'I1'.
Public ReadOnly Property Zing(x As String) As String Implements I1.Zing, I1.Foo
~~~~~~~
BC30401: 'Zing' cannot implement 'Foo' because there is no matching property on interface 'I1'.
Public ReadOnly Property Zing(x As String) As String Implements I1.Zing, I1.Foo
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub GenericSubstitutionAmbiguity()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericSubstitutionAmbiguity">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1(Of T)
Sub Foo(ByVal i As T, ByVal j As String)
Sub Bar(ByVal x As T)
Sub Bar(ByVal x As String)
End Interface
Interface I2
Inherits I1(Of String)
Overloads Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Public Class Class1
Implements I2
Public Sub A1(ByVal i As String, ByVal j As String) Implements I2.Foo
End Sub
Public Sub A2(ByVal i As String, ByVal j As String) Implements I1(Of String).Foo
End Sub
Public Sub B(ByVal x As String) Implements I2.Bar
End Sub
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Bar(x As String)' for interface 'I1(Of String)'.
Implements I2
~~
BC30937: Member 'I1(Of String).Bar' that matches this signature cannot be implemented because the interface 'I1(Of String)' contains multiple members with this same name and signature:
'Sub Bar(x As String)'
'Sub Bar(x As String)'
Public Sub B(ByVal x As String) Implements I2.Bar
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub GenericSubstitutionAmbiguityProperty()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericSubstitutionAmbiguityProperty">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1(Of T)
Property Foo As T
Property Bar(ByVal x As T) As Integer
Property Bar(ByVal x As String) As Integer
End Interface
Interface I2
Inherits I1(Of String)
Overloads Property Foo As String
End Interface
Public Class Class1
Implements I2
Public Property A1 As String Implements I1(Of String).Foo
Get
Return ""
End Get
Set(value As String)
End Set
End Property
Public Overloads Property A2 As String Implements I2.Foo
Get
Return ""
End Get
Set(value As String)
End Set
End Property
Public Property B(x As String) As Integer Implements I1(Of String).Bar
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Property Bar(x As String) As Integer' for interface 'I1(Of String)'.
Implements I2
~~
BC30937: Member 'I1(Of String).Bar' that matches this signature cannot be implemented because the interface 'I1(Of String)' contains multiple members with this same name and signature:
'Property Bar(x As String) As Integer'
'Property Bar(x As String) As Integer'
Public Property B(x As String) As Integer Implements I1(Of String).Bar
~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceReimplementation2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceReimplementation2">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Bar(ByVal x As String)
Function Baz() As Integer
ReadOnly Property Zip As Integer
End Interface
Interface I2
Inherits I1
End Interface
Public Class Class1
Implements I1
Public Sub FooXX(ByVal x As String) Implements I1.Bar
End Sub
Public Function BazXX() As Integer Implements I1.Baz
Return 0
End Function
Public ReadOnly Property ZipXX As Integer Implements I1.Zip
Get
Return 0
End Get
End Property
End Class
Public Class Class2
Inherits Class1
Implements I2
Public Sub Quux(ByVal x As String) Implements I1.Bar
End Sub
Public Function Quux2() As Integer Implements I1.Baz
Return 0
End Function
Public ReadOnly Property Quux3 As Integer Implements I1.Zip
Get
Return 0
End Get
End Property
End Class
Public Class Class3
Inherits Class1
Implements I1
Public Sub Zap(ByVal x As String) Implements I1.Bar
End Sub
Public Function Zap2() As Integer Implements I1.Baz
Return 0
End Function
Public ReadOnly Property Zap3 As Integer Implements I1.Zip
Get
Return 0
End Get
End Property
End Class
End Namespace
</file>
</compilation>)
' BC42015 is deprecated
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
</expected>)
End Sub
<Fact>
Public Sub UnimplementedMembers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnimplementedMembers">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Namespace MyNS
Interface I1(Of T, U)
Sub Foo(ByVal i As T, ByVal j As U)
Function Quack(ByVal o As Integer) As Long
ReadOnly Property Zing(i As U) As T
End Interface
Interface I2(Of W)
Inherits I1(Of String, IEnumerable(Of W))
Sub Bar(ByVal i As Long)
End Interface
Interface I3
Sub Zap()
End Interface
Public Class Class1(Of T)
Implements I2(Of T), I3
Public Function Quack(ByVal o As Integer) As Long Implements I1(Of String, System.Collections.Generic.IEnumerable(Of T)).Quack
Return 0
End Function
End Class
End Namespace
Module Module1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'ReadOnly Property Zing(i As IEnumerable(Of T)) As String' for interface 'I1(Of String, IEnumerable(Of T))'.
Implements I2(Of T), I3
~~~~~~~~
BC30149: Class 'Class1' must implement 'Sub Bar(i As Long)' for interface 'I2(Of T)'.
Implements I2(Of T), I3
~~~~~~~~
BC30149: Class 'Class1' must implement 'Sub Foo(i As String, j As IEnumerable(Of T))' for interface 'I1(Of String, IEnumerable(Of T))'.
Implements I2(Of T), I3
~~~~~~~~
BC30149: Class 'Class1' must implement 'Sub Zap()' for interface 'I3'.
Implements I2(Of T), I3
~~
</expected>)
End Sub
<Fact>
Public Sub ImplementTwice()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementTwice">
<file name="a.vb">
Interface IFoo
Sub Foo(x As Integer)
WriteOnly Property Bang As Integer
End Interface
Interface IBar
Sub Bar(x As Integer)
End Interface
Public Class Class1
Implements IFoo, IBar
Public Sub Foo(x As Integer) Implements IFoo.Foo
End Sub
Public Sub Baz(x As Integer) Implements IBar.Bar, IFoo.Foo
End Sub
Public WriteOnly Property A As Integer Implements IFoo.Bang
Set
End Set
End Property
Public Property B As Integer Implements IFoo.Bang
Get
Return 0
End Get
Set
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30583: 'IFoo.Foo' cannot be implemented more than once.
Public Sub Baz(x As Integer) Implements IBar.Bar, IFoo.Foo
~~~~~~~~
BC30583: 'IFoo.Bang' cannot be implemented more than once.
Public Property B As Integer Implements IFoo.Bang
~~~~~~~~~
</expected>)
End Sub
' DEV10 gave BC31415 for this case, but (at least for now), just use BC30401 since BC31415 is such a bad
' error message.
<Fact>
Public Sub ImplementStatic()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="ImplementStatic">
<file name="a.vb">
Public Class Class1
Implements ContainsStatic
Public Sub Foo() Implements ContainsStatic.Bar
End Sub
Public Sub Baz() Implements ContainsStatic.StaticMethod
End Sub
End Class
</file>
</compilation>, {TestReferences.SymbolsTests.Interface.StaticMethodInInterface})
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30401: 'Baz' cannot implement 'StaticMethod' because there is no matching sub on interface 'ContainsStatic'.
Public Sub Baz() Implements ContainsStatic.StaticMethod
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceUnification1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification1">
<file name="a.vb">
Imports System.Collections.Generic
Namespace Q
Interface IFoo(Of T)
Sub M(i As T)
End Interface
Interface Z(Of W)
Inherits IFoo(Of W)
End Interface
Class Outer(Of X)
Class Inner(Of Y)
Implements IFoo(Of List(Of X)), Z(Of Y)
Public Sub M1(i As List(Of X)) Implements IFoo(Of List(Of X)).M
End Sub
Public Sub M2(i As Y) Implements IFoo(Of Y).M
End Sub
End Class
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC32131: Cannot implement interface 'Z(Of Y)' because the interface 'IFoo(Of Y)' from which it inherits could be identical to implemented interface 'IFoo(Of List(Of X))' for some type arguments.
Implements IFoo(Of List(Of X)), Z(Of Y)
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceUnification2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification2">
<file name="a.vb">
Interface I(Of T)
End Interface
Class G1(Of T1, T2)
Implements I(Of T1), I(Of T2) 'bad
End Class
Class G2(Of T1, T2)
Implements I(Of Integer), I(Of T2) 'bad
End Class
Class G3(Of T1, T2)
Implements I(Of Integer), I(Of Short) 'ok
End Class
Class G4(Of T1, T2)
Implements I(Of I(Of T1)), I(Of T1) 'ok
End Class
Class G5(Of T1, T2)
Implements I(Of I(Of T1)), I(Of T2) 'bad
End Class
Interface I2(Of T)
Inherits I(Of T)
End Interface
Class G6(Of T1, T2)
Implements I(Of T1), I2(Of T2) 'bad
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC32072: Cannot implement interface 'I(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I(Of T1)' for some type arguments.
Implements I(Of T1), I(Of T2) 'bad
~~~~~~~~
BC32072: Cannot implement interface 'I(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I(Of Integer)' for some type arguments.
Implements I(Of Integer), I(Of T2) 'bad
~~~~~~~~
BC32072: Cannot implement interface 'I(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I(Of I(Of T1))' for some type arguments.
Implements I(Of I(Of T1)), I(Of T2) 'bad
~~~~~~~~
BC32131: Cannot implement interface 'I2(Of T2)' because the interface 'I(Of T2)' from which it inherits could be identical to implemented interface 'I(Of T1)' for some type arguments.
Implements I(Of T1), I2(Of T2) 'bad
~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceUnification3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification1">
<file name="a.vb">
Interface I(Of T, S)
End Interface
Class A(Of T, S)
Implements I(Of I(Of T, T), T)
Implements I(Of I(Of T, S), S)
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC32072: Cannot implement interface 'I(Of I(Of T, S), S)' because its implementation could conflict with the implementation of another implemented interface 'I(Of I(Of T, T), T)' for some type arguments.
Implements I(Of I(Of T, S), S)
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceUnification4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification4">
<file name="a.vb">
Class A(Of T, S)
Class B
Inherits A(Of B, B)
End Class
Interface IA
Sub M()
End Interface
Interface IB
Inherits B.IA
Inherits B.B.IA
End Interface 'ok
End Class
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub InterfaceUnification5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification5">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Class Outer(Of X, Y)
Interface IFoo(Of T, U)
End Interface
End Class
Class OuterFoo(Of A, B)
Class Foo(Of C, D)
Implements Outer(Of C, B).IFoo(Of A, D), Outer(Of D, A).IFoo(Of B, C) 'error
End Class
Class Bar(Of C, D)
Implements Outer(Of C, B).IFoo(Of A, D), Outer(Of D, A).IFoo(Of B, List(Of C)) ' ok
End Class
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC32072: Cannot implement interface 'Outer(Of D, A).IFoo(Of B, C)' because its implementation could conflict with the implementation of another implemented interface 'Outer(Of C, B).IFoo(Of A, D)' for some type arguments.
Implements Outer(Of C, B).IFoo(Of A, D), Outer(Of D, A).IFoo(Of B, C) 'error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub SimpleImplementationApi()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SimpleImplementation">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal style As String)
Sub SayItWithStyle(ByVal answer As Integer)
End Interface
Class Foo
Implements IFoo
Public Sub X(ByVal style As String) Implements IFoo.SayItWithStyle
System.Console.WriteLine("I said: {0}", style)
End Sub
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
Class Bar
Inherits Foo
Public Overrides Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim barType = DirectCast(globalNS.GetMembers("Bar").First(), NamedTypeSymbol)
Dim ifooMethods = iFooType.GetMembers("SayItWithStyle").AsEnumerable().Cast(Of MethodSymbol)()
Dim ifooTypeSayWithString = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_String).First()
Dim ifooTypeSayWithInt = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim fooX = DirectCast(fooType.GetMembers("X").First(), MethodSymbol)
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), MethodSymbol)
Dim fooSay = DirectCast(fooType.GetMembers("SayItWithStyle").First(), MethodSymbol)
Dim barSay = DirectCast(barType.GetMembers("SayItWithStyle").First(), MethodSymbol)
Assert.Equal(fooY, barType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Equal(fooX, barType.FindImplementationForInterfaceMember(ifooTypeSayWithString))
Assert.Equal(fooY, fooType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Equal(fooX, fooType.FindImplementationForInterfaceMember(ifooTypeSayWithString))
Assert.Equal(1, fooX.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithString, fooX.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithInt, fooY.ExplicitInterfaceImplementations(0))
Assert.Equal(0, fooSay.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barSay.ExplicitInterfaceImplementations.Length)
CompilationUtils.AssertNoErrors(comp)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue">
<file name="a.vb">
Option Strict On
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Integer)
Sub Foo(Optional x As Integer = 0) Implements I(Of Integer).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue2()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue2">
<file name="a.vb">
Option Strict On
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Date)
Sub Foo(Optional x As Date = Nothing) Implements I(Of Date).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue3()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue3">
<file name="a.vb">
Option Strict On
Imports Microsoft.VisualBasic
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Char)
Sub Foo(Optional x As Char = ChrW(0)) Implements I(Of Char).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue4()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue4">
<file name="a.vb">
Option Strict On
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Single)
Sub Foo(Optional x As Single = Nothing) Implements I(Of Single).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue5()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue5">
<file name="a.vb">
Option Strict On
Imports System
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of DayOfWeek)
Public Sub Foo(Optional x As DayOfWeek = 0) Implements I(Of DayOfWeek).Foo
Throw New NotImplementedException()
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545891")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue6()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue6">
<file name="a.vb">
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Decimal)
Public Sub Foo(Optional x As Decimal = 0.0D) Implements I(Of Decimal).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545891")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue7()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue7">
<file name="a.vb">
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Double)
Public Sub Foo(Optional x As Double = -0D) Implements I(Of Double).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545891")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue8()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue7">
<file name="a.vb">
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Single)
Public Sub Foo(Optional x As Single = -0D) Implements I(Of Single).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfaceMethodWithNanDefaultValue()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNanDefaultValue">
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Optional x As Double = Double.NaN)
End Interface
Class C
Implements I
Sub Foo(Optional x As Double = Double.NaN) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfaceMethodWithNanDefaultValue2()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNanDefaultValue2">
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Optional x As Single = Single.NaN)
End Interface
Class C
Implements I
Sub Foo(Optional x As Single = Single.NaN) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfaceMethodWithNanDefaultValue3()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNanDefaultValue3">
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Optional x As Single = Single.NaN)
End Interface
Class C
Implements I
Sub Foo(Optional x As Single = Double.NaN) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfaceMethodWithNanDefaultValue4()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNanDefaultValue4">
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Optional x As Single = Single.NaN)
End Interface
Class C
Implements I
Sub Foo(Optional x As Single = 0/0) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfacePropertyWithNanDefaultValue()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfacePropertyWithNanDefaultValue">
<file name="a.vb">
Option Strict On
Interface I
ReadOnly Property Foo(Optional x As Double = Double.NaN) As Integer
End Interface
Class C
Implements I
Public ReadOnly Property Foo(Optional x As Double = Double.NaN) As Integer Implements I.Foo
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfacePropertyWithNanDefaultValue2()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfacePropertyWithNanDefaultValue2">
<file name="a.vb">
Option Strict On
Interface I
ReadOnly Property Foo(Optional x As Double = Double.NegativeInfinity) As Integer
End Interface
Class C
Implements I
Public ReadOnly Property Foo(Optional x As Double = Single.NegativeInfinity) As Integer Implements I.Foo
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfacePropertyWithNanDefaultValue3()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfacePropertyWithNanDefaultValue3">
<file name="a.vb">
Option Strict On
Interface I
ReadOnly Property Foo(Optional x As Double = Double.NegativeInfinity) As Integer
End Interface
Class C
Implements I
Public ReadOnly Property Foo(Optional x As Double = (-1.0)/0) As Integer Implements I.Foo
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfacePropertyWithNanDefaultValue4()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfacePropertyWithNanDefaultValue4">
<file name="a.vb">
Option Strict On
Interface I
ReadOnly Property Foo(Optional x As Double = Double.NegativeInfinity) As Integer
End Interface
Class C
Implements I
Public ReadOnly Property Foo(Optional x As Double = 1.0/0) As Integer Implements I.Foo
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC30149: Class 'C' must implement 'ReadOnly Property Foo([x As Double = -Infinity]) As Integer' for interface 'I'.
Implements I
~
BC30401: 'Foo' cannot implement 'Foo' because there is no matching property on interface 'I'.
Public ReadOnly Property Foo(Optional x As Double = 1.0/0) As Integer Implements I.Foo
~~~~~
</errors>)
End Sub
<Fact>
Public Sub SimpleImplementationApiProperty()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SimpleImplementationProperty">
<file name="a.vb">
Option Strict On
Interface IFoo
ReadOnly Property Style(ByVal s As String) As String
ReadOnly Property Style(ByVal answer As Integer) As String
End Interface
Class Foo
Implements IFoo
Public Property X(ByVal style As String) As String Implements IFoo.Style
Get
Return "I said: " + style
End Get
Set
End Set
End Property
Public ReadOnly Property Y(ByVal a As Integer) As String Implements IFoo.Style
Get
Return "I said: " + a.ToString()
End Get
End Property
Public Overridable ReadOnly Property Style(ByVal s As String) As String
Get
Return "You dont say: " + s
End Get
End Property
End Class
Class Bar
Inherits Foo
Public Overrides ReadOnly Property Style(ByVal s As String) As String
Get
Return "I dont say: " + s
End Get
End Property
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim barType = DirectCast(globalNS.GetMembers("Bar").First(), NamedTypeSymbol)
Dim ifooProps = iFooType.GetMembers("Style").AsEnumerable().Cast(Of PropertySymbol)()
Dim ifooTypeStyleWithString = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_String).First()
Dim ifooTypeStyleWithStringGetter = ifooTypeStyleWithString.GetMethod
Dim ifooTypeStyleWithInt = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim ifooTypeStyleWithIntGetter = ifooTypeStyleWithInt.GetMethod
Dim fooX = DirectCast(fooType.GetMembers("X").First(), PropertySymbol)
Dim fooXGetter = fooX.GetMethod
Dim fooXSetter = fooX.SetMethod
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), PropertySymbol)
Dim fooYGetter = fooY.GetMethod
Dim fooStyle = DirectCast(fooType.GetMembers("Style").First(), PropertySymbol)
Dim fooStyleGetter = fooStyle.GetMethod
Dim barStyle = DirectCast(barType.GetMembers("Style").First(), PropertySymbol)
Dim barStyleGetter = barStyle.GetMethod
Assert.Equal(fooY, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithInt))
Assert.Equal(fooYGetter, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithIntGetter))
Assert.Equal(fooX, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithString))
Assert.Equal(fooXGetter, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithStringGetter))
Assert.Equal(fooY, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithInt))
Assert.Equal(fooYGetter, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithIntGetter))
Assert.Equal(fooX, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithString))
Assert.Equal(fooXGetter, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithStringGetter))
Assert.Equal(1, fooX.ExplicitInterfaceImplementations.Length)
Assert.Equal(1, fooXGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, fooXSetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithString, fooX.ExplicitInterfaceImplementations(0))
Assert.Equal(ifooTypeStyleWithStringGetter, fooXGetter.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(1, fooYGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithInt, fooY.ExplicitInterfaceImplementations(0))
Assert.Equal(ifooTypeStyleWithIntGetter, fooYGetter.ExplicitInterfaceImplementations(0))
Assert.Equal(0, fooStyle.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barStyle.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, fooStyleGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barStyleGetter.ExplicitInterfaceImplementations.Length)
CompilationUtils.AssertNoErrors(comp)
End Sub
<Fact>
Public Sub UnimplementedMethods()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SimpleImplementation">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal style As String)
Sub SayItWithStyle(ByVal answer As Integer)
Sub SayItWithStyle(ByVal answer As Long)
End Interface
Class Foo
Implements IFoo
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal answer As Long)
System.Console.WriteLine("You don't say: {0}", answer)
End Sub
End Class
Class Bar
Inherits Foo
Implements IFoo
Public Overrides Sub SayItWithStyle(ByVal answer As Long)
System.Console.WriteLine("You don't say: {0}", answer)
End Sub
Public Sub X(ByVal style As String) Implements IFoo.SayItWithStyle
System.Console.WriteLine("I said: {0}", style)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim barType = DirectCast(globalNS.GetMembers("Bar").First(), NamedTypeSymbol)
Dim ifooMethods = iFooType.GetMembers("SayItWithStyle").AsEnumerable().Cast(Of MethodSymbol)()
Dim ifooTypeSayWithString = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_String).First()
Dim ifooTypeSayWithInt = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim ifooTypeSayWithLong = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int64).First()
Dim barX = DirectCast(barType.GetMembers("X").First(), MethodSymbol)
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), MethodSymbol)
Dim fooSay = DirectCast(fooType.GetMembers("SayItWithStyle").First(), MethodSymbol)
Dim barSay = DirectCast(barType.GetMembers("SayItWithStyle").First(), MethodSymbol)
Assert.Equal(fooY, barType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Equal(barX, barType.FindImplementationForInterfaceMember(ifooTypeSayWithString))
Assert.Equal(fooY, fooType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeSayWithString))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeSayWithLong))
Assert.Null(barType.FindImplementationForInterfaceMember(ifooTypeSayWithLong))
Assert.Equal(1, barX.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithString, barX.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithInt, fooY.ExplicitInterfaceImplementations(0))
Assert.Equal(0, fooSay.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barSay.ExplicitInterfaceImplementations.Length)
CompilationUtils.AssertTheseDiagnostics(comp, <expected>
BC30149: Class 'Foo' must implement 'Sub SayItWithStyle(answer As Long)' for interface 'IFoo'.
Implements IFoo
~~~~
BC30149: Class 'Foo' must implement 'Sub SayItWithStyle(style As String)' for interface 'IFoo'.
Implements IFoo
~~~~
</expected>)
End Sub
<Fact>
Public Sub UnimplementedProperties()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedProperties">
<file name="a.vb">
Option Strict On
Interface IFoo
ReadOnly Property Style(ByVal s As String) As String
ReadOnly Property Style(ByVal answer As Integer) As String
ReadOnly Property Style(ByVal answer As Long) As String
End Interface
Class Foo
Implements IFoo
Public ReadOnly Property Y(ByVal a As Integer) As String Implements IFoo.Style
Get
Return "I said: " + a.ToString()
End Get
End Property
Public Overridable ReadOnly Property Style(ByVal s As Long) As String
Get
Return "You dont say: "
End Get
End Property
End Class
Class Bar
Inherits Foo
Implements IFoo
Public Overrides ReadOnly Property Style(ByVal s As Long) As String
Get
Return "You dont say: "
End Get
End Property
Public ReadOnly Property X(ByVal a As String) As String Implements IFoo.Style
Get
Return "I said: " + a.ToString()
End Get
End Property
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim barType = DirectCast(globalNS.GetMembers("Bar").First(), NamedTypeSymbol)
Dim ifooProps = iFooType.GetMembers("Style").AsEnumerable().Cast(Of PropertySymbol)()
Dim ifooTypeStyleWithString = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_String).First()
Dim ifooTypeStyleWithStringGetter = ifooTypeStyleWithString.GetMethod
Dim ifooTypeStyleWithInt = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim ifooTypeStyleWithIntGetter = ifooTypeStyleWithInt.GetMethod
Dim ifooTypeStyleWithLong = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int64).First()
Dim ifooTypeStyleWithLongGetter = ifooTypeStyleWithLong.GetMethod
Dim barX = DirectCast(barType.GetMembers("X").First(), PropertySymbol)
Dim barXGetter = barX.GetMethod
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), PropertySymbol)
Dim fooYGetter = fooY.GetMethod
Dim fooStyle = DirectCast(fooType.GetMembers("Style").First(), PropertySymbol)
Dim fooStyleGetter = fooStyle.GetMethod
Dim barStyle = DirectCast(barType.GetMembers("Style").First(), PropertySymbol)
Dim barStyleGetter = barStyle.GetMethod
Assert.Equal(fooY, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithInt))
Assert.Equal(fooYGetter, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithIntGetter))
Assert.Equal(barX, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithString))
Assert.Equal(barXGetter, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithStringGetter))
Assert.Equal(fooY, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithInt))
Assert.Equal(fooYGetter, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithIntGetter))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithString))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithStringGetter))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithLong))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithLongGetter))
Assert.Null(barType.FindImplementationForInterfaceMember(ifooTypeStyleWithLong))
Assert.Null(barType.FindImplementationForInterfaceMember(ifooTypeStyleWithLongGetter))
Assert.Equal(1, barX.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithString, barX.ExplicitInterfaceImplementations(0))
Assert.Equal(1, barXGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithStringGetter, barXGetter.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithInt, fooY.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooYGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithIntGetter, fooYGetter.ExplicitInterfaceImplementations(0))
Assert.Equal(0, fooStyle.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, fooStyleGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barStyle.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barStyleGetter.ExplicitInterfaceImplementations.Length)
CompilationUtils.AssertTheseDiagnostics(comp, <expected>
BC30149: Class 'Foo' must implement 'ReadOnly Property Style(answer As Long) As String' for interface 'IFoo'.
Implements IFoo
~~~~
BC30149: Class 'Foo' must implement 'ReadOnly Property Style(s As String) As String' for interface 'IFoo'.
Implements IFoo
~~~~
</expected>)
End Sub
<Fact>
Public Sub UnimplementedInterfaceAPI()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedInterfaceAPI">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal a As Integer)
End Interface
Class Foo
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal answer As Long)
System.Console.WriteLine("You don't say: {0}", answer)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim ifooMethods = iFooType.GetMembers("SayItWithStyle").AsEnumerable().Cast(Of MethodSymbol)()
Dim ifooTypeSayWithInt = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), MethodSymbol)
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithInt, fooY.ExplicitInterfaceImplementations(0))
CompilationUtils.AssertTheseDiagnostics(comp, <expected>
BC31035: Interface 'IFoo' is not implemented by this class.
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
~~~~
</expected>)
End Sub
<Fact>
Public Sub GenericInterface()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SimpleImplementation">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Class Outer(Of X)
Interface IFoo(Of T, U)
Sub SayItWithStyle(ByVal a As T, c As X)
Sub SayItWithStyle(ByVal b As U, c As X)
End Interface
Class Foo(Of Y)
Implements IFoo(Of X, List(Of Y))
Public Sub M1(a As X, c As X) Implements Outer(Of X).IFoo(Of X, List(Of Y)).SayItWithStyle
End Sub
Public Sub M2(b As List(Of Y), c As X) Implements Outer(Of X).IFoo(Of X, List(Of Y)).SayItWithStyle
End Sub
End Class
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim listOfT = comp.GetTypeByMetadataName("System.Collections.Generic.List`1")
Dim listOfString = listOfT.Construct(comp.GetSpecialType(SpecialType.System_String))
Dim outerOfX = DirectCast(globalNS.GetMembers("Outer").First(), NamedTypeSymbol)
Dim outerOfInt = outerOfX.Construct(comp.GetSpecialType(SpecialType.System_Int32))
Dim iFooOfIntTU = DirectCast(outerOfInt.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim iFooOfIntIntListOfString = iFooOfIntTU.Construct(comp.GetSpecialType(SpecialType.System_Int32), listOfString)
Dim fooOfIntY = DirectCast(outerOfInt.GetMembers("Foo").First(), NamedTypeSymbol)
Dim fooOfIntString = fooOfIntY.Construct(comp.GetSpecialType(SpecialType.System_String))
Dim iFooOfIntIntListOfStringMethods = iFooOfIntIntListOfString.GetMembers("SayItWithStyle").AsEnumerable().Cast(Of MethodSymbol)()
Dim ifooOfIntIntStringSay1 = (From m In iFooOfIntIntListOfStringMethods Where m.Parameters(0).Type = comp.GetSpecialType(SpecialType.System_Int32)).First()
Dim ifooOfIntIntStringSay2 = (From m In iFooOfIntIntListOfStringMethods Where m.Parameters(0).Type <> comp.GetSpecialType(SpecialType.System_Int32)).First()
Dim fooOfIntStringM1 = DirectCast(fooOfIntString.GetMembers("M1").First(), MethodSymbol)
Dim fooOfIntStringM2 = DirectCast(fooOfIntString.GetMembers("M2").First(), MethodSymbol)
Assert.Equal(1, fooOfIntStringM1.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooOfIntIntStringSay1, fooOfIntStringM1.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooOfIntStringM2.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooOfIntIntStringSay2, fooOfIntStringM2.ExplicitInterfaceImplementations(0))
CompilationUtils.AssertNoErrors(comp)
End Sub
' See MDInterfaceMapping.cs to understand this test case.
<Fact>
Public Sub MetadataInterfaceMapping()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="ImplementStatic">
<file name="a.vb">
Public Class D
Inherits C
Implements IFoo
End Class
</file>
</compilation>, {TestReferences.SymbolsTests.Interface.MDInterfaceMapping})
Dim globalNS = comp.GlobalNamespace
Dim iFoo = DirectCast(globalNS.GetMembers("IFoo").Single(), NamedTypeSymbol)
Dim dClass = DirectCast(globalNS.GetMembers("D").Single(), NamedTypeSymbol)
Dim iFooMethod = DirectCast(iFoo.GetMembers("Foo").Single(), MethodSymbol)
' IFoo.Foo should be found in A.
Dim implementedMethod = dClass.FindImplementationForInterfaceMember(iFooMethod)
Assert.Equal("A", implementedMethod.ContainingType.Name)
CompilationUtils.AssertNoErrors(comp)
End Sub
<Fact>
Public Sub InterfaceReimplementation()
CompileAndVerify(
<compilation name="InterfaceReimplementation">
<file name="a.vb">
Imports System
Interface I1
Sub foo()
Sub quux()
End Interface
Interface I2
Inherits I1
Sub bar()
End Interface
Class X
Implements I1
Public Sub foo1() Implements I1.foo
Console.WriteLine("X.foo1")
End Sub
Public Sub quux1() Implements I1.quux
Console.WriteLine("X.quux1")
End Sub
Public Overridable Sub foo()
Console.WriteLine("x.foo")
End Sub
End Class
Class Y
Inherits X
Implements I2
Public Overridable Sub bar()
Console.WriteLine("Y.bar")
End Sub
Public Overridable Sub quux()
Console.WriteLine("Y.quux")
End Sub
Public Overrides Sub foo()
Console.WriteLine("Y.foo")
End Sub
Public Sub bar1() Implements I2.bar
Console.WriteLine("Y.bar1")
End Sub
End Class
Module Module1
Sub Main()
Dim a As Y = New Y()
a.foo()
a.bar()
a.quux()
Dim b As I2 = a
b.foo()
b.bar()
b.quux()
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Y.foo
Y.bar
Y.quux
X.foo1
Y.bar1
X.quux1
]]>)
End Sub
<Fact>
Public Sub Bug6095()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug6095">
<file name="a.vb">
Imports System
Namespace ArExtByVal001
Friend Module ArExtByVal001mod
Class Cls7
Implements I7
Interface I7
Function Scen7(ByVal Ary() As Single)
End Interface
Function Cls7_Scen7(ByVal Ary() As Single) Implements I7.Scen7
Ary(70) = Ary(70) + 100
Return Ary(0)
End Function
End Class
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub Bug7931()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug6095">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Namespace NS
Interface IFoo(Of T)
Function F(Of R)(ParamArray p As R()) As R
End Interface
Interface IBar(Of R)
Function F(ParamArray p As R()) As R
End Interface
Class Impl
Implements NS.IFoo(Of Char)
Implements IBar(Of Short)
Function F(ParamArray p As Short()) As Short Implements IFoo(Of Char).F, IBar(Of Short).F
Return Nothing
End Function
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30149: Class 'Impl' must implement 'Function F(Of R)(ParamArray p As R()) As R' for interface 'IFoo(Of Char)'.
Implements NS.IFoo(Of Char)
~~~~~~~~~~~~~~~~
BC30401: 'F' cannot implement 'F' because there is no matching function on interface 'IFoo(Of Char)'.
Function F(ParamArray p As Short()) As Short Implements IFoo(Of Char).F, IBar(Of Short).F
~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(543664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543664")>
<Fact()>
Public Sub Bug11554()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug11554">
<file name="a.vb">
Interface I
Sub M(Optional ByRef x As Short = 1)
End Interface
Class C
'COMPILEERROR: BC30149, "I"
Implements I
'COMPILEERROR: BC30401, "I.M"
Sub M(Optional ByRef x As Short = 0) Implements I.M
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30149: Class 'C' must implement 'Sub M([ByRef x As Short = 1])' for interface 'I'.
Implements I
~
BC30401: 'M' cannot implement 'M' because there is no matching sub on interface 'I'.
Sub M(Optional ByRef x As Short = 0) Implements I.M
~~~
</expected>)
End Sub
<Fact>
Public Sub PropAccessorAgreement()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PropAccessorAgreement">
<file name="a.vb">
Interface I1
Property rw1 As Integer
Property rw2 As Integer
Property rw3 As Integer
ReadOnly Property ro1 As Integer
ReadOnly Property ro2 As Integer
ReadOnly Property ro3 As Integer
WriteOnly Property wo1 As Integer
WriteOnly Property wo2 As Integer
WriteOnly Property wo3 As Integer
End Interface
Class X
Implements I1
Public Property a As Integer Implements I1.ro1
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public ReadOnly Property b As Integer Implements I1.ro2
Get
Return 0
End Get
End Property
Public WriteOnly Property c As Integer Implements I1.ro3
Set(value As Integer)
End Set
End Property
Public Property d As Integer Implements I1.rw1
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public ReadOnly Property e As Integer Implements I1.rw2
Get
Return 0
End Get
End Property
Public WriteOnly Property f As Integer Implements I1.rw3
Set(value As Integer)
End Set
End Property
Public Property g As Integer Implements I1.wo1
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public ReadOnly Property h As Integer Implements I1.wo2
Get
Return 0
End Get
End Property
Public WriteOnly Property i As Integer Implements I1.wo3
Set(value As Integer)
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC31444: 'ReadOnly Property ro3 As Integer' cannot be implemented by a WriteOnly property.
Public WriteOnly Property c As Integer Implements I1.ro3
~~~~~~
BC31444: 'Property rw2 As Integer' cannot be implemented by a ReadOnly property.
Public ReadOnly Property e As Integer Implements I1.rw2
~~~~~~
BC31444: 'Property rw3 As Integer' cannot be implemented by a WriteOnly property.
Public WriteOnly Property f As Integer Implements I1.rw3
~~~~~~
BC31444: 'WriteOnly Property wo2 As Integer' cannot be implemented by a ReadOnly property.
Public ReadOnly Property h As Integer Implements I1.wo2
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ImplementDefaultProperty()
Dim source =
<compilation>
<file name="a.vb">
Interface I1
Default Property P1(param1 As Integer) As String
End Interface
Class C1 : Implements I1
Private _p1 As String
Private _p2 As String
Public Property P1(param1 As Integer) As String Implements I1.P1
Get
Return _p1
End Get
Set(value As String)
_p1 = value
End Set
End Property
Default Public Property P2(param1 As Integer) As String
Get
Return _p2
End Get
Set(value As String)
_p2 = value
End Set
End Property
End Class
Module Program
Sub Main(args As String())
Dim c As C1 = New C1()
DirectCast(c, I1)(1) = "P1"
c(1) = "P2"
System.Console.WriteLine(String.Join(",", c.P1(1), c.P2(1)))
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="P1,P2")
End Sub
<Fact>
Public Sub ImplementReadOnlyUsingReadWriteWithPrivateSet()
Dim source =
<compilation>
<file name="a.vb">
Interface I1
ReadOnly Property bar() As Integer
End Interface
Public Class C2
Implements I1
Public Property bar() As Integer Implements I1.bar
Get
Return 2
End Get
Private Set(ByVal value As Integer)
End Set
End Property
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<WorkItem(541934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541934")>
<Fact>
Public Sub ImplementGenericInterfaceProperties()
Dim source =
<compilation>
<file name="a.vb">
Imports ImportedAlias = System.Int32
Interface I1(Of T)
ReadOnly Property P1() As T
End Interface
Public Class C1(Of T)
Implements I1(Of T)
Public ReadOnly Property P() As T Implements I1(Of T).P1
Get
Return Nothing
End Get
End Property
End Class
Public Class C2
Implements I1(Of Integer)
Public ReadOnly Property P1() As Integer Implements I1(Of Integer).P1
Get
Return 2
End Get
End Property
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact>
Public Sub ImplementGenericInterfaceMethods()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Collections.Generic
Imports ImportedAlias = System.Int32
Interface I1(Of T)
Sub M1()
Function M1(Of U)(x As U, y As List(Of U), z As T, w As List(Of T)) As Dictionary(Of T, List(Of U))
End Interface
Public Class C1(Of T)
Implements I1(Of T)
Public Sub M() Implements I1(Of T).M1
End Sub
Public Function M(Of U)(x As U, y As List(Of U), z As T, w As List(Of T)) As Dictionary(Of T, List(Of U)) Implements I1(Of T).M1
Return Nothing
End Function
End Class
Public Class C2
Implements I1(Of Integer)
Public Sub M1() Implements I1(Of ImportedAlias).M1
End Sub
Public Function M1(Of U)(x As U, y As List(Of U), z As ImportedAlias, w As List(Of ImportedAlias)) As Dictionary(Of ImportedAlias, List(Of U)) Implements I1(Of ImportedAlias).M1
Return Nothing
End Function
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<WorkItem(543253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543253")>
<Fact()>
Public Sub ImplementMethodWithOptionalParameter()
Dim source =
<compilation>
<file name="a.vb">
Public Enum E1
A
B
C
End Enum
Public Interface I1
Sub S1(i as integer, optional j as integer = 10, optional e as E1 = E1.B)
End Interface
Public Class C1
Implements I1
Sub C1_S1(i as integer, optional j as integer = 10, optional e as E1 = E1.B) implements I1.S1
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source).VerifyDiagnostics()
End Sub
<Fact, WorkItem(544531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544531")>
Public Sub VarianceAmbiguity1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity1">
<file name="a.vb">
Option Strict On
Class Animals : End Class
Class Mammals : Inherits Animals
End Class
Class Fish
Inherits Mammals
End Class
Interface IEnumerable(Of Out T)
Function Foo() As T
End Interface
Class C
Implements IEnumerable(Of Fish)
Implements IEnumerable(Of Mammals)
Implements IEnumerable(Of Animals)
Public Function Foo() As Fish Implements IEnumerable(Of Fish).Foo
Return New Fish
End Function
Public Function Foo1() As Mammals Implements IEnumerable(Of Mammals).Foo
Return New Mammals
End Function
Public Function Foo2() As Animals Implements IEnumerable(Of Animals).Foo
Return New Animals
End Function
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'IEnumerable(Of Mammals)' is ambiguous with another implemented interface 'IEnumerable(Of Fish)' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Implements IEnumerable(Of Mammals)
~~~~~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IEnumerable(Of Animals)' is ambiguous with another implemented interface 'IEnumerable(Of Fish)' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Implements IEnumerable(Of Animals)
~~~~~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IEnumerable(Of Animals)' is ambiguous with another implemented interface 'IEnumerable(Of Mammals)' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Implements IEnumerable(Of Animals)
~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact, WorkItem(544531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544531")>
Public Sub VarianceAmbiguity2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity2">
<file name="a.vb">
Option Strict On
Class Animals : End Class
Class Mammals : Inherits Animals
End Class
Class Fish
Inherits Mammals
End Class
Interface IEnumerable(Of Out T)
Function Foo() As T
End Interface
Interface EnumFish
Inherits IEnumerable(Of Fish)
End Interface
Interface EnumAnimals
Inherits IEnumerable(Of Animals)
End Interface
Interface I
Inherits EnumFish, EnumAnimals, IEnumerable(Of Mammals)
End Interface
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'EnumAnimals' is ambiguous with another implemented interface 'EnumFish' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Inherits EnumFish, EnumAnimals, IEnumerable(Of Mammals)
~~~~~~~~~~~
BC42333: Interface 'IEnumerable(Of Mammals)' is ambiguous with another implemented interface 'EnumAnimals' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Inherits EnumFish, EnumAnimals, IEnumerable(Of Mammals)
~~~~~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IEnumerable(Of Mammals)' is ambiguous with another implemented interface 'EnumFish' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Inherits EnumFish, EnumAnimals, IEnumerable(Of Mammals)
~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub VarianceAmbiguity3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity3">
<file name="a.vb">
Option Strict On
Public Interface IFoo(Of Out T, U)
End Interface
Class X
End Class
Class Y
End Class
Class GX(Of T)
End Class
Class GY(Of T)
End Class
Class A
' Not conflicting: 2nd type parameter is invariant, types are different and cannot unify
' Dev11 reports not conflicting
Implements IFoo(Of X, X), IFoo(Of Y, Y)
End Class
Class B(Of T)
' Not conflicting: 2nd type parameter is invariant, types are different and cannot unify
' Dev11 reports conflicting
Implements IFoo(Of X, GX(Of Integer)), IFoo(Of Y, GY(Of Integer))
End Class
Class C(Of T, U)
' Conflicting: 2nd type parameter is invariant, GX(Of T) and GX(Of U) might unify
' Dev11 reports conflicting
Implements IFoo(Of X, GX(Of T)), IFoo(Of Y, GX(Of U))
End Class
Class D(Of T, U)
' Conflicting: 2nd type parameter is invariant, T and U might unify
' E.g., If D(Of String, String) is cast to IFoo(Of Object, String), its implementation is ambiguous.
' Dev11 reports non-conflicting
Implements IFoo(Of X, T), IFoo(Of Y, U)
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'IFoo(Of Y, GX(Of U))' is ambiguous with another implemented interface 'IFoo(Of X, GX(Of T))' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of Out T, U)'.
Implements IFoo(Of X, GX(Of T)), IFoo(Of Y, GX(Of U))
~~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IFoo(Of Y, U)' is ambiguous with another implemented interface 'IFoo(Of X, T)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of Out T, U)'.
Implements IFoo(Of X, T), IFoo(Of Y, U)
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub VarianceAmbiguity4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity4">
<file name="a.vb">
Option Strict On
Public Interface IFoo(Of Out T, Out U)
End Interface
Class X
End Class
Class Y
End Class
Class GX(Of T)
End Class
Class GY(Of T)
End Class
Structure S(Of T)
End Structure
Class A
' Not conflicting: 2nd type parameter is "Out", types can't unify and one is value type
' Dev11 reports not conflicting
Implements IFoo(Of X, Integer), IFoo(Of Y, Y)
End Class
Class B(Of T)
' Conflicting: 2nd type parameter is "Out", 2nd type parameter could unify in B(Of Integer)
' Dev11 reports not conflicting
Implements IFoo(Of X, Integer), IFoo(Of Y, T)
End Class
Class C(Of T, U)
' Conflicting: 2nd type parameter is "Out", , S(Of T) and S(Of U) might unify
' Dev11 reports conflicting
Implements IFoo(Of X, S(Of T)), IFoo(Of Y, S(Of U))
End Class
Class D(Of T, U)
' Not Conflicting: 2nd type parameter is "Out", String and S(Of U) can't unify and S(Of U) is a value type.
' Dev11 reports conflicting
Implements IFoo(Of X, String), IFoo(Of Y, S(Of U))
End Class
Class E(Of T, U)
' Not Conflicting: 1st type parameter; one is Object; 2nd type parameter is "Out", S(Of T) is a value type.
' Dev11 reports not conflicting
Implements IFoo(Of Object, S(Of T)), IFoo(Of X, S(Of U))
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'IFoo(Of Y, T)' is ambiguous with another implemented interface 'IFoo(Of X, Integer)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of Out T, Out U)'.
Implements IFoo(Of X, Integer), IFoo(Of Y, T)
~~~~~~~~~~~~~
BC42333: Interface 'IFoo(Of Y, S(Of U))' is ambiguous with another implemented interface 'IFoo(Of X, S(Of T))' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of Out T, Out U)'.
Implements IFoo(Of X, S(Of T)), IFoo(Of Y, S(Of U))
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub VarianceAmbiguity5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity5">
<file name="a.vb">
Option Strict On
Public Interface IFoo(Of In T, In U)
End Interface
Class X
End Class
Class Y
End Class
NotInheritable Class Z
End Class
Class W
Inherits X
End Class
Interface J
End Interface
Interface K
End Interface
Class GX(Of T)
End Class
Class GY(Of T)
End Class
Structure S(Of T)
End Structure
Class A
' Not conflicting: Neither X or Y derives from each other
' Dev11 reports conflicting
Implements IFoo(Of X, Integer), IFoo(Of Y, Integer)
End Class
Class B
' Conflicting: 1st type argument could convert to type deriving from X implementing J.
' Dev11 reports conflicting
Implements IFoo(Of X, Integer), IFoo(Of J, Integer)
End Class
Class C(Of T, U)
' Not conflicting: 1st type argument has sealed type Z.
' Dev11 reports conflicting
Implements IFoo(Of J, Integer), IFoo(Of Z, Integer)
End Class
Class D(Of T, U)
' Not conflicting: 1st type argument has value type Integer.
' Dev11 reports not conflicting
Implements IFoo(Of Integer, Integer), IFoo(Of X, Integer)
End Class
Class E
' Conflicting, W derives from X
' Dev11 reports conflicting
Implements IFoo(Of W, Integer), IFoo(Of X, Integer)
End Class
Class F(Of T)
' Conflicting: X and J cause ambiguity, T and Integer could unify
' Dev11 reports not conflicting
Implements IFoo(Of X, Integer), IFoo(Of J, T)
End Class
Class G(Of T)
' Not conflicting: X and J cause ambiguity, GX(Of T) and Integer can't unify, Integer is value type prevents ambiguity
' Dev11 reports conflicting
Implements IFoo(Of X, Integer), IFoo(Of J, GX(Of T))
End Class
Class H
' Not conflicting, X and J cause ambiguity, neither X or Z derive from each other.
' Dev11 reports conflicting
Implements IFoo(Of X, Z), IFoo(Of J, X)
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'IFoo(Of J, Integer)' is ambiguous with another implemented interface 'IFoo(Of X, Integer)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of In T, In U)'.
Implements IFoo(Of X, Integer), IFoo(Of J, Integer)
~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IFoo(Of X, Integer)' is ambiguous with another implemented interface 'IFoo(Of W, Integer)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of In T, In U)'.
Implements IFoo(Of W, Integer), IFoo(Of X, Integer)
~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IFoo(Of J, T)' is ambiguous with another implemented interface 'IFoo(Of X, Integer)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of In T, In U)'.
Implements IFoo(Of X, Integer), IFoo(Of J, T)
~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(545863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545863")>
<Fact>
Public Sub Bug14589()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug14589">
<file name="a.vb">
Interface I(Of T)
Sub Foo(x As T)
End Interface
Class A(Of T)
Class B
Inherits A(Of B)
Implements I(Of B.B)
End Class
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'B' must implement 'Sub Foo(x As A(Of A(Of A(Of T).B).B).B)' for interface 'I(Of B)'.
Implements I(Of B.B)
~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(578706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578706")>
<Fact>
Public Sub ImplicitImplementationSourceVsMetadata()
Dim source1 = <![CDATA[
public interface I
{
void Implicit();
void Explicit();
}
public class A
{
public void Implicit()
{
System.Console.WriteLine("A.Implicit");
}
public void Explicit()
{
System.Console.WriteLine("A.Explicit");
}
}
public class B : A, I
{
}
]]>
Dim source2 =
<compilation name="Lib2">
<file name="a.vb">
Public Class C
Inherits B
Public Shadows Sub Implicit()
System.Console.WriteLine("C.Implicit")
End Sub
Public Shadows Sub Explicit()
System.Console.WriteLine("C.Explicit")
End Sub
End Class
Public Class D
Inherits C
Implements I
Public Shadows Sub Explicit() Implements I.Explicit
System.Console.WriteLine("D.Explicit")
End Sub
End Class
</file>
</compilation>
Dim source3 =
<compilation name="Test">
<file name="a.vb">
Module Test
Sub Main()
Dim a As New A()
Dim b As New B()
Dim c As New C()
Dim d As New D()
a.Implicit()
b.Implicit()
c.Implicit()
d.Implicit()
System.Console.WriteLine()
a.Explicit()
b.Explicit()
c.Explicit()
d.Explicit()
System.Console.WriteLine()
Dim i As I
'i = a
'i.Implicit()
'i.Explicit()
i = b
i.Implicit()
i.Explicit()
i = c
i.Implicit()
i.Explicit()
i = d
i.Implicit()
i.Explicit()
End Sub
End Module
</file>
</compilation>
Dim expectedOutput = <![CDATA[
A.Implicit
A.Implicit
C.Implicit
C.Implicit
A.Explicit
A.Explicit
C.Explicit
D.Explicit
A.Implicit
A.Explicit
A.Implicit
A.Explicit
A.Implicit
D.Explicit
]]>
Dim comp1 = CreateCSharpCompilation("Lib1", source1)
Dim ref1a = comp1.EmitToImageReference()
Dim ref1b = comp1.EmitToImageReference()
Dim comp2 = CreateCompilationWithMscorlib40AndReferences(source2, {ref1a})
Dim ref2Metadata = comp2.EmitToImageReference()
Dim ref2Source = New VisualBasicCompilationReference(comp2)
Dim verifyComp3 As Action(Of MetadataReference, MetadataReference) =
Sub(ref1, ref2)
Dim comp3 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {ref1, ref2}, TestOptions.ReleaseExe)
CompileAndVerify(comp3, expectedOutput:=expectedOutput)
Dim globalNamespace = comp3.GlobalNamespace
Dim typeI = globalNamespace.GetMember(Of NamedTypeSymbol)("I")
Dim typeA = globalNamespace.GetMember(Of NamedTypeSymbol)("A")
Dim typeB = globalNamespace.GetMember(Of NamedTypeSymbol)("B")
Dim typeC = globalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim typeD = globalNamespace.GetMember(Of NamedTypeSymbol)("D")
Dim interfaceImplicit = typeI.GetMember(Of MethodSymbol)("Implicit")
Dim interfaceExplicit = typeI.GetMember(Of MethodSymbol)("Explicit")
Assert.Null(typeA.FindImplementationForInterfaceMember(interfaceImplicit))
Assert.Null(typeA.FindImplementationForInterfaceMember(interfaceExplicit))
Assert.Equal(typeA, typeB.FindImplementationForInterfaceMember(interfaceImplicit).ContainingType)
Assert.Equal(typeA, typeB.FindImplementationForInterfaceMember(interfaceExplicit).ContainingType)
Assert.Equal(typeA, typeC.FindImplementationForInterfaceMember(interfaceImplicit).ContainingType)
Assert.Equal(typeA, typeC.FindImplementationForInterfaceMember(interfaceExplicit).ContainingType)
Assert.Equal(typeA, typeD.FindImplementationForInterfaceMember(interfaceImplicit).ContainingType)
Assert.Equal(typeD, typeD.FindImplementationForInterfaceMember(interfaceExplicit).ContainingType)
' In metadata, D does not declare that it implements I.
Assert.Equal(If(TypeOf ref2 Is MetadataImageReference, 0, 1), typeD.Interfaces.Length)
End Sub
' Normal
verifyComp3(ref1a, ref2Metadata)
verifyComp3(ref1a, ref2Source)
' Retargeting
verifyComp3(ref1b, ref2Metadata)
verifyComp3(ref1b, ref2Source)
End Sub
<WorkItem(578746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578746")>
<Fact>
Public Sub Bug578746a()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I(Of T)
Sub Foo(Optional x As Integer = Nothing)
End Interface
Class C
Implements I(Of Integer)
Public Sub Foo(Optional x As Integer = 0) Implements I(Of Integer).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(578746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578746")>
<Fact>
Public Sub Bug578746b()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Sub Foo(Optional x As Decimal = Nothing)
End Interface
Class C
Implements I
Public Sub Foo(Optional x As Decimal = 0.0f) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(578746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578746")>
<Fact>
Public Sub Bug578746c()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Sub Foo(Optional x As Object = Nothing)
End Interface
Class C
Implements I
Public Sub Foo(Optional x As Object = 0) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30149: Class 'C' must implement 'Sub Foo([x As Object = Nothing])' for interface 'I'.
Implements I
~
BC30401: 'Foo' cannot implement 'Foo' because there is no matching sub on interface 'I'.
Public Sub Foo(Optional x As Object = 0) Implements I.Foo
~~~~~
</expected>)
End Sub
<WorkItem(578746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578746")>
<Fact>
Public Sub Bug578746d()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Class A : End Class
Interface I
Sub Foo(Of T As A)(Optional x As A = DirectCast(Nothing, T))
End Interface
Class C: Implements I
Public Sub Foo(Of T As A)(Optional x As A = Nothing) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(578074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578074")>
<Fact>
Public Sub Bug578074()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Sub Foo(Optional x As Object = 1D)
End Interface
Class C
Implements I
Public Sub Foo(Optional x As Object = 1.0D) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(608228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608228")>
<Fact>
Public Sub ImplementPropertyWithByRefParameter()
Dim il = <![CDATA[
.class interface public abstract auto ansi IRef
{
.method public newslot specialname abstract strict virtual
instance string get_P(int32& x) cil managed
{
} // end of method IRef::get_P
.method public newslot specialname abstract strict virtual
instance void set_P(int32& x,
string Value) cil managed
{
} // end of method IRef::set_P
.property instance string P(int32&)
{
.get instance string IRef::get_P(int32&)
.set instance void IRef::set_P(int32&,
string)
} // end of property IRef::P
} // end of class IRef
]]>
Dim source =
<compilation>
<file name="a.vb">
Public Class Impl
Implements IRef
Public Property P(x As Integer) As String Implements IRef.P
Get
Return Nothing
End Get
Set(value As String)
End Set
End Property
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(source, il)
' CONSIDER: Dev11 doesn't report ERR_UnimplementedMember3.
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_IdentNotMemberOfInterface4, "IRef.P").WithArguments("P", "P", "property", "IRef"),
Diagnostic(ERRID.ERR_UnimplementedMember3, "IRef").WithArguments("Class", "Impl", "Property P(ByRef x As Integer) As String", "IRef"))
Dim globalNamespace = compilation.GlobalNamespace
Dim interfaceType = globalNamespace.GetMember(Of NamedTypeSymbol)("IRef")
Dim interfaceProperty = interfaceType.GetMember(Of PropertySymbol)("P")
Assert.True(interfaceProperty.Parameters.Single().IsByRef)
Dim classType = globalNamespace.GetMember(Of NamedTypeSymbol)("Impl")
Dim classProperty = classType.GetMember(Of PropertySymbol)("P")
Assert.False(classProperty.Parameters.Single().IsByRef)
Assert.Null(classType.FindImplementationForInterfaceMember(interfaceProperty))
End Sub
<WorkItem(718115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718115")>
<Fact>
Public Sub ExplicitlyImplementedAccessorsWithoutEvent()
Dim il = <![CDATA[
.class interface public abstract auto ansi I
{
.method public hidebysig newslot specialname abstract virtual
instance void add_E(class [mscorlib]System.Action 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void remove_E(class [mscorlib]System.Action 'value') cil managed
{
}
.event [mscorlib]System.Action E
{
.addon instance void I::add_E(class [mscorlib]System.Action)
.removeon instance void I::remove_E(class [mscorlib]System.Action)
}
} // end of class I
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
implements I
{
.method private hidebysig newslot specialname virtual final
instance void I.add_E(class [mscorlib]System.Action 'value') cil managed
{
.override I::add_E
ldstr "Explicit implementation"
call void [mscorlib]System.Console::WriteLine(string)
ret
}
.method private hidebysig newslot specialname virtual final
instance void I.remove_E(class [mscorlib]System.Action 'value') cil managed
{
.override I::remove_E
ret
}
.method family hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldstr "Protected event"
call void [mscorlib]System.Console::WriteLine(string)
ret
}
.method family hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
// NOTE: No event I.E
.event [mscorlib]System.Action E
{
.addon instance void Base::add_E(class [mscorlib]System.Action)
.removeon instance void Base::remove_E(class [mscorlib]System.Action)
}
} // end of class Base
]]>
Dim source =
<compilation>
<file name="a.vb">
Public Class Derived
Inherits Base
Implements I
Public Sub Test()
AddHandler DirectCast(Me, I).E, Nothing
End Sub
End Class
Module Program
Sub Main()
Dim d As New Derived()
d.Test()
Dim id As I = d
AddHandler id.E, Nothing
End Sub
End Module
</file>
</compilation>
Dim ilRef = CompileIL(il.Value)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {ilRef}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
Explicit implementation
Explicit implementation
]]>)
Dim [global] = compilation.GlobalNamespace
Dim [interface] = [global].GetMember(Of NamedTypeSymbol)("I")
Dim baseType = [global].GetMember(Of NamedTypeSymbol)("Base")
Dim derivedType = [global].GetMember(Of NamedTypeSymbol)("Derived")
Dim interfaceEvent = [interface].GetMember(Of EventSymbol)("E")
Dim interfaceAdder = interfaceEvent.AddMethod
Dim baseAdder = baseType.GetMembers().OfType(Of MethodSymbol)().
Where(Function(m) m.ExplicitInterfaceImplementations.Any()).
Single(Function(m) m.ExplicitInterfaceImplementations.Single().MethodKind = MethodKind.EventAdd)
Assert.Equal(baseAdder, derivedType.FindImplementationForInterfaceMember(interfaceAdder))
Assert.Equal(baseAdder, baseType.FindImplementationForInterfaceMember(interfaceAdder))
Assert.Null(derivedType.FindImplementationForInterfaceMember(interfaceEvent))
Assert.Null(baseType.FindImplementationForInterfaceMember(interfaceEvent))
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_01()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed
{
} // end of method I1::M2
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M1(x As Integer) As Integer() Implements I1.M1
System.Console.WriteLine("Implementation.M1")
Return Nothing
End Function
Public Function M2(x() As Integer) As Integer Implements I1.M2
System.Console.WriteLine("Implementation.M2")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M1
Implementation.M2
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M1")
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Dim m1_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M1")
Assert.Equal("Function Implementation.$VB$Stub_M1(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ToTestDisplayString())
Assert.Equal(1, m1_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M1(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
Assert.Equal(Accessibility.Private, m1_stub.DeclaredAccessibility)
Assert.True(m1_stub.IsMetadataVirtual)
Assert.True(m1_stub.IsMetadataNewSlot)
Assert.False(m1_stub.IsOverridable)
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_02()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance !!T[] M1<T>(!!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) & x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance !!S modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M2<S>(!!S modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []& x) cil managed
{
} // end of method I1::M2
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
Dim x1 As Integer = 1
Dim x2 As Integer() = Nothing
v.M1(Of Integer)(x1)
System.Console.WriteLine(x1)
v.M2(Of Integer)(x2)
System.Console.WriteLine(x2)
End Sub
End Module
Class Implementation
Implements I1
Public Function M1(Of U)(ByRef x As U) As U() Implements I1.M1
System.Console.WriteLine("Implementation.M1")
x = Nothing
Return Nothing
End Function
Public Function M2(Of W)(ByRef x() As W) As W Implements I1.M2
System.Console.WriteLine("Implementation.M2")
x = New W() {}
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M1
0
Implementation.M2
System.Int32[]
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M1")
Assert.Equal("Function Implementation.$VB$Stub_M1(Of U)(ByRef x As U modopt(System.Runtime.CompilerServices.IsLong)) As U()", m1_stub.ToTestDisplayString())
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_03()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot specialname abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::get_P1
.method public newslot specialname abstract strict virtual
instance void modopt([mscorlib]System.Runtime.CompilerServices.IsLong) set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Value) cil managed
{
} // end of method I1::set_P1
.method public newslot specialname abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed
{
} // end of method I1::get_P2
.method public newslot specialname abstract strict virtual
instance void modopt([mscorlib]System.Runtime.CompilerServices.IsLong) set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Value) cil managed
{
} // end of method I1::set_P2
.property instance int32[] P1(int32)
{
.get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] I1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) )
.set instance void modopt([mscorlib]System.Runtime.CompilerServices.IsLong) I1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) ,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [])
} // end of property I1::P1
.property instance int32 P2()
{
.get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) I1::get_P2()
.set instance void modopt([mscorlib]System.Runtime.CompilerServices.IsLong) I1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) )
} // end of property I1::P2
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.P1(Nothing) = v.P1(Nothing)
v.P2 = 123
System.Console.WriteLine(v.P2)
System.Console.WriteLine(DirectCast(v, Implementation).P2)
End Sub
End Module
Class Implementation
Implements I1
Public Property P1(x As Integer) As Integer() Implements I1.P1
Get
System.Console.WriteLine("Implementation.P1_get")
Return Nothing
End Get
Set(value As Integer())
System.Console.WriteLine("Implementation.P1_set")
End Set
End Property
Public Property P2 As Integer Implements I1.P2
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.P1_get
Implementation.P1_set
123
123
]]>)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_04()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] M1(int32 x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(x As Integer) As Integer() Implements I1.M1, I1.M2
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(1, m1.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M1(x As System.Int32) As System.Int32()", m1.ExplicitInterfaceImplementations(0).ToTestDisplayString())
Dim m1_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M12")
Assert.Equal("Function Implementation.$VB$Stub_M12(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ToTestDisplayString())
Assert.Equal(1, m1_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M2(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_05()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] M1(int32 x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(x As Integer) As Integer() Implements I1.M2, I1.M1
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(1, m1.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M1(x As System.Int32) As System.Int32()", m1.ExplicitInterfaceImplementations(0).ToTestDisplayString())
Dim m1_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M12")
Assert.Equal("Function Implementation.$VB$Stub_M12(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ToTestDisplayString())
Assert.Equal(1, m1_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M2(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_06()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(x As Integer) As Integer() Implements I1.M2, I1.M1
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Dim m12_stubs = t.GetMembers("$VB$Stub_M12")
Assert.Equal(2, m12_stubs.Length)
Dim m1_stub As MethodSymbol
Dim m2_stub As MethodSymbol
If DirectCast(m12_stubs(0), MethodSymbol).ReturnTypeCustomModifiers.IsEmpty Then
m2_stub = DirectCast(m12_stubs(0), MethodSymbol)
m1_stub = DirectCast(m12_stubs(1), MethodSymbol)
Else
m2_stub = DirectCast(m12_stubs(1), MethodSymbol)
m1_stub = DirectCast(m12_stubs(0), MethodSymbol)
End If
Assert.Equal("Function Implementation.$VB$Stub_M12(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32() modopt(System.Runtime.CompilerServices.IsLong)", m1_stub.ToTestDisplayString())
Assert.Equal(1, m1_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M1(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32() modopt(System.Runtime.CompilerServices.IsLong)", m1_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
Assert.Equal("Function Implementation.$VB$Stub_M12(x As System.Int32) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m2_stub.ToTestDisplayString())
Assert.Equal(1, m2_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M2(x As System.Int32) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m2_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_07()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(x As Integer) As Integer() Implements I1.M2, I1.M1
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Dim m12_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M12")
Assert.Equal(2, m12_stub.ExplicitInterfaceImplementations.Length)
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_08()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] M1(int32 & modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32[] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) & x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(ByRef x As Integer) As Integer() Implements I1.M2, I1.M1
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Dim m12_stubs = t.GetMembers("$VB$Stub_M12")
Assert.Equal(2, m12_stubs.Length)
For Each stub As MethodSymbol In m12_stubs
Assert.Equal(1, stub.ExplicitInterfaceImplementations.Length)
Next
End Sub)
End Sub
End Class
End Namespace
|
lorcanmooney/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ImplementsTests.vb
|
Visual Basic
|
apache-2.0
| 147,587
|
Public Class Form1
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim response As Integer
response = MsgBox("Are you sure you want to exit", MsgBoxStyle.OkCancel + MsgBoxStyle.Question, "Close GSF Database")
If response = vbOK Then End
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Form8.Show()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Form7.Show()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database1DataSet.password' table. You can move, or remove it, as needed.
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Private Sub AboutUsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutUsToolStripMenuItem.Click
End Sub
Private Sub DatabaseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DatabaseToolStripMenuItem.Click
Form7.Show()
End Sub
Private Sub ChagePasswordToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChagePasswordToolStripMenuItem.Click
End Sub
Private Sub EitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EitToolStripMenuItem.Click
End
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Form14.Show()
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Form15.Show()
End Sub
Private Sub Label2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label2.Click
End Sub
End Class
|
superibk/ChurchManager
|
real/Form1.vb
|
Visual Basic
|
apache-2.0
| 2,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.Concurrent
Imports System.Collections.Immutable
Imports System.Reflection.PortableExecutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Partial Friend MustInherit Class PEModuleBuilder
Inherits PEModuleBuilder(Of VisualBasicCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, VisualBasicSyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState)
' Not many methods should end up here.
Private ReadOnly _disableJITOptimization As ConcurrentDictionary(Of MethodSymbol, Boolean) = New ConcurrentDictionary(Of MethodSymbol, Boolean)(ReferenceEqualityComparer.Instance)
' Gives the name of this module (may not reflect the name of the underlying symbol).
' See Assembly.MetadataName.
Private ReadOnly _metadataName As String
Private _lazyExportedTypes As ImmutableArray(Of TypeExport(Of NamedTypeSymbol))
Private _lazyImports As ImmutableArray(Of Cci.UsedNamespaceOrType)
Private _lazyDefaultNamespace As String
' These fields will only be set when running tests. They allow realized IL for a given method to be looked up by method display name.
Private _testData As ConcurrentDictionary(Of String, CompilationTestData.MethodData)
Private _testDataKeyFormat As SymbolDisplayFormat
Private _testDataOperatorKeyFormat As SymbolDisplayFormat
Friend Sub New(sourceModule As SourceModuleSymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
assemblySymbolMapper As Func(Of AssemblySymbol, AssemblyIdentity))
MyBase.New(sourceModule.ContainingSourceAssembly.DeclaringCompilation,
sourceModule,
serializationProperties,
manifestResources,
outputKind,
assemblySymbolMapper,
emitOptions,
New ModuleCompilationState())
Dim specifiedName = sourceModule.MetadataName
_metadataName = If(specifiedName <> Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName,
specifiedName,
If(emitOptions.OutputNameOverride, specifiedName))
m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, Me)
If sourceModule.AnyReferencedAssembliesAreLinked Then
_embeddedTypesManagerOpt = New NoPia.EmbeddedTypesManager(Me)
End If
End Sub
''' <summary>
''' True if conditional calls may be omitted when the required preprocessor symbols are not defined.
''' </summary>
''' <remarks>
''' Only false in debugger scenarios (where calls should never be omitted).
''' </remarks>
Friend MustOverride ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Friend Overrides ReadOnly Property Name As String
Get
Return _metadataName
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ModuleName As String
Get
Return _metadataName
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property CorLibrary As AssemblySymbol
Get
Return SourceModule.ContainingSourceAssembly.CorLibrary
End Get
End Property
Protected Overrides ReadOnly Property GenerateVisualBasicStylePdb As Boolean
Get
Return True
End Get
End Property
Protected Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String)
Get
' NOTE: Dev12 does not seem to emit anything but the name (i.e. no version, token, etc).
' See Builder::WriteNoPiaPdbList
Return SourceModule.ReferencedAssemblySymbols.Where(Function(a) a.IsLinked).Select(Function(a) a.Name)
End Get
End Property
Protected NotOverridable Overrides Function GetImports(context As EmitContext) As ImmutableArray(Of Cci.UsedNamespaceOrType)
If _lazyImports.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(
_lazyImports,
NamespaceScopeBuilder.BuildNamespaceScope(context, SourceModule.XmlNamespaces, SourceModule.AliasImports, SourceModule.MemberImports))
End If
Return _lazyImports
End Function
Protected NotOverridable Overrides ReadOnly Property DefaultNamespace As String
Get
If _lazyDefaultNamespace IsNot Nothing Then
Return _lazyDefaultNamespace
End If
Dim rootNamespace = SourceModule.RootNamespace
If rootNamespace Is Nothing OrElse rootNamespace.IsGlobalNamespace Then
Return Nothing
End If
_lazyDefaultNamespace = rootNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)
Return _lazyDefaultNamespace
End Get
End Property
Protected Overrides Iterator Function GetAssemblyReferencesFromAddedModules(diagnostics As DiagnosticBag) As IEnumerable(Of Cci.IAssemblyReference)
Dim modules As ImmutableArray(Of ModuleSymbol) = SourceModule.ContainingAssembly.Modules
For i As Integer = 1 To modules.Length - 1
For Each aRef As AssemblySymbol In modules(i).GetReferencedAssemblySymbols()
Yield Translate(aRef, diagnostics)
Next
Next
End Function
Private Sub ValidateReferencedAssembly(assembly As AssemblySymbol, asmRef As AssemblyReference, diagnostics As DiagnosticBag)
Dim asmIdentity As AssemblyIdentity = SourceModule.ContainingAssembly.Identity
Dim refIdentity As AssemblyIdentity = asmRef.MetadataIdentity
If asmIdentity.IsStrongName AndAlso Not refIdentity.IsStrongName AndAlso
DirectCast(asmRef, Cci.IAssemblyReference).ContentType <> Reflection.AssemblyContentType.WindowsRuntime Then
' Dev12 reported error, we have changed it to a warning to allow referencing libraries
' built for platforms that don't support strong names.
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton)
End If
If OutputKind <> OutputKind.NetModule AndAlso
Not String.IsNullOrEmpty(refIdentity.CultureName) AndAlso
Not String.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase) Then
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton)
End If
Dim refMachine = assembly.Machine
' If other assembly is agnostic, this is always safe
' Also, if no mscorlib was specified for back compat we add a reference to mscorlib
' that resolves to the current framework directory. If the compiler Is 64-bit
' this Is a 64-bit mscorlib, which will produce a warning if /platform:x86 Is
' specified.A reference to the default mscorlib should always succeed without
' warning so we ignore it here.
If assembly IsNot assembly.CorLibrary AndAlso
Not (refMachine = Machine.I386 AndAlso Not assembly.Bit32Required) Then
Dim machine = SourceModule.Machine
If Not (machine = machine.I386 AndAlso Not SourceModule.Bit32Required) AndAlso
machine <> refMachine Then
' Different machine types, and neither is agnostic
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton)
End If
End If
If _embeddedTypesManagerOpt IsNot Nothing AndAlso _embeddedTypesManagerOpt.IsFrozen Then
_embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics)
End If
End Sub
Friend NotOverridable Overrides Function SynthesizeAttribute(attributeConstructor As WellKnownMember) As Cci.ICustomAttribute
Return Me.Compilation.TrySynthesizeAttribute(attributeConstructor)
End Function
Friend NotOverridable Overrides Function GetSourceAssemblyAttributes() As IEnumerable(Of Cci.ICustomAttribute)
Return SourceModule.ContainingSourceAssembly.GetCustomAttributesToEmit(Me.CompilationState, emittingAssemblyAttributesInNetModule:=OutputKind.IsNetModule())
End Function
Friend NotOverridable Overrides Function GetSourceAssemblySecurityAttributes() As IEnumerable(Of Cci.SecurityAttribute)
Return SourceModule.ContainingSourceAssembly.GetSecurityAttributes()
End Function
Friend NotOverridable Overrides Function GetSourceModuleAttributes() As IEnumerable(Of Cci.ICustomAttribute)
Return SourceModule.GetCustomAttributesToEmit(Me.CompilationState)
End Function
Protected Overrides Function GetSymbolToLocationMap() As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)
Dim result As New MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)()
Dim namespacesAndTypesToProcess As New Stack(Of NamespaceOrTypeSymbol)()
namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace)
Dim location As Location = Nothing
While namespacesAndTypesToProcess.Count > 0
Dim symbol As NamespaceOrTypeSymbol = namespacesAndTypesToProcess.Pop()
Select Case symbol.Kind
Case SymbolKind.Namespace
location = GetSmallestSourceLocationOrNull(symbol)
' filtering out synthesized symbols not having real source
' locations such as anonymous types, my types, etc...
If location IsNot Nothing Then
For Each member In symbol.GetMembers()
Select Case member.Kind
Case SymbolKind.Namespace, SymbolKind.NamedType
namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
Next
End If
Case SymbolKind.NamedType
location = GetSmallestSourceLocationOrNull(symbol)
If location IsNot Nothing Then
' add this named type location
AddSymbolLocation(result, location, DirectCast(symbol, Cci.IDefinition))
For Each member In symbol.GetMembers()
Select Case member.Kind
Case SymbolKind.NamedType
namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol))
Case SymbolKind.Method
Dim method = DirectCast(member, MethodSymbol)
If Not method.IsDefaultValueTypeConstructor() Then
AddSymbolLocation(result, member)
End If
Case SymbolKind.Property,
SymbolKind.Field
AddSymbolLocation(result, member)
Case SymbolKind.Event
AddSymbolLocation(result, member)
Dim AssociatedField = (DirectCast(member, EventSymbol)).AssociatedField
If AssociatedField IsNot Nothing Then
' event backing fields do not show up in GetMembers
AddSymbolLocation(result, AssociatedField)
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
Next
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.Kind)
End Select
End While
Return result
End Function
Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), symbol As Symbol)
Dim location As Location = GetSmallestSourceLocationOrNull(symbol)
If location IsNot Nothing Then
AddSymbolLocation(result, location, DirectCast(symbol, Cci.IDefinition))
End If
End Sub
Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), location As Location, definition As Cci.IDefinition)
Dim span As FileLinePositionSpan = location.GetLineSpan()
Dim doc As Cci.DebugSourceDocument = Me.TryGetDebugDocument(span.Path, basePath:=location.SourceTree.FilePath)
If (doc IsNot Nothing) Then
result.Add(doc,
New Cci.DefinitionWithLocation(
definition,
span.StartLinePosition.Line,
span.StartLinePosition.Character,
span.EndLinePosition.Line,
span.EndLinePosition.Character))
End If
End Sub
Private Function GetSmallestSourceLocationOrNull(symbol As Symbol) As Location
Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation
Debug.Assert(Me.Compilation Is compilation, "How did we get symbol from different compilation?")
Dim result As Location = Nothing
For Each loc In symbol.Locations
If loc.IsInSource AndAlso (result Is Nothing OrElse compilation.CompareSourceLocations(result, loc) > 0) Then
result = loc
End If
Next
Return result
End Function
''' <summary>
''' Ignore accessibility when resolving well-known type
''' members, in particular for generic type arguments
''' (e.g.: binding to internal types in the EE).
''' </summary>
Friend Overridable ReadOnly Property IgnoreAccessibility As Boolean
Get
Return False
End Get
End Property
Friend Overridable Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol) As VariableSlotAllocator
Return Nothing
End Function
Friend Overridable Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey)
Return ImmutableArray(Of AnonymousTypeKey).Empty
End Function
Friend Overridable Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer
Return 0
End Function
Friend Overridable Function TryGetAnonymousTypeName(template As NamedTypeSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean
Debug.Assert(Compilation Is template.DeclaringCompilation)
name = Nothing
index = -1
Return False
End Function
Friend Overrides Function GetAnonymousTypes() As ImmutableArray(Of Cci.INamespaceTypeDefinition)
If EmitOptions.EmitMetadataOnly Then
Return ImmutableArray(Of Cci.INamespaceTypeDefinition).Empty
End If
Return StaticCast(Of Cci.INamespaceTypeDefinition).
From(SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates)
End Function
Friend Overrides Iterator Function GetTopLevelTypesCore(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition)
For Each topLevel In GetAdditionalTopLevelTypes()
Yield topLevel
Next
Dim embeddedSymbolManager As EmbeddedSymbolManager = SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager
Dim stack As New Stack(Of NamespaceOrTypeSymbol)()
stack.Push(SourceModule.GlobalNamespace)
Do
Dim sym As NamespaceOrTypeSymbol = stack.Pop()
If sym.Kind = SymbolKind.NamedType Then
Debug.Assert(sym Is sym.OriginalDefinition)
Debug.Assert(sym.ContainingType Is Nothing)
' Skip unreferenced embedded types.
If Not sym.IsEmbedded OrElse embeddedSymbolManager.IsSymbolReferenced(sym) Then
Dim type = DirectCast(sym, NamedTypeSymbol)
Yield type
End If
Else
Debug.Assert(sym.Kind = SymbolKind.Namespace)
Dim members As ImmutableArray(Of Symbol) = sym.GetMembers()
For i As Integer = members.Length - 1 To 0 Step -1
Dim nortsym As NamespaceOrTypeSymbol = TryCast(members(i), NamespaceOrTypeSymbol)
If nortsym IsNot Nothing Then
stack.Push(nortsym)
End If
Next
End If
Loop While stack.Count > 0
End Function
Friend Overridable Function GetAdditionalTopLevelTypes() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetExportedTypes(context As EmitContext) As IEnumerable(Of Cci.ITypeExport)
Debug.Assert(HaveDeterminedTopLevelTypes)
If _lazyExportedTypes.IsDefault Then
Dim builder = ArrayBuilder(Of TypeExport(Of NamedTypeSymbol)).GetInstance()
Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly
If Not OutputKind.IsNetModule() Then
Dim modules = sourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1 'NOTE: skipping modules(0)
GetExportedTypes(modules(i).GlobalNamespace, builder)
Next
End If
Dim seenTopLevelForwardedTypes = New HashSet(Of NamedTypeSymbol)()
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder)
If Not OutputKind.IsNetModule() Then
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder)
End If
Debug.Assert(_lazyExportedTypes.IsDefault)
_lazyExportedTypes = builder.ToImmutableAndFree()
If _lazyExportedTypes.Length > 0 Then
' Report name collisions.
Dim exportedNamesMap = New Dictionary(Of String, NamedTypeSymbol)()
For Each [alias] In _lazyExportedTypes
Dim aliasedType As NamedTypeSymbol = [alias].AliasedType
Debug.Assert(aliasedType.IsDefinition)
If aliasedType.ContainingType Is Nothing Then
Dim fullEmittedName As String = MetadataHelpers.BuildQualifiedName((DirectCast(aliasedType, Cci.INamespaceTypeReference)).NamespaceName,
Cci.MetadataWriter.GetMangledName(aliasedType))
' First check against types declared in the primary module
If ContainsTopLevelType(fullEmittedName) Then
If aliasedType.ContainingAssembly Is sourceAssembly Then
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ExportedTypeConflictsWithDeclaration, aliasedType, aliasedType.ContainingModule),
NoLocation.Singleton))
Else
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ForwardedTypeConflictsWithDeclaration, aliasedType),
NoLocation.Singleton))
End If
Continue For
End If
Dim contender As NamedTypeSymbol = Nothing
' Now check against other exported types
If exportedNamesMap.TryGetValue(fullEmittedName, contender) Then
If aliasedType.ContainingAssembly Is sourceAssembly Then
' all exported types precede forwarded types, therefore contender cannot be a forwarded type.
Debug.Assert(contender.ContainingAssembly Is sourceAssembly)
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ExportedTypesConflict,
aliasedType, aliasedType.ContainingModule,
contender, contender.ContainingModule),
NoLocation.Singleton))
Else
If contender.ContainingAssembly Is sourceAssembly Then
' Forwarded type conflicts with exported type
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ForwardedTypeConflictsWithExportedType,
aliasedType, aliasedType.ContainingAssembly,
contender, contender.ContainingModule),
NoLocation.Singleton))
Else
' Forwarded type conflicts with another forwarded type
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ForwardedTypesConflict,
aliasedType, aliasedType.ContainingAssembly,
contender, contender.ContainingAssembly),
NoLocation.Singleton))
End If
End If
Continue For
End If
exportedNamesMap.Add(fullEmittedName, aliasedType)
End If
Next
End If
End If
Return _lazyExportedTypes
End Function
Private Overloads Sub GetExportedTypes(sym As NamespaceOrTypeSymbol, builder As ArrayBuilder(Of TypeExport(Of NamedTypeSymbol)))
If sym.Kind = SymbolKind.NamedType Then
If sym.DeclaredAccessibility = Accessibility.Public Then
Debug.Assert(sym.IsDefinition)
builder.Add(New TypeExport(Of NamedTypeSymbol)(DirectCast(sym, NamedTypeSymbol)))
Else
Return
End If
End If
For Each t In sym.GetMembers()
Dim nortsym = TryCast(t, NamespaceOrTypeSymbol)
If nortsym IsNot Nothing Then
GetExportedTypes(nortsym, builder)
End If
Next
End Sub
Private Shared Sub GetForwardedTypes(
seenTopLevelTypes As HashSet(Of NamedTypeSymbol),
wellKnownAttributeData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol),
builder As ArrayBuilder(Of TypeExport(Of NamedTypeSymbol))
)
If wellKnownAttributeData IsNot Nothing AndAlso wellKnownAttributeData.ForwardedTypes IsNot Nothing Then
For Each forwardedType As NamedTypeSymbol In wellKnownAttributeData.ForwardedTypes
Dim originalDefinition As NamedTypeSymbol = forwardedType.OriginalDefinition
Debug.Assert(originalDefinition.ContainingType Is Nothing, "How did a nested type get forwarded?")
' De-dup the original definitions before emitting.
If Not seenTopLevelTypes.Add(originalDefinition) Then
Continue For
End If
' Return all nested types.
' Note the order: depth first, children in reverse order (to match dev10, not a requirement).
Dim stack = New Stack(Of NamedTypeSymbol)()
stack.Push(originalDefinition)
While stack.Count > 0
Dim curr As NamedTypeSymbol = stack.Pop()
' In general, we don't want private types to appear in the ExportedTypes table.
If curr.DeclaredAccessibility = Accessibility.Private Then
' NOTE: this will also exclude nested types of curr.
Continue While
End If
' NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection.
builder.Add(New TypeExport(Of NamedTypeSymbol)(curr))
' Iterate backwards so they get popped in forward order.
Dim nested As ImmutableArray(Of NamedTypeSymbol) = curr.GetTypeMembers() ' Ordered.
For i As Integer = nested.Length - 1 To 0 Step -1
stack.Push(nested(i))
Next
End While
Next
End If
End Sub
Friend NotOverridable Overrides ReadOnly Property LinkerMajorVersion As Byte
Get
'EDMAURER the Windows loader team says that this value is not used in loading but is used by the appcompat infrastructure.
'It is useful for us to have
'a mechanism to identify the compiler that produced the binary. This is the appropriate
'value to use for that. That is what it was invented for. We don't want to have the high
'bit set for this in case some users perform a signed comparision to determine if the value
'is less than some version. The C++ linker is at 0x0B. Roslyn C# will start at &H30. We'll start our numbering at &H50.
Return &H50
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property LinkerMinorVersion As Byte
Get
Return 0
End Get
End Property
Friend Iterator Function GetReferencedAssembliesUsedSoFar() As IEnumerable(Of AssemblySymbol)
For Each assembly In SourceModule.GetReferencedAssemblySymbols()
If Not assembly.IsLinked AndAlso
Not assembly.IsMissing AndAlso
m_AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(assembly) Then
Yield assembly
End If
Next
End Function
Friend NotOverridable Overrides Function GetSystemType(syntaxOpt As VisualBasicSyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference
Dim systemTypeSymbol As NamedTypeSymbol = SourceModule.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type)
Dim useSiteError = Binder.GetUseSiteErrorForWellKnownType(systemTypeSymbol)
If useSiteError IsNot Nothing Then
Binder.ReportDiagnostic(diagnostics,
If(syntaxOpt IsNot Nothing, syntaxOpt.GetLocation(), NoLocation.Singleton),
useSiteError)
End If
Return Translate(systemTypeSymbol, syntaxOpt, diagnostics, needDeclaration:=True)
End Function
Friend NotOverridable Overrides Function GetSpecialType(specialType As SpecialType, syntaxNodeOpt As VisualBasicSyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference
Dim typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType)
Dim info = Binder.GetUseSiteErrorForSpecialType(typeSymbol)
If info IsNot Nothing Then
Binder.ReportDiagnostic(diagnostics, If(syntaxNodeOpt IsNot Nothing, syntaxNodeOpt.GetLocation(), NoLocation.Singleton), info)
End If
Return Translate(typeSymbol,
needDeclaration:=True,
syntaxNodeOpt:=syntaxNodeOpt,
diagnostics:=diagnostics)
End Function
Public Overrides Function GetInitArrayHelper() As Cci.IMethodReference
Return DirectCast(Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle), MethodSymbol)
End Function
Protected Overrides Function IsPlatformType(typeRef As Cci.ITypeReference, platformType As Cci.PlatformType) As Boolean
Dim namedType = TryCast(typeRef, NamedTypeSymbol)
If namedType IsNot Nothing Then
If platformType = Cci.PlatformType.SystemType Then
Return namedType Is Compilation.GetWellKnownType(WellKnownType.System_Type)
End If
Return namedType.SpecialType = CType(platformType, SpecialType)
End If
Return False
End Function
Protected Overrides Function GetCorLibraryReferenceToEmit(context As EmitContext) As Cci.IAssemblyReference
Dim corLib = CorLibrary
If Not corLib.IsMissing AndAlso
Not corLib.IsLinked AndAlso
corLib IsNot SourceModule.ContainingAssembly Then
Return Translate(corLib, context.Diagnostics)
End If
Return Nothing
End Function
Friend NotOverridable Overrides Function GetSynthesizedNestedTypes(container As NamedTypeSymbol) As IEnumerable(Of Cci.INestedTypeDefinition)
Return container.GetSynthesizedNestedTypes()
End Function
Public Sub SetDisableJITOptimization(methodSymbol As MethodSymbol)
Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition)
_disableJITOptimization.TryAdd(methodSymbol, True)
End Sub
Public Function JITOptimizationIsDisabled(methodSymbol As MethodSymbol) As Boolean
Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition)
Return _disableJITOptimization.ContainsKey(methodSymbol)
End Function
#Region "Test Hooks"
Friend ReadOnly Property SaveTestData() As Boolean
Get
Return _testData IsNot Nothing
End Get
End Property
Friend Sub SetMethodTestData(methodSymbol As MethodSymbol, builder As ILBuilder)
If _testData Is Nothing Then
Throw New InvalidOperationException("Must call SetILBuilderMap before calling SetILBuilder")
End If
' If this ever throws "ArgumentException: An item with the same key has already been added.", then
' the ilBuilderMapKeyFormat will need to be updated to provide a unique key (see SetILBuilderMap).
_testData.Add(
methodSymbol.ToDisplayString(If(methodSymbol.IsUserDefinedOperator(), _testDataOperatorKeyFormat, _testDataKeyFormat)),
New CompilationTestData.MethodData(builder, methodSymbol))
End Sub
Friend Sub SetMethodTestData(methods As ConcurrentDictionary(Of String, CompilationTestData.MethodData))
Me._testData = methods
Me._testDataKeyFormat = New SymbolDisplayFormat(
compilerInternalOptions:=SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames Or SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers,
globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining,
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:=
SymbolDisplayMemberOptions.IncludeParameters Or
SymbolDisplayMemberOptions.IncludeContainingType Or
SymbolDisplayMemberOptions.IncludeExplicitInterface,
parameterOptions:=
SymbolDisplayParameterOptions.IncludeParamsRefOut Or
SymbolDisplayParameterOptions.IncludeExtensionThis Or
SymbolDisplayParameterOptions.IncludeType,
miscellaneousOptions:=
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers Or
SymbolDisplayMiscellaneousOptions.UseSpecialTypes Or
SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays Or
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName)
' most methods don't need return type to disambiguate signatures, however,
' it is necessary to disambiguate user defined operators:
' Operator op_Implicit(Type) As Integer
' Operator op_Implicit(Type) As Single
' ... etc ...
Me._testDataOperatorKeyFormat = New SymbolDisplayFormat(
_testDataKeyFormat.CompilerInternalOptions,
_testDataKeyFormat.GlobalNamespaceStyle,
_testDataKeyFormat.TypeQualificationStyle,
_testDataKeyFormat.GenericsOptions,
_testDataKeyFormat.MemberOptions Or SymbolDisplayMemberOptions.IncludeType,
_testDataKeyFormat.ParameterOptions,
_testDataKeyFormat.DelegateStyle,
_testDataKeyFormat.ExtensionMethodStyle,
_testDataKeyFormat.PropertyStyle,
_testDataKeyFormat.LocalOptions,
_testDataKeyFormat.KindOptions,
_testDataKeyFormat.MiscellaneousOptions)
End Sub
#End Region
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.vb
|
Visual Basic
|
apache-2.0
| 36,516
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
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("AutomEVT.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
|
marshallcoz/RegSis
|
4 C¢digo Fuente/AutomEVT/AutomEVT/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,773
|
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Namespace Casascius.Bitcoin
Public Class Base58
''' <summary>
''' Converts a base-58 string to a byte array, returning null if it wasn't valid.
''' </summary>
Public Shared Function ToByteArray(ByVal base58 As String) As Byte()
Dim bi2 As New Org.BouncyCastle.Math.BigInteger("0")
Dim b58 As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
Dim sOut As String = "hi"
For Each c As Char In base58
If b58.IndexOf(c) <> -1 Then
bi2 = bi2.Multiply(New Org.BouncyCastle.Math.BigInteger("58"))
bi2 = bi2.Add(New Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString()))
Else
Return Nothing
End If
Next
Dim bb As Byte() = bi2.ToByteArrayUnsigned()
' interpret leading '1's as leading zero bytes
For Each c As Char In base58
If c <> "1"c Then
Exit For
End If
Dim bbb As Byte() = New Byte(bb.Length) {}
Array.Copy(bb, 0, bbb, 1, bb.Length)
bb = bbb
Next
Return bb
End Function
Public Shared Function FromByteArray(ByVal ba As Byte()) As String
Dim addrremain As New Org.BouncyCastle.Math.BigInteger(1, ba)
Dim big0 As New Org.BouncyCastle.Math.BigInteger("0")
Dim big58 As New Org.BouncyCastle.Math.BigInteger("58")
Dim b58 As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
Dim rv As String = ""
While addrremain.CompareTo(big0) > 0
Dim d As Integer = Convert.ToInt32(addrremain.[Mod](big58).ToString())
addrremain = addrremain.Divide(big58)
rv = b58.Substring(d, 1) & rv
End While
' handle leading zeroes
For Each b As Byte In ba
If b <> 0 Then
Exit For
End If
rv = "1" & rv
Next
Return rv
End Function
End Class
End Namespace
|
bitspill/Gridcoin-master
|
contrib/RD/GridCoinDotNet/GridCoin/cls58.vb
|
Visual Basic
|
mit
| 2,296
|
'********************************************************************************************************
'File Name: frmScript.vb
'Description: MapWindow Script System
'********************************************************************************************************
'The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/
'Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
'ANY KIND, either express or implied. See the License for the specificlanguage governing rights and
'limitations under the License.
'
' The original code is
' Adapted for MapWindow by Chris Michaelis (cmichaelis@happysquirrel.com) on Jan 1 2006
' Originally created by Mark Gray of AquaTerra Consultants
'
'The Initial Developer of this version of the Original Code is Christopher Michaelis, done
'by reshifting and moving about the various utility functions from MapWindow's modPublic.vb
'(which no longer exists) and some useful utility functions from Aqua Terra Consulting.
'
'Contributor(s): (Open source contributors should list themselves and their modifications here).
'Feb 8 2006 - Chris Michaelis - Added the "Online Script Directory" features.
'8/9/2006 - Paul Meems (pm) - Started Duth translation
'1/28/2008 - Jiri Kadlec - changed ResourceManager (message strings moved to GlobalResource.resx)
'12/11/2010 - Kurt Wolfe - ported to DotSpatial
'12/28/2011 - Kurt Wolfe - Move plugin type to DotSpatial.Controls.Extension instead of IExtension
'********************************************************************************************************
Imports System.CodeDom.Compiler
Imports System.ComponentModel.Composition.Hosting
Imports System.Drawing
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Threading
Imports System.Windows.Forms
Imports DotSpatial.Controls
Public Class frmScript
'Inherits MapWindow.baseForm '5/5/2008 jk
Inherits System.Windows.Forms.Form
Private _appMgr As AppManager
#Region "Declarations"
'changed by Jiri Kadlec
Private resources As System.Resources.ResourceManager = _
New System.Resources.ResourceManager("MapWindow.GlobalResource", System.Reflection.Assembly.GetExecutingAssembly())
'Public Declare Function LockWindowUpdate Lib "user32" (ByVal hWnd As Integer) As Integer
#End Region
Private pDefaultScript_VB As String = _
"Imports DotSpatial.Controls" & vbCrLf _
& "Imports System.Windows.Forms" & vbCrLf _
& "Imports Microsoft.VisualBasic" & vbCrLf _
& "Imports System" & vbCrLf _
& vbCrLf _
& "'Each script should (but doesn't have to) have a unique name. Change MyExample here to something meaningful. ScriptMain should remain as ""Main"" however." & vbCrLf _
& "Public Module MyExample" & vbCrLf _
& " Public Sub ScriptMain(appMgr as AppManager)" & vbCrLf _
& " MessageBox.Show(""This is a simple script to display the number of loaded layers in the map: "" & appMgr.Map.Layers.Count)" & vbCrLf _
& " End Sub" & vbCrLf _
& "End Module"
Private pDefaultPlugin_VB As String = _
"Imports DotSpatial.Controls" & vbCrLf _
& "Imports DotSpatial.Controls.Header" & vbCrLf _
& "Imports System.Windows.Forms" & vbCrLf _
& "Imports Microsoft.VisualBasic" & vbCrLf _
& "Imports System" & vbCrLf & _
vbCrLf & _
vbCrLf & _
"Public Class MyPlugin" & vbCrLf & _
" Inherits Extension" & vbCrLf & _
"" + vbCrLf & _
" Dim host As AppManager" & vbCrLf & _
" Dim btnSample As ToolStripButton" & vbCrLf & _
vbCrLf & _
" Public Sub New()" & vbCrLf & _
" End Sub" & vbCrLf & _
"" & vbCrLf & _
" Public Overrides Sub Activate()" & vbCrLf & _
"" & vbCrLf & _
" MyBase.Activate()" & vbCrLf & _
" host = Me.App" & vbCrLf & _
" Dim SamplePluginMenuKey as String = ""kSampleScriptPlugin""" + vbCrLf & _
" Dim samplePlugin as String = ""Sample Script Plugin""" + vbCrLf & _
"" & vbCrLf & _
" host.HeaderControl.Add(New RootItem(SamplePluginMenuKey, samplePlugin))" & vbCrLf & _
" host.HeaderControl.Add(New SimpleActionItem(SamplePluginMenuKey, samplePlugin, New EventHandler(AddressOf btnSample_Click))" & vbCrLf & _
"" & vbCrLf & _
" End Sub" & vbCrLf & _
vbCrLf & _
" Public Overrides Sub Deactivate()" & vbCrLf & _
" host.HeaderControl.RemoveAll()" & vbCrLf & _
" MyBase.Deactivate()" & vbCrLf & _
" End Sub" & vbCrLf & _
vbCrLf & _
vbCrLf & _
" Private Sub btnSample_Click(ByVal sender As Object, ByVal e As EventArgs)" & vbCrLf & _
" MessageBox.Show(""Hello World"")" & vbCrLf & _
" End Sub" & vbCrLf & _
"End Class"
Private pFilter As String = "VB.net (*.vb)|*.vb|C#.net (*.cs)|*.cs|All files|*.*"
Private pFilterVB As String = "VB.net (*.vb)|*.vb|All files|*.*"
Private pFilterCS As String = "C#.net (*.cs)|*.cs|All files|*.*"
Public pFileName As String = ""
Private DataChanged As Boolean = False
Private IgnoreDataChange As Boolean = False
Private pDefaultScript_CS As String = _
"using DotSpatial.Controls;" & vbCrLf _
& "using System.Windows.Forms;" & vbCrLf _
& "using Microsoft.VisualBasic;" & vbCrLf _
& "using System;" & vbCrLf & _
vbCrLf & _
"namespace MyNamespace" + vbCrLf & _
"{" + vbCrLf & _
" // You must change the name of this class to something unique!" & vbCrLf & _
" class MyExample" + vbCrLf & _
" {" + vbCrLf & _
" public static void ScriptMain(AppManager appMgr)" + vbCrLf & _
" { " + vbCrLf & _
" MessageBox.Show(""This is a simple script to display the number of loaded layers in the map: "" + appMgr.Map.Layers.Count);" + vbCrLf & _
" }" + vbCrLf & _
" }" & vbCrLf & _
"}" & vbCrLf
Friend WithEvents ImageList1 As System.Windows.Forms.ImageList
Friend WithEvents tbbNew As System.Windows.Forms.ToolStripButton
Friend WithEvents tbbOpen As System.Windows.Forms.ToolStripButton
Friend WithEvents tbbSave As System.Windows.Forms.ToolStripButton
Friend WithEvents tbbsep As System.Windows.Forms.ToolStripSeparator
Friend WithEvents tbbRun As System.Windows.Forms.ToolStripButton
Friend WithEvents tbbCompile As System.Windows.Forms.ToolStripButton
Friend WithEvents tbbHelp As System.Windows.Forms.ToolStripButton
Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip
Friend WithEvents ToolStripMenuItem1 As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuNew As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuOpen As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuSave As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuClose As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ToolStripMenuItem6 As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuRun As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuCompile As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ToolStripMenuItem2 As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuViewRun As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuSubmit As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuHelp As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents BottomToolStripPanel As System.Windows.Forms.ToolStripPanel
Friend WithEvents TopToolStripPanel As System.Windows.Forms.ToolStripPanel
Friend WithEvents RightToolStripPanel As System.Windows.Forms.ToolStripPanel
Friend WithEvents LeftToolStripPanel As System.Windows.Forms.ToolStripPanel
Friend WithEvents ContentPanel As System.Windows.Forms.ToolStripContentPanel
Friend WithEvents ToolStripContainer1 As System.Windows.Forms.ToolStripContainer
Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox
Friend WithEvents rdScript As System.Windows.Forms.RadioButton
Friend WithEvents rdPlugin As System.Windows.Forms.RadioButton
Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
Friend WithEvents rdVBNet As System.Windows.Forms.RadioButton
Friend WithEvents rdCS As System.Windows.Forms.RadioButton
Friend WithEvents mnuSep As System.Windows.Forms.ToolStripSeparator
<CLSCompliant(False)> _
Public WithEvents txtScript As CSharpEditor.MainForm
Private pDefaultPlugin_CS As String = _
"using DotSpatial.Controls;" & vbCrLf _
& "using DotSpatial.Controls.Header;" & vbCrLf _
& "using System.Windows.Forms;" & vbCrLf _
& "using Microsoft.VisualBasic;" & vbCrLf _
& "using System;" & vbCrLf & _
"" & vbCrLf & _
"namespace MyNamespace" & vbCrLf & _
"{" + vbCrLf & _
" public class MyExample : Extension" & vbCrLf & _
" {" + vbCrLf & _
" private AppManager _host;" + vbCrLf & _
"" + vbCrLf & _
" // Change this to match the name of your class. This is the constructor." + vbCrLf & _
" public MyExample()" + vbCrLf & _
" {" + vbCrLf & _
"" + vbCrLf & _
" }" + vbCrLf & _
"" + vbCrLf & _
vbCrLf & _
" public override void Activate()" & vbCrLf & _
" {" + vbCrLf & _
"" + vbCrLf & _
" base.Activate();" + vbCrLf & _
" _host = App;" + vbCrLf & _
" string SamplePluginMenuKey = ""kSampleScriptPlugin"";" + vbCrLf & _
" string samplePlugin = ""Sample Scripts Plugin"";" + vbCrLf & _
" _host.HeaderControl.Add(new RootItem(SamplePluginMenuKey, samplePlugin));" & vbCrLf & _
" _host.HeaderControl.Add(new SimpleActionItem(SamplePluginMenuKey, samplePlugin, btnSample_Click));" & vbCrLf & _
"" & vbCrLf & _
" }" + vbCrLf & _
vbCrLf & _
" public override void Deactivate()" & vbCrLf & _
" {" & vbCrLf & _
" _host.HeaderControl.RemoveAll();" & vbCrLf & _
" base.Deactivate();" & vbCrLf & _
" }" & vbCrLf & _
vbCrLf & _
" private void btnSample_Click(object sender, EventArgs e )" & vbCrLf & _
" {" & vbCrLf & _
" MessageBox.Show(""Hello World"");" & vbCrLf & _
" }" & vbCrLf & _
" }" & vbCrLf & _
"}"
#Region " Windows Form Designer generated code "
Public Sub New(ByVal appManager As AppManager)
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
_appMgr = appManager
'May/12/2008 Jiri Kadlec - load icon from shared resources to reduce size of the program
'Me.Icon = My.Resources.MapWindow_new
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 tools As System.Windows.Forms.ToolStrip
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmScript))
Me.ToolStripContainer1 = New System.Windows.Forms.ToolStripContainer()
Me.txtScript = New CSharpEditor.MainForm()
Me.GroupBox2 = New System.Windows.Forms.GroupBox()
Me.rdScript = New System.Windows.Forms.RadioButton()
Me.rdPlugin = New System.Windows.Forms.RadioButton()
Me.GroupBox1 = New System.Windows.Forms.GroupBox()
Me.rdVBNet = New System.Windows.Forms.RadioButton()
Me.rdCS = New System.Windows.Forms.RadioButton()
Me.MenuStrip1 = New System.Windows.Forms.MenuStrip()
Me.ToolStripMenuItem1 = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuNew = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuOpen = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuSave = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuSep = New System.Windows.Forms.ToolStripSeparator()
Me.mnuClose = New System.Windows.Forms.ToolStripMenuItem()
Me.ToolStripMenuItem6 = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuRun = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuCompile = New System.Windows.Forms.ToolStripMenuItem()
Me.ToolStripMenuItem2 = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuViewRun = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuSubmit = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuHelp = New System.Windows.Forms.ToolStripMenuItem()
Me.tools = New System.Windows.Forms.ToolStrip()
Me.ImageList1 = New System.Windows.Forms.ImageList(Me.components)
Me.tbbNew = New System.Windows.Forms.ToolStripButton()
Me.tbbOpen = New System.Windows.Forms.ToolStripButton()
Me.tbbSave = New System.Windows.Forms.ToolStripButton()
Me.tbbsep = New System.Windows.Forms.ToolStripSeparator()
Me.tbbRun = New System.Windows.Forms.ToolStripButton()
Me.tbbCompile = New System.Windows.Forms.ToolStripButton()
Me.tbbHelp = New System.Windows.Forms.ToolStripButton()
Me.BottomToolStripPanel = New System.Windows.Forms.ToolStripPanel()
Me.TopToolStripPanel = New System.Windows.Forms.ToolStripPanel()
Me.RightToolStripPanel = New System.Windows.Forms.ToolStripPanel()
Me.LeftToolStripPanel = New System.Windows.Forms.ToolStripPanel()
Me.ContentPanel = New System.Windows.Forms.ToolStripContentPanel()
Me.ToolStripContainer1.ContentPanel.SuspendLayout()
Me.ToolStripContainer1.TopToolStripPanel.SuspendLayout()
Me.ToolStripContainer1.SuspendLayout()
Me.GroupBox2.SuspendLayout()
Me.GroupBox1.SuspendLayout()
Me.MenuStrip1.SuspendLayout()
Me.tools.SuspendLayout()
Me.SuspendLayout()
'
'ToolStripContainer1
'
Me.ToolStripContainer1.AllowDrop = True
'
'ToolStripContainer1.ContentPanel
'
Me.ToolStripContainer1.ContentPanel.Controls.Add(Me.txtScript)
Me.ToolStripContainer1.ContentPanel.Controls.Add(Me.GroupBox2)
Me.ToolStripContainer1.ContentPanel.Controls.Add(Me.GroupBox1)
resources.ApplyResources(Me.ToolStripContainer1.ContentPanel, "ToolStripContainer1.ContentPanel")
resources.ApplyResources(Me.ToolStripContainer1, "ToolStripContainer1")
Me.ToolStripContainer1.Name = "ToolStripContainer1"
'
'ToolStripContainer1.TopToolStripPanel
'
Me.ToolStripContainer1.TopToolStripPanel.Controls.Add(Me.MenuStrip1)
Me.ToolStripContainer1.TopToolStripPanel.Controls.Add(Me.tools)
'
'txtScript
'
resources.ApplyResources(Me.txtScript, "txtScript")
Me.txtScript.Name = "txtScript"
'
'GroupBox2
'
Me.GroupBox2.Controls.Add(Me.rdScript)
Me.GroupBox2.Controls.Add(Me.rdPlugin)
resources.ApplyResources(Me.GroupBox2, "GroupBox2")
Me.GroupBox2.Name = "GroupBox2"
Me.GroupBox2.TabStop = False
'
'rdScript
'
Me.rdScript.Checked = True
resources.ApplyResources(Me.rdScript, "rdScript")
Me.rdScript.Name = "rdScript"
Me.rdScript.TabStop = True
'
'rdPlugin
'
resources.ApplyResources(Me.rdPlugin, "rdPlugin")
Me.rdPlugin.Name = "rdPlugin"
'
'GroupBox1
'
Me.GroupBox1.Controls.Add(Me.rdVBNet)
Me.GroupBox1.Controls.Add(Me.rdCS)
resources.ApplyResources(Me.GroupBox1, "GroupBox1")
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.TabStop = False
'
'rdVBNet
'
Me.rdVBNet.Checked = True
resources.ApplyResources(Me.rdVBNet, "rdVBNet")
Me.rdVBNet.Name = "rdVBNet"
Me.rdVBNet.TabStop = True
'
'rdCS
'
resources.ApplyResources(Me.rdCS, "rdCS")
Me.rdCS.Name = "rdCS"
'
'MenuStrip1
'
resources.ApplyResources(Me.MenuStrip1, "MenuStrip1")
Me.MenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripMenuItem1, Me.ToolStripMenuItem6, Me.ToolStripMenuItem2, Me.mnuHelp})
Me.MenuStrip1.Name = "MenuStrip1"
'
'ToolStripMenuItem1
'
Me.ToolStripMenuItem1.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mnuNew, Me.mnuOpen, Me.mnuSave, Me.mnuSep, Me.mnuClose})
Me.ToolStripMenuItem1.Name = "ToolStripMenuItem1"
resources.ApplyResources(Me.ToolStripMenuItem1, "ToolStripMenuItem1")
'
'mnuNew
'
Me.mnuNew.Name = "mnuNew"
resources.ApplyResources(Me.mnuNew, "mnuNew")
'
'mnuOpen
'
Me.mnuOpen.Name = "mnuOpen"
resources.ApplyResources(Me.mnuOpen, "mnuOpen")
'
'mnuSave
'
Me.mnuSave.Name = "mnuSave"
resources.ApplyResources(Me.mnuSave, "mnuSave")
'
'mnuSep
'
Me.mnuSep.Name = "mnuSep"
resources.ApplyResources(Me.mnuSep, "mnuSep")
'
'mnuClose
'
Me.mnuClose.Name = "mnuClose"
resources.ApplyResources(Me.mnuClose, "mnuClose")
'
'ToolStripMenuItem6
'
Me.ToolStripMenuItem6.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mnuRun, Me.mnuCompile})
Me.ToolStripMenuItem6.Name = "ToolStripMenuItem6"
resources.ApplyResources(Me.ToolStripMenuItem6, "ToolStripMenuItem6")
'
'mnuRun
'
Me.mnuRun.Name = "mnuRun"
resources.ApplyResources(Me.mnuRun, "mnuRun")
'
'mnuCompile
'
Me.mnuCompile.Name = "mnuCompile"
resources.ApplyResources(Me.mnuCompile, "mnuCompile")
'
'ToolStripMenuItem2
'
Me.ToolStripMenuItem2.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mnuViewRun, Me.mnuSubmit})
Me.ToolStripMenuItem2.Name = "ToolStripMenuItem2"
resources.ApplyResources(Me.ToolStripMenuItem2, "ToolStripMenuItem2")
'
'mnuViewRun
'
Me.mnuViewRun.Name = "mnuViewRun"
resources.ApplyResources(Me.mnuViewRun, "mnuViewRun")
'
'mnuSubmit
'
Me.mnuSubmit.Name = "mnuSubmit"
resources.ApplyResources(Me.mnuSubmit, "mnuSubmit")
'
'mnuHelp
'
Me.mnuHelp.Name = "mnuHelp"
resources.ApplyResources(Me.mnuHelp, "mnuHelp")
'
'tools
'
resources.ApplyResources(Me.tools, "tools")
Me.tools.ImageList = Me.ImageList1
Me.tools.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.tbbNew, Me.tbbOpen, Me.tbbSave, Me.tbbsep, Me.tbbRun, Me.tbbCompile, Me.tbbHelp})
Me.tools.Name = "tools"
'
'ImageList1
'
Me.ImageList1.ImageStream = CType(resources.GetObject("ImageList1.ImageStream"), System.Windows.Forms.ImageListStreamer)
Me.ImageList1.TransparentColor = System.Drawing.Color.Transparent
Me.ImageList1.Images.SetKeyName(0, "")
Me.ImageList1.Images.SetKeyName(1, "")
Me.ImageList1.Images.SetKeyName(2, "")
Me.ImageList1.Images.SetKeyName(3, "")
Me.ImageList1.Images.SetKeyName(4, "")
Me.ImageList1.Images.SetKeyName(5, "")
'
'tbbNew
'
resources.ApplyResources(Me.tbbNew, "tbbNew")
Me.tbbNew.Name = "tbbNew"
'
'tbbOpen
'
resources.ApplyResources(Me.tbbOpen, "tbbOpen")
Me.tbbOpen.Name = "tbbOpen"
'
'tbbSave
'
resources.ApplyResources(Me.tbbSave, "tbbSave")
Me.tbbSave.Name = "tbbSave"
'
'tbbsep
'
Me.tbbsep.Name = "tbbsep"
resources.ApplyResources(Me.tbbsep, "tbbsep")
'
'tbbRun
'
resources.ApplyResources(Me.tbbRun, "tbbRun")
Me.tbbRun.Name = "tbbRun"
'
'tbbCompile
'
resources.ApplyResources(Me.tbbCompile, "tbbCompile")
Me.tbbCompile.Name = "tbbCompile"
'
'tbbHelp
'
resources.ApplyResources(Me.tbbHelp, "tbbHelp")
Me.tbbHelp.Name = "tbbHelp"
'
'BottomToolStripPanel
'
resources.ApplyResources(Me.BottomToolStripPanel, "BottomToolStripPanel")
Me.BottomToolStripPanel.Name = "BottomToolStripPanel"
Me.BottomToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal
Me.BottomToolStripPanel.RowMargin = New System.Windows.Forms.Padding(3, 0, 0, 0)
'
'TopToolStripPanel
'
resources.ApplyResources(Me.TopToolStripPanel, "TopToolStripPanel")
Me.TopToolStripPanel.Name = "TopToolStripPanel"
Me.TopToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal
Me.TopToolStripPanel.RowMargin = New System.Windows.Forms.Padding(3, 0, 0, 0)
'
'RightToolStripPanel
'
resources.ApplyResources(Me.RightToolStripPanel, "RightToolStripPanel")
Me.RightToolStripPanel.Name = "RightToolStripPanel"
Me.RightToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal
Me.RightToolStripPanel.RowMargin = New System.Windows.Forms.Padding(3, 0, 0, 0)
'
'LeftToolStripPanel
'
resources.ApplyResources(Me.LeftToolStripPanel, "LeftToolStripPanel")
Me.LeftToolStripPanel.Name = "LeftToolStripPanel"
Me.LeftToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal
Me.LeftToolStripPanel.RowMargin = New System.Windows.Forms.Padding(3, 0, 0, 0)
'
'ContentPanel
'
resources.ApplyResources(Me.ContentPanel, "ContentPanel")
'
'frmScript
'
Me.AllowDrop = True
resources.ApplyResources(Me, "$this")
Me.Controls.Add(Me.ToolStripContainer1)
Me.Name = "frmScript"
Me.ToolStripContainer1.ContentPanel.ResumeLayout(False)
Me.ToolStripContainer1.TopToolStripPanel.ResumeLayout(False)
Me.ToolStripContainer1.TopToolStripPanel.PerformLayout()
Me.ToolStripContainer1.ResumeLayout(False)
Me.ToolStripContainer1.PerformLayout()
Me.GroupBox2.ResumeLayout(False)
Me.GroupBox1.ResumeLayout(False)
Me.MenuStrip1.ResumeLayout(False)
Me.MenuStrip1.PerformLayout()
Me.tools.ResumeLayout(False)
Me.tools.PerformLayout()
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub tools_ButtonClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles tools.ItemClicked
PerformAction(CStr(e.ClickedItem.Name))
End Sub
Private Function Language() As String
If rdVBNet.Checked Then
Return "vb"
ElseIf rdCS.Checked Then
Return "cs"
Else
Return ""
End If
End Function
Private Sub PerformAction(ByVal action As String)
action = action.ToLower().Replace("&", "")
Select Case action
Case "tbbnew", "new"
If rdVBNet.Checked Then
txtScript.Text = pDefaultScript_VB
Else
txtScript.Text = pDefaultScript_CS
End If
Case "tbbopen", "open"
Dim cdOpen As New Windows.Forms.OpenFileDialog
Try
cdOpen.InitialDirectory = GetSetting("MapWindow", "Defaults", "ScriptPath", cdOpen.InitialDirectory)
Catch
End Try
cdOpen.Filter = pFilter
' Paul Meems 3 aug 2009 Added:
If rdVBNet.Checked Then
cdOpen.FilterIndex = 1
Else
cdOpen.FilterIndex = 2
End If
cdOpen.FileName = pFileName
If cdOpen.ShowDialog() = Windows.Forms.DialogResult.OK Then
pFileName = cdOpen.FileName
Try
SaveSetting("MapWindow", "Defaults", "ScriptPath", System.IO.Path.GetDirectoryName(pFileName))
Catch
End Try
If (cdOpen.FileName.ToLower.EndsWith("cs")) Then
rdCS.Checked = True
Else
rdVBNet.Checked = True
End If
IgnoreDataChange = True
txtScript.Text = MapWinUtility.Strings.WholeFileString(pFileName)
IgnoreDataChange = False
End If
Case "tbbsave", "save"
Dim cdSave As New Windows.Forms.SaveFileDialog
If rdVBNet.Checked Then
cdSave.Filter = pFilterVB
Else
cdSave.Filter = pFilterCS
End If
Try
cdSave.InitialDirectory = GetSetting("MapWindow", "Defaults", "ScriptPath", cdSave.InitialDirectory)
Catch
End Try
cdSave.FileName = pFileName
If cdSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
pFileName = cdSave.FileName
Try
SaveSetting("MapWindow", "Defaults", "ScriptPath", System.IO.Path.GetDirectoryName(pFileName))
Catch
End Try
MapWinUtility.Strings.SaveFileString(pFileName, txtScript.Text)
End If
IgnoreDataChange = True
IgnoreDataChange = False
Case "tbbrun", "run script", "run"
Run()
Case "tbbcompile", "plugin", "plug-in", "compile plug-in", "compile plugin", "compile"
Compile()
Case "tbbhelp", "help"
'Dim hlp As New frmScriptHelp
'hlp.Icon = Me.Icon
'hlp.ShowDialog()
Case "tbbclose", "close"
Me.Close()
End Select
End Sub
Private Sub Run()
Dim errors As String = ""
Dim args(0) As Object
Dim sPluginFolder As String = Assembly.GetEntryAssembly().Location
Dim dirInfo As DirectoryInfo = Directory.GetParent(sPluginFolder)
sPluginFolder = dirInfo.FullName & "\Plugins\ScriptRunner"
Dim assy As Assembly
assy = MapWinUtility.Scripting.PrepareScript(Language, Nothing, txtScript.Text, errors, sPluginFolder)
If (assy Is Nothing) Then
Return
End If
If rdPlugin.Checked Then
Dim types As Type() = assy.GetTypes()
For Each tmpType As Type In types
If tmpType.IsSubclassOf(GetType(DotSpatial.Controls.Extension)) Then
_appMgr.Catalog.Catalogs.Add(New AssemblyCatalog(assy))
Exit For
End If
Next
Else
args(0) = _appMgr
MapWinUtility.Scripting.Run(assy, errors, args)
End If
If Not errors Is Nothing AndAlso errors.Trim().Length > 0 Then
'should the logger be used here?
'MapWinUtility.Logger.Msg(errors, MsgBoxStyle.Exclamation, resources.GetString("msgScriptError.Text"))
End If
End Sub
Private Sub Compile()
Dim cdSave As New Windows.Forms.SaveFileDialog
Dim errors As String = ""
Dim outPath As String = ""
Dim assy As System.Reflection.Assembly
cdSave.Filter = "DLL files (*.dll)|*.dll"
'cdSave.InitialDirectory = frmMain.Plugins.PluginFolder
cdSave.OverwritePrompt = True
Dim MustRename As Boolean = False
If cdSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
outPath = cdSave.FileName
If System.IO.File.Exists(outPath) Then
'Get the key, so we can turn it off and unload it:
'Dim info As New PluginInfo()
'info.Init(outPath, GetType(PluginInterfaces.IBasePlugin).GUID)
'If Not info.Key = "" Then
' frmMain.Plugins.StopPlugin(info.Key)
' Dim plugin As Interfaces.IPlugin
' For Each plugin In frmMain.m_PluginManager.LoadedPlugins
' If plugin.Name = info.Name Then
' plugin.Terminate()
' plugin = Nothing
' End If
' Next
' 'Do not scan here -- or it will immediately reload the plug-in.
' 'frmMain.m_PluginManager.ScanPluginFolder()
' 'frmMain.SynchPluginMenu()
'End If
'info = Nothing 'no Dispose on this object; mark it as nothing
'Try
' System.IO.File.Delete(outPath)
'Catch ex As Exception
' MustRename = True
'End Try
'If MustRename Then
' 'Cannot delete the old file; the assembly is still referenced
' 'by .NET for some reason. Since it's not loaded in MW,
' 'just change the name and move on.
' For z As Integer = 1 To 500
' If Not System.IO.File.Exists(System.IO.Path.GetFileNameWithoutExtension(outPath) + "-" + z.ToString() + ".dll") Then
' outPath = System.IO.Path.GetFileNameWithoutExtension(outPath) + "-" + z.ToString() + ".dll"
' MapWinUtility.Logger.Msg("Notice -- The old file could not be deleted." + vbCrLf + "The newest version of your plug-in will be called: " + vbCrLf + vbCrLf + outPath + vbCrLf + vbCrLf + _
' "You may need to close MapWindow and delete the old version for the new plug-in to load properly.", MsgBoxStyle.Information, "Renamed Plugin")
' Exit For
' End If
' Next z
'End If
End If
assy = MapWinUtility.Scripting.Compile(Language, txtScript.Text, _
errors, _
outPath)
If errors.Length = 0 Then
'frmMain.Plugins.AddFromFile(outPath)
Else
'jk
MapWinUtility.Logger.Msg(errors, MsgBoxStyle.Exclamation, resources.GetString("msgScriptError.Text"))
End If
End If
End Sub
Private Sub frmScript_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop, ToolStripContainer1.DragDrop
Try
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim a As Array = e.Data.GetData(DataFormats.FileDrop)
If a.Length > 0 Then
If System.IO.File.Exists(a(0)) Then
IgnoreDataChange = True
txtScript.Text = MapWinUtility.Strings.WholeFileString(a(0))
IgnoreDataChange = False
e.Data.SetData(Nothing)
Exit Sub
End If
End If
End If
Catch
End Try
End Sub
Private Sub frmScript_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter, ToolStripContainer1.DragEnter
e.Effect = DragDropEffects.Copy
End Sub
Private Sub frmScript_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
txtScript.Shutdown()
End Sub
Private Sub frmScript_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtScript.AllowDrop = True
If pFileName = "" Then
'Load the default. Don't overwrite something already in the box
'(a loaded saved script)
IgnoreDataChange = True
If System.IO.File.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\mw_LastScript.dat") Then
txtScript.Text = MapWinUtility.Strings.WholeFileString(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\mw_LastScript.dat")
Else
txtScript.Text = pDefaultScript_CS
End If
DataChanged = False
' Paul Meems 3 aug 2009 Added:
If txtScript.Text.IndexOf("using ") < 0 Then
rdVBNet.Checked = True
txtScript.SetVB()
Else
rdCS.Checked = True
txtScript.SetCS()
End If
'If GetSetting("MapWindow", "LastScript", "CS", "True") = "False" Then
' rdVBNet.Checked = True
' txtScript.SetVB()
'Else
' rdCS.Checked = True
' txtScript.SetCS()
'End If
IgnoreDataChange = False
End If
txtScript.Init()
'Height adjust -- internationalization seems to randomly reset the txtscript size
txtScript.Width = Me.Width - 25
txtScript.Height = Me.Height - 144
End Sub
Private Sub rdLangOrOutput_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdVBNet.CheckedChanged, rdCS.CheckedChanged, rdPlugin.CheckedChanged, rdScript.CheckedChanged
If IgnoreDataChange Then Exit Sub
If DataChanged Then
'PM
'Dim b As MsgBoxResult = mapwinutility.logger.msg("Do you wish to save your current script first?", MsgBoxStyle.YesNo, "Save first?")
Dim b As MsgBoxResult = MapWinUtility.Logger.Msg(resources.GetString("msgSaveCurrentScript.Text"), MsgBoxStyle.YesNo)
If b = MsgBoxResult.Yes Then
Dim cdSave As New Windows.Forms.SaveFileDialog
cdSave.Filter = pFilter
cdSave.FileName = pFileName
If cdSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
pFileName = cdSave.FileName
MapWinUtility.Strings.SaveFileString(pFileName, txtScript.Text)
End If
End If
End If
Me.Cursor = Cursors.WaitCursor
IgnoreDataChange = True
'Change the enabled menu buttons appropriately
'(only allow run on scripts, only allow compile on plugins)
mnuCompile.Enabled = Not rdScript.Checked
mnuRun.Enabled = rdScript.Checked
For i As Integer = 0 To tools.Items.Count - 1
If CStr(tools.Items(i).Tag) = "Compile" Then
tools.Items(i).Enabled = Not rdScript.Checked
End If
If CStr(tools.Items(i).Tag) = "Run" Then
tools.Items(i).Enabled = rdScript.Checked
End If
Next
If rdScript.Checked Then
If rdVBNet.Checked Then
txtScript.Text = pDefaultScript_VB
txtScript.SetVB()
Else
txtScript.Text = pDefaultScript_CS
txtScript.SetCS()
End If
Else
If rdVBNet.Checked Then
txtScript.Text = pDefaultPlugin_VB
txtScript.SetVB()
Else
txtScript.Text = pDefaultPlugin_CS
txtScript.SetCS()
End If
End If
'If not visible, loading - don't save the state yet
If (Me.Visible) Then SaveSetting("MapWindow", "LastScript", "CS", rdCS.Checked.ToString())
Me.Cursor = Cursors.Default
IgnoreDataChange = False
DataChanged = False
End Sub
Private Sub txtScript_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtScript.KeyDown
If e.KeyCode = Keys.F5 Then
PerformAction("Run")
End If
End Sub
Private Sub txtScript_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If IgnoreDataChange Then Exit Sub
DataChanged = True
End Sub
Public Sub RunSavedScript()
If pFileName = "" Then Exit Sub 'nothing to do
If Not System.IO.File.Exists(pFileName) Then
'PM
'mapwinutility.logger.msg("Warning: Ignoring the script name provided on the command line because it doesn't exist." & vbCrLf & vbCrLf & pFileName, MsgBoxStyle.Exclamation, "Nonexistant Script Passed")
Dim sMsg = String.Format(resources.GetString("msgIgnoreScript.Text"), pFileName)
MapWinUtility.Logger.Msg(sMsg, MsgBoxStyle.Exclamation, resources.GetString("msgScriptNotExists.Text"))
Exit Sub
End If
Me.Show()
Me.WindowState = FormWindowState.Minimized
IgnoreDataChange = True
txtScript.Text = MapWinUtility.Strings.WholeFileString(pFileName)
IgnoreDataChange = False
'Make it pretty
Dim errors As String = ""
Dim args(0) As Object
'args(0) = frmMain
args(0) = Nothing
Dim sPluginFolder As String = ""
Dim sLanguage = System.IO.Path.GetExtension(pFileName)
Dim assy As Assembly
'MapWinUtility.Scripting.Run(System.IO.Path.GetExtension(pFileName), Nothing, txtScript.Text, errors, rdPlugin.Checked, CObj(frmMain), args)
assy = MapWinUtility.Scripting.PrepareScript(sLanguage, Nothing, txtScript.Text, errors, sPluginFolder)
MapWinUtility.Scripting.Run(assy, errors, args)
If Not errors Is Nothing And Not errors.Trim() = "" Then
MapWinUtility.Logger.Msg(errors, MsgBoxStyle.Exclamation, "Script Error")
End If
Me.Close()
End Sub
Private Sub ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHelp.Click, mnuSubmit.Click, mnuViewRun.Click, mnuRun.Click, mnuCompile.Click, mnuNew.Click, mnuSave.Click, mnuOpen.Click, mnuClose.Click, mnuCompile.Click
PerformAction((CType(sender, System.Windows.Forms.ToolStripMenuItem).Text.Replace("&", "")))
End Sub
Private Sub ToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuViewRun.Click
If Not MapWinUtility.MiscUtils.CheckInternetConnection("http://MapWindow.org/site_is_up_flag.txt", 5000) Then
'PM
'mapwinutility.logger.msg("There is no active internet connection, or there has been some other communications problem." + vbCrLf + vbCrLf + "Please check your connection and try again.", MsgBoxStyle.Exclamation, "No Connection")
MapWinUtility.Logger.Msg(resources.GetString("msgNoConnection.Text"), MsgBoxStyle.Exclamation, "No Connection")
Exit Sub
Else
Me.Cursor = Cursors.WaitCursor
'Dim onlinescriptform As New frmOnlineScriptDirectory
'onlinescriptform.Show()
Me.Cursor = Cursors.Default
End If
End Sub
Private Sub ToolStripMenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSubmit.Click
If Not MapWinUtility.MiscUtils.CheckInternetConnection("http://MapWindow.org/site_is_up_flag.txt", 5000) Then
'PM
'mapwinutility.logger.msg("There is no active internet connection, or there has been some other communications problem." + vbCrLf + vbCrLf + "Please check your connection and try again.", MsgBoxStyle.Exclamation, "No Connection")
MapWinUtility.Logger.Msg(resources.GetString("msgNoConnection.Text"), MsgBoxStyle.Exclamation, resources.GetString("titleNoConnection.Text"))
Exit Sub
Else
'Dim onlinescriptform As New frmOnlineScriptSubmit
'onlinescriptform.Show()
End If
End Sub
Private Sub frmScript_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If Not txtScript.Text = "" Then
SaveSetting("MapWindow", "LastScript", "CS", rdCS.Checked.ToString())
If System.IO.File.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\mw_LastScript.dat") Then
Kill(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\mw_LastScript.dat")
End If
MapWinUtility.Strings.SaveFileString(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\mw_LastScript.dat", txtScript.Text)
End If
End Sub
Private Sub frmScript_LocationChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LocationChanged
End Sub
End Class
|
swsglobal/DotSpatial
|
Source/DotSpatial.Plugins.ScriptRunner/frmScript.vb
|
Visual Basic
|
mit
| 44,031
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeGeneration
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent
Partial Friend Class GenerateEventCodeFixProvider
Private Class GenerateEventCodeAction
Inherits CodeAction
Private ReadOnly _solution As Solution
Private ReadOnly _targetSymbol As INamedTypeSymbol
Private ReadOnly _generatedEvent As IEventSymbol
Private ReadOnly _codeGenService As ICodeGenerationService
Public Sub New(solution As Solution,
targetSymbol As INamedTypeSymbol,
generatedEvent As IEventSymbol,
codeGenService As ICodeGenerationService)
_solution = solution
_targetSymbol = targetSymbol
_generatedEvent = generatedEvent
_codeGenService = codeGenService
End Sub
Public Overrides ReadOnly Property Title As String
Get
Return String.Format(VBFeaturesResources.Create_event_0_in_1, _generatedEvent.Name, _targetSymbol.Name)
End Get
End Property
Protected Overrides Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document)
Return _codeGenService.AddEventAsync(
_solution, _targetSymbol, _generatedEvent,
CodeGenerationContext.Default, cancellationToken)
End Function
End Class
End Class
End Namespace
|
sharwell/roslyn
|
src/Features/VisualBasic/Portable/CodeFixes/GenerateEvent/GenerateEventCodeFixProvider.CodeAction.vb
|
Visual Basic
|
mit
| 1,828
|
Public Class MainForm
Inherits System.Windows.Forms.Form
Private myConnection As VACCESSLib.Connection
Private myProtocolState As String
Const queryCacheSize As Integer = 10
Private Enum queryCacheIndices
iQuery = 0
iResult = 1
iDate = 2
iCurrency = 3
End Enum
Private queryCache(queryCacheSize, 4) As String
Private queryCacheSelection(queryCacheSize, 2) As Integer
Private queryCount As Integer = -1
Private viewingQuery As Integer = -1
Private oldestCachedQuery As Integer = 0
Private focussedTextBox As TextBox
Private findReplaceDialog As FindReplaceForm
#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
Me.myConnection = New VACCESSLib.Connection
Dim sessionNames As String = Me.myConnection.SessionNames
If (sessionNames <> Nothing) Then
Me.SessionComboBox.Items.AddRange(Split(sessionNames, Chr(10)))
Else
Me.SessionComboBox.Enabled = False
End If
Me.LoadPreferences()
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 StatusBar As System.Windows.Forms.StatusBar
Friend WithEvents Panel1 As System.Windows.Forms.Panel
Friend WithEvents ResultsGroupBox As System.Windows.Forms.GroupBox
Friend WithEvents ResultsTextBox As System.Windows.Forms.TextBox
Friend WithEvents ConnectionGroupBox As System.Windows.Forms.GroupBox
Friend WithEvents Splitter1 As System.Windows.Forms.Splitter
Friend WithEvents QueryGroupBox As System.Windows.Forms.GroupBox
Friend WithEvents QueryTextBox As System.Windows.Forms.TextBox
Friend WithEvents DateLabel As System.Windows.Forms.Label
Friend WithEvents DateTextBox As System.Windows.Forms.TextBox
Friend WithEvents CurrencyTextBox As System.Windows.Forms.TextBox
Friend WithEvents CurrencyLabel As System.Windows.Forms.Label
Friend WithEvents ExecuteButton As System.Windows.Forms.Button
Friend WithEvents Panel3 As System.Windows.Forms.Panel
Friend WithEvents Panel4 As System.Windows.Forms.Panel
Friend WithEvents ProtocolLabel As System.Windows.Forms.Label
Friend WithEvents ProtocolComboBox As System.Windows.Forms.ComboBox
Friend WithEvents HostLabel As System.Windows.Forms.Label
Friend WithEvents UserLabel As System.Windows.Forms.Label
Friend WithEvents PassLabel As System.Windows.Forms.Label
Friend WithEvents HostTextBox As System.Windows.Forms.TextBox
Friend WithEvents UserTextBox As System.Windows.Forms.TextBox
Friend WithEvents PasswordTextBox As System.Windows.Forms.TextBox
Friend WithEvents ConnectionOnOffButton As System.Windows.Forms.Button
Friend WithEvents ConnectionOnOffPanel As System.Windows.Forms.Panel
Friend WithEvents QueryOptionsPanel As System.Windows.Forms.Panel
Friend WithEvents FileMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents FileExitMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents SessionMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents SessionConnectMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents SessionDisconnectMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents SessionExecuteMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
Friend WithEvents SessionPreviousQueryMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents SessionNextQueryMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
Friend WithEvents SessionComboBox As System.Windows.Forms.ComboBox
Friend WithEvents EditMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents EditCutMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents EditCopyMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents EditPasteMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents EditSelectAllMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
Friend WithEvents EditFindMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents QueryPanel As System.Windows.Forms.Panel
Friend WithEvents FormatMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents FormatWordWrapMenuItem As System.Windows.Forms.MenuItem
Friend WithEvents FormatFontMenuItem As System.Windows.Forms.MenuItem
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(MainForm))
Me.StatusBar = New System.Windows.Forms.StatusBar
Me.Panel1 = New System.Windows.Forms.Panel
Me.QueryGroupBox = New System.Windows.Forms.GroupBox
Me.QueryPanel = New System.Windows.Forms.Panel
Me.QueryTextBox = New System.Windows.Forms.TextBox
Me.QueryOptionsPanel = New System.Windows.Forms.Panel
Me.DateLabel = New System.Windows.Forms.Label
Me.DateTextBox = New System.Windows.Forms.TextBox
Me.CurrencyTextBox = New System.Windows.Forms.TextBox
Me.CurrencyLabel = New System.Windows.Forms.Label
Me.ExecuteButton = New System.Windows.Forms.Button
Me.Splitter1 = New System.Windows.Forms.Splitter
Me.ResultsGroupBox = New System.Windows.Forms.GroupBox
Me.ResultsTextBox = New System.Windows.Forms.TextBox
Me.ConnectionGroupBox = New System.Windows.Forms.GroupBox
Me.Panel3 = New System.Windows.Forms.Panel
Me.SessionComboBox = New System.Windows.Forms.ComboBox
Me.ConnectionOnOffPanel = New System.Windows.Forms.Panel
Me.ConnectionOnOffButton = New System.Windows.Forms.Button
Me.HostLabel = New System.Windows.Forms.Label
Me.UserLabel = New System.Windows.Forms.Label
Me.PassLabel = New System.Windows.Forms.Label
Me.HostTextBox = New System.Windows.Forms.TextBox
Me.UserTextBox = New System.Windows.Forms.TextBox
Me.PasswordTextBox = New System.Windows.Forms.TextBox
Me.Panel4 = New System.Windows.Forms.Panel
Me.ProtocolLabel = New System.Windows.Forms.Label
Me.ProtocolComboBox = New System.Windows.Forms.ComboBox
Me.FileMenuItem = New System.Windows.Forms.MenuItem
Me.FileExitMenuItem = New System.Windows.Forms.MenuItem
Me.SessionMenuItem = New System.Windows.Forms.MenuItem
Me.SessionConnectMenuItem = New System.Windows.Forms.MenuItem
Me.SessionDisconnectMenuItem = New System.Windows.Forms.MenuItem
Me.SessionExecuteMenuItem = New System.Windows.Forms.MenuItem
Me.MenuItem1 = New System.Windows.Forms.MenuItem
Me.SessionPreviousQueryMenuItem = New System.Windows.Forms.MenuItem
Me.SessionNextQueryMenuItem = New System.Windows.Forms.MenuItem
Me.MainMenu1 = New System.Windows.Forms.MainMenu
Me.EditMenuItem = New System.Windows.Forms.MenuItem
Me.EditCutMenuItem = New System.Windows.Forms.MenuItem
Me.EditCopyMenuItem = New System.Windows.Forms.MenuItem
Me.EditPasteMenuItem = New System.Windows.Forms.MenuItem
Me.EditSelectAllMenuItem = New System.Windows.Forms.MenuItem
Me.MenuItem2 = New System.Windows.Forms.MenuItem
Me.EditFindMenuItem = New System.Windows.Forms.MenuItem
Me.FormatMenuItem = New System.Windows.Forms.MenuItem
Me.FormatWordWrapMenuItem = New System.Windows.Forms.MenuItem
Me.FormatFontMenuItem = New System.Windows.Forms.MenuItem
Me.Panel1.SuspendLayout()
Me.QueryGroupBox.SuspendLayout()
Me.QueryPanel.SuspendLayout()
Me.QueryOptionsPanel.SuspendLayout()
Me.ResultsGroupBox.SuspendLayout()
Me.ConnectionGroupBox.SuspendLayout()
Me.Panel3.SuspendLayout()
Me.ConnectionOnOffPanel.SuspendLayout()
Me.Panel4.SuspendLayout()
Me.SuspendLayout()
'
'StatusBar
'
Me.StatusBar.Location = New System.Drawing.Point(0, 590)
Me.StatusBar.Name = "StatusBar"
Me.StatusBar.Size = New System.Drawing.Size(744, 22)
Me.StatusBar.TabIndex = 11
'
'Panel1
'
Me.Panel1.Controls.Add(Me.QueryGroupBox)
Me.Panel1.Controls.Add(Me.Splitter1)
Me.Panel1.Controls.Add(Me.ResultsGroupBox)
Me.Panel1.Controls.Add(Me.ConnectionGroupBox)
Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
Me.Panel1.DockPadding.All = 8
Me.Panel1.Location = New System.Drawing.Point(0, 0)
Me.Panel1.Name = "Panel1"
Me.Panel1.Size = New System.Drawing.Size(744, 590)
Me.Panel1.TabIndex = 12
'
'QueryGroupBox
'
Me.QueryGroupBox.Controls.Add(Me.QueryPanel)
Me.QueryGroupBox.Dock = System.Windows.Forms.DockStyle.Fill
Me.QueryGroupBox.Location = New System.Drawing.Point(8, 56)
Me.QueryGroupBox.Name = "QueryGroupBox"
Me.QueryGroupBox.Size = New System.Drawing.Size(728, 281)
Me.QueryGroupBox.TabIndex = 105
Me.QueryGroupBox.TabStop = False
Me.QueryGroupBox.Text = "Query"
'
'QueryPanel
'
Me.QueryPanel.Controls.Add(Me.QueryTextBox)
Me.QueryPanel.Controls.Add(Me.QueryOptionsPanel)
Me.QueryPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.QueryPanel.Location = New System.Drawing.Point(3, 16)
Me.QueryPanel.Name = "QueryPanel"
Me.QueryPanel.Size = New System.Drawing.Size(722, 262)
Me.QueryPanel.TabIndex = 9
'
'QueryTextBox
'
Me.QueryTextBox.AcceptsReturn = True
Me.QueryTextBox.AcceptsTab = True
Me.QueryTextBox.Dock = System.Windows.Forms.DockStyle.Fill
Me.QueryTextBox.Font = New System.Drawing.Font("Lucida Console", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.QueryTextBox.HideSelection = False
Me.QueryTextBox.Location = New System.Drawing.Point(0, 0)
Me.QueryTextBox.Multiline = True
Me.QueryTextBox.Name = "QueryTextBox"
Me.QueryTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.QueryTextBox.Size = New System.Drawing.Size(722, 230)
Me.QueryTextBox.TabIndex = 4
Me.QueryTextBox.Text = ""
Me.QueryTextBox.WordWrap = False
'
'QueryOptionsPanel
'
Me.QueryOptionsPanel.Controls.Add(Me.DateLabel)
Me.QueryOptionsPanel.Controls.Add(Me.DateTextBox)
Me.QueryOptionsPanel.Controls.Add(Me.CurrencyTextBox)
Me.QueryOptionsPanel.Controls.Add(Me.CurrencyLabel)
Me.QueryOptionsPanel.Controls.Add(Me.ExecuteButton)
Me.QueryOptionsPanel.Dock = System.Windows.Forms.DockStyle.Bottom
Me.QueryOptionsPanel.DockPadding.Bottom = 5
Me.QueryOptionsPanel.DockPadding.Top = 6
Me.QueryOptionsPanel.Location = New System.Drawing.Point(0, 230)
Me.QueryOptionsPanel.Name = "QueryOptionsPanel"
Me.QueryOptionsPanel.Size = New System.Drawing.Size(722, 32)
Me.QueryOptionsPanel.TabIndex = 8
'
'DateLabel
'
Me.DateLabel.Location = New System.Drawing.Point(-1, 8)
Me.DateLabel.Name = "DateLabel"
Me.DateLabel.Size = New System.Drawing.Size(32, 16)
Me.DateLabel.TabIndex = 9
Me.DateLabel.Text = "Date:"
Me.DateLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight
'
'DateTextBox
'
Me.DateTextBox.Location = New System.Drawing.Point(31, 8)
Me.DateTextBox.Name = "DateTextBox"
Me.DateTextBox.TabIndex = 8
Me.DateTextBox.Text = ""
'
'CurrencyTextBox
'
Me.CurrencyTextBox.Location = New System.Drawing.Point(199, 8)
Me.CurrencyTextBox.Name = "CurrencyTextBox"
Me.CurrencyTextBox.TabIndex = 10
Me.CurrencyTextBox.Text = ""
'
'CurrencyLabel
'
Me.CurrencyLabel.Location = New System.Drawing.Point(135, 8)
Me.CurrencyLabel.Name = "CurrencyLabel"
Me.CurrencyLabel.Size = New System.Drawing.Size(56, 16)
Me.CurrencyLabel.TabIndex = 12
Me.CurrencyLabel.Text = "Currency:"
Me.CurrencyLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight
'
'ExecuteButton
'
Me.ExecuteButton.Dock = System.Windows.Forms.DockStyle.Right
Me.ExecuteButton.Enabled = False
Me.ExecuteButton.Location = New System.Drawing.Point(642, 6)
Me.ExecuteButton.Name = "ExecuteButton"
Me.ExecuteButton.Size = New System.Drawing.Size(80, 21)
Me.ExecuteButton.TabIndex = 11
Me.ExecuteButton.Text = "Execute"
'
'Splitter1
'
Me.Splitter1.BackColor = System.Drawing.SystemColors.Control
Me.Splitter1.Dock = System.Windows.Forms.DockStyle.Bottom
Me.Splitter1.Location = New System.Drawing.Point(8, 337)
Me.Splitter1.MinExtra = 100
Me.Splitter1.MinSize = 50
Me.Splitter1.Name = "Splitter1"
Me.Splitter1.Size = New System.Drawing.Size(728, 5)
Me.Splitter1.TabIndex = 104
Me.Splitter1.TabStop = False
'
'ResultsGroupBox
'
Me.ResultsGroupBox.Controls.Add(Me.ResultsTextBox)
Me.ResultsGroupBox.Dock = System.Windows.Forms.DockStyle.Bottom
Me.ResultsGroupBox.Location = New System.Drawing.Point(8, 342)
Me.ResultsGroupBox.Name = "ResultsGroupBox"
Me.ResultsGroupBox.Size = New System.Drawing.Size(728, 240)
Me.ResultsGroupBox.TabIndex = 103
Me.ResultsGroupBox.TabStop = False
Me.ResultsGroupBox.Text = "Results"
'
'ResultsTextBox
'
Me.ResultsTextBox.AutoSize = False
Me.ResultsTextBox.Dock = System.Windows.Forms.DockStyle.Fill
Me.ResultsTextBox.Font = New System.Drawing.Font("Lucida Console", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.ResultsTextBox.HideSelection = False
Me.ResultsTextBox.Location = New System.Drawing.Point(3, 16)
Me.ResultsTextBox.Multiline = True
Me.ResultsTextBox.Name = "ResultsTextBox"
Me.ResultsTextBox.ReadOnly = True
Me.ResultsTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.ResultsTextBox.Size = New System.Drawing.Size(722, 221)
Me.ResultsTextBox.TabIndex = 8
Me.ResultsTextBox.Text = ""
Me.ResultsTextBox.WordWrap = False
'
'ConnectionGroupBox
'
Me.ConnectionGroupBox.Controls.Add(Me.Panel3)
Me.ConnectionGroupBox.Controls.Add(Me.Panel4)
Me.ConnectionGroupBox.Dock = System.Windows.Forms.DockStyle.Top
Me.ConnectionGroupBox.Location = New System.Drawing.Point(8, 8)
Me.ConnectionGroupBox.Name = "ConnectionGroupBox"
Me.ConnectionGroupBox.Size = New System.Drawing.Size(728, 48)
Me.ConnectionGroupBox.TabIndex = 101
Me.ConnectionGroupBox.TabStop = False
Me.ConnectionGroupBox.Text = "Connection"
'
'Panel3
'
Me.Panel3.Controls.Add(Me.SessionComboBox)
Me.Panel3.Controls.Add(Me.ConnectionOnOffPanel)
Me.Panel3.Controls.Add(Me.HostLabel)
Me.Panel3.Controls.Add(Me.UserLabel)
Me.Panel3.Controls.Add(Me.PassLabel)
Me.Panel3.Controls.Add(Me.HostTextBox)
Me.Panel3.Controls.Add(Me.UserTextBox)
Me.Panel3.Controls.Add(Me.PasswordTextBox)
Me.Panel3.Dock = System.Windows.Forms.DockStyle.Fill
Me.Panel3.Location = New System.Drawing.Point(184, 16)
Me.Panel3.Name = "Panel3"
Me.Panel3.Size = New System.Drawing.Size(541, 29)
Me.Panel3.TabIndex = 4
'
'SessionComboBox
'
Me.SessionComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.SessionComboBox.Location = New System.Drawing.Point(48, 4)
Me.SessionComboBox.Name = "SessionComboBox"
Me.SessionComboBox.Size = New System.Drawing.Size(232, 21)
Me.SessionComboBox.TabIndex = 18
Me.SessionComboBox.Visible = False
'
'ConnectionOnOffPanel
'
Me.ConnectionOnOffPanel.Controls.Add(Me.ConnectionOnOffButton)
Me.ConnectionOnOffPanel.Dock = System.Windows.Forms.DockStyle.Right
Me.ConnectionOnOffPanel.DockPadding.Bottom = 5
Me.ConnectionOnOffPanel.DockPadding.Top = 3
Me.ConnectionOnOffPanel.Location = New System.Drawing.Point(461, 0)
Me.ConnectionOnOffPanel.Name = "ConnectionOnOffPanel"
Me.ConnectionOnOffPanel.Size = New System.Drawing.Size(80, 29)
Me.ConnectionOnOffPanel.TabIndex = 17
'
'ConnectionOnOffButton
'
Me.ConnectionOnOffButton.Dock = System.Windows.Forms.DockStyle.Fill
Me.ConnectionOnOffButton.Location = New System.Drawing.Point(0, 3)
Me.ConnectionOnOffButton.Name = "ConnectionOnOffButton"
Me.ConnectionOnOffButton.Size = New System.Drawing.Size(80, 21)
Me.ConnectionOnOffButton.TabIndex = 4
Me.ConnectionOnOffButton.Text = "Connect"
'
'HostLabel
'
Me.HostLabel.Location = New System.Drawing.Point(8, 6)
Me.HostLabel.Name = "HostLabel"
Me.HostLabel.Size = New System.Drawing.Size(40, 16)
Me.HostLabel.TabIndex = 15
Me.HostLabel.Text = "Host"
Me.HostLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight
'
'UserLabel
'
Me.UserLabel.Location = New System.Drawing.Point(152, 6)
Me.UserLabel.Name = "UserLabel"
Me.UserLabel.Size = New System.Drawing.Size(32, 16)
Me.UserLabel.TabIndex = 16
Me.UserLabel.Text = "User"
Me.UserLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight
'
'PassLabel
'
Me.PassLabel.Location = New System.Drawing.Point(288, 6)
Me.PassLabel.Name = "PassLabel"
Me.PassLabel.Size = New System.Drawing.Size(64, 16)
Me.PassLabel.TabIndex = 14
Me.PassLabel.Text = "Password"
Me.PassLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight
'
'HostTextBox
'
Me.HostTextBox.Location = New System.Drawing.Point(48, 4)
Me.HostTextBox.Name = "HostTextBox"
Me.HostTextBox.TabIndex = 11
Me.HostTextBox.Text = ""
'
'UserTextBox
'
Me.UserTextBox.Location = New System.Drawing.Point(184, 4)
Me.UserTextBox.Name = "UserTextBox"
Me.UserTextBox.TabIndex = 12
Me.UserTextBox.Text = ""
'
'PasswordTextBox
'
Me.PasswordTextBox.Location = New System.Drawing.Point(360, 4)
Me.PasswordTextBox.Name = "PasswordTextBox"
Me.PasswordTextBox.PasswordChar = Microsoft.VisualBasic.ChrW(183)
Me.PasswordTextBox.TabIndex = 13
Me.PasswordTextBox.Text = ""
'
'Panel4
'
Me.Panel4.Controls.Add(Me.ProtocolLabel)
Me.Panel4.Controls.Add(Me.ProtocolComboBox)
Me.Panel4.Dock = System.Windows.Forms.DockStyle.Left
Me.Panel4.Location = New System.Drawing.Point(3, 16)
Me.Panel4.Name = "Panel4"
Me.Panel4.Size = New System.Drawing.Size(181, 29)
Me.Panel4.TabIndex = 5
'
'ProtocolLabel
'
Me.ProtocolLabel.Location = New System.Drawing.Point(0, 6)
Me.ProtocolLabel.Name = "ProtocolLabel"
Me.ProtocolLabel.Size = New System.Drawing.Size(56, 16)
Me.ProtocolLabel.TabIndex = 17
Me.ProtocolLabel.Text = "Protocol"
Me.ProtocolLabel.TextAlign = System.Drawing.ContentAlignment.BottomRight
'
'ProtocolComboBox
'
Me.ProtocolComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.ProtocolComboBox.Items.AddRange(New Object() {"SSH", "RExec", "Plain", "Session"})
Me.ProtocolComboBox.Location = New System.Drawing.Point(64, 4)
Me.ProtocolComboBox.Name = "ProtocolComboBox"
Me.ProtocolComboBox.Size = New System.Drawing.Size(112, 21)
Me.ProtocolComboBox.TabIndex = 18
'
'FileMenuItem
'
Me.FileMenuItem.Index = 0
Me.FileMenuItem.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.FileExitMenuItem})
Me.FileMenuItem.Text = "&File"
'
'FileExitMenuItem
'
Me.FileExitMenuItem.Index = 0
Me.FileExitMenuItem.Text = "&Exit"
'
'SessionMenuItem
'
Me.SessionMenuItem.Index = 3
Me.SessionMenuItem.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.SessionConnectMenuItem, Me.SessionDisconnectMenuItem, Me.SessionExecuteMenuItem, Me.MenuItem1, Me.SessionPreviousQueryMenuItem, Me.SessionNextQueryMenuItem})
Me.SessionMenuItem.Text = "&Session"
'
'SessionConnectMenuItem
'
Me.SessionConnectMenuItem.Index = 0
Me.SessionConnectMenuItem.Text = "&Connect"
'
'SessionDisconnectMenuItem
'
Me.SessionDisconnectMenuItem.Enabled = False
Me.SessionDisconnectMenuItem.Index = 1
Me.SessionDisconnectMenuItem.Text = "&Disconnect"
'
'SessionExecuteMenuItem
'
Me.SessionExecuteMenuItem.Enabled = False
Me.SessionExecuteMenuItem.Index = 2
Me.SessionExecuteMenuItem.Shortcut = System.Windows.Forms.Shortcut.F2
Me.SessionExecuteMenuItem.Text = "&Execute"
'
'MenuItem1
'
Me.MenuItem1.Index = 3
Me.MenuItem1.Text = "-"
'
'SessionPreviousQueryMenuItem
'
Me.SessionPreviousQueryMenuItem.Enabled = False
Me.SessionPreviousQueryMenuItem.Index = 4
Me.SessionPreviousQueryMenuItem.Text = "&Previous Query"
'
'SessionNextQueryMenuItem
'
Me.SessionNextQueryMenuItem.Enabled = False
Me.SessionNextQueryMenuItem.Index = 5
Me.SessionNextQueryMenuItem.Text = "&Next Query"
'
'MainMenu1
'
Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.FileMenuItem, Me.EditMenuItem, Me.FormatMenuItem, Me.SessionMenuItem})
'
'EditMenuItem
'
Me.EditMenuItem.Index = 1
Me.EditMenuItem.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.EditCutMenuItem, Me.EditCopyMenuItem, Me.EditPasteMenuItem, Me.EditSelectAllMenuItem, Me.MenuItem2, Me.EditFindMenuItem})
Me.EditMenuItem.Text = "&Edit"
'
'EditCutMenuItem
'
Me.EditCutMenuItem.Enabled = False
Me.EditCutMenuItem.Index = 0
Me.EditCutMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlX
Me.EditCutMenuItem.Text = "Cu&t"
'
'EditCopyMenuItem
'
Me.EditCopyMenuItem.Enabled = False
Me.EditCopyMenuItem.Index = 1
Me.EditCopyMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlC
Me.EditCopyMenuItem.Text = "&Copy"
'
'EditPasteMenuItem
'
Me.EditPasteMenuItem.Enabled = False
Me.EditPasteMenuItem.Index = 2
Me.EditPasteMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlV
Me.EditPasteMenuItem.Text = "&Paste"
'
'EditSelectAllMenuItem
'
Me.EditSelectAllMenuItem.Enabled = False
Me.EditSelectAllMenuItem.Index = 3
Me.EditSelectAllMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlA
Me.EditSelectAllMenuItem.Text = "Select &All"
'
'MenuItem2
'
Me.MenuItem2.Index = 4
Me.MenuItem2.Text = "-"
'
'EditFindMenuItem
'
Me.EditFindMenuItem.Index = 5
Me.EditFindMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF
Me.EditFindMenuItem.Text = "&Find"
'
'FormatMenuItem
'
Me.FormatMenuItem.Index = 2
Me.FormatMenuItem.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.FormatWordWrapMenuItem, Me.FormatFontMenuItem})
Me.FormatMenuItem.Text = "Format"
'
'FormatWordWrapMenuItem
'
Me.FormatWordWrapMenuItem.Index = 0
Me.FormatWordWrapMenuItem.Text = "Word Wrap"
'
'FormatFontMenuItem
'
Me.FormatFontMenuItem.Index = 1
Me.FormatFontMenuItem.Text = "Font..."
'
'MainForm
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(744, 612)
Me.Controls.Add(Me.Panel1)
Me.Controls.Add(Me.StatusBar)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Menu = Me.MainMenu1
Me.MinimumSize = New System.Drawing.Size(752, 600)
Me.Name = "MainForm"
Me.Text = "VAccess Session"
Me.Panel1.ResumeLayout(False)
Me.QueryGroupBox.ResumeLayout(False)
Me.QueryPanel.ResumeLayout(False)
Me.QueryOptionsPanel.ResumeLayout(False)
Me.ResultsGroupBox.ResumeLayout(False)
Me.ConnectionGroupBox.ResumeLayout(False)
Me.Panel3.ResumeLayout(False)
Me.ConnectionOnOffPanel.ResumeLayout(False)
Me.Panel4.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub Log(ByVal message As String)
Me.StatusBar.Text = message
End Sub
Private Function IsConnected() As Boolean
Return (Me.myConnection.IsConnected > 0)
End Function
Private Sub Connect()
If Me.IsConnected() Then
Me.Disconnect()
End If
Me.Log("Connecting...")
Dim protocol As String = Me.ProtocolComboBox.Text.ToLower
Dim host As String = Me.HostTextBox.Text
Dim user As String = Me.UserTextBox.Text
Dim pass As String = Me.PasswordTextBox.Text
Dim command As String = "batchvision"
Dim result As String
If protocol = "plain" Then
Dim port As Integer = Convert.ToInt32(user) ' Our user field becomes our port field by ugly hackery on combo box change. TODO: should be Integer rather than Double
Me.myConnection.Connect(host, port)
Else
If protocol = "" Then
protocol = "ssh"
ElseIf protocol = "session" Then
host = Me.SessionComboBox.Text
user = ""
pass = ""
End If
Me.myConnection.Login(protocol + "://" + host, user, pass, command)
End If
Me.ConnectionOnOffButton.Text = "Disconnect"
Me.SessionConnectMenuItem.Enabled = False
Me.ProtocolComboBox.Enabled = False
Me.HostTextBox.Enabled = False
Me.UserTextBox.Enabled = False
Me.PasswordTextBox.Enabled = False
Me.SessionComboBox.Enabled = False
Me.SessionDisconnectMenuItem.Enabled = True
Me.ExecuteButton.Enabled = True
Me.SessionExecuteMenuItem.Enabled = True
Me.Log("Connected.")
Me.Text = host & " - VAccess Session"
End Sub
Private Sub OnClose(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Me.Disconnect()
End Sub
Private Sub Disconnect()
If Not Me.myConnection Is Nothing Then
Me.Log("Disconnecting...")
Me.myConnection.Disconnect()
Me.Log("Disconnected.")
End If
Me.ConnectionOnOffButton.Text = "Connect"
Me.SessionConnectMenuItem.Enabled = True
Me.ProtocolComboBox.Enabled = True
Me.HostTextBox.Enabled = True
Me.UserTextBox.Enabled = True
Me.PasswordTextBox.Enabled = True
Me.SessionComboBox.Enabled = True
Me.SessionDisconnectMenuItem.Enabled = False
Me.ExecuteButton.Enabled = False
Me.SessionExecuteMenuItem.Enabled = False
Me.Text = "VAccess Session"
End Sub
Private Function RunQuery(ByVal queryString As String, ByVal dateString As String, ByVal currencyString As String) As String
On Error GoTo HandleError
' Ensure that we're connected.
If Not Me.IsConnected() Then
MsgBox("Connection required but not found.")
Exit Function
End If
' Run the query
Me.Log("Running query...")
Dim result = Me.myConnection.Submit(queryString, dateString, currencyString)
Me.Log("Ran query.")
' Return result.
If (result = Nothing) Then Return "(No result.)"
Return result.Replace(Chr(10), Chr(13) + Chr(10))
Exit Function
HandleError:
MsgBox("Error (" & Hex$(Err.Number) & ") from " & Err.Source & ": " & Err.Description)
Log("Error encountered executing query.")
End Function
Private Function ValidateConnectInput() As Boolean
If (Me.myProtocolState = "session") Then
If (Me.SessionComboBox.Text = "") Then
Return False
Else
Return True
End If
End If
If (Me.HostTextBox.Text = "") Then Return False
If (Me.UserTextBox.Text = "") Then Return False
If (Me.myProtocolState = "plain") Then Return True
If (Me.PasswordTextBox.Text = "") Then Return False
Return True
End Function
Private Sub ExecuteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SessionExecuteMenuItem.Click, ExecuteButton.Click
On Error GoTo HandleError
' Get Query Parameters
Dim queryString
If (Me.QueryTextBox.SelectionLength > 0) Then
queryString = Me.QueryTextBox.SelectedText
Else
queryString = Me.QueryTextBox.Text
End If
Dim dateString = Me.DateTextBox.Text
If (dateString Is "") Then
dateString = Nothing
End If
Dim currencyString = Me.CurrencyTextBox.Text
If (currencyString Is "") Then
currencyString = Nothing
End If
' Submit query.
Dim result = Me.RunQuery(queryString, dateString, currencyString)
' Cache query and results.
Me.queryCount += 1
Dim queryQueuePos = queryCount Mod Me.queryCacheSize
Me.queryCache(queryQueuePos, Me.queryCacheIndices.iQuery) = Me.QueryTextBox.Text
Me.queryCache(queryQueuePos, Me.queryCacheIndices.iResult) = result
Me.queryCache(queryQueuePos, Me.queryCacheIndices.iDate) = dateString
Me.queryCache(queryQueuePos, Me.queryCacheIndices.iCurrency) = currencyString
Me.queryCacheSelection(queryQueuePos, 0) = Me.QueryTextBox.SelectionStart
Me.queryCacheSelection(queryQueuePos, 1) = Me.QueryTextBox.SelectionLength
If (Me.queryCount >= Me.queryCacheSize) Then
Me.oldestCachedQuery = Me.queryCount - Me.queryCacheSize + 1
End If
' TODO: Also cache date/currency values?
' Display result in results text box.
Me.ViewQueryCache(queryCount, True)
Exit Sub
HandleError:
MsgBox("Error (" & Hex$(Err.Number) & ") from " & Err.Source & ": " & Err.Description)
Log("Error encountered processing query.")
End Sub
Private Sub ConnectionDetails_Enter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles HostTextBox.KeyPress, UserTextBox.KeyPress, PasswordTextBox.KeyPress
If Asc(e.KeyChar) = Keys.Enter Then
ConnectionOnOffButton_Click(sender, e)
End If
End Sub
Private Sub ConnectionOnOffButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectionOnOffButton.Click, SessionConnectMenuItem.Click, SessionDisconnectMenuItem.Click ' , UserTextBox.Enter, PasswordTextBox.Enter
On Error GoTo HandleError
If Not Me.IsConnected() Then
If ValidateConnectInput() Then
Me.Connect()
Else
MsgBox("Invalid connection details.")
End If
Else
Me.Disconnect()
End If
Exit Sub
HandleError:
MsgBox("Connectivity Error (" & Hex$(Err.Number) & ") from " & Err.Source & ": " & Err.Description)
Log("Connectivity error encountered.")
End Sub
Private Sub ProtocolComboBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProtocolComboBox.SelectedIndexChanged
Dim protocol = Me.ProtocolComboBox.Text.ToLower
If Me.myProtocolState = protocol Then Return
If (protocol = "plain") Then
' Switch to Port by hackery.
Me.HostLabel.Text = "Host:"
Me.HostTextBox.Visible = True
Me.UserLabel.Text = "Port:"
Me.UserTextBox.Text = ""
Me.UserLabel.Visible = True
Me.UserTextBox.Visible = True
Me.PassLabel.Visible = False
Me.PasswordTextBox.Visible = False
Me.SessionComboBox.Visible = False
ElseIf (protocol = "session") Then
' Switch to Name by hackery.
Me.HostLabel.Text = "Name:"
Me.HostTextBox.Visible = False
Me.UserTextBox.Text = ""
Me.UserLabel.Visible = False
Me.UserTextBox.Visible = False
Me.PassLabel.Visible = False
Me.PasswordTextBox.Visible = False
Me.SessionComboBox.Visible = True
ElseIf (Me.myProtocolState <> "ssh" And Me.myProtocolState <> "rexec") Then
' Switch to User/Pass by hackery.
Me.HostLabel.Text = "Host:"
Me.HostTextBox.Visible = True
Me.UserLabel.Text = "User:"
Me.UserTextBox.Text = ""
Me.UserLabel.Visible = True
Me.UserTextBox.Visible = True
Me.PassLabel.Visible = True
Me.PasswordTextBox.Visible = True
Me.SessionComboBox.Visible = False
End If
Me.myProtocolState = protocol
End Sub
Private Sub FileExitMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FileExitMenuItem.Click
Me.Close()
End Sub
Private Sub SessionPreviousQueryMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SessionPreviousQueryMenuItem.Click
Me.ViewQueryCache(Me.viewingQuery - 1)
End Sub
Private Sub SessionNextQueryMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SessionNextQueryMenuItem.Click
Me.ViewQueryCache(Me.viewingQuery + 1)
End Sub
Private Sub ViewQueryCache(ByVal query As Integer, Optional ByVal onlyResult As Boolean = False)
' Sanitize arguments.
If (query < Me.oldestCachedQuery) Then
MsgBox("Sorry, my query history doesn't go back that far.")
Exit Sub
End If
If (query > Me.queryCount Or query < 0) Then
MsgBox("Error: Attempted to retrieve invalid query (" & query & ") from history.")
Exit Sub
End If
' Find the correct index in the queue.
Dim cacheIndex = query Mod Me.queryCacheSize
' Show the correct query/result.
If (Not onlyResult) Then
Me.QueryTextBox.Text = Me.queryCache(cacheIndex, Me.queryCacheIndices.iQuery)
Me.QueryTextBox.SelectionStart = Me.queryCacheSelection(cacheIndex, 0)
Me.QueryTextBox.SelectionLength = Me.queryCacheSelection(cacheIndex, 1)
Me.DateTextBox.Text = Me.queryCache(cacheIndex, Me.queryCacheIndices.iDate)
Me.CurrencyTextBox.Text = Me.queryCache(cacheIndex, Me.queryCacheIndices.iCurrency)
End If
Me.ResultsTextBox.Text = Me.queryCache(cacheIndex, Me.queryCacheIndices.iResult)
' Update viewingQuery.
Me.viewingQuery = query
' Enable/disable next/previous buttons.
If (Me.viewingQuery = Me.queryCount) Then
Me.SessionNextQueryMenuItem.Enabled = False
Else
Me.SessionNextQueryMenuItem.Enabled = True
End If
If (Me.viewingQuery = Me.oldestCachedQuery) Then
Me.SessionPreviousQueryMenuItem.Enabled = False
Else
Me.SessionPreviousQueryMenuItem.Enabled = True
End If
End Sub
Private Sub TextBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CurrencyTextBox.Enter, DateTextBox.Enter, HostTextBox.Enter, PasswordTextBox.Enter, QueryTextBox.Enter, ResultsTextBox.Enter, UserTextBox.Enter
Me.focussedTextBox = sender
Me.EditCopyMenuItem.Enabled = True
Me.EditSelectAllMenuItem.Enabled = True
If (Me.focussedTextBox.ReadOnly) Then
Exit Sub
End If
Me.EditCutMenuItem.Enabled = True
Me.EditPasteMenuItem.Enabled = True
End Sub
Private Sub TextBox_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CurrencyTextBox.Leave, DateTextBox.Leave, HostTextBox.Leave, PasswordTextBox.Leave, QueryTextBox.Leave, ResultsTextBox.Leave, UserTextBox.Leave
Me.focussedTextBox = Nothing
Me.EditCopyMenuItem.Enabled = False
Me.EditCutMenuItem.Enabled = False
Me.EditPasteMenuItem.Enabled = False
Me.EditSelectAllMenuItem.Enabled = False
End Sub
Private Sub EditCutMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditCutMenuItem.Click
Me.focussedTextBox.Cut()
End Sub
Private Sub EditCopyMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditCopyMenuItem.Click
Me.focussedTextBox.Copy()
End Sub
Private Sub EditPasteMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditPasteMenuItem.Click
Me.focussedTextBox.Paste()
End Sub
Private Sub EditSelectAllMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditSelectAllMenuItem.Click
Me.focussedTextBox.SelectAll()
End Sub
Private Sub EditFindMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditFindMenuItem.Click
If (Me.findReplaceDialog Is Nothing) Then
Me.findReplaceDialog = New FindReplaceForm
End If
Me.findReplaceDialog.SetContext(Me.focussedTextBox)
If (Me.focussedTextBox Is Me.QueryTextBox) Then
Me.findReplaceDialog.Text = "Find in Query"
ElseIf (Me.focussedTextBox Is Me.ResultsTextBox) Then
Me.findReplaceDialog.Text = "Find in Result"
End If
Me.findReplaceDialog.Show()
End Sub
Private Sub FormatWordWrapMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FormatWordWrapMenuItem.Click
Dim wrapping As Boolean = Not Me.FormatWordWrapMenuItem.Checked
Me.FormatWordWrapMenuItem.Checked = wrapping
Me.QueryTextBox.WordWrap = wrapping
Me.ResultsTextBox.WordWrap = wrapping
If wrapping Then
Me.QueryTextBox.ScrollBars = ScrollBars.Vertical
Me.ResultsTextBox.ScrollBars = ScrollBars.Vertical
Else
Me.QueryTextBox.ScrollBars = ScrollBars.Both
Me.ResultsTextBox.ScrollBars = ScrollBars.Both
End If
End Sub
Private Sub FormatFontMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FormatFontMenuItem.Click
Dim d As FontDialog
d = New FontDialog
d.Font = Me.QueryTextBox.Font
d.ShowEffects = False
If (d.ShowDialog <> DialogResult.Cancel) Then
Me.QueryTextBox.Font = d.Font
Me.ResultsTextBox.Font = d.Font
Me.SavePreference("FontFamily", d.Font.FontFamily.GetName(0))
Me.SavePreference("FontSize", Convert.ToString(d.Font.Size))
Me.SavePreference("FontStyle", d.Font.Style.ToString)
End If
End Sub
Private Sub SavePreference(ByVal name As String, ByVal value As String)
SaveSetting("VAccessSession", "UserPreferences", name, value)
End Sub
Private Function LoadPreference(ByVal name, ByVal defaultValue) As String
Return GetSetting("VAccessSession", "UserPreferences", name, defaultValue)
End Function
Private Sub LoadPreferences()
Dim newFontFamily As String = Me.LoadPreference("FontFamily", "Lucida Console")
Dim newFontSize As Single = Convert.ToSingle(Me.LoadPreference("FontSize", "10"))
Dim newFontStyle As System.Drawing.FontStyle = [Enum].Parse(GetType(System.Drawing.FontStyle), Me.LoadPreference("FontStyle", System.Drawing.FontStyle.Regular.ToString))
Dim newFont As System.Drawing.Font = New System.Drawing.Font(newFontFamily, newFontSize, newFontStyle)
Me.QueryTextBox.Font = newFont
Me.ResultsTextBox.Font = newFont
End Sub
End Class
|
MichaelJCaruso/vision
|
software/src/master/src/VAccess_Sample/MainForm.vb
|
Visual Basic
|
bsd-3-clause
| 41,805
|
Public Class FRMProgram
Dim RATE_GST As Single = 5
Dim RATE_PST As Single = 8.5
Dim currCompany As Company = FRMChooseCompany.companies(FRMChooseCompany.currPosition)
Dim currCar As Car
Dim currTab As String = ""
Dim carSelected As Boolean = False
Dim newPoint As New System.Drawing.Point()
Dim mouseX As Integer
Dim mouseY As Integer
Dim OriginalTitle As String
Dim defName As String = Nothing
Dim defPrice As String = Nothing
Dim InactiveColor As Color = System.Drawing.Color.FromArgb(CType(CType(85, Byte), Integer), CType(CType(85, Byte), Integer), CType(CType(85, Byte), Integer))
Dim optionsTotal, ACtax, tradein, subTotal, GST, PST, total, rate, downPayment, monthlyPayment, totalPayment As Double
Private Sub FRMProgram_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
FRMChooseCompany.Show()
End Sub
Private Sub FRMProgram_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Width = 759
Me.CenterToScreen()
optionsTotal = 975
ACtax = 0
tradein = 0
rate = 0.01
OriginalTitle = LBLtitle.Text
PICsummary.Parent = PICwheel
PICoptions.Parent = PICwheel
PICfinancing.Parent = PICwheel
PICcolor.Parent = PICwheel
PICsecurity.Parent = PICwheel
PICtradein.Parent = PICwheel
PICwheelLogo.Parent = PICwheel
PNLsummary.Parent = PICwheel
PNLtradein.Parent = PICwheel
PNLoptions.Parent = PICwheel
PNLsecurity.Parent = PICwheel
PNLcolor.Parent = PICwheel
PNLfinancing.Parent = PICwheel
PICsummary.Left = 201
PICsummary.Top = 28
PICoptions.Left = 494
PICoptions.Top = 94
PICfinancing.Left = 472
PICfinancing.Top = 346
PICcolor.Left = 247
PICcolor.Top = 589
PICsecurity.Left = 23
PICsecurity.Top = 366
PICtradein.Left = 26
PICtradein.Top = 85
PICwheelLogo.Left = 315
PICwheelLogo.Top = 321
PNLsummary.Left = 213
PNLsummary.Top = 140
PNLtradein.Left = 213
PNLtradein.Top = 140
PNLoptions.Left = 213
PNLoptions.Top = 140
PNLsecurity.Left = 213
PNLsecurity.Top = 140
PNLcolor.Left = 213
PNLcolor.Top = 140
PNLfinancing.Left = 213
PNLfinancing.Top = 140
ChooseCompany()
End Sub
Sub Calculate()
UpdateCheckAll()
If CHKtradein.Checked = False Then tradein = 0
subTotal = currCar.price + optionsTotal + ACtax - tradein
GST = subTotal * RATE_GST / 100.0
PST = (subTotal + GST) * RATE_PST / 100.0
GST = Math.Floor(GST * 100) / 100
PST = Math.Floor(PST * 100) / 100
total = subTotal + GST + PST
If CHKfinancing.Checked Then
If CHKdownPayment.Checked Then
total -= downPayment
LBLdownPayment.Text = FormatCurrency(downPayment)
LBLdownPaymentL.Visible = True
LBLdownPayment.Visible = True
Else
LBLdownPaymentL.Visible = False
LBLdownPayment.Visible = False
End If
monthlyPayment = Pmt(rate / 12, (TRBmonths.Value + TRByears.Value * 12), -total, 0, 1)
totalPayment = monthlyPayment * (TRBmonths.Value + TRByears.Value * 12)
defPrice = FormatCurrency(totalPayment, 0)
LBLtotal.Text = FormatCurrency(total)
LBLmonthly.Text = FormatCurrency(monthlyPayment)
LBLfinal.Text = FormatCurrency(totalPayment)
' hide and show
LBLmonthlyL.Visible = True
LBLmonthly.Visible = True
LBLtotalL.Visible = True
LBLtotal.Visible = True
Else
LBLfinal.Text = FormatCurrency(total)
defPrice = FormatCurrency(total, 0)
' hide and show
LBLdownPaymentL.Visible = False
LBLdownPayment.Visible = False
LBLmonthlyL.Visible = False
LBLmonthly.Visible = False
LBLtotalL.Visible = False
LBLtotal.Visible = False
End If
LBLoptionsPrice.Text = FormatCurrency(optionsTotal)
LBLoptionsTotal.Text = FormatCurrency(optionsTotal)
LBLoptionsTotal2.Text = FormatCurrency(optionsTotal)
LBLACtax.Text = FormatCurrency(ACtax)
LBLtradeinValue.Text = FormatCurrency(tradein)
LBLGST.Text = FormatCurrency(GST)
LBLPST.Text = FormatCurrency(PST)
LBLcarPrice.Text = defPrice
End Sub
Sub ChooseCompany()
PICcar0.Image = currCompany.cars(0).picture
PICcar1.Image = currCompany.cars(1).picture
PICcar2.Image = currCompany.cars(2).picture
PICcar3.Image = currCompany.cars(3).picture
PICcar4.Image = currCompany.cars(4).picture
PICcar5.Image = currCompany.cars(5).picture
PICcompany.Image = currCompany.logo
If currCompany.name = "Audi" Then
PICicon.Image = My.Resources.Audi_small
Me.Icon = System.Drawing.Icon.FromHandle(My.Resources.Audi_small.GetHicon)
PICwheelLogo.Image = My.Resources.Audi_small
Else
PICicon.Image = currCompany.logo
Me.Icon = System.Drawing.Icon.FromHandle(My.Resources.ResourceManager.GetObject(currCompany.name).GetHicon)
PICwheelLogo.Image = currCompany.logo
End If
LBLcompany.Text = currCompany.name
SetTitle(currCompany.name)
defName = Nothing
defPrice = Nothing
ResetCarLBL()
ResetBorders()
If carSelected Then ChooseTab(currTab)
carSelected = False
FRMChooseCompany.chooseCompany()
FRMChooseCompany.DisplayAvailable()
End Sub
Sub ChooseCar(ByRef picture As System.Windows.Forms.PictureBox, ByVal position As Integer)
If picture.BorderStyle = BorderStyle.Fixed3D Then ' car already selected -> deselect it
defName = Nothing
defPrice = Nothing
ResetBorders()
ChooseTab(currTab)
carSelected = False
Else
carSelected = True
currCar = currCompany.cars(position)
currTab = ""
PICsummary.Image = My.Resources.summary_hover
ChooseTab("summary")
defName = LBLcarName.Text
defPrice = LBLcarPrice.Text
ResetBorders()
picture.BorderStyle = BorderStyle.Fixed3D
LBLbase.Text = FormatCurrency(currCar.price)
NUDtradein.Maximum = currCar.price
UncheckAll()
Calculate()
End If
End Sub
Sub ChooseTab(ByVal tab As String)
If carSelected Then
If tab = currTab Then ' tab already selected -> deselect it
currTab = ""
ResetTabs()
PICwheel.Image = My.Resources.ResourceManager.GetObject("wheel")
PICwheelLogo.Visible = True
Else
currTab = tab
PICwheel.Image = My.Resources.ResourceManager.GetObject("wheel_dim")
PICwheelLogo.Visible = False
If tab = "summary" Then
PNLsummary.Visible = True
PNLsummary.BringToFront()
PICsummary.Image = My.Resources.ResourceManager.GetObject("summary_hover")
Else
PICsummary.Image = My.Resources.ResourceManager.GetObject("summary")
End If
If tab = "options" Then
PNLoptions.Visible = True
PNLoptions.BringToFront()
PICoptions.Image = My.Resources.ResourceManager.GetObject("options_hover")
Else
PICoptions.Image = My.Resources.ResourceManager.GetObject("options")
End If
If tab = "financing" Then
PNLfinancing.Visible = True
PNLfinancing.BringToFront()
PICfinancing.Image = My.Resources.ResourceManager.GetObject("financing_hover")
Else
PICfinancing.Image = My.Resources.ResourceManager.GetObject("financing")
End If
If tab = "color" Then
PNLcolor.Visible = True
PNLcolor.BringToFront()
PICcolor.Image = My.Resources.ResourceManager.GetObject("color_hover")
Else
PICcolor.Image = My.Resources.ResourceManager.GetObject("color")
End If
If tab = "security" Then
PNLsecurity.Visible = True
PNLsecurity.BringToFront()
PICsecurity.Image = My.Resources.ResourceManager.GetObject("security_hover")
Else
PICsecurity.Image = My.Resources.ResourceManager.GetObject("security")
End If
If tab = "tradein" Then
PNLtradein.Visible = True
PNLtradein.BringToFront()
PICtradein.Image = My.Resources.ResourceManager.GetObject("tradein_hover")
Else
PICtradein.Image = My.Resources.ResourceManager.GetObject("tradein")
End If
End If
Else
MsgBox("Please select a car before trying to open a tab", MsgBoxStyle.Exclamation, "Warning")
End If
End Sub
Sub ResetCarLBL()
LBLcarName.Text = defName
LBLcarPrice.Text = defPrice
End Sub
Sub ResetBorders()
PICcar0.BorderStyle = BorderStyle.None
PICcar1.BorderStyle = BorderStyle.None
PICcar2.BorderStyle = BorderStyle.None
PICcar3.BorderStyle = BorderStyle.None
PICcar4.BorderStyle = BorderStyle.None
PICcar5.BorderStyle = BorderStyle.None
End Sub
Sub ResetTabs()
PICsummary.Image = My.Resources.ResourceManager.GetObject("summary")
PICoptions.Image = My.Resources.ResourceManager.GetObject("options")
PICfinancing.Image = My.Resources.ResourceManager.GetObject("financing")
PICcolor.Image = My.Resources.ResourceManager.GetObject("color")
PICsecurity.Image = My.Resources.ResourceManager.GetObject("security")
PICtradein.Image = My.Resources.ResourceManager.GetObject("tradein")
PNLsummary.Visible = False
PNLoptions.Visible = False
PNLfinancing.Visible = False
PNLcolor.Visible = False
PNLsecurity.Visible = False
PNLtradein.Visible = False
End Sub
Sub UpdateCheckAll()
If CHKAC.Checked And CHKairbags.Checked And CHKbulletproof.Checked And CHKcameras.Checked And CHKdeluxe.Checked And CHKDVD.Checked And CHKGPS.Checked And CHKheated.Checked And CHKonstar.Checked And CHKroof.Checked And CHKtires.Checked And CHKtinted.Checked And CHKmissile.Checked And CHKM60.Checked Then
CHKall.CheckState = CheckState.Checked
CHKall2.CheckState = CheckState.Checked
CHKall.Text = "Uncheck All"
CHKall2.Text = "Uncheck All"
ElseIf CHKAC.Checked Or CHKairbags.Checked Or CHKbulletproof.Checked Or CHKcameras.Checked Or CHKdeluxe.Checked Or CHKDVD.Checked Or CHKGPS.Checked Or CHKheated.Checked Or CHKonstar.Checked Or CHKroof.Checked Or CHKtires.Checked Or CHKtinted.Checked Or CHKmissile.Checked Or CHKM60.Checked Then
CHKall.CheckState = CheckState.Indeterminate
CHKall2.CheckState = CheckState.Indeterminate
CHKall.Text = "Check All"
CHKall2.Text = "Check All"
Else
CHKall.CheckState = CheckState.Unchecked
CHKall2.CheckState = CheckState.Unchecked
CHKall.Text = "Check All"
CHKall2.Text = "Check All"
End If
End Sub
Sub CheckAll()
optionsTotal = 82051
CHKAC.Checked = True
CHKairbags.Checked = True
CHKbulletproof.Checked = True
CHKcameras.Checked = True
CHKdeluxe.Checked = True
CHKDVD.Checked = True
CHKGPS.Checked = True
CHKheated.Checked = True
CHKonstar.Checked = True
CHKroof.Checked = True
CHKtires.Checked = True
CHKtinted.Checked = True
CHKmissile.Checked = True
CHKM60.Checked = True
Calculate()
End Sub
Sub UncheckAll()
optionsTotal = 975
CHKAC.Checked = False
CHKairbags.Checked = False
CHKbulletproof.Checked = False
CHKcameras.Checked = False
CHKdeluxe.Checked = False
CHKDVD.Checked = False
CHKGPS.Checked = False
CHKheated.Checked = False
CHKonstar.Checked = False
CHKroof.Checked = False
CHKtires.Checked = False
CHKtinted.Checked = False
CHKmissile.Checked = False
CHKM60.Checked = False
Calculate()
End Sub
Private Sub Program_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Left Then
PrevCompany()
End If
If e.KeyCode = Keys.Right Then
NextCompany()
End If
If e.KeyCode = Keys.Escape Or e.KeyCode = Keys.Back Then
Me.Close()
End If
End Sub
Private Sub Panel1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Panel1.Click
Me.Close()
End Sub
Private Sub LBLcompany_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LBLcompany.Click
Me.Close()
End Sub
Private Sub PICcompany_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICcompany.Click
Me.Close()
End Sub
Private Sub PICcompany_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcompany.MouseEnter
LBLgoback.Visible = True
End Sub
Private Sub PICcompany_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcompany.MouseLeave
LBLgoback.Visible = False
End Sub
Sub SetTitle(ByVal title As String)
title &= " - " & OriginalTitle
LBLtitle.Text = title
Me.Text = title
End Sub
Private Sub PNLtitlebar_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PNLtitlebar.MouseDown
StartMoving()
End Sub
Private Sub PNLtitlebar_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PNLtitlebar.MouseMove
MoveWindow(e)
End Sub
Private Sub LBLtitle_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles LBLtitle.MouseDown
StartMoving()
End Sub
Private Sub LBLtitle_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles LBLtitle.MouseMove
MoveWindow(e)
End Sub
Sub StartMoving()
mouseX = Control.MousePosition.X - Me.Location.X
mouseY = Control.MousePosition.Y - Me.Location.Y
End Sub
Sub MoveWindow(ByVal e As System.Windows.Forms.MouseEventArgs)
If e.Button = MouseButtons.Left Then
newPoint = Control.MousePosition
newPoint.X = newPoint.X - (mouseX)
newPoint.Y = newPoint.Y - (mouseY)
Me.Location = newPoint
End If
End Sub
Private Sub PICminimize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICminimize.Click
Me.WindowState = FormWindowState.Minimized
End Sub
Private Sub PICminimize_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICminimize.MouseEnter
PICminimize.Image = My.Resources.minimize_hover
End Sub
Private Sub PICminimize_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICminimize.MouseLeave
PICminimize.Image = My.Resources.minimize
End Sub
Private Sub PICclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICclose.Click
End
End Sub
Private Sub PICclose_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICclose.MouseEnter
PICclose.Image = My.Resources.close_hover
End Sub
Private Sub PICclose_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICclose.MouseLeave
PICclose.Image = My.Resources.close
End Sub
Private Sub PICcar0_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICcar0.Click
ChooseCar(PICcar0, 0)
End Sub
Private Sub PICcar1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICcar1.Click
ChooseCar(PICcar1, 1)
End Sub
Private Sub PICcar2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICcar2.Click
ChooseCar(PICcar2, 2)
End Sub
Private Sub PICcar3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICcar3.Click
ChooseCar(PICcar3, 3)
End Sub
Private Sub PICcar4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICcar4.Click
ChooseCar(PICcar4, 4)
End Sub
Private Sub PICcar5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICcar5.Click
ChooseCar(PICcar5, 5)
End Sub
Private Sub PICcar0_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar0.MouseEnter
LBLcarName.Text = currCompany.name & " " & currCompany.cars(0).name
LBLcarPrice.Text = FormatCurrency(currCompany.cars(0).price, 0)
End Sub
Private Sub PICcar1_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar1.MouseEnter
LBLcarName.Text = currCompany.name & " " & currCompany.cars(1).name
LBLcarPrice.Text = FormatCurrency(currCompany.cars(1).price, 0)
End Sub
Private Sub PICcar2_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar2.MouseEnter
LBLcarName.Text = currCompany.name & " " & currCompany.cars(2).name
LBLcarPrice.Text = FormatCurrency(currCompany.cars(2).price, 0)
End Sub
Private Sub PICcar3_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar3.MouseEnter
LBLcarName.Text = currCompany.name & " " & currCompany.cars(3).name
LBLcarPrice.Text = FormatCurrency(currCompany.cars(3).price, 0)
End Sub
Private Sub PICcar4_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar4.MouseEnter
LBLcarName.Text = currCompany.name & " " & currCompany.cars(4).name
LBLcarPrice.Text = FormatCurrency(currCompany.cars(4).price, 0)
End Sub
Private Sub PICcar5_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar5.MouseEnter
LBLcarName.Text = currCompany.name & " " & currCompany.cars(5).name
LBLcarPrice.Text = FormatCurrency(currCompany.cars(5).price, 0)
End Sub
Private Sub PICcar0_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar0.MouseLeave
ResetCarLBL()
End Sub
Private Sub PICcar1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar1.MouseLeave
ResetCarLBL()
End Sub
Private Sub PICcar2_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar2.MouseLeave
ResetCarLBL()
End Sub
Private Sub PICcar3_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar3.MouseLeave
ResetCarLBL()
End Sub
Private Sub PICcar4_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar4.MouseLeave
ResetCarLBL()
End Sub
Private Sub PICcar5_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcar5.MouseLeave
ResetCarLBL()
End Sub
Function PrevPos(ByVal pos As Integer)
pos -= 1
If pos < 0 Then pos = 5
Return pos
End Function
Function NextPos(ByVal pos As Integer)
pos += 1
If pos > 5 Then pos = 0
Return pos
End Function
Function PrevPosComp(ByVal pos As Integer)
pos -= 1
If pos < 0 Then pos = 4
Return pos
End Function
Function NextPosComp(ByVal pos As Integer)
pos += 1
If pos > 4 Then pos = 0
Return pos
End Function
Private Sub PICprev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICprev.Click
PrevCompany()
End Sub
Private Sub PICprev_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICprev.MouseEnter
PICprev.Image = My.Resources.prev_hover
End Sub
Private Sub PICprev_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICprev.MouseLeave
PICprev.Image = My.Resources.prev
End Sub
Private Sub PICnext_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICnext.MouseEnter
PICnext.Image = My.Resources.next_hover
End Sub
Private Sub PICnext_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICnext.MouseLeave
PICnext.Image = My.Resources._next
End Sub
Private Sub PICnext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICnext.Click
NextCompany()
End Sub
Sub PrevCompany()
currCompany = FRMChooseCompany.companies(PrevPosComp(FRMChooseCompany.currPosition))
FRMChooseCompany.currPosition = PrevPosComp(FRMChooseCompany.currPosition)
ChooseCompany()
End Sub
Sub NextCompany()
currCompany = FRMChooseCompany.companies(NextPosComp(FRMChooseCompany.currPosition))
FRMChooseCompany.currPosition = NextPosComp(FRMChooseCompany.currPosition)
ChooseCompany()
End Sub
Private Sub PICsummary_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICsummary.Click
ChooseTab("summary")
End Sub
Private Sub PICoptions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICoptions.Click
ChooseTab("options")
End Sub
Private Sub PICfinancing_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICfinancing.Click
ChooseTab("financing")
End Sub
Private Sub PICcolor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICcolor.Click
ChooseTab("color")
End Sub
Private Sub PICsecurity_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICsecurity.Click
ChooseTab("security")
End Sub
Private Sub PICtradeIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICtradein.Click
ChooseTab("tradein")
End Sub
Private Sub PICsummary_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICsummary.MouseEnter
PICsummary.Image = My.Resources.ResourceManager.GetObject("summary_hover")
End Sub
Private Sub PICoptions_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICoptions.MouseEnter
PICoptions.Image = My.Resources.ResourceManager.GetObject("options_hover")
End Sub
Private Sub PICfinancing_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICfinancing.MouseEnter
PICfinancing.Image = My.Resources.ResourceManager.GetObject("financing_hover")
End Sub
Private Sub PICcolor_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcolor.MouseEnter
PICcolor.Image = My.Resources.ResourceManager.GetObject("color_hover")
End Sub
Private Sub PICsecurity_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICsecurity.MouseEnter
PICsecurity.Image = My.Resources.ResourceManager.GetObject("security_hover")
End Sub
Private Sub PICtradein_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICtradein.MouseEnter
PICtradein.Image = My.Resources.ResourceManager.GetObject("tradein_hover")
End Sub
Private Sub PICsummary_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICsummary.MouseLeave
If currTab <> "summary" Then PICsummary.Image = My.Resources.ResourceManager.GetObject("summary")
End Sub
Private Sub PICoptions_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICoptions.MouseLeave
If currTab <> "options" Then PICoptions.Image = My.Resources.ResourceManager.GetObject("options")
End Sub
Private Sub PICfinancing_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICfinancing.MouseLeave
If currTab <> "financing" Then PICfinancing.Image = My.Resources.ResourceManager.GetObject("financing")
End Sub
Private Sub PICcolor_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICcolor.MouseLeave
If currTab <> "color" Then PICcolor.Image = My.Resources.ResourceManager.GetObject("color")
End Sub
Private Sub PICsecurity_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICsecurity.MouseLeave
If currTab <> "security" Then PICsecurity.Image = My.Resources.ResourceManager.GetObject("security")
End Sub
Private Sub PICtradein_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICtradein.MouseLeave
If currTab <> "tradein" Then PICtradein.Image = My.Resources.ResourceManager.GetObject("tradein")
End Sub
Private Sub CHKtradein_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKtradein.CheckedChanged
If CHKtradein.Checked Then
LBLtradinAmount.ForeColor = Color.White
NUDtradein.Enabled = True
tradein = NUDtradein.Value
Else
LBLtradinAmount.ForeColor = InactiveColor
NUDtradein.Enabled = False
tradein = 0
End If
Calculate()
End Sub
Private Sub NUDtradein_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NUDtradein.ValueChanged
tradein = NUDtradein.Value
Calculate()
End Sub
Private Sub CHKAC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKAC.Click
If CHKAC.Checked Then
ACtax = 100
optionsTotal += 1300
Else
ACtax = 0
optionsTotal -= 1300
End If
Calculate()
End Sub
Private Sub CHKdeluxe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKdeluxe.Click
If CHKdeluxe.Checked Then
optionsTotal += 1200
Else
optionsTotal -= 1200
End If
Calculate()
End Sub
Private Sub CHKheated_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKheated.Click
If CHKheated.Checked Then
optionsTotal += 700
Else
optionsTotal -= 700
End If
Calculate()
End Sub
Private Sub CHKDVD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKDVD.Click
If CHKDVD.Checked Then
optionsTotal += 150
Else
optionsTotal -= 150
End If
Calculate()
End Sub
Private Sub CHKGPS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKGPS.Click
If CHKGPS.Checked Then
optionsTotal += 400
Else
optionsTotal -= 400
End If
Calculate()
End Sub
Private Sub CHKroof_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKroof.Click
If CHKroof.Checked Then
optionsTotal += 1000
Else
optionsTotal -= 1000
End If
Calculate()
End Sub
Private Sub CHKtinted_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKtinted.Click
If CHKtinted.Checked Then
optionsTotal += 300
Else
optionsTotal -= 300
End If
Calculate()
End Sub
Private Sub CHKmissile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKmissile.Click
If CHKmissile.Checked Then
optionsTotal += 14000
Else
optionsTotal -= 14000
End If
Calculate()
End Sub
Private Sub CHKM60_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKM60.Click
If CHKM60.Checked Then
optionsTotal += 6000
Else
optionsTotal -= 6000
End If
Calculate()
End Sub
Private Sub CHKairbags_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKairbags.Click
If CHKairbags.Checked Then
optionsTotal += 2000
Else
optionsTotal -= 2000
End If
Calculate()
End Sub
Private Sub CHKbulletproof_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKbulletproof.Click
If CHKbulletproof.Checked Then
optionsTotal += 50000
Else
optionsTotal -= 50000
End If
Calculate()
End Sub
Private Sub CHKonstar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKonstar.Click
If CHKonstar.Checked Then
optionsTotal += 186
Else
optionsTotal -= 186
End If
Calculate()
End Sub
Private Sub CHKcameras_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKcameras.Click
If CHKcameras.Checked Then
optionsTotal += 340
Else
optionsTotal -= 340
End If
Calculate()
End Sub
Private Sub CHKtires_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKtires.Click
If CHKtires.Checked Then
optionsTotal += 3500
Else
optionsTotal -= 3500
End If
Calculate()
End Sub
Private Sub CHKall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKall.Click
If CHKall.CheckState = CheckState.Checked Then
UncheckAll()
Else
CheckAll()
End If
End Sub
Private Sub CHKall2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKall2.Click
If CHKall2.CheckState = CheckState.Checked Then
UncheckAll()
Else
CheckAll()
End If
End Sub
Private Sub Label29_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
'Pmt(Rate / 100 / 12, years * 12, amount, 0, 1)
End Sub
Private Sub CHKfinancing_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKfinancing.CheckedChanged
If CHKfinancing.Checked Then
LBLrate.ForeColor = Color.White
LBLrateL.ForeColor = Color.White
LBLmonths.ForeColor = Color.White
LBLmonthsL.ForeColor = Color.White
LBLyears.ForeColor = Color.White
LBLyearsL.ForeColor = Color.White
CHKdownPayment.ForeColor = Color.White
TRBrate.Enabled = True
TRBmonths.Enabled = True
TRByears.Enabled = True
CHKdownPayment.Enabled = True
If CHKdownPayment.Checked Then
NUDdownPayment.Enabled = True
downPayment = NUDdownPayment.Value
Else
NUDdownPayment.Enabled = False
downPayment = 0
End If
Else
LBLrate.ForeColor = InactiveColor
LBLrateL.ForeColor = InactiveColor
LBLmonths.ForeColor = InactiveColor
LBLmonthsL.ForeColor = InactiveColor
LBLyears.ForeColor = InactiveColor
LBLyearsL.ForeColor = InactiveColor
CHKdownPayment.ForeColor = InactiveColor
TRBrate.Enabled = False
TRBmonths.Enabled = False
TRByears.Enabled = False
CHKdownPayment.Enabled = False
NUDdownPayment.Enabled = False
downPayment = 0
End If
Calculate()
End Sub
Private Sub CHKdownPayment_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHKdownPayment.CheckedChanged
If CHKdownPayment.Checked Then
NUDdownPayment.Enabled = True
downPayment = NUDdownPayment.Value
Else
NUDdownPayment.Enabled = False
downPayment = 0
End If
Calculate()
End Sub
Private Sub NUDdownPayment_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NUDdownPayment.ValueChanged
downPayment = NUDdownPayment.Value
Calculate()
End Sub
Private Sub TRBrate_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TRBrate.Scroll
rate = TRBrate.Value / 1000
LBLrate.Text = FormatPercent(rate, 1)
Calculate()
End Sub
Private Sub TRBmonths_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TRBmonths.Scroll
LBLmonths.Text = TRBmonths.Value
Calculate()
End Sub
Private Sub TRByears_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TRByears.Scroll
LBLyears.Text = TRByears.Value
Calculate()
End Sub
Private Sub PICback_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICback.Click
Me.Close()
End Sub
Private Sub PICreset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PICreset.Click
CHKtradein.Checked = False
NUDtradein.Value = 1000
CHKdownPayment.Checked = False
NUDdownPayment.Value = 1000
CHKfinancing.Checked = False
TRBrate.Value = 30
LBLrate.Text = "3.0%"
TRBmonths.Value = 0
TRByears.Value = 2
ChooseCompany()
End Sub
Private Sub PICback_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICback.MouseEnter
PICback.Image = My.Resources.back_hover
LBLgoback.Visible = True
End Sub
Private Sub PICreset_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICreset.MouseEnter
PICreset.Image = My.Resources.reset_hover
End Sub
Private Sub PICback_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICback.MouseLeave
PICback.Image = My.Resources.back
LBLgoback.Visible = False
End Sub
Private Sub PICreset_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PICreset.MouseLeave
PICreset.Image = My.Resources.reset
End Sub
End Class
|
gumgl/VB.NET
|
CarProject/Program.vb
|
Visual Basic
|
mit
| 35,506
|
Imports System.IO
Imports Aspose.Cells
Namespace Files.Handling
Public Class SaveInHtmlFormat
Public Shared Sub Run()
' ExStart:1
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Creating a Workbook object
Dim workbook As New Workbook()
' Save in Html format
workbook.Save(dataDir & "output.html", SaveFormat.Html)
' ExEnd:1
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Files/Handling/SaveInHtmlFormat.vb
|
Visual Basic
|
mit
| 583
|
Imports System.Web.UI
Imports System.Web
Namespace Common
''' <summary>
''' A base page from which all other pages inherit
''' </summary>
''' <remarks>This page is required to handle culture changes, as pages within master pages have no InitCulture sub</remarks>
Public Class BasePage
Inherits Page
''' <summary>
''' Set the user culture language
''' </summary>
''' <param name="myCulture"></param>
''' <remarks>This stores a cookie on the client machine for 1 year</remarks>
Private Overloads Sub SetUserCulture(ByVal myCulture As String)
Dim userCultureCookie As New HttpCookie("UserCulture")
userCultureCookie.Expires = Now.AddYears(1) 'Expire the cookie in 1 year, therefore held for next car tax
userCultureCookie.Values("UserCulture") = IIf(IsNothing(myCulture), Nothing, myCulture)
Response.Cookies.Add(userCultureCookie)
End Sub
''' <summary>
''' SetUserCulture
''' </summary>
''' <remarks></remarks>
Private Overloads Sub SetUserCulture()
SetUserCulture(Nothing)
End Sub
''' <summary>
''' InitializeCulture sets the cookie
''' </summary>
''' <remarks></remarks>
Protected Overrides Sub InitializeCulture()
Dim qString As Object = HttpContext.Current.Request.QueryString("l")
If Not qString Is Nothing AndAlso qString.ToString <> "" Then
If qString.ToString.ToLower = "cy-gb" Then
SetUserCulture("cy-GB")
End If
End If
Dim rCookie As HttpCookie = HttpContext.Current.Request.Cookies("UserCulture")
If Not rCookie Is Nothing Then
Select Case rCookie.Values("UserCulture")
Case "cy-GB"
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo(rCookie("UserCulture").ToString)
System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(rCookie("UserCulture").ToString)
Case Else
'If english then remove the cookie
rCookie.Expires = Now.AddDays(-1)
Response.Cookies.Add(rCookie)
End Select
End If
MyBase.InitializeCulture()
End Sub
End Class
End Namespace
|
dvla/evl-public-code
|
EVLPublicCode/EVLPublicCode/Code/Controls/BasePage.vb
|
Visual Basic
|
mit
| 2,518
|
Public Class Template
End Class
|
sddhscathletics/Solution
|
main/main/Template.vb
|
Visual Basic
|
mit
| 35
|
'Copyright © exc-jdbi 2016
'© mnPassing 2016
'mnPassing - www.github.com/exc-jdbi/passing
'mnPassing is Free and Opensource Software
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34209
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.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("TestDll.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
exc-jdbi/passing
|
mnPassingVb/TestDll/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,856
|
Imports System
Imports Independentsoft.Office
Imports Independentsoft.Office.Vml
Imports Independentsoft.Office.Word
Module Module1
Sub Main(ByVal args() As String)
Dim doc As New WordDocument()
Dim embeddedObject As New EmbeddedObject()
Dim imageShapeStyle As New ShapeStyle()
imageShapeStyle.Width = "76pt"
imageShapeStyle.Height = "48pt"
Dim imageShape As New Shape()
imageShape.ID = "Shape1"
imageShape.Style = imageShapeStyle
Dim image As New Image("c:\test\image1.emf") 'excel icon
image.Title = "image1" 'important
imageShape.Content.Add(image)
Dim oleObject As New EmbeddedOleObject("c:\test\workbook.xlsx")
oleObject.Type = OleType.EmbeddedObject
oleObject.Application = "Excel.Sheet.12"
oleObject.ShapeID = "Shape1"
oleObject.DrawAspect = OleDrawAspect.Icon
oleObject.ObjectID = "123"
embeddedObject.Content.Add(imageShape)
embeddedObject.Content.Add(oleObject)
Dim run1 As New Run()
run1.Add(embeddedObject)
Dim paragraph1 As New Paragraph()
paragraph1.Add(run1)
doc.Body.Add(paragraph1)
doc.Save("c:\test\output.docx", True)
End Sub
End Module
|
AndreKuzubov/Easy_Report
|
packages/Independentsoft.Office.Word.2.0.400/Tutorial/VBInsertExcelWorkbook/Module1.vb
|
Visual Basic
|
apache-2.0
| 1,281
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34209
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
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("ProyectoVisual1erParcial.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
|
VisualStudioProyecto/ProyectoVSP1
|
ProyectoVisual1erParcial/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,793
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class EventBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
Public Sub New()
End Sub
Protected Overrides Function GetHighlights(node As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of TextSpan)
Dim eventBlock = node.GetAncestor(Of EventBlockSyntax)()
If eventBlock Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of TextSpan)()
End If
Dim highlights As New List(Of TextSpan)()
With eventBlock
With .EventStatement
' This span calculation should also capture the Custom keyword
Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword)
highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End))
If .ImplementsClause IsNot Nothing Then
highlights.Add(.ImplementsClause.ImplementsKeyword.Span)
End If
End With
highlights.Add(.EndEventStatement.Span)
End With
Return highlights
End Function
End Class
End Namespace
|
aelij/roslyn
|
src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/EventBlockHighlighter.vb
|
Visual Basic
|
apache-2.0
| 1,796
|
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.IO
Imports System.Collections.Generic
Imports System.Data
Imports System.Text
Imports System.Object
Imports System.Security.Cryptography
Imports System.Timers
Module modUtilization
<System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack:=1)> _
Public Structure Process_Basic_Information
Public ExitStatus As IntPtr
Public PepBaseAddress As IntPtr
Public AffinityMask As IntPtr
Public BasePriority As IntPtr
Public UniqueProcessID As IntPtr
Public InheritedFromUniqueProcessId As IntPtr
End Structure
<System.Runtime.InteropServices.DllImport("ntdll.dll", EntryPoint:="NtQueryInformationProcess")> _
Public Function NtQueryInformationProcess(ByVal handle As IntPtr, ByVal processinformationclass As UInteger, ByRef ProcessInformation As Process_Basic_Information, ByVal ProcessInformationLength As Integer, ByRef ReturnLength As UInteger) As Integer
End Function
Private mBCE As Long = 0
Public Const PROCESSBASICINFORMATION As UInteger = 0
Public LastBlockHash As String = ""
Public _timerBoincCredits As System.Timers.Timer
Public _timerBoincUtilization As System.Timers.Timer
Public mnBestBlock As Long
Public Const BOINC_MEMORY_FOOTPRINT As Double = 5000000
Public Const KERNEL_OVERHEAD As Double = 1.5
Private last_sample As Double = 0
Public BoincAvgOverTime As String = ""
Public _BoincMD5 = ""
Public _oldBA As Double = 0
Public BlockData As String = ""
Public PublicWalletAddress As String = ""
Public mdProcNarrComponent1 As Double
Public mdProcNarrComponent2 As Double
Public mBoincProcessorUtilization As Double = 0
Public mBoincThreads As Double = 0
Public Sub Initialize()
Try
Housecleaning()
Catch ex As Exception
End Try
If _timerBoincUtilization Is Nothing Then
_timerBoincUtilization = New System.Timers.Timer(600000)
AddHandler _timerBoincUtilization.Elapsed, New ElapsedEventHandler(AddressOf BoincUtilizationTimerElapsed)
_timerBoincUtilization.Enabled = True
End If
If _timerBoincCredits Is Nothing Then
_timerBoincCredits = New System.Timers.Timer(6000000)
AddHandler _timerBoincCredits.Elapsed, New ElapsedEventHandler(AddressOf BoincCreditsElapsed)
_timerBoincCredits.Enabled = True
BoincCreditsElapsed()
End If
End Sub
Private Sub BoincUtilizationTimerElapsed()
Try
_timerBoincUtilization.Enabled = False
Catch ex As Exception
End Try
_timerBoincUtilization.Enabled = True
End Sub
Private Sub BoincCreditsElapsed()
Try
mBCE = mBCE + 1
If mBCE > 1 Then LogBoincCredits()
ReturnBoincCreditsAtPointInTime(86400 / 2)
modBoincCredits.BoincCredits = BoincCreditsAtPointInTime
modBoincCredits.BoincCreditsAvg = BoincCreditsAvgAtPointInTime
Catch ex As Exception
End Try
End Sub
Public Function modAvgOverTime()
Try
Dim sample1 As Double
Dim sample2 As Double
Dim sample3 As Double
sample1 = ReturnBoincCreditsAtPointInTime(86400)
sample2 = ReturnBoincCreditsAtPointInTime(604800)
sample3 = ReturnBoincCreditsAtPointInTime(2419200)
Dim sOut As String
sOut = Trim(Math.Round(sample1, 0)) + ":" + Trim(Math.Round(sample2, 0)) + ":" + Trim(Math.Round(sample3, 0))
BoincAvgOverTime = sOut
Return sOut
Catch ex As Exception
Return "?:?:?"
End Try
End Function
Public Function GetUtilizationByPID(ByVal PID As Integer) As Double
Dim instances() As String = Nothing
Try
Dim cat As New PerformanceCounterCategory("Process")
instances = cat.GetInstanceNames()
Catch
Return 0
End Try
Dim i As Integer
Try
For Each instance In instances
Using cnt As PerformanceCounter = New PerformanceCounter("Process", "ID Process", instance, True)
Dim val As Integer = CType(cnt.RawValue, Int32)
If val = PID Then
Dim pc As PerformanceCounter = New PerformanceCounter("Process", "% Processor Time", instance, True)
pc.NextValue()
Dim dPIDProcessorTime As Double
For i = 1 To 4
Threading.Thread.Sleep(100)
dPIDProcessorTime = pc.NextValue
If dPIDProcessorTime > 0 And i > 1 Then Return dPIDProcessorTime
Next i
End If
End Using
Next
Return 0
Catch ex As Exception
Return 0
End Try
End Function
Public Function ReturnBoincCPUUsage() As Double
Dim thBoincCPU As New Thread(AddressOf Thread_ReturnBoincCPUUsage)
thBoincCPU.IsBackground = True
thBoincCPU.Start()
Return mBoincProcessorUtilization
End Function
Public Function Thread_ReturnBoincCPUUsage() As Double
Try
Dim masterProcess As Process()
masterProcess = Process.GetProcessesByName("BOINC")
If masterProcess.Length = 0 Then
GoTo CalculateUsage
End If
Dim p As Process
Dim localAll As Process() = Process.GetProcesses()
Dim runningtime As TimeSpan
Dim processortime As TimeSpan
Dim percent As Double
Dim total_runningtime As TimeSpan
Dim total_processortime As TimeSpan
Dim lThreadCount As Double
Dim total_memory_usage As Double
Dim current_pid_utilization As Double
Dim ptc As ProcessThreadCollection
Dim pt As ProcessThread
Dim parentProcess As Process
Dim greatParent As Process
Dim isBoinc As Boolean
For Each p In localAll
'If this a boinc process
If p.ProcessName <> "System" And p.ProcessName <> "Idle" Then
Try
isBoinc = False
parentProcess = GetInheritedParent(p.Handle)
greatParent = GetInheritedParent(parentProcess.Handle)
If Not parentProcess Is Nothing Then
If parentProcess.Id = masterProcess(0).Id Then isBoinc = True
If parentProcess.ProcessName.ToLower = "boinc" Or parentProcess.ProcessName.ToLower = "boincmgr" Then isBoinc = True
End If
If Not greatParent Is Nothing Then
If greatParent.ProcessName.ToLower = "boinc" Or greatParent.ProcessName.ToLower = "boincmgr" Then isBoinc = True
End If
If isBoinc Then
current_pid_utilization = GetUtilizationByPID(p.Id)
If current_pid_utilization > 0 Then
runningtime = Now - p.StartTime
processortime = p.TotalProcessorTime
percent = (processortime.TotalSeconds + p.UserProcessorTime.TotalSeconds) / runningtime.TotalSeconds
total_runningtime = total_runningtime + runningtime
total_processortime = total_processortime + processortime
lThreadCount = lThreadCount + 1
total_memory_usage = total_memory_usage + p.PrivateMemorySize64
End If
End If
Catch ex As Exception
'This happens when a process is stopped in the middle of the count, or when we have a reference to an object that was collected
End Try
End If
Next
CalculateUsage:
Dim usage_percent As Double = 0
If total_runningtime.TotalSeconds > 0 Then
usage_percent = (total_processortime.TotalSeconds / total_runningtime.TotalSeconds) * KERNEL_OVERHEAD
End If
Dim memory_usage As Double
memory_usage = total_memory_usage / BOINC_MEMORY_FOOTPRINT
'Attribute up to 25% of the score to boinc project, memory usage
If memory_usage > 0.25 Then memory_usage = 0.25
If memory_usage < 0 Then memory_usage = 0
'Attribute up to 75% of the score to boinc thread processor utilization totals
If usage_percent > 0.75 Then usage_percent = 0.75
If usage_percent < 0 Then usage_percent = 0
'no credit for memory if processor is idle
If lThreadCount < 1 Then usage_percent = 0
If usage_percent = 0 Then memory_usage = 0
usage_percent = usage_percent + memory_usage
usage_percent = usage_percent * 100 'Convert to a 3 digit percent
If usage_percent > 100 Then usage_percent = 100
If usage_percent < 0 Then usage_percent = 0
Dim h As Double
h = HomogenizedDailyCredits(usage_percent)
usage_percent = h
'Create a two point moving average
Dim avg_sample As Double
avg_sample = (last_sample + usage_percent) / 2
mBoincProcessorUtilization = Math.Round(avg_sample, 0)
last_sample = mBoincProcessorUtilization
mBoincThreads = lThreadCount
Return usage_percent
Catch ex As Exception
Return 0
End Try
End Function
Public Function HomogenizedDailyCredits(cpu_use As Double)
Try
Dim dAvg As Double = BoincCreditsAvg
If dAvg > 3000 Then dAvg = 3000
If dAvg < 0.01 Then dAvg = 0.01
Dim dUsage As Double = dAvg / 10
If dUsage > 100 Then dUsage = 100
If dUsage < 0 Then dUsage = 0
mdProcNarrComponent1 = cpu_use
mdProcNarrComponent2 = dUsage
Dim avg1 As Double = (cpu_use + dUsage) / 2
Return avg1
Catch ex As Exception
End Try
End Function
Public Function GetInheritedParent(ByVal sPID As IntPtr) As Process
Try
Dim ProccessInfo As New Process_Basic_Information
'Used as an output parameter by the API function
Dim RetLength As UInteger
NtQueryInformationProcess(sPID, PROCESSBASICINFORMATION, ProccessInfo, Marshal.SizeOf(ProccessInfo), RetLength)
Dim sParentID As IntPtr
sParentID = ProccessInfo.InheritedFromUniqueProcessId
Dim pOut As Process
pOut = Process.GetProcessById(sParentID)
Return pOut
Catch ex As Exception
End Try
End Function
End Module
|
icede/Gridcoin-master
|
src/GridcoinInstallerWindows/Gridcoin/GridcoinVirtualMachine/modUtilization.vb
|
Visual Basic
|
mit
| 10,936
|
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
Imports System.IO
Imports System.Runtime.Serialization.Json
Imports System.Text
Public Module Extensions_856
''' <summary>
''' A string extension method that deserialize a Json string to object.
''' </summary>
''' <typeparam name="T">Generic type parameter.</typeparam>
''' <param name="this">The @this to act on.</param>
''' <returns>The object deserialized.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function DeserializeJson(Of T)(this As String) As T
Dim serializer = New DataContractJsonSerializer(GetType(T))
Using stream = New MemoryStream(Encoding.[Default].GetBytes(this))
Return DirectCast(serializer.ReadObject(stream), T)
End Using
End Function
''' <summary>
''' A string extension method that deserialize a Json string to object.
''' </summary>
''' <typeparam name="T">Generic type parameter.</typeparam>
''' <param name="this">The @this to act on.</param>
''' <param name="encoding">The encoding.</param>
''' <returns>The object deserialized.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function DeserializeJson(Of T)(this As String, encoding As Encoding) As T
Dim serializer = New DataContractJsonSerializer(GetType(T))
Using stream = New MemoryStream(encoding.GetBytes(this))
Return DirectCast(serializer.ReadObject(stream), T)
End Using
End Function
End Module
|
mario-loza/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Serialization/System.String/String.DeserializeJson.vb
|
Visual Basic
|
mit
| 1,749
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers
Friend Class MockCompilerHost
Implements IVbCompilerHost
Private ReadOnly _sdkPath As String
Public Sub New(sdkPath As String)
_sdkPath = sdkPath
End Sub
Public Shared ReadOnly Property FullFrameworkCompilerHost As MockCompilerHost
Get
Return New MockCompilerHost("Z:\FullFramework")
End Get
End Property
Public Shared ReadOnly Property NoSdkCompilerHost As MockCompilerHost
Get
Return New MockCompilerHost("")
End Get
End Property
Public Function GetWellKnownDllName(fileName As String) As String
Return Path.Combine(_sdkPath, fileName)
End Function
Public Sub OutputString(<MarshalAs(UnmanagedType.LPWStr)> [string] As String) Implements IVbCompilerHost.OutputString
Throw New NotImplementedException()
End Sub
Public Function GetSdkPath(ByRef sdkPath As String) As Integer Implements IVbCompilerHost.GetSdkPath
sdkPath = _sdkPath
If String.IsNullOrEmpty(sdkPath) Then
Return VSConstants.E_NOTIMPL
Else
Return VSConstants.S_OK
End If
End Function
Public Function GetTargetLibraryType() As VBTargetLibraryType Implements IVbCompilerHost.GetTargetLibraryType
Throw New NotImplementedException()
End Function
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/VisualStudio/TestUtilities2/ProjectSystemShim/VisualBasicHelpers/MockCompilerHost.vb
|
Visual Basic
|
apache-2.0
| 1,890
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The CommandLineArguments class provides members to Set and Get Visual Basic compilation and parse options.
''' </summary>
Public NotInheritable Class VisualBasicCommandLineArguments
Inherits CommandLineArguments
''' <summary>
''' Set and Get the Visual Basic compilation options.
''' </summary>
''' <returns>The currently set Visual Basic compilation options.</returns>
Public Overloads Property CompilationOptions As VisualBasicCompilationOptions
''' <summary>
''' Set and Get the Visual Basic parse options.
''' </summary>
''' <returns>The currently set Visual Basic parse options.</returns>
Public Overloads Property ParseOptions As VisualBasicParseOptions
Friend OutputLevel As OutputLevel
''' <summary>
''' Gets the core Parse options.
''' </summary>
''' <returns>The currently set core parse options.</returns>
Protected Overrides ReadOnly Property ParseOptionsCore As ParseOptions
Get
Return ParseOptions
End Get
End Property
''' <summary>
''' Gets the core compilation options.
''' </summary>
''' <returns>The currently set core compilation options.</returns>
Protected Overrides ReadOnly Property CompilationOptionsCore As CompilationOptions
Get
Return CompilationOptions
End Get
End Property
Friend Property DefaultCoreLibraryReference As CommandLineReference?
Friend Sub New()
End Sub
Friend Overrides Function ResolveMetadataReferences(
metadataResolver As MetadataReferenceResolver,
diagnostics As List(Of DiagnosticInfo),
messageProvider As CommonMessageProvider,
resolved As List(Of MetadataReference)
) As Boolean
If MyBase.ResolveMetadataReferences(metadataResolver, diagnostics, messageProvider, resolved) Then
' If there were no references, don't try to add default Cor library reference.
If Me.DefaultCoreLibraryReference IsNot Nothing AndAlso resolved.Count > 0 Then
' All references from arguments were resolved successfully. Let's see if we have a reference that can be used as a Cor library.
For Each reference In resolved
Dim refProps = reference.Properties
' The logic about deciding what assembly is a candidate for being a Cor library here and in
' CommonReferenceManager<TCompilation, TAssemblySymbol>.IndexOfCorLibrary
' should be equivalent.
If Not refProps.EmbedInteropTypes AndAlso refProps.Kind = MetadataImageKind.Assembly Then
Try
Dim assemblyMetadata = TryCast(DirectCast(reference, PortableExecutableReference).GetMetadataNoCopy(), AssemblyMetadata)
If assemblyMetadata Is Nothing OrElse Not assemblyMetadata.IsValidAssembly() Then
' There will be some errors reported later.
Return True
End If
Dim assembly As PEAssembly = assemblyMetadata.GetAssembly()
If assembly.AssemblyReferences.Length = 0 AndAlso Not assembly.ContainsNoPiaLocalTypes AndAlso assembly.DeclaresTheObjectClass Then
' This reference looks like a valid Cor library candidate, bail out.
Return True
End If
Catch e As BadImageFormatException
' error reported later
Return True
Catch e As IOException
' error reported later
Return True
End Try
End If
Next
' None of the supplied references could be used as a Cor library. Let's add a default one.
Dim defaultCorLibrary = ResolveMetadataReference(Me.DefaultCoreLibraryReference.Value, metadataResolver, diagnostics, messageProvider).FirstOrDefault()
If defaultCorLibrary Is Nothing OrElse defaultCorLibrary.IsUnresolved Then
Debug.Assert(diagnostics Is Nothing OrElse diagnostics.Any())
Return False
Else
resolved.Insert(0, defaultCorLibrary)
Return True
End If
End If
Return True
End If
Return False
End Function
End Class
Friend Enum OutputLevel
Quiet
Normal
Verbose
End Enum
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCommandLineArguments.vb
|
Visual Basic
|
apache-2.0
| 5,722
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class)
Protected Class FunctionData
Public Property Name As String
Public Property Kind As EnvDTE.vsCMFunction = EnvDTE.vsCMFunction.vsCMFunctionFunction
Public Property Type As Object
Public Property Position As Object = 0
Public Property Access As EnvDTE.vsCMAccess = EnvDTE.vsCMAccess.vsCMAccessDefault
Public Property Location As Object
End Class
End Class
End Namespace
|
ValentinRueda/roslyn
|
src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.FunctionData.vb
|
Visual Basic
|
apache-2.0
| 789
|
'------------------------------------------------------------------------------
' <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 Off
Option Explicit On
'''<summary>
'''Represents a strongly typed in-memory cache of data.
'''</summary>
<Global.System.Serializable(), _
Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema"), _
Global.System.Xml.Serialization.XmlRootAttribute("Login"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")> _
Partial Public Class Login
Inherits Global.System.Data.DataSet
Private tableUserDb As UserDbDataTable
Private _schemaSerializationMode As Global.System.Data.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.BeginInit
Me.InitClass
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler MyBase.Relations.CollectionChanged, schemaChangedHandler
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context, false)
If (Me.IsBinarySerialized(info, context) = true) Then
Me.InitVars(false)
Dim schemaChangedHandler1 As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler Me.Tables.CollectionChanged, schemaChangedHandler1
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler1
Return
End If
Dim strSchema As String = CType(info.GetValue("XmlSchema", GetType(String)),String)
If (Me.DetermineSchemaSerializationMode(info, context) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet()
ds.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
If (Not (ds.Tables("UserDb")) Is Nothing) Then
MyBase.Tables.Add(New UserDbDataTable(ds.Tables("UserDb")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
End If
Me.GetSerializationData(info, context)
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false), _
Global.System.ComponentModel.DesignerSerializationVisibility(Global.System.ComponentModel.DesignerSerializationVisibility.Content)> _
Public ReadOnly Property UserDb() As UserDbDataTable
Get
Return Me.tableUserDb
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.BrowsableAttribute(true), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Visible)> _
Public Overrides Property SchemaSerializationMode() As Global.System.Data.SchemaSerializationMode
Get
Return Me._schemaSerializationMode
End Get
Set
Me._schemaSerializationMode = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Tables() As Global.System.Data.DataTableCollection
Get
Return MyBase.Tables
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Relations() As Global.System.Data.DataRelationCollection
Get
Return MyBase.Relations
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub InitializeDerivedDataSet()
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataSet
Dim cln As Login = CType(MyBase.Clone,Login)
cln.InitVars
cln.SchemaSerializationMode = Me.SchemaSerializationMode
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function ShouldSerializeTables() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function ShouldSerializeRelations() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub ReadXmlSerializable(ByVal reader As Global.System.Xml.XmlReader)
If (Me.DetermineSchemaSerializationMode(reader) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Me.Reset
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet()
ds.ReadXml(reader)
If (Not (ds.Tables("UserDb")) Is Nothing) Then
MyBase.Tables.Add(New UserDbDataTable(ds.Tables("UserDb")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXml(reader)
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetSchemaSerializable() As Global.System.Xml.Schema.XmlSchema
Dim stream As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Me.WriteXmlSchema(New Global.System.Xml.XmlTextWriter(stream, Nothing))
stream.Position = 0
Return Global.System.Xml.Schema.XmlSchema.Read(New Global.System.Xml.XmlTextReader(stream), Nothing)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Overloads Sub InitVars()
Me.InitVars(true)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Overloads Sub InitVars(ByVal initTable As Boolean)
Me.tableUserDb = CType(MyBase.Tables("UserDb"),UserDbDataTable)
If (initTable = true) Then
If (Not (Me.tableUserDb) Is Nothing) Then
Me.tableUserDb.InitVars
End If
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.DataSetName = "Login"
Me.Prefix = ""
Me.Namespace = "http://tempuri.org/Login.xsd"
Me.EnforceConstraints = true
Me.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
Me.tableUserDb = New UserDbDataTable()
MyBase.Tables.Add(Me.tableUserDb)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function ShouldSerializeUserDb() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub SchemaChanged(ByVal sender As Object, ByVal e As Global.System.ComponentModel.CollectionChangeEventArgs)
If (e.Action = Global.System.ComponentModel.CollectionChangeAction.Remove) Then
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedDataSetSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim ds As Login = New Login()
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim any As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any.Namespace = ds.Namespace
sequence.Items.Add(any)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Delegate Sub UserDbRowChangeEventHandler(ByVal sender As Object, ByVal e As UserDbRowChangeEvent)
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class UserDbDataTable
Inherits Global.System.Data.TypedTableBase(Of UserDbRow)
Private columnID As Global.System.Data.DataColumn
Private columnPass As Global.System.Data.DataColumn
Private columnAccess_Level As Global.System.Data.DataColumn
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.TableName = "UserDb"
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal table As Global.System.Data.DataTable)
MyBase.New
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property IDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnID
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property PassColumn() As Global.System.Data.DataColumn
Get
Return Me.columnPass
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Access_LevelColumn() As Global.System.Data.DataColumn
Get
Return Me.columnAccess_Level
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Default ReadOnly Property Item(ByVal index As Integer) As UserDbRow
Get
Return CType(Me.Rows(index),UserDbRow)
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event UserDbRowChanging As UserDbRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event UserDbRowChanged As UserDbRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event UserDbRowDeleting As UserDbRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event UserDbRowDeleted As UserDbRowChangeEventHandler
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Sub AddUserDbRow(ByVal row As UserDbRow)
Me.Rows.Add(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Function AddUserDbRow(ByVal ID As String, ByVal Pass As String, ByVal Access_Level As Integer) As UserDbRow
Dim rowUserDbRow As UserDbRow = CType(Me.NewRow,UserDbRow)
Dim columnValuesArray() As Object = New Object() {ID, Pass, Access_Level}
rowUserDbRow.ItemArray = columnValuesArray
Me.Rows.Add(rowUserDbRow)
Return rowUserDbRow
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function FindByID(ByVal ID As String) As UserDbRow
Return CType(Me.Rows.Find(New Object() {ID}),UserDbRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataTable
Dim cln As UserDbDataTable = CType(MyBase.Clone,UserDbDataTable)
cln.InitVars
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function CreateInstance() As Global.System.Data.DataTable
Return New UserDbDataTable()
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub InitVars()
Me.columnID = MyBase.Columns("ID")
Me.columnPass = MyBase.Columns("Pass")
Me.columnAccess_Level = MyBase.Columns("Access Level")
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.columnID = New Global.System.Data.DataColumn("ID", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnID)
Me.columnPass = New Global.System.Data.DataColumn("Pass", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnPass)
Me.columnAccess_Level = New Global.System.Data.DataColumn("Access Level", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnAccess_Level)
Me.Constraints.Add(New Global.System.Data.UniqueConstraint("Constraint1", New Global.System.Data.DataColumn() {Me.columnID}, true))
Me.columnID.AllowDBNull = false
Me.columnID.Unique = true
Me.columnID.MaxLength = 255
Me.columnPass.MaxLength = 255
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function NewUserDbRow() As UserDbRow
Return CType(Me.NewRow,UserDbRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function NewRowFromBuilder(ByVal builder As Global.System.Data.DataRowBuilder) As Global.System.Data.DataRow
Return New UserDbRow(builder)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(UserDbRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanged(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanged(e)
If (Not (Me.UserDbRowChangedEvent) Is Nothing) Then
RaiseEvent UserDbRowChanged(Me, New UserDbRowChangeEvent(CType(e.Row,UserDbRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanging(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanging(e)
If (Not (Me.UserDbRowChangingEvent) Is Nothing) Then
RaiseEvent UserDbRowChanging(Me, New UserDbRowChangeEvent(CType(e.Row,UserDbRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleted(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleted(e)
If (Not (Me.UserDbRowDeletedEvent) Is Nothing) Then
RaiseEvent UserDbRowDeleted(Me, New UserDbRowChangeEvent(CType(e.Row,UserDbRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleting(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleting(e)
If (Not (Me.UserDbRowDeletingEvent) Is Nothing) Then
RaiseEvent UserDbRowDeleting(Me, New UserDbRowChangeEvent(CType(e.Row,UserDbRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub RemoveUserDbRow(ByVal row As UserDbRow)
Me.Rows.Remove(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedTableSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim ds As Login = New Login()
Dim any1 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any1.Namespace = "http://www.w3.org/2001/XMLSchema"
any1.MinOccurs = New Decimal(0)
any1.MaxOccurs = Decimal.MaxValue
any1.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any1)
Dim any2 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"
any2.MinOccurs = New Decimal(1)
any2.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any2)
Dim attribute1 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute1.Name = "namespace"
attribute1.FixedValue = ds.Namespace
type.Attributes.Add(attribute1)
Dim attribute2 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute2.Name = "tableTypeName"
attribute2.FixedValue = "UserDbDataTable"
type.Attributes.Add(attribute2)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
Partial Public Class UserDbRow
Inherits Global.System.Data.DataRow
Private tableUserDb As UserDbDataTable
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal rb As Global.System.Data.DataRowBuilder)
MyBase.New(rb)
Me.tableUserDb = CType(Me.Table,UserDbDataTable)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property ID() As String
Get
Return CType(Me(Me.tableUserDb.IDColumn),String)
End Get
Set
Me(Me.tableUserDb.IDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Pass() As String
Get
Try
Return CType(Me(Me.tableUserDb.PassColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'Pass' in table 'UserDb' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableUserDb.PassColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Access_Level() As Integer
Get
Try
Return CType(Me(Me.tableUserDb.Access_LevelColumn),Integer)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'Access Level' in table 'UserDb' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableUserDb.Access_LevelColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsPassNull() As Boolean
Return Me.IsNull(Me.tableUserDb.PassColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetPassNull()
Me(Me.tableUserDb.PassColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsAccess_LevelNull() As Boolean
Return Me.IsNull(Me.tableUserDb.Access_LevelColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetAccess_LevelNull()
Me(Me.tableUserDb.Access_LevelColumn) = Global.System.Convert.DBNull
End Sub
End Class
'''<summary>
'''Row event argument class
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Class UserDbRowChangeEvent
Inherits Global.System.EventArgs
Private eventRow As UserDbRow
Private eventAction As Global.System.Data.DataRowAction
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New(ByVal row As UserDbRow, ByVal action As Global.System.Data.DataRowAction)
MyBase.New
Me.eventRow = row
Me.eventAction = action
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Row() As UserDbRow
Get
Return Me.eventRow
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Action() As Global.System.Data.DataRowAction
Get
Return Me.eventAction
End Get
End Property
End Class
End Class
Namespace LoginTableAdapters
'''<summary>
'''Represents the connection and commands used to retrieve and save data.
'''</summary>
<Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.ComponentModel.DataObjectAttribute(true), _
Global.System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner"& _
", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Partial Public Class UserDbTableAdapter
Inherits Global.System.ComponentModel.Component
Private WithEvents _adapter As Global.System.Data.OleDb.OleDbDataAdapter
Private _connection As Global.System.Data.OleDb.OleDbConnection
Private _transaction As Global.System.Data.OleDb.OleDbTransaction
Private _commandCollection() As Global.System.Data.OleDb.OleDbCommand
Private _clearBeforeFill As Boolean
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.ClearBeforeFill = true
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Friend ReadOnly Property Adapter() As Global.System.Data.OleDb.OleDbDataAdapter
Get
If (Me._adapter Is Nothing) Then
Me.InitAdapter
End If
Return Me._adapter
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Property Connection() As Global.System.Data.OleDb.OleDbConnection
Get
If (Me._connection Is Nothing) Then
Me.InitConnection
End If
Return Me._connection
End Get
Set
Me._connection = value
If (Not (Me.Adapter.InsertCommand) Is Nothing) Then
Me.Adapter.InsertCommand.Connection = value
End If
If (Not (Me.Adapter.DeleteCommand) Is Nothing) Then
Me.Adapter.DeleteCommand.Connection = value
End If
If (Not (Me.Adapter.UpdateCommand) Is Nothing) Then
Me.Adapter.UpdateCommand.Connection = value
End If
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
If (Not (Me.CommandCollection(i)) Is Nothing) Then
CType(Me.CommandCollection(i),Global.System.Data.OleDb.OleDbCommand).Connection = value
End If
i = (i + 1)
Loop
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Property Transaction() As Global.System.Data.OleDb.OleDbTransaction
Get
Return Me._transaction
End Get
Set
Me._transaction = value
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
Me.CommandCollection(i).Transaction = Me._transaction
i = (i + 1)
Loop
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.DeleteCommand) Is Nothing)) Then
Me.Adapter.DeleteCommand.Transaction = Me._transaction
End If
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.InsertCommand) Is Nothing)) Then
Me.Adapter.InsertCommand.Transaction = Me._transaction
End If
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.UpdateCommand) Is Nothing)) Then
Me.Adapter.UpdateCommand.Transaction = Me._transaction
End If
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected ReadOnly Property CommandCollection() As Global.System.Data.OleDb.OleDbCommand()
Get
If (Me._commandCollection Is Nothing) Then
Me.InitCommandCollection
End If
Return Me._commandCollection
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property ClearBeforeFill() As Boolean
Get
Return Me._clearBeforeFill
End Get
Set
Me._clearBeforeFill = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitAdapter()
Me._adapter = New Global.System.Data.OleDb.OleDbDataAdapter()
Dim tableMapping As Global.System.Data.Common.DataTableMapping = New Global.System.Data.Common.DataTableMapping()
tableMapping.SourceTable = "Table"
tableMapping.DataSetTable = "UserDb"
tableMapping.ColumnMappings.Add("ID", "ID")
tableMapping.ColumnMappings.Add("Pass", "Pass")
tableMapping.ColumnMappings.Add("Access Level", "Access Level")
Me._adapter.TableMappings.Add(tableMapping)
Me._adapter.DeleteCommand = New Global.System.Data.OleDb.OleDbCommand()
Me._adapter.DeleteCommand.Connection = Me.Connection
Me._adapter.DeleteCommand.CommandText = "DELETE FROM `UserDb` WHERE ((`ID` = ?) AND ((? = 1 AND `Pass` IS NULL) OR (`Pass`"& _
" = ?)) AND ((? = 1 AND `Access Level` IS NULL) OR (`Access Level` = ?)))"
Me._adapter.DeleteCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Original_ID", Global.System.Data.OleDb.OleDbType.VarWChar, 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "ID", Global.System.Data.DataRowVersion.Original, false, Nothing))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("IsNull_Pass", Global.System.Data.OleDb.OleDbType.[Integer], 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Pass", Global.System.Data.DataRowVersion.Original, true, Nothing))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Original_Pass", Global.System.Data.OleDb.OleDbType.VarWChar, 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Pass", Global.System.Data.DataRowVersion.Original, false, Nothing))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("IsNull_Access_Level", Global.System.Data.OleDb.OleDbType.[Integer], 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Access Level", Global.System.Data.DataRowVersion.Original, true, Nothing))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Original_Access_Level", Global.System.Data.OleDb.OleDbType.[Integer], 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Access Level", Global.System.Data.DataRowVersion.Original, false, Nothing))
Me._adapter.InsertCommand = New Global.System.Data.OleDb.OleDbCommand()
Me._adapter.InsertCommand.Connection = Me.Connection
Me._adapter.InsertCommand.CommandText = "INSERT INTO `UserDb` (`ID`, `Pass`, `Access Level`) VALUES (?, ?, ?)"
Me._adapter.InsertCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("ID", Global.System.Data.OleDb.OleDbType.VarWChar, 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "ID", Global.System.Data.DataRowVersion.Current, false, Nothing))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Pass", Global.System.Data.OleDb.OleDbType.VarWChar, 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Pass", Global.System.Data.DataRowVersion.Current, false, Nothing))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Access_Level", Global.System.Data.OleDb.OleDbType.[Integer], 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Access Level", Global.System.Data.DataRowVersion.Current, false, Nothing))
Me._adapter.UpdateCommand = New Global.System.Data.OleDb.OleDbCommand()
Me._adapter.UpdateCommand.Connection = Me.Connection
Me._adapter.UpdateCommand.CommandText = "UPDATE `UserDb` SET `ID` = ?, `Pass` = ?, `Access Level` = ? WHERE ((`ID` = ?) AN"& _
"D ((? = 1 AND `Pass` IS NULL) OR (`Pass` = ?)) AND ((? = 1 AND `Access Level` IS"& _
" NULL) OR (`Access Level` = ?)))"
Me._adapter.UpdateCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("ID", Global.System.Data.OleDb.OleDbType.VarWChar, 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "ID", Global.System.Data.DataRowVersion.Current, false, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Pass", Global.System.Data.OleDb.OleDbType.VarWChar, 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Pass", Global.System.Data.DataRowVersion.Current, false, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Access_Level", Global.System.Data.OleDb.OleDbType.[Integer], 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Access Level", Global.System.Data.DataRowVersion.Current, false, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Original_ID", Global.System.Data.OleDb.OleDbType.VarWChar, 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "ID", Global.System.Data.DataRowVersion.Original, false, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("IsNull_Pass", Global.System.Data.OleDb.OleDbType.[Integer], 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Pass", Global.System.Data.DataRowVersion.Original, true, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Original_Pass", Global.System.Data.OleDb.OleDbType.VarWChar, 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Pass", Global.System.Data.DataRowVersion.Original, false, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("IsNull_Access_Level", Global.System.Data.OleDb.OleDbType.[Integer], 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Access Level", Global.System.Data.DataRowVersion.Original, true, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.OleDb.OleDbParameter("Original_Access_Level", Global.System.Data.OleDb.OleDbType.[Integer], 0, Global.System.Data.ParameterDirection.Input, CType(0,Byte), CType(0,Byte), "Access Level", Global.System.Data.DataRowVersion.Original, false, Nothing))
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitConnection()
Me._connection = New Global.System.Data.OleDb.OleDbConnection()
Me._connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\User.accdb"
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitCommandCollection()
Me._commandCollection = New Global.System.Data.OleDb.OleDbCommand(0) {}
Me._commandCollection(0) = New Global.System.Data.OleDb.OleDbCommand()
Me._commandCollection(0).Connection = Me.Connection
Me._commandCollection(0).CommandText = "SELECT ID, Pass, [Access Level] FROM UserDb"
Me._commandCollection(0).CommandType = Global.System.Data.CommandType.Text
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Fill, true)> _
Public Overloads Overridable Function Fill(ByVal dataTable As Login.UserDbDataTable) As Integer
Me.Adapter.SelectCommand = Me.CommandCollection(0)
If (Me.ClearBeforeFill = true) Then
dataTable.Clear
End If
Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Return returnValue
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.[Select], true)> _
Public Overloads Overridable Function GetData() As Login.UserDbDataTable
Me.Adapter.SelectCommand = Me.CommandCollection(0)
Dim dataTable As Login.UserDbDataTable = New Login.UserDbDataTable()
Me.Adapter.Fill(dataTable)
Return dataTable
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataTable As Login.UserDbDataTable) As Integer
Return Me.Adapter.Update(dataTable)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataSet As Login) As Integer
Return Me.Adapter.Update(dataSet, "UserDb")
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataRow As Global.System.Data.DataRow) As Integer
Return Me.Adapter.Update(New Global.System.Data.DataRow() {dataRow})
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataRows() As Global.System.Data.DataRow) As Integer
Return Me.Adapter.Update(dataRows)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Delete, true)> _
Public Overloads Overridable Function Delete(ByVal Original_ID As String, ByVal Original_Pass As String, ByVal Original_Access_Level As Global.System.Nullable(Of Integer)) As Integer
If (Original_ID Is Nothing) Then
Throw New Global.System.ArgumentNullException("Original_ID")
Else
Me.Adapter.DeleteCommand.Parameters(0).Value = CType(Original_ID,String)
End If
If (Original_Pass Is Nothing) Then
Me.Adapter.DeleteCommand.Parameters(1).Value = CType(1,Object)
Me.Adapter.DeleteCommand.Parameters(2).Value = Global.System.DBNull.Value
Else
Me.Adapter.DeleteCommand.Parameters(1).Value = CType(0,Object)
Me.Adapter.DeleteCommand.Parameters(2).Value = CType(Original_Pass,String)
End If
If (Original_Access_Level.HasValue = true) Then
Me.Adapter.DeleteCommand.Parameters(3).Value = CType(0,Object)
Me.Adapter.DeleteCommand.Parameters(4).Value = CType(Original_Access_Level.Value,Integer)
Else
Me.Adapter.DeleteCommand.Parameters(3).Value = CType(1,Object)
Me.Adapter.DeleteCommand.Parameters(4).Value = Global.System.DBNull.Value
End If
Dim previousConnectionState As Global.System.Data.ConnectionState = Me.Adapter.DeleteCommand.Connection.State
If ((Me.Adapter.DeleteCommand.Connection.State And Global.System.Data.ConnectionState.Open) _
<> Global.System.Data.ConnectionState.Open) Then
Me.Adapter.DeleteCommand.Connection.Open
End If
Try
Dim returnValue As Integer = Me.Adapter.DeleteCommand.ExecuteNonQuery
Return returnValue
Finally
If (previousConnectionState = Global.System.Data.ConnectionState.Closed) Then
Me.Adapter.DeleteCommand.Connection.Close
End If
End Try
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Insert, true)> _
Public Overloads Overridable Function Insert(ByVal ID As String, ByVal Pass As String, ByVal Access_Level As Global.System.Nullable(Of Integer)) As Integer
If (ID Is Nothing) Then
Throw New Global.System.ArgumentNullException("ID")
Else
Me.Adapter.InsertCommand.Parameters(0).Value = CType(ID,String)
End If
If (Pass Is Nothing) Then
Me.Adapter.InsertCommand.Parameters(1).Value = Global.System.DBNull.Value
Else
Me.Adapter.InsertCommand.Parameters(1).Value = CType(Pass,String)
End If
If (Access_Level.HasValue = true) Then
Me.Adapter.InsertCommand.Parameters(2).Value = CType(Access_Level.Value,Integer)
Else
Me.Adapter.InsertCommand.Parameters(2).Value = Global.System.DBNull.Value
End If
Dim previousConnectionState As Global.System.Data.ConnectionState = Me.Adapter.InsertCommand.Connection.State
If ((Me.Adapter.InsertCommand.Connection.State And Global.System.Data.ConnectionState.Open) _
<> Global.System.Data.ConnectionState.Open) Then
Me.Adapter.InsertCommand.Connection.Open
End If
Try
Dim returnValue As Integer = Me.Adapter.InsertCommand.ExecuteNonQuery
Return returnValue
Finally
If (previousConnectionState = Global.System.Data.ConnectionState.Closed) Then
Me.Adapter.InsertCommand.Connection.Close
End If
End Try
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Update, true)> _
Public Overloads Overridable Function Update(ByVal ID As String, ByVal Pass As String, ByVal Access_Level As Global.System.Nullable(Of Integer), ByVal Original_ID As String, ByVal Original_Pass As String, ByVal Original_Access_Level As Global.System.Nullable(Of Integer)) As Integer
If (ID Is Nothing) Then
Throw New Global.System.ArgumentNullException("ID")
Else
Me.Adapter.UpdateCommand.Parameters(0).Value = CType(ID,String)
End If
If (Pass Is Nothing) Then
Me.Adapter.UpdateCommand.Parameters(1).Value = Global.System.DBNull.Value
Else
Me.Adapter.UpdateCommand.Parameters(1).Value = CType(Pass,String)
End If
If (Access_Level.HasValue = true) Then
Me.Adapter.UpdateCommand.Parameters(2).Value = CType(Access_Level.Value,Integer)
Else
Me.Adapter.UpdateCommand.Parameters(2).Value = Global.System.DBNull.Value
End If
If (Original_ID Is Nothing) Then
Throw New Global.System.ArgumentNullException("Original_ID")
Else
Me.Adapter.UpdateCommand.Parameters(3).Value = CType(Original_ID,String)
End If
If (Original_Pass Is Nothing) Then
Me.Adapter.UpdateCommand.Parameters(4).Value = CType(1,Object)
Me.Adapter.UpdateCommand.Parameters(5).Value = Global.System.DBNull.Value
Else
Me.Adapter.UpdateCommand.Parameters(4).Value = CType(0,Object)
Me.Adapter.UpdateCommand.Parameters(5).Value = CType(Original_Pass,String)
End If
If (Original_Access_Level.HasValue = true) Then
Me.Adapter.UpdateCommand.Parameters(6).Value = CType(0,Object)
Me.Adapter.UpdateCommand.Parameters(7).Value = CType(Original_Access_Level.Value,Integer)
Else
Me.Adapter.UpdateCommand.Parameters(6).Value = CType(1,Object)
Me.Adapter.UpdateCommand.Parameters(7).Value = Global.System.DBNull.Value
End If
Dim previousConnectionState As Global.System.Data.ConnectionState = Me.Adapter.UpdateCommand.Connection.State
If ((Me.Adapter.UpdateCommand.Connection.State And Global.System.Data.ConnectionState.Open) _
<> Global.System.Data.ConnectionState.Open) Then
Me.Adapter.UpdateCommand.Connection.Open
End If
Try
Dim returnValue As Integer = Me.Adapter.UpdateCommand.ExecuteNonQuery
Return returnValue
Finally
If (previousConnectionState = Global.System.Data.ConnectionState.Closed) Then
Me.Adapter.UpdateCommand.Connection.Close
End If
End Try
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Update, true)> _
Public Overloads Overridable Function Update(ByVal Pass As String, ByVal Access_Level As Global.System.Nullable(Of Integer), ByVal Original_ID As String, ByVal Original_Pass As String, ByVal Original_Access_Level As Global.System.Nullable(Of Integer)) As Integer
Return Me.Update(Original_ID, Pass, Access_Level, Original_ID, Original_Pass, Original_Access_Level)
End Function
End Class
'''<summary>
'''TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios
'''</summary>
<Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD"& _
"esigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")> _
Partial Public Class TableAdapterManager
Inherits Global.System.ComponentModel.Component
Private _updateOrder As UpdateOrderOption
Private _userDbTableAdapter As UserDbTableAdapter
Private _backupDataSetBeforeUpdate As Boolean
Private _connection As Global.System.Data.IDbConnection
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property UpdateOrder() As UpdateOrderOption
Get
Return Me._updateOrder
End Get
Set
Me._updateOrder = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso"& _
"ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3"& _
"a", "System.Drawing.Design.UITypeEditor")> _
Public Property UserDbTableAdapter() As UserDbTableAdapter
Get
Return Me._userDbTableAdapter
End Get
Set
Me._userDbTableAdapter = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property BackupDataSetBeforeUpdate() As Boolean
Get
Return Me._backupDataSetBeforeUpdate
End Get
Set
Me._backupDataSetBeforeUpdate = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public Property Connection() As Global.System.Data.IDbConnection
Get
If (Not (Me._connection) Is Nothing) Then
Return Me._connection
End If
If ((Not (Me._userDbTableAdapter) Is Nothing) _
AndAlso (Not (Me._userDbTableAdapter.Connection) Is Nothing)) Then
Return Me._userDbTableAdapter.Connection
End If
Return Nothing
End Get
Set
Me._connection = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property TableAdapterInstanceCount() As Integer
Get
Dim count As Integer = 0
If (Not (Me._userDbTableAdapter) Is Nothing) Then
count = (count + 1)
End If
Return count
End Get
End Property
'''<summary>
'''Update rows in top-down order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateUpdatedRows(ByVal dataSet As Login, ByVal allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow), ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._userDbTableAdapter) Is Nothing) Then
Dim updatedRows() As Global.System.Data.DataRow = dataSet.UserDb.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.ModifiedCurrent)
updatedRows = Me.GetRealUpdatedRows(updatedRows, allAddedRows)
If ((Not (updatedRows) Is Nothing) _
AndAlso (0 < updatedRows.Length)) Then
result = (result + Me._userDbTableAdapter.Update(updatedRows))
allChangedRows.AddRange(updatedRows)
End If
End If
Return result
End Function
'''<summary>
'''Insert rows in top-down order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateInsertedRows(ByVal dataSet As Login, ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._userDbTableAdapter) Is Nothing) Then
Dim addedRows() As Global.System.Data.DataRow = dataSet.UserDb.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.Added)
If ((Not (addedRows) Is Nothing) _
AndAlso (0 < addedRows.Length)) Then
result = (result + Me._userDbTableAdapter.Update(addedRows))
allAddedRows.AddRange(addedRows)
End If
End If
Return result
End Function
'''<summary>
'''Delete rows in bottom-up order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateDeletedRows(ByVal dataSet As Login, ByVal allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._userDbTableAdapter) Is Nothing) Then
Dim deletedRows() As Global.System.Data.DataRow = dataSet.UserDb.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.Deleted)
If ((Not (deletedRows) Is Nothing) _
AndAlso (0 < deletedRows.Length)) Then
result = (result + Me._userDbTableAdapter.Update(deletedRows))
allChangedRows.AddRange(deletedRows)
End If
End If
Return result
End Function
'''<summary>
'''Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function GetRealUpdatedRows(ByVal updatedRows() As Global.System.Data.DataRow, ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Global.System.Data.DataRow()
If ((updatedRows Is Nothing) _
OrElse (updatedRows.Length < 1)) Then
Return updatedRows
End If
If ((allAddedRows Is Nothing) _
OrElse (allAddedRows.Count < 1)) Then
Return updatedRows
End If
Dim realUpdatedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim i As Integer = 0
Do While (i < updatedRows.Length)
Dim row As Global.System.Data.DataRow = updatedRows(i)
If (allAddedRows.Contains(row) = false) Then
realUpdatedRows.Add(row)
End If
i = (i + 1)
Loop
Return realUpdatedRows.ToArray
End Function
'''<summary>
'''Update all changes to the dataset.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overridable Function UpdateAll(ByVal dataSet As Login) As Integer
If (dataSet Is Nothing) Then
Throw New Global.System.ArgumentNullException("dataSet")
End If
If (dataSet.HasChanges = false) Then
Return 0
End If
If ((Not (Me._userDbTableAdapter) Is Nothing) _
AndAlso (Me.MatchTableAdapterConnection(Me._userDbTableAdapter.Connection) = false)) Then
Throw New Global.System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s"& _
"tring.")
End If
Dim workConnection As Global.System.Data.IDbConnection = Me.Connection
If (workConnection Is Nothing) Then
Throw New Global.System.ApplicationException("TableAdapterManager contains no connection information. Set each TableAdapterMana"& _
"ger TableAdapter property to a valid TableAdapter instance.")
End If
Dim workConnOpened As Boolean = false
If ((workConnection.State And Global.System.Data.ConnectionState.Broken) _
= Global.System.Data.ConnectionState.Broken) Then
workConnection.Close
End If
If (workConnection.State = Global.System.Data.ConnectionState.Closed) Then
workConnection.Open
workConnOpened = true
End If
Dim workTransaction As Global.System.Data.IDbTransaction = workConnection.BeginTransaction
If (workTransaction Is Nothing) Then
Throw New Global.System.ApplicationException("The transaction cannot begin. The current data connection does not support transa"& _
"ctions or the current state is not allowing the transaction to begin.")
End If
Dim allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim adaptersWithAcceptChangesDuringUpdate As Global.System.Collections.Generic.List(Of Global.System.Data.Common.DataAdapter) = New Global.System.Collections.Generic.List(Of Global.System.Data.Common.DataAdapter)()
Dim revertConnections As Global.System.Collections.Generic.Dictionary(Of Object, Global.System.Data.IDbConnection) = New Global.System.Collections.Generic.Dictionary(Of Object, Global.System.Data.IDbConnection)()
Dim result As Integer = 0
Dim backupDataSet As Global.System.Data.DataSet = Nothing
If Me.BackupDataSetBeforeUpdate Then
backupDataSet = New Global.System.Data.DataSet()
backupDataSet.Merge(dataSet)
End If
Try
'---- Prepare for update -----------
'
If (Not (Me._userDbTableAdapter) Is Nothing) Then
revertConnections.Add(Me._userDbTableAdapter, Me._userDbTableAdapter.Connection)
Me._userDbTableAdapter.Connection = CType(workConnection,Global.System.Data.OleDb.OleDbConnection)
Me._userDbTableAdapter.Transaction = CType(workTransaction,Global.System.Data.OleDb.OleDbTransaction)
If Me._userDbTableAdapter.Adapter.AcceptChangesDuringUpdate Then
Me._userDbTableAdapter.Adapter.AcceptChangesDuringUpdate = false
adaptersWithAcceptChangesDuringUpdate.Add(Me._userDbTableAdapter.Adapter)
End If
End If
'
'---- Perform updates -----------
'
If (Me.UpdateOrder = UpdateOrderOption.UpdateInsertDelete) Then
result = (result + Me.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows))
result = (result + Me.UpdateInsertedRows(dataSet, allAddedRows))
Else
result = (result + Me.UpdateInsertedRows(dataSet, allAddedRows))
result = (result + Me.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows))
End If
result = (result + Me.UpdateDeletedRows(dataSet, allChangedRows))
'
'---- Commit updates -----------
'
workTransaction.Commit
If (0 < allAddedRows.Count) Then
Dim rows((allAddedRows.Count) - 1) As Global.System.Data.DataRow
allAddedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
i = (i + 1)
Loop
End If
If (0 < allChangedRows.Count) Then
Dim rows((allChangedRows.Count) - 1) As Global.System.Data.DataRow
allChangedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
i = (i + 1)
Loop
End If
Catch ex As Global.System.Exception
workTransaction.Rollback
'---- Restore the dataset -----------
If Me.BackupDataSetBeforeUpdate Then
Global.System.Diagnostics.Debug.Assert((Not (backupDataSet) Is Nothing))
dataSet.Clear
dataSet.Merge(backupDataSet)
Else
If (0 < allAddedRows.Count) Then
Dim rows((allAddedRows.Count) - 1) As Global.System.Data.DataRow
allAddedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
row.SetAdded
i = (i + 1)
Loop
End If
End If
Throw ex
Finally
If workConnOpened Then
workConnection.Close
End If
If (Not (Me._userDbTableAdapter) Is Nothing) Then
Me._userDbTableAdapter.Connection = CType(revertConnections(Me._userDbTableAdapter),Global.System.Data.OleDb.OleDbConnection)
Me._userDbTableAdapter.Transaction = Nothing
End If
If (0 < adaptersWithAcceptChangesDuringUpdate.Count) Then
Dim adapters((adaptersWithAcceptChangesDuringUpdate.Count) - 1) As Global.System.Data.Common.DataAdapter
adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters)
Dim i As Integer = 0
Do While (i < adapters.Length)
Dim adapter As Global.System.Data.Common.DataAdapter = adapters(i)
adapter.AcceptChangesDuringUpdate = true
i = (i + 1)
Loop
End If
End Try
Return result
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overridable Sub SortSelfReferenceRows(ByVal rows() As Global.System.Data.DataRow, ByVal relation As Global.System.Data.DataRelation, ByVal childFirst As Boolean)
Global.System.Array.Sort(Of Global.System.Data.DataRow)(rows, New SelfReferenceComparer(relation, childFirst))
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overridable Function MatchTableAdapterConnection(ByVal inputConnection As Global.System.Data.IDbConnection) As Boolean
If (Not (Me._connection) Is Nothing) Then
Return true
End If
If ((Me.Connection Is Nothing) _
OrElse (inputConnection Is Nothing)) Then
Return true
End If
If String.Equals(Me.Connection.ConnectionString, inputConnection.ConnectionString, Global.System.StringComparison.Ordinal) Then
Return true
End If
Return false
End Function
'''<summary>
'''Update Order Option
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Enum UpdateOrderOption
InsertUpdateDelete = 0
UpdateInsertDelete = 1
End Enum
'''<summary>
'''Used to sort self-referenced table's rows
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Class SelfReferenceComparer
Inherits Object
Implements Global.System.Collections.Generic.IComparer(Of Global.System.Data.DataRow)
Private _relation As Global.System.Data.DataRelation
Private _childFirst As Integer
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal relation As Global.System.Data.DataRelation, ByVal childFirst As Boolean)
MyBase.New
Me._relation = relation
If childFirst Then
Me._childFirst = -1
Else
Me._childFirst = 1
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function GetRoot(ByVal row As Global.System.Data.DataRow, ByRef distance As Integer) As Global.System.Data.DataRow
Global.System.Diagnostics.Debug.Assert((Not (row) Is Nothing))
Dim root As Global.System.Data.DataRow = row
distance = 0
Dim traversedRows As Global.System.Collections.Generic.IDictionary(Of Global.System.Data.DataRow, Global.System.Data.DataRow) = New Global.System.Collections.Generic.Dictionary(Of Global.System.Data.DataRow, Global.System.Data.DataRow)()
traversedRows(row) = row
Dim parent As Global.System.Data.DataRow = row.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.[Default])
Do While ((Not (parent) Is Nothing) _
AndAlso (traversedRows.ContainsKey(parent) = false))
distance = (distance + 1)
root = parent
traversedRows(parent) = parent
parent = parent.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.[Default])
Loop
If (distance = 0) Then
traversedRows.Clear
traversedRows(row) = row
parent = row.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.Original)
Do While ((Not (parent) Is Nothing) _
AndAlso (traversedRows.ContainsKey(parent) = false))
distance = (distance + 1)
root = parent
traversedRows(parent) = parent
parent = parent.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.Original)
Loop
End If
Return root
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function Compare(ByVal row1 As Global.System.Data.DataRow, ByVal row2 As Global.System.Data.DataRow) As Integer Implements Global.System.Collections.Generic.IComparer(Of Global.System.Data.DataRow).Compare
If Object.ReferenceEquals(row1, row2) Then
Return 0
End If
If (row1 Is Nothing) Then
Return -1
End If
If (row2 Is Nothing) Then
Return 1
End If
Dim distance1 As Integer = 0
Dim root1 As Global.System.Data.DataRow = Me.GetRoot(row1, distance1)
Dim distance2 As Integer = 0
Dim root2 As Global.System.Data.DataRow = Me.GetRoot(row2, distance2)
If Object.ReferenceEquals(root1, root2) Then
Return (Me._childFirst * distance1.CompareTo(distance2))
Else
Global.System.Diagnostics.Debug.Assert(((Not (root1.Table) Is Nothing) _
AndAlso (Not (root2.Table) Is Nothing)))
If (root1.Table.Rows.IndexOf(root1) < root2.Table.Rows.IndexOf(root2)) Then
Return -1
Else
Return 1
End If
End If
End Function
End Class
End Class
End Namespace
|
sddhscathletics/Solution
|
main/main/login.Designer.vb
|
Visual Basic
|
mit
| 86,209
|
Imports System.Collections.ObjectModel
Public Class ObserverCollection(Of T)
Inherits ObservableCollection(Of T)
Implements IObserver(Of T)
Public Sub OnCompleted() Implements System.IObserver(Of T).OnCompleted
End Sub
Public Sub OnError(ByVal [error] As System.Exception) Implements System.IObserver(Of T).OnError
End Sub
Public Sub OnNext(ByVal value As T) Implements System.IObserver(Of T).OnNext
Me.Add(value)
End Sub
End Class
|
jwooley/RxSamples
|
ObservableSensor/ObservableClient/ObserverCollection.vb
|
Visual Basic
|
mit
| 482
|
Namespace Security.SystemOptions_FileAccess
Public Class Open
Inherits SecurityItemBase
Public Sub New()
_ConceptItemName = "Open"
_ConceptName = "System Options_File Access"
_Description = "Allow access to 'File Access'"
_IsEnterprise = True
_IsSmallBusiness = True
_IsViewer = False
_IsWeb = False
_IsWebPlus = False
End Sub
End Class
End Namespace
|
nublet/DMS
|
DMS.Forms.Shared/Security/Items/SystemOptions/FileAccess/Open.vb
|
Visual Basic
|
mit
| 488
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.17929
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.VBUpdateMeetingAttendee.My.MySettings
Get
Return Global.VBUpdateMeetingAttendee.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBUpdateMeetingAttendee/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,936
|
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("Tests.VisualBasic")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("Tests.VisualBasic")>
<Assembly: AssemblyCopyright("Copyright © 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("07a70e3b-5a02-43d1-909b-6f02e67083b9")>
' 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")>
|
ptrelford/Foq
|
Tests/Tests.VisualBasic/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,187
|
Imports System.Runtime.Serialization
Imports System.ComponentModel
Public MustInherit Class SectionItem
Inherits GenericObject
Implements ISerializable
#Region "Properties"
Friend _mainText As New Dictionary(Of Integer, String)
Friend _parent As GenericObject = Nothing
Friend _number As String = Nothing
' Main text Property.
<CategoryAttribute("(Main)"), _
DisplayName("Main Text"), _
DefaultValueAttribute(""), _
DescriptionAttribute("The question to be displayed."), _
EditorAttribute(GetType(MultiLanguageEditor), GetType(System.Drawing.Design.UITypeEditor))> _
Public Property MainText() As String
Get
If _mainText.ContainsKey(BO.ContextClass.CurrentLanguage.LanguageID) Then
Return _mainText(BO.ContextClass.CurrentLanguage.LanguageID)
Else
Return ""
End If
End Get
Set(ByVal value As String)
If value IsNot Nothing Then value = value.Trim
_mainText.Item(BO.ContextClass.CurrentLanguage.LanguageID) = value
End Set
End Property
' Main Text Dictionary Property.
<Browsable(False)> _
Public Property MainTextDictionary() As Dictionary(Of Integer, String)
Get
Return _mainText
End Get
Set(ByVal value As Dictionary(Of Integer, String))
_mainText = value
End Set
End Property
' Number Property.
<BrowsableAttribute(False)> _
Public Property Number() As String
Get
Return _number
End Get
Set(ByVal value As String)
_number = value
End Set
End Property
<BrowsableAttribute(False)> _
Public Shadows Property DataTableName() As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
<BrowsableAttribute(False)> _
Public Shadows Property LogTableName() As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
<BrowsableAttribute(False)> _
Public Shadows Property PDADataTableName() As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
<[ReadOnly](True), _
CategoryAttribute("System Information")> _
Public ReadOnly Property SectionID() As Integer
Get
Dim obj As GenericObject = Me
While obj IsNot Nothing
If obj.GetType.Equals(GetType(BO.Section)) Then
Return obj.DataBaseID
Else
obj = obj.Parent
End If
End While
End Get
End Property
<[ReadOnly](True), _
CategoryAttribute("System Information")> _
Public ReadOnly Property QuestionnaireID() As Integer
Get
Dim obj As GenericObject = Me
While obj IsNot Nothing
If obj.GetType.Equals(GetType(BO.Questionnaire)) Then
Return obj.DataBaseID
Else
obj = obj.Parent
End If
End While
End Get
End Property
<[ReadOnly](True), _
CategoryAttribute("System Information")> _
Public ReadOnly Property QuestionnaireSetID() As Integer
Get
Dim obj As GenericObject = Me
While obj IsNot Nothing
If obj.GetType.Equals(GetType(BO.QuestionnaireSet)) Then
Return obj.DataBaseID
Else
obj = obj.Parent
End If
End While
End Get
End Property
#End Region
#Region "Functions"
Public Overrides Function ToString() As String
If Me.GetType.Equals(GetType(BO.Question)) Then
Return String.Format("{0}) {1} {2}", _number, CType(Me, BO.Question).GroupText, MainText.Replace(vbCrLf, ""))
Else
Return String.Format("{0}) {1}", _number, MainText.Replace(vbCrLf, ""))
End If
End Function
Public Sub New()
Me.DataBaseID = Nothing
End Sub
Public Function GetMainTextDictionary() As Dictionary(Of Integer, String)
Return Me._mainText
End Function
Public Sub SetMainTextDictionary(ByVal dictionary As Dictionary(Of Integer, String))
Me._mainText = dictionary
End Sub
#End Region
Public Overrides Function Difference(ByVal genericObject As GenericObject) As GenericObject
End Function
Public Overrides ReadOnly Property HasSectionItems() As Boolean
Get
End Get
End Property
Public Overrides ReadOnly Property HasVariables() As Boolean
Get
End Get
End Property
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
End Sub
Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) Implements ISerializable.GetObjectData
End Sub
End Class
|
QMDevTeam/QMDesigner
|
BO/BO classes/SectionItem.vb
|
Visual Basic
|
apache-2.0
| 5,074
|
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("VB")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("VB")>
<Assembly: AssemblyCopyright("Copyright © 2007")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("31c1bc59-917e-4a04-815e-7faa88e2b41c")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
wschult23/LOOM.NET
|
Deploy/RapierLoom.Examples/16-Visitor/VB/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,122
|
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Imports System.IO
Imports System.Xml
Imports AnimatGuiCtrls.Controls
Imports AnimatGUI.Framework
Namespace DataObjects.Behavior.Nodes
Public Class OffPage
Inherits Behavior.Node
#Region " Attributes "
Protected m_thLinkedNode As TypeHelpers.LinkedNode
'Only used during loading
Protected m_strLinkedNodeID As String = ""
#End Region
#Region " Properties "
Public Overrides ReadOnly Property TypeName() As String
Get
Return "OffPage Connector"
End Get
End Property
Public Overridable Property LinkedNode() As TypeHelpers.LinkedNode
Get
Return m_thLinkedNode
End Get
Set(ByVal Value As TypeHelpers.LinkedNode)
Dim thPrevLinked As TypeHelpers.LinkedNode = m_thLinkedNode
RemoveLinkages(thPrevLinked, Value)
DisconnectLinkedNodeEvents()
m_thLinkedNode = Value
ReaddLinkages(thPrevLinked, Value)
ConnectLinkedNodeEvents()
SetDataType()
End Set
End Property
Public Overrides Property Organism As Physical.Organism
Get
Return MyBase.Organism
End Get
Set(ByVal value As Physical.Organism)
MyBase.Organism = value
If Not Me.Organism Is Nothing Then
m_thLinkedNode = New TypeHelpers.LinkedNode(Me.Organism, Nothing)
End If
End Set
End Property
Public Overrides ReadOnly Property NeuralModuleType() As System.Type
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property WorkspaceImageName() As String
Get
Return "AnimatGUI.OffPageConnector.gif"
End Get
End Property
#End Region
#Region " Methods "
Public Sub New(ByVal doParent As Framework.DataObject)
MyBase.New(doParent)
Try
m_thLinkedNode = New TypeHelpers.LinkedNode(Nothing, Nothing)
Shape = Behavior.Node.enumShape.OffPageConnection
Size = New SizeF(40, 40)
Me.DrawColor = Color.Black
Me.FillColor = Color.Gold
Dim myAssembly As System.Reflection.Assembly
myAssembly = System.Reflection.Assembly.Load("AnimatGUI")
Me.WorkspaceImage = AnimatGUI.Framework.ImageManager.LoadImage(myAssembly, "AnimatGUI.OffPageConnector.gif")
Me.Name = "Off Page Connector"
Me.Font = New Font("Arial", 12, FontStyle.Bold)
Me.Description = "This item allows you to connect nodes on one diagram to nodes that reside on a different diagram."
Catch ex As System.Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
Public Overrides Function Clone(ByVal doParent As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject) As AnimatGUI.Framework.DataObject
Dim oNewNode As New Behavior.Nodes.OffPage(doParent)
oNewNode.CloneInternal(Me, bCutData, doRoot)
If Not doRoot Is Nothing AndAlso doRoot Is Me Then oNewNode.AfterClone(Me, bCutData, doRoot, oNewNode)
Return oNewNode
End Function
Protected Overrides Sub CloneInternal(ByVal doOriginal As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject)
MyBase.CloneInternal(doOriginal, bCutData, doRoot)
Dim bnOrig As Behavior.Nodes.OffPage = DirectCast(doOriginal, Behavior.Nodes.OffPage)
bnOrig.m_thLinkedNode = DirectCast(m_thLinkedNode.Clone(Me, bCutData, doRoot), TypeHelpers.LinkedNode)
End Sub
'We do not want offpage connectors to show up in the node tree view drop down.
Public Overrides Sub CreateNodeTreeView(ByRef tvTree As Crownwood.DotNetMagic.Controls.TreeControl, ByVal aryNodes As Crownwood.DotNetMagic.Controls.NodeCollection)
End Sub
Public Overrides Sub DoubleClicked()
If Not m_thLinkedNode Is Nothing AndAlso Not m_thLinkedNode.Node Is Nothing Then
If Not m_thLinkedNode.Node.ParentDiagram Is Nothing AndAlso Not m_thLinkedNode.Node.ParentDiagram.TabPage Is Nothing Then
m_thLinkedNode.Node.ParentDiagram.TabPage.Selected = True
End If
m_thLinkedNode.Node.SelectItem(False)
End If
End Sub
Public Overrides Sub CheckForErrors()
MyBase.CheckForErrors()
If Util.Application.ProjectErrors Is Nothing Then Return
If m_thLinkedNode Is Nothing OrElse m_thLinkedNode.Node Is Nothing Then
If Not Util.Application.ProjectErrors.Errors.Contains(DiagramErrors.DataError.GenerateID(Me, DiagramError.enumErrorTypes.NodeNotSet)) Then
Dim deError As New DiagramErrors.DataError(Me, DiagramError.enumErrorLevel.Error, DiagramError.enumErrorTypes.NodeNotSet, _
"The offpage connector '" & Me.Text & "' has not been linked to another node. ")
Util.Application.ProjectErrors.Errors.Add(deError.ID, deError)
End If
Else
If Util.Application.ProjectErrors.Errors.Contains(DiagramErrors.DataError.GenerateID(Me, DiagramError.enumErrorTypes.NodeNotSet)) Then
Util.Application.ProjectErrors.Errors.Remove(DiagramErrors.DataError.GenerateID(Me, DiagramError.enumErrorTypes.NodeNotSet))
End If
End If
End Sub
Public Overrides Sub CheckCanAttachAdapter()
'Only allow an adapter if we have a linked body part.
If Not (Not m_thLinkedNode Is Nothing AndAlso Not m_thLinkedNode.Node Is Nothing) Then
Throw New System.Exception("You must specify a linked node before you can add an adapter to this node.")
End If
End Sub
Public Overrides Function NeedToUpdateAdapterID(ByVal propInfo As System.Reflection.PropertyInfo) As Boolean
If propInfo.Name = "LinkedNode" Then
Return True
End If
End Function
Public Overrides Function CreateDataItemTreeView(ByVal frmDataItem As Forms.Tools.SelectDataItem, ByVal tnParent As Crownwood.DotNetMagic.Controls.Node, ByVal tpTemplatePartType As Type) As Crownwood.DotNetMagic.Controls.Node
End Function
Protected Overridable Sub RemoveLinkages(ByVal thOldLink As TypeHelpers.LinkedNode, ByVal thNewLink As TypeHelpers.LinkedNode)
'If the user changes the item this node is linked to directly in the diagram after it
'has already been connected up then we need to change the inlink/outlinks for all nodes
'connected to this one.
Dim aryRemoveLinks As New ArrayList
Dim doNewNode As Behavior.Node = Nothing
If Not thNewLink Is Nothing Then
doNewNode = thNewLink.Node
End If
If Not thOldLink Is Nothing AndAlso Not thOldLink.Node Is Nothing AndAlso Not doNewNode Is thOldLink.Node Then
'switch the inlinks from the prev node to the new one
Dim bdLink As AnimatGUI.DataObjects.Behavior.Link
For Each deEntry As DictionaryEntry In Me.InLinks
bdLink = DirectCast(deEntry.Value, AnimatGUI.DataObjects.Behavior.Link)
If bdLink.IsLinkCompatibleWithNodes(bdLink.Origin, doNewNode) Then
If thOldLink.Node.InLinks.Contains(bdLink.ID) Then thOldLink.Node.RemoveInLink(bdLink)
If Not thNewLink.Node.InLinks.Contains(bdLink.ID) Then thNewLink.Node.AddInLink(bdLink)
bdLink.RemoveFromSim(True)
Else
aryRemoveLinks.Add(bdLink)
End If
Next
'switch the outlinks from the prev node to the new one
For Each deEntry As DictionaryEntry In Me.OutLinks
bdLink = DirectCast(deEntry.Value, AnimatGUI.DataObjects.Behavior.Link)
If bdLink.IsLinkCompatibleWithNodes(doNewNode, bdLink.Destination) Then
If thOldLink.Node.OutLinks.Contains(bdLink.ID) Then thOldLink.Node.RemoveOutLink(bdLink)
If Not thNewLink.Node.OutLinks.Contains(bdLink.ID) Then thNewLink.Node.AddOutLink(bdLink)
bdLink.RemoveFromSim(True)
Else
aryRemoveLinks.Add(bdLink)
End If
Next
End If
For Each bdLink As AnimatGUI.DataObjects.Behavior.Link In aryRemoveLinks
bdLink.Delete(False)
Next
End Sub
Protected Overridable Sub ReaddLinkages(ByVal thOldLink As TypeHelpers.LinkedNode, ByVal thNewLink As TypeHelpers.LinkedNode)
If Not thNewLink Is Nothing AndAlso Not thNewLink.Node Is Nothing _
AndAlso Not thOldLink Is Nothing AndAlso Not thOldLink.Node Is Nothing _
AndAlso Not thNewLink.Node Is thOldLink.Node Then
'switch the inlinks from the prev node to the new one
Dim bdLink As AnimatGUI.DataObjects.Behavior.Link
For Each deEntry As DictionaryEntry In Me.InLinks
bdLink = DirectCast(deEntry.Value, AnimatGUI.DataObjects.Behavior.Link)
bdLink.ActualDestination = Me
bdLink.RemoveWorksapceTreeView()
bdLink.AddWorkspaceTreeNode()
bdLink.AddToSim(True)
Next
'switch the outlinks from the prev node to the new one
For Each deEntry As DictionaryEntry In Me.OutLinks
bdLink = DirectCast(deEntry.Value, AnimatGUI.DataObjects.Behavior.Link)
bdLink.ActualOrigin = Me
bdLink.RemoveWorksapceTreeView()
bdLink.AddWorkspaceTreeNode()
bdLink.AddToSim(True)
Next
End If
End Sub
Protected Sub SetDataType()
If Not m_thLinkedNode.Node Is Nothing AndAlso Not m_thLinkedNode.Node.DataTypes Is Nothing Then
m_thDataTypes = DirectCast(m_thLinkedNode.Node.DataTypes.Clone(m_thLinkedNode.Node.DataTypes.Parent, False, Nothing), TypeHelpers.DataTypeID)
'Go through and change all of the adapters connected to this body part.
For Each deItem As System.Collections.DictionaryEntry In Me.m_aryOutLinks
If Util.IsTypeOf(deItem.Value.GetType(), GetType(AnimatGUI.DataObjects.Behavior.Links.Adapter), False) Then
Dim blAdapter As AnimatGUI.DataObjects.Behavior.Links.Adapter = DirectCast(deItem.Value, AnimatGUI.DataObjects.Behavior.Links.Adapter)
If Not blAdapter.Destination Is Nothing Then
blAdapter.Destination.DataTypes = DirectCast(m_thDataTypes.Clone(blAdapter.Destination, False, Nothing), TypeHelpers.DataTypeID)
End If
End If
Next
Else
m_thDataTypes = New AnimatGUI.TypeHelpers.DataTypeID(Me)
End If
CheckForErrors()
End Sub
Protected Sub ConnectLinkedNodeEvents()
DisconnectLinkedNodeEvents()
If Not m_thLinkedNode Is Nothing AndAlso Not m_thLinkedNode.Node Is Nothing Then
Me.Text = m_thLinkedNode.Node.Text
AddHandler m_thLinkedNode.Node.AfterRemoveItem, AddressOf Me.OnAfterRemoveLinkedNode
End If
End Sub
Protected Sub DisconnectLinkedNodeEvents()
If Not m_thLinkedNode Is Nothing AndAlso Not m_thLinkedNode.Node Is Nothing Then
RemoveHandler m_thLinkedNode.Node.AfterRemoveItem, AddressOf Me.OnAfterRemoveLinkedNode
End If
End Sub
Public Overrides Sub Automation_SetLinkedItem(ByVal strItemPath As String, ByVal strLinkedItemPath As String)
Dim tnLinkedNode As Crownwood.DotNetMagic.Controls.Node = Util.FindTreeNodeByPath(strLinkedItemPath, Util.ProjectWorkspace.TreeView.Nodes)
If tnLinkedNode Is Nothing OrElse tnLinkedNode.Tag Is Nothing OrElse Not Util.IsTypeOf(tnLinkedNode.Tag.GetType, GetType(DataObjects.Behavior.Node), False) Then
Throw New System.Exception("The path to the specified linked node was not the correct node type.")
End If
Dim bnLinkedNode As DataObjects.Behavior.Node = DirectCast(tnLinkedNode.Tag, DataObjects.Behavior.Node)
Dim lnNode As New TypeHelpers.LinkedNode(bnLinkedNode.Organism, bnLinkedNode)
Dim strOriginalName As String = Me.Name
Me.LinkedNode = lnNode
'Reset the original name while doing automation tests so that each object can maintain a unique name.
Me.Name = strOriginalName
Util.ProjectWorkspace.RefreshProperties()
End Sub
#Region " DataObject Methods "
Public Overrides Sub BuildProperties(ByRef propTable As AnimatGuiCtrls.Controls.PropertyTable)
MyBase.BuildProperties(propTable)
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Linked Node", GetType(AnimatGUI.TypeHelpers.LinkedNode), "LinkedNode", _
"Node Properties", "Sets the node that this associated with this connector.", m_thLinkedNode, _
GetType(AnimatGUI.TypeHelpers.DropDownTreeEditor), _
GetType(AnimatGUI.TypeHelpers.LinkedNodeTypeConverter)))
End Sub
Public Overrides Sub ClearIsDirty()
MyBase.ClearIsDirty()
If Not m_thLinkedNode Is Nothing Then m_thLinkedNode.ClearIsDirty()
End Sub
Public Overrides Sub LoadData(ByVal oXml As ManagedAnimatInterfaces.IStdXml)
MyBase.LoadData(oXml)
oXml.IntoElem()
m_strLinkedNodeID = Util.LoadID(oXml, "LinkedNode", True, "")
'm_strLinkedDiagramID = Util.LoadID(oXml, "LinkedDiagram", True, "")
oXml.OutOfElem()
End Sub
Public Overrides Sub InitializeAfterLoad()
If m_strLinkedNodeID.Trim.Length > 0 Then
Dim bnNode As Behavior.Node = Me.Organism.FindBehavioralNode(m_strLinkedNodeID, False)
If Not bnNode Is Nothing Then
Me.LinkedNode = New TypeHelpers.LinkedNode(bnNode.Organism, bnNode)
Else
Util.Application.DeleteItemAfterLoading(Me)
Util.DisplayError(New System.Exception("The offpage connector ID: " & Me.ID & " was unable to find its linked node ID: " & m_strLinkedNodeID & " in the diagram. This node and all links will be removed."))
End If
End If
ConnectLinkedNodeEvents()
m_bIsInitialized = True
End Sub
''' \brief Initializes the simulation references.
'''
''' \details The offpage connector does not have a corresponding part in the simulation, so we need to skip this method
''' for this object.
'''
''' \author dcofer
''' \date 9/7/2011
Public Overrides Sub InitializeSimulationReferences(Optional ByVal bShowError As Boolean = True)
End Sub
Public Overrides Sub SaveData(ByVal oXml As ManagedAnimatInterfaces.IStdXml)
MyBase.SaveData(oXml)
oXml.IntoElem() 'Into Node Element
If Not m_thLinkedNode Is Nothing AndAlso Not m_thLinkedNode.Node Is Nothing Then
'oXml.AddChildElement("LinkedDiagramID", m_thLinkedNode.Node.ParentDiagram.ID)
oXml.AddChildElement("LinkedNodeID", m_thLinkedNode.Node.ID)
End If
oXml.OutOfElem() ' Outof Node Element
End Sub
Public Overrides Sub AddInLink(ByRef blLink As Behavior.Link)
MyBase.AddInLink(blLink)
If Not Me.LinkedNode Is Nothing AndAlso Not Me.LinkedNode.Node Is Nothing Then
Me.LinkedNode.Node.AddInLink(blLink)
End If
End Sub
Public Overrides Sub RemoveInLink(ByRef blLink As Behavior.Link)
MyBase.RemoveInLink(blLink)
If Not Me.LinkedNode Is Nothing AndAlso Not Me.LinkedNode.Node Is Nothing Then
Me.LinkedNode.Node.RemoveInLink(blLink)
End If
End Sub
Public Overrides Sub AddOutLink(ByRef blLink As Behavior.Link)
MyBase.AddOutLink(blLink)
If Not Me.LinkedNode Is Nothing AndAlso Not Me.LinkedNode.Node Is Nothing Then
Me.LinkedNode.Node.AddOutLink(blLink)
End If
End Sub
Public Overrides Sub RemoveOutLink(ByRef blLink As Behavior.Link)
MyBase.RemoveOutLink(blLink)
If Not Me.LinkedNode Is Nothing AndAlso Not Me.LinkedNode.Node Is Nothing Then
Me.LinkedNode.Node.RemoveOutLink(blLink)
End If
End Sub
#End Region
#End Region
#Region "Events"
Private Sub OnAfterRemoveLinkedNode(ByRef doObject As Framework.DataObject)
Try
Me.LinkedNode = New TypeHelpers.LinkedNode(Me.ParentSubsystem.Organism, Nothing)
Catch ex As Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
Protected Overrides Sub OnBeforeParentRemoveFromList(ByRef doObject As AnimatGUI.Framework.DataObject)
Try
DisconnectLinkedNodeEvents()
MyBase.OnBeforeParentRemoveFromList(doObject)
Catch ex As Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
#End Region
End Class
End Namespace
|
NeuroRoboticTech/AnimatLabPublicSource
|
Libraries/AnimatGUI/DataObjects/Behavior/Nodes/OffPage.vb
|
Visual Basic
|
bsd-3-clause
| 19,022
|
'
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2018
' 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.Web
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Reflection
Imports System.Globalization
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Imports DotNetNuke.Web.Client
Imports DotNetNuke.Web.Client.ClientResourceManagement
Namespace DotNetNuke.UI.Utilities
''' -----------------------------------------------------------------------------
''' Project : DotNetNuke
''' Class : ClientAPI
''' -----------------------------------------------------------------------------
''' <summary>
''' Library responsible for interacting with DNN Client API.
''' </summary>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Class ClientAPI
#Region "Public Constants"
Public Const SCRIPT_CALLBACKID As String = "__DNNCAPISCI"
Public Const SCRIPT_CALLBACKTYPE As String = "__DNNCAPISCT"
Public Const SCRIPT_CALLBACKPARAM As String = "__DNNCAPISCP"
Public Const SCRIPT_CALLBACKPAGEID As String = "__DNNCAPISCPAGEID"
Public Const SCRIPT_CALLBACKSTATUSID As String = "__DNNCAPISCSI"
Public Const SCRIPT_CALLBACKSTATUSDESCID As String = "__DNNCAPISCSDI"
Public Const DNNVARIABLE_CONTROLID As String = "__dnnVariable"
#End Region
#Region "Public Enums"
Public Enum ClientFunctionality As Integer
DHTML = CInt(2 ^ 0)
XML = CInt(2 ^ 1)
XSLT = CInt(2 ^ 2)
Positioning = CInt(2 ^ 3) 'what we would call adaquate positioning support
XMLJS = CInt(2 ^ 4)
XMLHTTP = CInt(2 ^ 5)
XMLHTTPJS = CInt(2 ^ 6)
SingleCharDelimiters = CInt(2 ^ 7)
UseExternalScripts = CInt(2 ^ 8)
Motion = CInt(2 ^ 9)
End Enum
''' -----------------------------------------------------------------------------
''' <summary>
''' Enumerates each namespace with a seperate js file
''' </summary>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Enum ClientNamespaceReferences As Integer
dnn
dnn_dom
dnn_dom_positioning
dnn_xml
dnn_xmlhttp
dnn_motion
End Enum
#End Region
#Region "Private Shared Members"
''' -----------------------------------------------------------------------------
''' <summary>Private variable holding location of client side js files. Shared by entire application.</summary>
''' -----------------------------------------------------------------------------
Private Shared m_sScriptPath As String
Private Shared m_ClientAPIDisabled As String = String.Empty
#End Region
#Region "Private Shared Properties"
''' -----------------------------------------------------------------------------
''' <summary>
''' Finds __dnnVariable control on page, if not found it attempts to add its own.
''' </summary>
''' <param name="objPage">Current page rendering content</param>
''' <value></value>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Private Shared ReadOnly Property ClientVariableControl(ByVal objPage As Page) As HtmlInputHidden
Get
Return RegisterDNNVariableControl(objPage)
End Get
End Property
''' -----------------------------------------------------------------------------
''' <summary>
''' Loop up parent controls to find form
''' </summary>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 2/2/2006 Commented
''' </history>
''' -----------------------------------------------------------------------------
Private Shared Function FindForm(ByVal oCtl As Control) As Control
Return oCtl.Page.Form
'Do While Not TypeOf oCtl Is HtmlControls.HtmlForm
' If oCtl Is Nothing OrElse TypeOf oCtl Is Page Then Return Nothing
' oCtl = oCtl.Parent
'Loop
'Return oCtl
End Function
''' -----------------------------------------------------------------------------
''' <summary>
''' Returns __dnnVariable control if present
''' </summary>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 4/6/2005 Commented
''' </history>
''' -----------------------------------------------------------------------------
Private Shared Function GetDNNVariableControl(ByVal objParent As Control) As HtmlInputHidden
Return CType(DotNetNuke.UI.Utilities.Globals.FindControlRecursive(objParent.Page, DNNVARIABLE_CONTROLID), System.Web.UI.HtmlControls.HtmlInputHidden)
End Function
#End Region
#Region "Public Shared Properties"
''' -----------------------------------------------------------------------------
''' <summary>Character used for delimiting name from value</summary>
''' -----------------------------------------------------------------------------
Public Shared ReadOnly Property COLUMN_DELIMITER() As String
Get
If BrowserSupportsFunctionality(ClientFunctionality.SingleCharDelimiters) Then
Return Chr(18)
Else
Return "~|~"
End If
End Get
End Property
''' -----------------------------------------------------------------------------
''' <summary>Character used for delimiting name from value</summary>
''' -----------------------------------------------------------------------------
Public Shared ReadOnly Property CUSTOM_COLUMN_DELIMITER() As String
Get
If BrowserSupportsFunctionality(ClientFunctionality.SingleCharDelimiters) Then
Return Chr(16)
Else
Return "~.~"
End If
End Get
End Property
''' -----------------------------------------------------------------------------
''' <summary>Character used for delimiting name/value pairs</summary>
''' -----------------------------------------------------------------------------
Public Shared ReadOnly Property CUSTOM_ROW_DELIMITER() As String
Get
If BrowserSupportsFunctionality(ClientFunctionality.SingleCharDelimiters) Then
Return Chr(15)
Else
Return "~,~"
End If
End Get
End Property
''' -----------------------------------------------------------------------------
''' <summary>In order to reduce payload, substitute out " with different char, since when put in a hidden control it uses "</summary>
''' -----------------------------------------------------------------------------
Public Shared ReadOnly Property QUOTE_REPLACEMENT() As String
Get
If BrowserSupportsFunctionality(ClientFunctionality.SingleCharDelimiters) Then
Return Chr(19)
Else
Return "~!~"
End If
End Get
End Property
''' -----------------------------------------------------------------------------
''' <summary>Character used for delimiting name/value pairs</summary>
''' -----------------------------------------------------------------------------
Public Shared ReadOnly Property ROW_DELIMITER() As String
Get
If BrowserSupportsFunctionality(ClientFunctionality.SingleCharDelimiters) Then
Return Chr(17)
Else
Return "~`~"
End If
End Get
End Property
''' -----------------------------------------------------------------------------
''' <summary>
''' Path where js files are placed
''' </summary>
''' <value></value>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/19/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Property ScriptPath() As String
Get
Dim script As String = ""
If Len(m_sScriptPath) > 0 Then
script = m_sScriptPath
ElseIf Not System.Web.HttpContext.Current Is Nothing Then
If System.Web.HttpContext.Current.Request.ApplicationPath.EndsWith("/") Then
script = System.Web.HttpContext.Current.Request.ApplicationPath & "js/"
Else
script = System.Web.HttpContext.Current.Request.ApplicationPath & "/js/"
End If
End If
Return script
End Get
Set(ByVal Value As String)
m_sScriptPath = Value
End Set
End Property
Public Shared ReadOnly Property UseExternalScripts() As Boolean
Get
Return BrowserSupportsFunctionality(ClientFunctionality.UseExternalScripts)
End Get
End Property
Public Shared Function EscapeForJavascript(ByVal s As String) As String
Return s.Replace("\", "\\").Replace("'", "\'")
End Function
#End Region
#Region "Private Shared Methods"
Private Shared Sub AddAttribute(ByVal objControl As Control, ByVal strName As String, ByVal strValue As String)
If TypeOf objControl Is HtmlControl Then
CType(objControl, HtmlControl).Attributes.Add(strName, strValue)
ElseIf TypeOf objControl Is WebControl Then
CType(objControl, WebControl).Attributes.Add(strName, strValue)
End If
End Sub
Public Shared Function GetClientVariableList(ByVal objPage As Page) As Generic.Dictionary(Of String, String)
Dim ctlVar As HtmlInputHidden = ClientVariableControl(objPage)
Dim strValue As String = ""
If Not ctlVar Is Nothing Then strValue = ctlVar.Value
If Len(strValue) = 0 Then strValue = System.Web.HttpContext.Current.Request(DNNVARIABLE_CONTROLID) 'using request object in case we are loading before controls have values set
If strValue Is Nothing Then strValue = ""
Dim objDict As Generic.Dictionary(Of String, String) = CType(HttpContext.Current.Items("CAPIVariableList"), Generic.Dictionary(Of String, String))
If objDict Is Nothing Then
'Dim objJSON As Script.Serialization.JavaScriptSerializer = New Script.Serialization.JavaScriptSerializer()
If String.IsNullOrEmpty(strValue) = False Then
Try
'fix serialization issues with invalid json objects
If strValue.IndexOf("`") = 0 Then
strValue = strValue.Substring(1).Replace("`", """")
End If
objDict = MSAJAX.Deserialize(Of Generic.Dictionary(Of String, String))(strValue) 'objJSON.Deserialize(Of Generic.Dictionary(Of String, String))(strValue)
Catch
'ignore error
End Try
End If
If objDict Is Nothing Then
objDict = New Generic.Dictionary(Of String, String)
End If
HttpContext.Current.Items("CAPIVariableList") = objDict
End If
Return objDict
End Function
Public Shared Sub SerializeClientVariableDictionary(ByVal objPage As Page, ByVal objDict As Generic.Dictionary(Of String, String))
Dim ctlVar As HtmlInputHidden = ClientVariableControl(objPage)
ctlVar.Value = MSAJAX.Serialize(objDict)
'minimize payload by using ` for ", which serializes to "
If ctlVar.Value.IndexOf("`") = -1 Then
'prefix the value with ` to denote that we escaped it (it was safe)
ctlVar.Value = "`" & ctlVar.Value.Replace("""", "`")
End If
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Parses DNN Variable control contents and returns out the delimited name/value pair
''' </summary>
''' <param name="objPage">Current page rendering content</param>
''' <param name="strVar">Name to retrieve</param>
''' <returns>Delimited name/value pair string</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Private Shared Function GetClientVariableNameValuePair(ByVal objPage As Page, ByVal strVar As String) As String
Dim objDict As Generic.Dictionary(Of String, String) = GetClientVariableList(objPage)
If objDict.ContainsKey(strVar) Then
Return strVar & COLUMN_DELIMITER & objDict(strVar)
End If
Return ""
End Function
''' -----------------------------------------------------------------------------
''' <summary>
''' Returns javascript to call dnncore.js key handler logic
''' </summary>
''' <param name="intKeyAscii">ASCII value to trap</param>
''' <param name="strJavascript">Javascript to execute</param>
''' <returns>Javascript to handle key press</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 2/17/2005 Created
''' </history>
''' -----------------------------------------------------------------------------
Private Shared Function GetKeyDownHandler(ByVal intKeyAscii As Integer, ByVal strJavascript As String) As String
Return "return __dnn_KeyDown('" & intKeyAscii & "', '" & strJavascript.Replace("'", "%27") & "', event);"
End Function
#End Region
#Region "Public Shared Methods"
''' -----------------------------------------------------------------------------
''' <summary>
''' Common way to handle confirmation prompts on client
''' </summary>
''' <param name="objButton">Button to trap click event</param>
''' <param name="strText">Text to display in confirmation</param>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 2/17/2005 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Sub AddButtonConfirm(ByVal objButton As WebControl, ByVal strText As String)
objButton.Attributes.Add("onClick", "javascript:return confirm('" & GetSafeJSString(strText) & "');")
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Determines of browser currently requesting page adaquately supports passed un client-side functionality
''' </summary>
''' <param name="eFunctionality">Desired Functionality</param>
''' <returns>True when browser supports it</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Function BrowserSupportsFunctionality(ByVal eFunctionality As ClientFunctionality) As Boolean
Try
If System.Web.HttpContext.Current Is Nothing Then Return True
Dim blnSupports As Boolean = False
If ClientAPIDisabled() = False Then
Dim objCaps As BrowserCaps = BrowserCaps.GetBrowserCaps()
If Not objCaps Is Nothing Then
Dim objRequest As HttpRequest = System.Web.HttpContext.Current.Request
Dim strUserAgent As String = objRequest.UserAgent
If Len(strUserAgent) > 0 Then
'First check whether we have checked this browser before
If objCaps.FunctionalityDictionary.ContainsKey(strUserAgent) = False Then
Dim strBrowser As String = objRequest.Browser.Browser
'if no version present, Framework dies, hence need for try
Dim dblVersion As Double = CDbl(objRequest.Browser.MajorVersion + objRequest.Browser.MinorVersion)
Dim iBitValue As Integer = 0
Dim objFuncInfo As FunctionalityInfo = Nothing
'loop through all functionalities for this UserAgent and determine the bitvalue
For Each eFunc As ClientFunctionality In System.Enum.GetValues(GetType(ClientFunctionality))
objFuncInfo = objCaps.Functionality(eFunc)
If Not objFuncInfo Is Nothing AndAlso objFuncInfo.HasMatch(strUserAgent, strBrowser, dblVersion) Then
iBitValue += eFunc
End If
Next
objCaps.FunctionalityDictionary(strUserAgent) = iBitValue
End If
blnSupports = (DirectCast(objCaps.FunctionalityDictionary(strUserAgent), Integer) And eFunctionality) <> 0
End If
End If
End If
Return blnSupports
Catch
'bad user agent (CAP-7321)
End Try
Return False
End Function
Public Shared Function GetCallbackEventReference(ByVal objControl As Control, ByVal strArgument As String, ByVal strClientCallBack As String, ByVal strContext As String, ByVal srtClientErrorCallBack As String) As String
Return GetCallbackEventReference(objControl, strArgument, strClientCallBack, strContext, srtClientErrorCallBack, Nothing, "")
End Function
Public Shared Function GetCallbackEventReference(ByVal objControl As Control, ByVal strArgument As String, ByVal strClientCallBack As String, ByVal strContext As String, ByVal srtClientErrorCallBack As String, ByVal eCallbackType As ClientAPICallBackResponse.CallBackTypeCode) As String
Return GetCallbackEventReference(objControl, strArgument, strClientCallBack, strContext, srtClientErrorCallBack, Nothing, Nothing, eCallbackType)
End Function
Public Shared Function GetCallbackEventReference(ByVal objControl As Control, ByVal strArgument As String, ByVal strClientCallBack As String, ByVal strContext As String, ByVal srtClientErrorCallBack As String, ByVal objPostChildrenOf As Control) As String
Return GetCallbackEventReference(objControl, strArgument, strClientCallBack, strContext, srtClientErrorCallBack, Nothing, objPostChildrenOf.ClientID, ClientAPICallBackResponse.CallBackTypeCode.Simple)
End Function
Public Shared Function GetCallbackEventReference(ByVal objControl As Control, ByVal strArgument As String, ByVal strClientCallBack As String, ByVal strContext As String, ByVal srtClientErrorCallBack As String, ByVal strClientStatusCallBack As String) As String
Return GetCallbackEventReference(objControl, strArgument, strClientCallBack, strContext, srtClientErrorCallBack, strClientStatusCallBack, Nothing, ClientAPICallBackResponse.CallBackTypeCode.Simple)
End Function
Public Shared Function GetCallbackEventReference(ByVal objControl As Control, ByVal strArgument As String, ByVal strClientCallBack As String, ByVal strContext As String, ByVal srtClientErrorCallBack As String, ByVal strClientStatusCallBack As String, ByVal eCallbackType As ClientAPICallBackResponse.CallBackTypeCode) As String
Return GetCallbackEventReference(objControl, strArgument, strClientCallBack, strContext, srtClientErrorCallBack, strClientStatusCallBack, Nothing, eCallbackType)
End Function
Public Shared Function GetCallbackEventReference(ByVal objControl As Control, ByVal strArgument As String, ByVal strClientCallBack As String, ByVal strContext As String, ByVal srtClientErrorCallBack As String, ByVal strClientStatusCallBack As String, ByVal objPostChildrenOf As Control) As String
Return GetCallbackEventReference(objControl, strArgument, strClientCallBack, strContext, srtClientErrorCallBack, strClientStatusCallBack, objPostChildrenOf.ClientID, ClientAPICallBackResponse.CallBackTypeCode.Simple)
End Function
Public Shared Function GetCallbackEventReference(ByVal objControl As Control, ByVal strArgument As String, ByVal strClientCallBack As String, ByVal strContext As String, ByVal srtClientErrorCallBack As String, ByVal strClientStatusCallBack As String, ByVal strPostChildrenOfId As String) As String
Return GetCallbackEventReference(objControl, strArgument, strClientCallBack, strContext, srtClientErrorCallBack, strClientStatusCallBack, strPostChildrenOfId, ClientAPICallBackResponse.CallBackTypeCode.Simple)
End Function
Public Shared Function GetCallbackEventReference(ByVal objControl As Control, ByVal strArgument As String, ByVal strClientCallBack As String, ByVal strContext As String, ByVal srtClientErrorCallBack As String, ByVal strClientStatusCallBack As String, ByVal strPostChildrenOfId As String, ByVal eCallbackType As ClientAPICallBackResponse.CallBackTypeCode) As String
Dim strCallbackType As String = CInt(eCallbackType).ToString
If strArgument Is Nothing Then strArgument = "null"
If strContext Is Nothing Then strContext = "null"
If srtClientErrorCallBack Is Nothing Then srtClientErrorCallBack = "null"
If strClientStatusCallBack Is Nothing Then strClientStatusCallBack = "null"
If Len(strPostChildrenOfId) = 0 Then
strPostChildrenOfId = "null"
ElseIf strPostChildrenOfId.StartsWith("'") = False Then
strPostChildrenOfId = "'" & strPostChildrenOfId & "'"
End If
Dim strControlID As String = objControl.ID
If BrowserSupportsFunctionality(ClientFunctionality.XMLHTTP) AndAlso BrowserSupportsFunctionality(ClientFunctionality.XML) Then
DotNetNuke.UI.Utilities.ClientAPI.RegisterClientReference(objControl.Page, DotNetNuke.UI.Utilities.ClientAPI.ClientNamespaceReferences.dnn_xml)
DotNetNuke.UI.Utilities.ClientAPI.RegisterClientReference(objControl.Page, DotNetNuke.UI.Utilities.ClientAPI.ClientNamespaceReferences.dnn_xmlhttp)
If TypeOf (objControl) Is Page AndAlso Len(strControlID) = 0 Then 'page doesn't usually have an ID so we need to make one up
strControlID = SCRIPT_CALLBACKPAGEID
End If
If TypeOf (objControl) Is Page = False Then
strControlID = strControlID & " " & objControl.ClientID 'ID is not unique (obviously)
End If
Return String.Format("dnn.xmlhttp.doCallBack('{0}',{1},{2},{3},{4},{5},{6},{7},{8});", strControlID, strArgument, strClientCallBack, strContext, srtClientErrorCallBack, strClientStatusCallBack, "null", strPostChildrenOfId, strCallbackType)
Else
Return ""
End If
End Function
''' -----------------------------------------------------------------------------
''' <summary>
''' Retrieves DNN Client Variable value
''' </summary>
''' <param name="objPage">Current page rendering content</param>
''' <param name="strVar">Variable name to retrieve value for</param>
''' <returns>Value of variable</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Function GetClientVariable(ByVal objPage As Page, ByVal strVar As String) As String
Dim strPair As String = GetClientVariableNameValuePair(objPage, strVar)
If strPair.IndexOf(COLUMN_DELIMITER) > -1 Then
Return Split(strPair, COLUMN_DELIMITER)(1)
Else
Return ""
End If
End Function
''' -----------------------------------------------------------------------------
''' <summary>
''' Retrieves DNN Client Variable value
''' </summary>
''' <param name="objPage">Current page rendering content</param>
''' <param name="strVar">Variable name to retrieve value for</param>
''' <param name="strDefaultValue">Default value if variable not found</param>
''' <returns>Value of variable</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Function GetClientVariable(ByVal objPage As Page, ByVal strVar As String, ByVal strDefaultValue As String) As String
Dim strPair As String = GetClientVariableNameValuePair(objPage, strVar)
If strPair.IndexOf(COLUMN_DELIMITER) > -1 Then
Return Split(strPair, COLUMN_DELIMITER)(1)
Else
Return strDefaultValue
End If
End Function
''' -----------------------------------------------------------------------------
''' <summary>
''' Escapes string to be safely used in client side javascript.
''' </summary>
''' <param name="strString">String to escape</param>
''' <returns>Escaped string</returns>
''' <remarks>
''' Currently this only escapes out quotes and apostrophes
''' </remarks>
''' <history>
''' [Jon Henning] 2/17/2005 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Function GetSafeJSString(ByVal strString As String) As String
If String.IsNullOrEmpty(strString) Then
Return String.Empty
End If
Return HttpUtility.JavaScriptStringEncode(strString)
End Function
Public Shared Function IsInCallback(ByVal objPage As Page) As Boolean
Return Len(objPage.Request(SCRIPT_CALLBACKID)) > 0 AndAlso objPage.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)
End Function
Public Shared Sub HandleClientAPICallbackEvent(ByVal objPage As Page)
HandleClientAPICallbackEvent(objPage, GetCallbackType(objPage))
End Sub
Private Shared Function GetCallbackType(ByVal objPage As Page) As ClientAPICallBackResponse.CallBackTypeCode
Dim eType As ClientAPICallBackResponse.CallBackTypeCode = ClientAPICallBackResponse.CallBackTypeCode.Simple
If Len(objPage.Request(SCRIPT_CALLBACKTYPE)) > 0 Then
eType = CType(objPage.Request(SCRIPT_CALLBACKTYPE), ClientAPICallBackResponse.CallBackTypeCode)
End If
Return eType
End Function
Public Shared Sub HandleClientAPICallbackEvent(ByVal objPage As Page, ByVal eType As ClientAPICallBackResponse.CallBackTypeCode)
If IsInCallback(objPage) Then
Select Case eType
Case ClientAPICallBackResponse.CallBackTypeCode.Simple, ClientAPICallBackResponse.CallBackTypeCode.CallbackMethod
Dim arrIDs() As String = objPage.Request(SCRIPT_CALLBACKID).Split(CChar(" "))
Dim strControlID As String = arrIDs(0)
Dim strClientID As String = ""
If arrIDs.Length > 1 Then
strClientID = arrIDs(1)
End If
Dim strParam As String = objPage.Server.UrlDecode(objPage.Request(SCRIPT_CALLBACKPARAM))
Dim objControl As Control
Dim objInterface As IClientAPICallbackEventHandler
Dim objResponse As ClientAPICallBackResponse = New ClientAPICallBackResponse(objPage, ClientAPICallBackResponse.CallBackTypeCode.Simple)
Try
objPage.Response.Clear() 'clear response stream
If strControlID = SCRIPT_CALLBACKPAGEID Then
objControl = objPage
Else
objControl = Globals.FindControlRecursive(objPage, strControlID, strClientID)
End If
If Not objControl Is Nothing Then
If eType = ClientAPICallBackResponse.CallBackTypeCode.CallbackMethod Then
Try
objResponse.Response = ExecuteControlMethod(objControl, strParam)
objResponse.StatusCode = ClientAPICallBackResponse.CallBackResponseStatusCode.OK
Catch ex As Exception
objResponse.StatusCode = ClientAPICallBackResponse.CallBackResponseStatusCode.GenericFailure
objResponse.StatusDesc = ex.Message
End Try
Else
If TypeOf (objControl) Is System.Web.UI.HtmlControls.HtmlForm Then 'form doesn't implement interface, so use page instead
objInterface = CType(objPage, IClientAPICallbackEventHandler)
Else
objInterface = CType(objControl, IClientAPICallbackEventHandler)
End If
If Not objInterface Is Nothing Then
Try
objResponse.Response = objInterface.RaiseClientAPICallbackEvent(strParam)
objResponse.StatusCode = ClientAPICallBackResponse.CallBackResponseStatusCode.OK
Catch ex As Exception
objResponse.StatusCode = ClientAPICallBackResponse.CallBackResponseStatusCode.GenericFailure
objResponse.StatusDesc = ex.Message
End Try
Else
objResponse.StatusCode = ClientAPICallBackResponse.CallBackResponseStatusCode.InterfaceNotSupported
objResponse.StatusDesc = "Interface Not Supported"
End If
End If
Else
objResponse.StatusCode = ClientAPICallBackResponse.CallBackResponseStatusCode.ControlNotFound
objResponse.StatusDesc = "Control Not Found"
End If
Catch ex As Exception
objResponse.StatusCode = ClientAPICallBackResponse.CallBackResponseStatusCode.GenericFailure
objResponse.StatusDesc = "Generic failure" 'ex.Message
Finally
objResponse.Write()
'objPage.Response.Flush()
objPage.Response.End()
End Try
Case ClientAPICallBackResponse.CallBackTypeCode.ProcessPage, ClientAPICallBackResponse.CallBackTypeCode.ProcessPageCallbackMethod
objPage.SetRenderMethodDelegate(AddressOf CallbackRenderMethod)
End Select
End If
End Sub
Private Shared Sub CallbackRenderMethod(ByVal output As System.Web.UI.HtmlTextWriter, ByVal container As System.Web.UI.Control)
Dim objPage As Page = CType(container, Page)
Dim eType As ClientAPICallBackResponse.CallBackTypeCode = GetCallbackType(objPage)
If eType = ClientAPICallBackResponse.CallBackTypeCode.ProcessPage Then
eType = ClientAPICallBackResponse.CallBackTypeCode.Simple
Else
eType = ClientAPICallBackResponse.CallBackTypeCode.CallbackMethod
End If
HandleClientAPICallbackEvent(objPage, eType)
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Determines if DNNVariable control is present in page's control collection
''' </summary>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 4/6/2005 Commented
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Function NeedsDNNVariable(ByVal objParent As Control) As Boolean
Return GetDNNVariableControl(objParent) Is Nothing
End Function
''' -----------------------------------------------------------------------------
''' <summary>
''' Responsible for registering client side js libraries and its dependecies.
''' </summary>
''' <param name="objPage">Current page rendering content</param>
''' <param name="eRef">Enumerator of library to reference</param>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Sub RegisterClientReference(ByVal objPage As Page, ByVal eRef As ClientNamespaceReferences)
Select Case eRef
Case ClientNamespaceReferences.dnn
If Not IsClientScriptBlockRegistered(objPage, "dnn.js") Then
RegisterClientScriptBlock(objPage, "dnn.js", "<script src=""" & ClientAPI.ScriptPath & "dnn.js""></script>")
If BrowserSupportsFunctionality(ClientFunctionality.SingleCharDelimiters) = False Then
RegisterClientVariable(objPage, "__scdoff", "1", True) 'SingleCharDelimiters Off!!!
End If
'allow scripts to be dynamically loaded when use external false
If ClientAPI.UseExternalScripts = False Then
ClientAPI.RegisterEmbeddedResource(objPage, "dnn.scripts.js", GetType(DotNetNuke.UI.Utilities.ClientAPI))
End If
End If
Case ClientNamespaceReferences.dnn_dom
RegisterClientReference(objPage, ClientNamespaceReferences.dnn)
Case ClientNamespaceReferences.dnn_dom_positioning
RegisterClientReference(objPage, ClientNamespaceReferences.dnn)
ClientResourceManager.RegisterScript(objPage, ScriptPath & "dnn.dom.positioning.js")
Case ClientNamespaceReferences.dnn_xml
RegisterClientReference(objPage, ClientNamespaceReferences.dnn)
ClientResourceManager.RegisterScript(objPage, ScriptPath & "dnn.xml.js", FileOrder.Js.DnnXml)
If BrowserSupportsFunctionality(ClientFunctionality.XMLJS) Then
ClientResourceManager.RegisterScript(objPage, ScriptPath & "dnn.xml.jsparser.js", FileOrder.Js.DnnXmlJsParser)
End If
Case ClientNamespaceReferences.dnn_xmlhttp
RegisterClientReference(objPage, ClientNamespaceReferences.dnn)
ClientResourceManager.RegisterScript(objPage, ScriptPath & "dnn.xmlhttp.js", FileOrder.Js.DnnXmlHttp)
If BrowserSupportsFunctionality(ClientFunctionality.XMLHTTPJS) Then
ClientResourceManager.RegisterScript(objPage, ScriptPath & "dnn.xmlhttp.jsxmlhttprequest.js", FileOrder.Js.DnnXmlHttpJsXmlHttpRequest)
End If
Case ClientNamespaceReferences.dnn_motion
RegisterClientReference(objPage, ClientNamespaceReferences.dnn_dom_positioning)
ClientResourceManager.RegisterScript(objPage, ScriptPath & "dnn.motion.js")
End Select
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Registers a client side variable (name/value) pair
''' </summary>
''' <param name="objPage">Current page rendering content</param>
''' <param name="strVar">Variable name</param>
''' <param name="strValue">Value</param>
''' <param name="blnOverwrite">Determins if a replace or append is applied when variable already exists</param>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 8/3/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Sub RegisterClientVariable(ByVal objPage As Page, ByVal strVar As String, ByVal strValue As String, ByVal blnOverwrite As Boolean)
'only add once
Dim objDict As Generic.Dictionary(Of String, String) = GetClientVariableList(objPage)
If objDict.ContainsKey(strVar) Then
If blnOverwrite Then
objDict(strVar) = strValue
Else
'appending value
objDict(strVar) &= strValue
End If
Else
objDict.Add(strVar, strValue)
End If
'instead of serializing each time, do it once
If HttpContext.Current.Items("CAPIPreRender") Is Nothing Then
'AddHandler objPage.PreRender, AddressOf CAPIPreRender
AddHandler GetDNNVariableControl(objPage).PreRender, AddressOf CAPIPreRender
HttpContext.Current.Items("CAPIPreRender") = True
End If
'if we are past prerender event then we need to keep serializing
If Not HttpContext.Current.Items("CAPIPostPreRender") Is Nothing Then
SerializeClientVariableDictionary(objPage, objDict)
End If
End Sub
Private Shared Sub CAPIPreRender(ByVal Sender As Object, ByVal Args As System.EventArgs)
Dim ctl As Control = CType(Sender, Control)
Dim objDict As Generic.Dictionary(Of String, String) = GetClientVariableList(ctl.Page)
SerializeClientVariableDictionary(ctl.Page, objDict)
HttpContext.Current.Items("CAPIPostPreRender") = True
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Responsible for inputting the hidden field necessary for the ClientAPI to pass variables back in forth
''' </summary>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 4/6/2005 Commented
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Function RegisterDNNVariableControl(ByVal objParent As System.Web.UI.Control) As HtmlInputHidden
Dim ctlVar As System.Web.UI.HtmlControls.HtmlInputHidden = GetDNNVariableControl(objParent)
If ctlVar Is Nothing Then
Dim oForm As Control = FindForm(objParent)
If Not oForm Is Nothing Then
'objParent.Page.ClientScript.RegisterHiddenField(DNNVARIABLE_CONTROLID, "")
ctlVar = New NonNamingHiddenInput() 'New System.Web.UI.HtmlControls.HtmlInputHidden
ctlVar.ID = DNNVARIABLE_CONTROLID
'oForm.Controls.AddAt(0, ctlVar)
oForm.Controls.Add(ctlVar)
End If
End If
Return ctlVar
End Function
''' -----------------------------------------------------------------------------
''' <summary>
''' Traps client side keydown event looking for passed in key press (ASCII) and hooks it up with server side postback handler
''' </summary>
''' <param name="objControl">Control that should trap the keydown</param>
''' <param name="objPostbackControl">Server-side control that has its onclick event handled server-side</param>
''' <param name="intKeyAscii">ASCII value of key to trap</param>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 2/17/2005 Commented
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Sub RegisterKeyCapture(ByVal objControl As Control, ByVal objPostbackControl As Control, ByVal intKeyAscii As Integer)
Globals.SetAttribute(objControl, "onkeydown", GetKeyDownHandler(intKeyAscii, GetPostBackClientHyperlink(objPostbackControl, "")))
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Traps client side keydown event looking for passed in key press (ASCII) and hooks it up with client-side javascript
''' </summary>
''' <param name="objControl">Control that should trap the keydown</param>
''' <param name="strJavascript">Javascript to execute when event fires</param>
''' <param name="intKeyAscii">ASCII value of key to trap</param>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 2/17/2005 Commented
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Sub RegisterKeyCapture(ByVal objControl As Control, ByVal strJavascript As String, ByVal intKeyAscii As Integer)
Globals.SetAttribute(objControl, "onkeydown", GetKeyDownHandler(intKeyAscii, strJavascript))
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Allows a listener to be associated to a client side post back
''' </summary>
''' <param name="objParent">The current control on the page or the page itself. Depending on where the page is in its lifecycle it may not be possible to add a control directly to the page object, therefore we will use the current control being rendered to append the postback control.</param>
''' <param name="strEventName">Name of the event to sync. If a page contains more than a single client side event only the events associated with the passed in name will be raised.</param>
''' <param name="objDelegate">Server side AddressOf the function to handle the event</param>
''' <param name="blnMultipleHandlers">Boolean flag to determine if multiple event handlers can be associated to an event.</param>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 9/15/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Sub RegisterPostBackEventHandler(ByVal objParent As Control, ByVal strEventName As String, ByVal objDelegate As ClientAPIPostBackControl.PostBackEvent, ByVal blnMultipleHandlers As Boolean)
Const CLIENTAPI_POSTBACKCTL_ID As String = "ClientAPIPostBackCtl"
Dim objCtl As Control = Globals.FindControlRecursive(objParent.Page, CLIENTAPI_POSTBACKCTL_ID) 'DotNetNuke.Globals.FindControlRecursive(objParent, CLIENTAPI_POSTBACKCTL_ID)
If objCtl Is Nothing Then
objCtl = New ClientAPIPostBackControl(objParent.Page, strEventName, objDelegate)
objCtl.ID = CLIENTAPI_POSTBACKCTL_ID
objParent.Controls.Add(objCtl)
ClientAPI.RegisterClientVariable(objParent.Page, "__dnn_postBack", GetPostBackClientHyperlink(objCtl, "[DATA]"), True)
ElseIf blnMultipleHandlers Then
CType(objCtl, ClientAPIPostBackControl).AddEventHandler(strEventName, objDelegate)
End If
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Registers a button inside a table for the ability to perform client-side reordering
''' </summary>
''' <param name="objButton">Button responsible for moving the row up or down.</param>
''' <param name="objPage">Page the table belongs to. Can't just use objButton.Page because inside ItemCreated event of grid the button has no page yet.</param>
''' <param name="blnUp">Determines if the button is responsible for moving the row up or down</param>
''' <param name="strKey">Unique key for the table/grid to be used to obtain the new order on postback. Needed when calling GetClientSideReOrder</param>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 3/10/2006 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Sub EnableClientSideReorder(ByVal objButton As Control, ByVal objPage As Page, ByVal blnUp As Boolean, ByVal strKey As String)
If BrowserSupportsFunctionality(ClientFunctionality.DHTML) Then
RegisterClientReference(objPage, ClientNamespaceReferences.dnn_dom)
ClientResourceManager.RegisterScript(objPage, ScriptPath & "dnn.util.tablereorder.js")
AddAttribute(objButton, "onclick", "if (dnn.util.tableReorderMove(this," & CInt(blnUp) & ",'" & strKey & "')) return false;")
Dim objParent As Control = objButton.Parent
While Not objParent Is Nothing
If TypeOf objParent Is TableRow Then
AddAttribute(objParent, "origidx", "-1") 'mark row as one that we care about, it will be numbered correctly on client
End If
objParent = objParent.Parent
End While
End If
End Sub
''' -----------------------------------------------------------------------------
''' <summary>
''' Retrieves an array of the new order for the rows
''' </summary>
''' <param name="strKey">Unique key for the table/grid to be used to obtain the new order on postback. Needed when calling GetClientSideReOrder</param>
''' <param name="objPage">Page the table belongs to. Can't just use objButton.Page because inside ItemCreated event of grid the button has no page yet.</param>
''' <remarks>
''' </remarks>
''' <history>
''' [Jon Henning] 3/10/2006 Created
''' </history>
''' -----------------------------------------------------------------------------
Public Shared Function GetClientSideReorder(ByVal strKey As String, ByVal objPage As Page) As String()
If Len(ClientAPI.GetClientVariable(objPage, strKey)) > 0 Then
Return ClientAPI.GetClientVariable(objPage, strKey).Split(","c)
Else
Return New String() {}
End If
End Function
Public Shared Function ClientAPIDisabled() As Boolean
'jon
Return False
If m_ClientAPIDisabled = String.Empty Then
If System.Configuration.ConfigurationManager.AppSettings("ClientAPI") Is Nothing Then
m_ClientAPIDisabled = "1"
Else
m_ClientAPIDisabled = System.Configuration.ConfigurationManager.AppSettings("ClientAPI")
End If
End If
Return m_ClientAPIDisabled = "0"
End Function
Public Shared Function GetPostBackClientEvent(ByVal objPage As Page, ByVal objControl As Control, ByVal arg As String) As String
Return objPage.ClientScript.GetPostBackEventReference(objControl, arg)
End Function
Public Shared Function GetPostBackClientHyperlink(ByVal objControl As Control, ByVal strArgument As String) As String
Return "javascript:" & GetPostBackEventReference(objControl, strArgument)
End Function
Public Shared Function GetPostBackEventReference(ByVal objControl As Control, ByVal strArgument As String) As String
Return objControl.Page.ClientScript.GetPostBackEventReference(objControl, strArgument)
End Function
Public Shared Function IsClientScriptBlockRegistered(ByVal objPage As Page, ByVal key As String) As Boolean
Return objPage.ClientScript.IsClientScriptBlockRegistered(objPage.GetType(), key)
End Function
Public Shared Sub RegisterClientScriptBlock(ByVal objPage As Page, ByVal key As String, ByVal strScript As String)
If Globals.IsEmbeddedScript(key) = False Then
'JON
'ScriptManager.RegisterClientScriptBlock(objPage, objPage.GetType(), key, strScript, False)
objPage.ClientScript.RegisterClientScriptBlock(objPage.GetType(), key, strScript)
Else
RegisterClientScriptBlock(objPage, key)
End If
End Sub
Public Shared Sub RegisterStartUpScript(ByVal objPage As Page, ByVal key As String, ByVal script As String)
MSAJAX.RegisterStartupScript(objPage, key, script)
'objPage.ClientScript.RegisterStartupScript(objPage.GetType(), key, script)
End Sub
Public Shared Sub RegisterClientScriptBlock(ByVal objPage As Page, ByVal key As String)
If UseExternalScripts Then
MSAJAX.RegisterClientScript(objPage, ClientAPI.ScriptPath & key)
Else
MSAJAX.RegisterClientScript(objPage, key, "DotNetNuke.WebUtility")
'client-side won't be able to get this info from dnn.js location, since its embedded.
' so we need to use where it would have gone instead
RegisterClientVariable(objPage, "__sp", ScriptPath, True)
End If
End Sub
Public Shared Function RegisterControlMethods(ByVal CallbackControl As Control) As Boolean
RegisterControlMethods(CallbackControl, String.Empty)
End Function
Public Shared Function RegisterControlMethods(ByVal CallbackControl As Control, ByVal FriendlyID As String) As Boolean
Dim classAttr As ControlMethodClassAttribute
Dim name As String
Dim ret As Boolean = True
classAttr = CType(Attribute.GetCustomAttribute(CallbackControl.GetType(), GetType(ControlMethodClassAttribute)), ControlMethodClassAttribute)
If Not classAttr Is Nothing Then
If String.IsNullOrEmpty(classAttr.FriendlyNamespace) Then
name = CallbackControl.GetType().FullName
Else
name = classAttr.FriendlyNamespace
End If
Dim format As String = "{0}.{1}={2} "
If String.IsNullOrEmpty(FriendlyID) Then
format = "{0}={2} "
End If
ClientAPI.RegisterClientVariable(CallbackControl.Page, "__dnncbm", String.Format(format, name, FriendlyID, CallbackControl.UniqueID), False)
If BrowserSupportsFunctionality(ClientFunctionality.XMLHTTP) AndAlso BrowserSupportsFunctionality(ClientFunctionality.XML) Then
DotNetNuke.UI.Utilities.ClientAPI.RegisterClientReference(CallbackControl.Page, DotNetNuke.UI.Utilities.ClientAPI.ClientNamespaceReferences.dnn_xml)
DotNetNuke.UI.Utilities.ClientAPI.RegisterClientReference(CallbackControl.Page, DotNetNuke.UI.Utilities.ClientAPI.ClientNamespaceReferences.dnn_xmlhttp)
Else
ret = False
End If
Else
Throw New Exception("Control does not have CallbackMethodAttribute")
End If
Return ret
End Function
Public Shared Function ExecuteControlMethod(ByVal CallbackControl As Control, ByVal callbackArgument As String) As String
Dim result As Object = Nothing
Dim controlType As Type = CallbackControl.GetType()
'Dim serializer As JavaScriptSerializer = New JavaScriptSerializer()
'Dim callInfo As Dictionary(Of String, Object) = TryCast(serializer.DeserializeObject(callbackArgument), Dictionary(Of String, Object))
Dim callInfo As Dictionary(Of String, Object) = TryCast(MSAJAX.DeserializeObject(callbackArgument), Dictionary(Of String, Object))
Dim methodName As String = CStr(callInfo.Item("method"))
Dim args As Dictionary(Of String, Object) = TryCast(callInfo.Item("args"), Dictionary(Of String, Object))
Dim mi As MethodInfo = controlType.GetMethod(methodName, (BindingFlags.Public Or (BindingFlags.Static Or BindingFlags.Instance)))
If (mi Is Nothing) Then
Throw New Exception(String.Format("Class: {0} does not have the method: {1}", controlType.FullName, methodName))
End If
Dim methodParams As ParameterInfo() = mi.GetParameters
'only allow methods with attribute to be called
Dim methAttr As ControlMethodAttribute = DirectCast(Attribute.GetCustomAttribute(mi, GetType(ControlMethodAttribute)), ControlMethodAttribute)
If methAttr Is Nothing OrElse args.Count <> methodParams.Length Then
Throw New Exception(String.Format("Class: {0} does not have the method: {1}", controlType.FullName, methodName))
End If
Dim targetArgs As Object() = New Object(args.Count - 1) {}
'Dim ser As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer(New SimpleTypeResolver())
Dim paramName As String
Dim arg As Object
Dim paramType As Type
For i As Integer = 0 To methodParams.Length - 1
paramName = methodParams(i).Name
paramType = methodParams(i).ParameterType
If (args.ContainsKey(paramName)) Then
arg = args(paramName)
If paramType.IsGenericType() Then
If Not TryCast(arg, IList) Is Nothing Then
Dim genTypes() As Type = paramType.GetGenericArguments()
targetArgs(i) = GetListFromType(genTypes(0), CType(arg, IList))
Else
targetArgs(i) = arg
End If
ElseIf paramType.IsClass AndAlso Not TryCast(arg, Dictionary(Of String, Object)) Is Nothing Then
targetArgs(i) = ConvertDictionaryToObject(CType(arg, Dictionary(Of String, Object)), paramType)
Else
targetArgs(i) = Convert.ChangeType(arg, methodParams(i).ParameterType, CultureInfo.InvariantCulture)
End If
End If
'Dim T As Type = methodParams(i).ParameterType
'targetArgs(i) = ser.ConvertToType(Of String)(args(i))
'targetArgs(i) = Convert.ChangeType(args(i), methodParams(i).ParameterType, CultureInfo.InvariantCulture)
'End If
Next
result = mi.Invoke(CallbackControl, targetArgs)
Dim resultInfo As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
resultInfo.Item("result") = result
'Return serializer.Serialize(resultInfo)
Return MSAJAX.Serialize(resultInfo)
End Function
Public Shared Function GetListFromType(ByVal TheType As Type, ByVal TheList As IList) As IList
Dim listOf As Type = GetType(List(Of ))
Dim argType As Type = listOf.MakeGenericType(TheType)
Dim instance As IList = CType(Activator.CreateInstance(argType), IList)
For Each listitem As Dictionary(Of String, Object) In TheList
If Not listitem Is Nothing Then
instance.Add(ConvertDictionaryToObject(listitem, TheType))
End If
Next
Return instance
End Function
Public Shared Function ConvertDictionaryToObject(ByVal dict As Dictionary(Of String, Object), ByVal TheType As Type) As Object
Dim item As Object = Activator.CreateInstance(TheType)
Dim pi As PropertyInfo
For Each pair As KeyValuePair(Of String, Object) In dict
pi = TheType.GetProperty(pair.Key)
If Not pi Is Nothing AndAlso pi.CanWrite AndAlso Not pair.Value Is Nothing Then
TheType.InvokeMember(pair.Key, System.Reflection.BindingFlags.SetProperty, Nothing, item, New Object() {pair.Value})
End If
Next
Return item
End Function
'Private Shared Function ConvertIt(Of T)(ByVal List As IList, ByVal TheType As Type) As List(Of T)
' Dim o As Object
' Dim fields() As FieldInfo = TheType.GetFields()
' For Each item As Object In List
' o = Activator.CreateInstance(TheType)
' For Each info As FieldInfo In fields
' Next
' Next
'End Function
Public Shared Sub RegisterEmbeddedResource(ByVal ThePage As Page, ByVal FileName As String, ByVal AssemblyType As Type)
RegisterClientVariable(ThePage, FileName & ".resx", ThePage.ClientScript.GetWebResourceUrl(AssemblyType, FileName), True)
End Sub
#End Region
End Class
Namespace Animation
Public Enum AnimationType
None
Slide
Expand
Diagonal
ReverseDiagonal
End Enum
Public Enum EasingDirection
[In]
Out
InOut
End Enum
Public Enum EasingType
Bounce
Circ
Cubic
Expo
Quad
Quint
Quart
Sine
End Enum
End Namespace
End Namespace
|
wael101/Dnn.Platform
|
DNN Platform/DotNetNuke.WebUtility/ClientAPI.vb
|
Visual Basic
|
mit
| 62,316
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.ExtractInterface
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractInterface
<ExportLanguageService(GetType(AbstractExtractInterfaceService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicExtractInterfaceService
Inherits AbstractExtractInterfaceService
<ImportingConstructor>
Public Sub New()
End Sub
Protected Overrides Async Function GetTypeDeclarationAsync(
document As Document, position As Integer,
typeDiscoveryRule As TypeDiscoveryRule,
cancellationToken As CancellationToken) As Task(Of SyntaxNode)
Dim tree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False)
Dim root = Await tree.GetRootAsync(cancellationToken).ConfigureAwait(False)
Dim token = root.FindToken(If(position <> tree.Length, position, Math.Max(0, position - 1)))
Dim typeDeclaration = token.GetAncestor(Of TypeBlockSyntax)()
If typeDeclaration Is Nothing OrElse
typeDeclaration.Kind = SyntaxKind.ModuleStatement Then
Return Nothing
ElseIf typeDiscoveryRule = TypeDiscoveryRule.TypeDeclaration Then
Return typeDeclaration
End If
Dim spanStart = typeDeclaration.BlockStatement.Identifier.SpanStart
Dim spanEnd = If(typeDeclaration.BlockStatement.TypeParameterList IsNot Nothing, typeDeclaration.BlockStatement.TypeParameterList.Span.End, typeDeclaration.BlockStatement.Identifier.Span.End)
Dim span = New TextSpan(spanStart, spanEnd - spanStart)
Return If(span.IntersectsWith(position), typeDeclaration, Nothing)
End Function
Friend Overrides Function GetGeneratedNameTypeParameterSuffix(typeParameters As IList(Of ITypeParameterSymbol), workspace As Workspace) As String
If typeParameters.IsEmpty() Then
Return String.Empty
End If
Dim typeParameterList = SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameters.Select(Function(p) SyntaxFactory.TypeParameter(p.Name))))
Return Formatter.Format(typeParameterList, workspace).ToString()
End Function
Friend Overrides Function GetContainingNamespaceDisplay(typeSymbol As INamedTypeSymbol, compilationOptions As CompilationOptions) As String
Dim namespaceSymbol = typeSymbol.ContainingNamespace
If namespaceSymbol.IsGlobalNamespace Then
Return String.Empty
End If
Dim fullDisplayName = namespaceSymbol.ToDisplayString()
Dim rootNamespace = DirectCast(compilationOptions, VisualBasicCompilationOptions).RootNamespace
If rootNamespace Is Nothing OrElse rootNamespace = String.Empty Then
Return fullDisplayName
End If
If rootNamespace.Equals(fullDisplayName, StringComparison.Ordinal) Then
Return String.Empty
End If
If fullDisplayName.StartsWith(rootNamespace + ".", StringComparison.Ordinal) Then
Return fullDisplayName.Substring(rootNamespace.Length + 1)
End If
Return fullDisplayName
End Function
Private Function GetUpdatedImplementsClause(implementsClause As ImplementsClauseSyntax, qualifiedName As QualifiedNameSyntax) As ImplementsClauseSyntax
If implementsClause IsNot Nothing Then
Return implementsClause.AddInterfaceMembers(qualifiedName).WithAdditionalAnnotations(Formatter.Annotation)
Else
Return SyntaxFactory.ImplementsClause(qualifiedName).WithAdditionalAnnotations(Formatter.Annotation)
End If
End Function
Private Function CreateFinalSolution(solutionWithInterfaceDocument As Solution, documentIds As IEnumerable(Of DocumentId), docToRootMap As Dictionary(Of DocumentId, CompilationUnitSyntax)) As Solution
Dim finalSolution = solutionWithInterfaceDocument
For Each docId In documentIds
finalSolution = finalSolution.WithDocumentSyntaxRoot(docId, docToRootMap(docId), PreservationMode.PreserveIdentity)
Next
Return finalSolution
End Function
Friend Overrides Function ShouldIncludeAccessibilityModifier(typeNode As SyntaxNode) As Boolean
Dim typeDeclaration = DirectCast(typeNode, TypeBlockSyntax)
Return typeDeclaration.GetModifiers().Any(Function(m) SyntaxFacts.IsAccessibilityModifier(m.Kind()))
End Function
Protected Overrides Async Function UpdateMembersWithExplicitImplementationsAsync(
unformattedSolution As Solution, documentIds As IReadOnlyList(Of DocumentId), extractedInterfaceSymbol As INamedTypeSymbol,
typeToExtractFrom As INamedTypeSymbol, includedMembers As IEnumerable(Of ISymbol),
symbolToDeclarationAnnotationMap As Dictionary(Of ISymbol, SyntaxAnnotation), cancellationToken As CancellationToken) As Task(Of Solution)
Dim docToRootMap = New Dictionary(Of DocumentId, CompilationUnitSyntax)
Dim implementedInterfaceStatementSyntax = If(extractedInterfaceSymbol.TypeParameters.Any(),
SyntaxFactory.GenericName(
SyntaxFactory.Identifier(extractedInterfaceSymbol.Name),
SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(extractedInterfaceSymbol.TypeParameters.Select(Function(p) SyntaxFactory.ParseTypeName(p.Name))))),
SyntaxFactory.ParseTypeName(extractedInterfaceSymbol.Name))
For Each member In includedMembers
Dim annotation = symbolToDeclarationAnnotationMap(member)
Dim token As SyntaxNodeOrToken = Nothing
Dim currentDocId As DocumentId = Nothing
Dim currentRoot As CompilationUnitSyntax = Nothing
For Each candidateDocId In documentIds
If docToRootMap.ContainsKey(candidateDocId) Then
currentRoot = docToRootMap(candidateDocId)
Else
Dim document = Await unformattedSolution.GetDocument(candidateDocId).GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
currentRoot = CType(document, CompilationUnitSyntax)
End If
token = currentRoot.DescendantNodesAndTokensAndSelf().FirstOrDefault(Function(x) x.HasAnnotation(annotation))
If token <> Nothing Then
currentDocId = candidateDocId
Exit For
End If
Next
If token = Nothing Then
Continue For
End If
Dim qualifiedName As QualifiedNameSyntax = SyntaxFactory.QualifiedName(implementedInterfaceStatementSyntax.GetRightmostName(), SyntaxFactory.IdentifierName(member.Name))
Dim method = TryCast(token.Parent, MethodStatementSyntax)
If method IsNot Nothing Then
docToRootMap(currentDocId) = currentRoot.ReplaceNode(method, method.WithImplementsClause(GetUpdatedImplementsClause(method.ImplementsClause, qualifiedName)))
Continue For
End If
Dim [event] = TryCast(token.Parent, EventStatementSyntax)
If [event] IsNot Nothing Then
docToRootMap(currentDocId) = currentRoot.ReplaceNode([event], [event].WithImplementsClause(GetUpdatedImplementsClause([event].ImplementsClause, qualifiedName)))
Continue For
End If
Dim prop = TryCast(token.Parent, PropertyStatementSyntax)
If prop IsNot Nothing Then
docToRootMap(currentDocId) = currentRoot.ReplaceNode(prop, prop.WithImplementsClause(GetUpdatedImplementsClause(prop.ImplementsClause, qualifiedName)))
Continue For
End If
Next
Return CreateFinalSolution(unformattedSolution, documentIds, docToRootMap)
End Function
End Class
End Namespace
|
nguerrera/roslyn
|
src/Features/VisualBasic/Portable/ExtractInterface/VisualBasicExtractInterfaceService.vb
|
Visual Basic
|
apache-2.0
| 8,688
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend MustInherit Class MethodSymbol
Inherits Symbol
Implements IMethodSymbolInternal
''' <summary>
''' Gets what kind of method this is. There are several different kinds of things in the
''' VB language that are represented as methods. This property allow distinguishing those things
''' without having to decode the name of the method.
''' </summary>
Public MustOverride ReadOnly Property MethodKind As MethodKind
''' <summary>
''' True, if the method kind was determined by examining a syntax node (i.e. for source methods -
''' including substituted and retargeted ones); false, otherwise.
''' </summary>
Friend MustOverride ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Friend Overridable Function IsParameterlessConstructor() As Boolean
Return Me.ParameterCount = 0 AndAlso Me.MethodKind = MethodKind.Constructor
End Function
''' <summary>
''' Returns whether this method is using VARARG calling convention.
''' </summary>
Public MustOverride ReadOnly Property IsVararg As Boolean Implements IMethodSymbol.IsVararg
''' <summary>
''' Returns whether this built-in operator checks for integer overflow.
''' </summary>
Public Overridable ReadOnly Property IsCheckedBuiltin As Boolean Implements IMethodSymbol.IsCheckedBuiltin
Get
Return False
End Get
End Property
''' <summary>
''' Returns whether this method is generic; i.e., does it have any type parameters?
''' </summary>
Public Overridable ReadOnly Property IsGenericMethod As Boolean
Get
Return Arity <> 0
End Get
End Property
''' <summary>
''' Returns the arity of this method, or the number of type parameters it takes.
''' A non-generic method has zero arity.
''' </summary>
Public MustOverride ReadOnly Property Arity As Integer
''' <summary>
''' Get the type parameters on this method. If the method has not generic,
''' returns an empty list.
''' </summary>
Public MustOverride ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
''' <summary>
''' Returns the type arguments that have been substituted for the type parameters.
''' If nothing has been substituted for a give type parameters,
''' then the type parameter itself is consider the type argument.
''' </summary>
Public MustOverride ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
''' <summary>
''' Get the original definition of this symbol. If this symbol is derived from another
''' symbol by (say) type substitution, this gets the original symbol, as it was defined
''' in source or metadata.
''' </summary>
Public Overridable Shadows ReadOnly Property OriginalDefinition As MethodSymbol
Get
' Default implements returns Me.
Return Me
End Get
End Property
Protected NotOverridable Overrides ReadOnly Property OriginalSymbolDefinition As Symbol
Get
Return Me.OriginalDefinition
End Get
End Property
''' <summary>
''' Returns the method symbol that this method was constructed from. This method symbol
''' has the same containing type (if any), but has type arguments that are the same
''' as the type parameters (although its containing type might not).
''' </summary>
Public Overridable ReadOnly Property ConstructedFrom As MethodSymbol
Get
Return Me
End Get
End Property
''' <summary>
''' Always returns false because the 'readonly members' feature is not available in VB.
''' </summary>
Private ReadOnly Property IMethodSymbol_IsReadOnly As Boolean Implements IMethodSymbol.IsReadOnly
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this method has no return type; i.e., is a Sub instead of a Function.
''' </summary>
Public MustOverride ReadOnly Property IsSub As Boolean
''' <summary>
''' Source: Returns whether this method is async; i.e., does it have the Async modifier?
''' Metadata: Returns False; methods from metadata cannot be async.
''' </summary>
Public MustOverride ReadOnly Property IsAsync As Boolean
''' <summary>
''' Source: Returns whether this method is an iterator; i.e., does it have the Iterator modifier?
''' Metadata: Returns False; methods from metadata cannot be an iterator.
''' </summary>
Public MustOverride ReadOnly Property IsIterator As Boolean
''' <summary>
''' Source: Returns False; methods from source cannot return by reference.
''' Metadata: Returns whether or not this method returns by reference.
''' </summary>
Public MustOverride ReadOnly Property ReturnsByRef As Boolean
''' <summary>
''' Gets the return type of the method. If the method is a Sub, returns
''' the same type symbol as is returned by Compilation.VoidType.
''' </summary>
Public MustOverride ReadOnly Property ReturnType As TypeSymbol
''' <summary>
''' Returns the list of custom modifiers, if any, associated with the returned value.
''' </summary>
Public MustOverride ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
''' <summary>
''' Custom modifiers associated with the ref modifier, or an empty array if there are none.
''' </summary>
Public MustOverride ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
''' <summary>
''' Returns the list of attributes, if any, associated with the return type.
''' </summary>
Public Overridable Function GetReturnTypeAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Return ImmutableArray(Of VisualBasicAttributeData).Empty
End Function
''' <summary>
''' Build and add synthesized return type attributes for this method symbol.
''' </summary>
Friend Overridable Sub AddSynthesizedReturnTypeAttributes(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
End Sub
''' <summary>
''' Optimization: in many cases, the parameter count (fast) is sufficient and we
''' don't need the actual parameter symbols (slow).
''' </summary>
''' <remarks>
''' The default implementation is always correct, but may be unnecessarily slow.
''' </remarks>
Friend Overridable ReadOnly Property ParameterCount As Integer
Get
Return Me.Parameters.Length
End Get
End Property
''' <summary>
''' Gets the parameters of this method. If this method has no parameters, returns
''' an empty list.
''' </summary>
Public MustOverride ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
''' <summary>
''' Should return syntax node that originated the method.
''' </summary>
Friend MustOverride ReadOnly Property Syntax As SyntaxNode
''' <summary>
''' Returns true if calls to this method are omitted in the given syntax tree at the given syntax node location.
''' Calls are omitted when the called method is a partial method with no implementation part, or when the
''' called method is a conditional method whose condition is not true at the given syntax node location in the source file
''' corresponding to the given syntax tree.
''' </summary>
Friend Overridable Function CallsAreOmitted(atNode As SyntaxNodeOrToken, syntaxTree As SyntaxTree) As Boolean
Return Me.IsPartialWithoutImplementation OrElse
(syntaxTree IsNot Nothing AndAlso Me.CallsAreConditionallyOmitted(atNode, syntaxTree))
End Function
''' <summary>
''' Calls are conditionally omitted if all the following requirements are true:
''' (a) Me.IsSub == True.
''' (b) Containing type is not an interface type.
''' (c) Me.IsConditional == True, i.e. it has at least one applied conditional attribute.
''' (d) This method is not the Property Set method.
''' (e) None of conditional symbols corresponding to these conditional attributes are true at the given syntax node location.
''' </summary>
''' <remarks>
''' Forces binding and decoding of attributes.
''' </remarks>
Private Function CallsAreConditionallyOmitted(atNode As SyntaxNodeOrToken, syntaxTree As SyntaxTree) As Boolean
' UNDONE: Ignore conditional attributes if within EE.
' For the EE, we always want to eval functions with the Conditional attribute applied to them (there are no CC symbols to check)
Dim containingType As NamedTypeSymbol = Me.ContainingType
If Me.IsConditional AndAlso Me.IsSub AndAlso
Me.MethodKind <> MethodKind.PropertySet AndAlso
(containingType Is Nothing OrElse Not containingType.IsInterfaceType) Then
Dim conditionalSymbols As IEnumerable(Of String) = Me.GetAppliedConditionalSymbols()
Debug.Assert(conditionalSymbols IsNot Nothing)
Debug.Assert(conditionalSymbols.Any())
If syntaxTree.IsAnyPreprocessorSymbolDefined(conditionalSymbols, atNode) Then
Return False
End If
' NOTE: Conditional symbols on the overridden method must be inherited by the overriding method, but the native VB compiler doesn't do so. We will maintain compatibility.
Return True
Else
Return False
End If
End Function
''' <summary>
''' Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none.
''' </summary>
Friend MustOverride Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
''' <summary>
''' Returns a flag indicating whether this symbol has at least one applied conditional attribute.
''' </summary>
''' <remarks>
''' Forces binding and decoding of attributes.
''' NOTE: Conditional symbols on the overridden method must be inherited by the overriding method, but the native VB compiler doesn't do so. We maintain compatibility.
''' </remarks>
Friend ReadOnly Property IsConditional As Boolean
Get
Return Me.GetAppliedConditionalSymbols.Any()
End Get
End Property
''' <summary>
''' True if the method itself Is excluded from code coverage instrumentation.
''' True for source methods marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>.
''' </summary>
Friend Overridable ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' True if this symbol has a special name (metadata flag SpecialName is set).
''' </summary>
''' <remarks>
''' This is set for methods with special semantics such as constructors or accessors
''' as well as in special synthetic methods such as lambdas.
''' Also set for methods marked with System.Runtime.CompilerServices.SpecialNameAttribute.
''' </remarks>
Friend MustOverride ReadOnly Property HasSpecialName As Boolean
''' <summary>
''' If this method has MethodKind of MethodKind.PropertyGet or MethodKind.PropertySet,
''' returns the property that this method is the getter or setter for.
''' If this method has MethodKind of MethodKind.EventAdd or MethodKind.EventRemove,
''' returns the event that this method is the adder or remover for.
''' Note, the set of possible associated symbols might be expanded in the future to
''' reflect changes in the languages.
''' </summary>
Public MustOverride ReadOnly Property AssociatedSymbol As Symbol
''' <summary>
''' If this method is a Lambda method (MethodKind = MethodKind.LambdaMethod) and
''' there is an anonymous delegate associated with it, returns this delegate.
'''
''' Returns Nothing if the symbol is not a lambda or if it does not have an
''' anonymous delegate associated with it.
''' </summary>
Public Overridable ReadOnly Property AssociatedAnonymousDelegate As NamedTypeSymbol
Get
Return Nothing
End Get
End Property
''' <summary>
''' If this method overrides another method (because it both had the Overrides modifier
''' and there correctly was a method to override), returns the overridden method.
''' </summary>
Public Overridable ReadOnly Property OverriddenMethod As MethodSymbol
Get
If Me.IsAccessor AndAlso Me.AssociatedSymbol.Kind = SymbolKind.Property Then
' Property accessors use the overridden property to determine overriding.
Return DirectCast(Me.AssociatedSymbol, PropertySymbol).GetAccessorOverride(getter:=(MethodKind = MethodKind.PropertyGet))
Else
If Me.IsOverrides AndAlso Me.ConstructedFrom Is Me Then
If IsDefinition Then
Return OverriddenMembers.OverriddenMember
End If
Return OverriddenMembersResult(Of MethodSymbol).GetOverriddenMember(Me, Me.OriginalDefinition.OverriddenMethod)
End If
End If
Return Nothing
End Get
End Property
' Get the set of overridden and hidden members for this method.
Friend Overridable ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol)
Get
' To save space, the default implementation does not cache its result. We expect there to
' be a very large number of MethodSymbols and we expect that a large percentage of them will
' obviously not override anything (e.g. static methods, constructors, destructors, etc).
Return OverrideHidingHelper(Of MethodSymbol).MakeOverriddenMembers(Me)
End Get
End Property
' Get the set of handled events for this method.
Public Overridable ReadOnly Property HandledEvents As ImmutableArray(Of HandledEvent)
Get
Return ImmutableArray(Of HandledEvent).Empty
End Get
End Property
''' <summary>
''' Returns interface methods explicitly implemented by this method.
''' </summary>
Public MustOverride ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
#Disable Warning CA1200 ' Avoid using cref tags with a prefix
''' <summary>
''' Returns true if this method is not implemented in IL of the assembly it is defined in.
''' </summary>
''' <remarks>
''' External methods are
''' 1) Declare Subs and Declare Functions,
''' 2) methods marked by <see cref="System.Runtime.InteropServices.DllImportAttribute"/>,
''' 3) methods marked by <see cref="System.Runtime.CompilerServices.MethodImplAttribute"/>
''' with <see cref="T:System.Runtime.CompilerServices.MethodImplOptions.InternalCall"/> or
''' <see cref="T:System.Runtime.CompilerServices.MethodCodeType.Runtime"/> flags.
''' 4) Synthesized constructors of ComImport types
''' </remarks>
#Enable Warning CA1200 ' Avoid using cref tags with a prefix
Public MustOverride ReadOnly Property IsExternalMethod As Boolean
''' <summary>
''' Returns platform invocation information for this method if it is a PlatformInvoke method, otherwise returns Nothing.
''' </summary>
Public MustOverride Function GetDllImportData() As DllImportData Implements IMethodSymbol.GetDllImportData
''' <summary>
''' Marshalling information for return value (FieldMarshal in metadata).
''' </summary>
Friend MustOverride ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
''' <summary>
''' Misc implementation metadata flags (ImplFlags in metadata).
''' </summary>
Friend MustOverride ReadOnly Property ImplementationAttributes As System.Reflection.MethodImplAttributes
''' <summary>
''' Declaration security information associated with this method, or null if there is none.
''' </summary>
Friend MustOverride Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
''' <summary>
''' True if the method has declarative security information (HasSecurity flags).
''' </summary>
Friend MustOverride ReadOnly Property HasDeclarativeSecurity As Boolean
''' <summary>
''' Returns true if this method is an extension method from the VB language perspective;
''' i.e., declared with an Extension attribute and meets other language requirements.
''' </summary>
Public MustOverride ReadOnly Property IsExtensionMethod As Boolean
''' <summary>
''' Returns true if this method might be a reducible extension method. This method may return true
''' even if the method is not an extension method, but if it returns false, it must be the
''' case that this is not an extension method.
'''
''' Allows checking extension methods from source in a quicker manner than fully binding attributes.
''' </summary>
Friend Overridable ReadOnly Property MayBeReducibleExtensionMethod As Boolean
Get
Return IsExtensionMethod AndAlso MethodKind <> MethodKind.ReducedExtension
End Get
End Property
''' <summary>
''' Returns true if this method hides a base method by name and signature.
''' The equivalent of the "hidebysig" flag in metadata.
''' </summary>
''' <remarks>
''' This property should not be confused with general method overloading in Visual Basic, and is not directly related.
''' This property will only return true if this method hides a base method by name and signature (Overloads keyword).
''' </remarks>
Public MustOverride ReadOnly Property IsOverloads As Boolean
''' <summary>
''' True if the implementation of this method is supplied by the runtime.
''' </summary>
''' <remarks>
''' <see cref="IsRuntimeImplemented"/> implies <see cref="IsExternalMethod"/>.
''' </remarks>
Friend ReadOnly Property IsRuntimeImplemented As Boolean
Get
Return (Me.ImplementationAttributes And Reflection.MethodImplAttributes.Runtime) <> 0
End Get
End Property
Friend Overrides ReadOnly Property ImplicitlyDefinedBy(Optional membersInProgress As Dictionary(Of String, ArrayBuilder(Of Symbol)) = Nothing) As Symbol
Get
Return Me.AssociatedSymbol
End Get
End Property
Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Method
End Get
End Property
Friend ReadOnly Property IsScriptConstructor As Boolean
Get
Return Me.MethodKind = MethodKind.Constructor AndAlso Me.ContainingType.IsScriptClass
End Get
End Property
Friend Overridable ReadOnly Property IsScriptInitializer As Boolean
Get
Return False
End Get
End Property
Friend ReadOnly Property IsSubmissionConstructor As Boolean
Get
Return IsScriptConstructor AndAlso ContainingAssembly.IsInteractive
End Get
End Property
''' <summary>
''' Determines whether this method is a candidate for a default
''' assembly entry point. Any method called "Main" is.
''' </summary>
''' <returns>True if the method can be used as an entry point.</returns>
Friend ReadOnly Property IsEntryPointCandidate As Boolean
Get
If Me.ContainingType.IsEmbedded Then
Return False
End If
If Me.IsSubmissionConstructor Then
Return False
End If
If Me.IsImplicitlyDeclared Then
Return False
End If
Return String.Equals(Name, WellKnownMemberNames.EntryPointMethodName, StringComparison.OrdinalIgnoreCase)
End Get
End Property
Friend ReadOnly Property IsViableMainMethod As Boolean
Get
Return IsShared AndAlso
IsAccessibleEntryPoint() AndAlso
HasEntryPointSignature()
End Get
End Property
''' <summary>
''' Entry point is considered accessible if it is not private and none of the containing types is private (they all might be Family or Friend).
''' </summary>
Private Function IsAccessibleEntryPoint() As Boolean
If Me.DeclaredAccessibility = Accessibility.Private Then
Return False
End If
Dim type = Me.ContainingType
While type IsNot Nothing
If type.DeclaredAccessibility = Accessibility.Private Then
Return False
End If
type = type.ContainingType
End While
Return True
End Function
''' <summary>
''' Checks if the method has an entry point compatible signature, i.e.
''' - the return type is either void or int
''' - has either no parameter or a single parameter of type string[]
''' </summary>
Friend Function HasEntryPointSignature() As Boolean
Dim returnType As TypeSymbol = Me.ReturnType
If returnType.SpecialType <> SpecialType.System_Int32 AndAlso returnType.SpecialType <> SpecialType.System_Void Then
Return False
End If
If Parameters.Length = 0 Then
Return True
End If
If Parameters.Length > 1 Then
Return False
End If
If Parameters(0).IsByRef Then
Return False
End If
Dim firstType = Parameters(0).Type
If firstType.TypeKind <> TypeKind.Array Then
Return False
End If
Dim array = DirectCast(firstType, ArrayTypeSymbol)
Return array.IsSZArray AndAlso array.ElementType.SpecialType = SpecialType.System_String
End Function
Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitMethod(Me, arg)
End Function
Friend Sub New()
End Sub
' Returns True if this method has Arity >= 1 and Construct can be called. This is primarily useful
' when deal with error cases.
Friend Overridable ReadOnly Property CanConstruct As Boolean
Get
Return Me.IsDefinition AndAlso Me.Arity > 0
End Get
End Property
''' <summary> Checks for validity of Construct(...) on this method with these type arguments. </summary>
Protected Sub CheckCanConstructAndTypeArguments(typeArguments As ImmutableArray(Of TypeSymbol))
'EDMAURER this exception is part of the public contract for Construct(...)
If Not CanConstruct OrElse Me IsNot ConstructedFrom Then
Throw New InvalidOperationException()
End If
' Check type arguments
typeArguments.CheckTypeArguments(Me.Arity)
End Sub
' Apply type substitution to a generic method to create an method symbol with the given type parameters supplied.
Public Overridable Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As MethodSymbol
CheckCanConstructAndTypeArguments(typeArguments)
Debug.Assert(Me.IsDefinition)
Dim substitution = TypeSubstitution.Create(Me, Me.TypeParameters, typeArguments, allowAlphaRenamedTypeParametersAsArguments:=True)
If substitution Is Nothing Then
' identity substitution
Return Me
Else
Debug.Assert(substitution.TargetGenericDefinition Is Me)
Return New SubstitutedMethodSymbol.ConstructedNotSpecializedGenericMethod(substitution, typeArguments)
End If
End Function
Public Function Construct(ParamArray typeArguments() As TypeSymbol) As MethodSymbol
Return Construct(ImmutableArray.Create(typeArguments))
End Function
Friend MustOverride ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
''' <summary>
''' Call <see cref="TryGetMeParameter"/> and throw if it returns false.
''' </summary>
''' <returns></returns>
Friend ReadOnly Property MeParameter As ParameterSymbol
Get
Dim parameter As ParameterSymbol = Nothing
If Not Me.TryGetMeParameter(parameter) Then
Throw ExceptionUtilities.Unreachable
End If
Return parameter
End Get
End Property
''' <returns>
''' True if this <see cref="MethodSymbol"/> type supports retrieving the Me parameter
''' and false otherwise. Note that a return value of true does not guarantee a non-Nothing
''' <paramref name="meParameter"/> (e.g. fails for shared methods).
''' </returns>
Friend Overridable Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean
meParameter = Nothing
Return False
End Function
Friend Overrides Function GetUseSiteErrorInfo() As DiagnosticInfo
If Me.IsDefinition Then
Return MyBase.GetUseSiteErrorInfo()
End If
' There is no reason to specially check type arguments because
' constructed members are never imported.
Return Me.OriginalDefinition.GetUseSiteErrorInfo()
End Function
Friend Function CalculateUseSiteErrorInfo() As DiagnosticInfo
Debug.Assert(IsDefinition)
' Check return type.
Dim errorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromType(Me.ReturnType)
If errorInfo IsNot Nothing AndAlso errorInfo.Code = ERRID.ERR_UnsupportedMethod1 Then
Return errorInfo
End If
' Check return type custom modifiers.
Dim refModifiersErrorInfo = DeriveUseSiteErrorInfoFromCustomModifiers(Me.RefCustomModifiers)
If refModifiersErrorInfo IsNot Nothing AndAlso refModifiersErrorInfo.Code = ERRID.ERR_UnsupportedMethod1 Then
Return refModifiersErrorInfo
End If
Dim typeModifiersErrorInfo = DeriveUseSiteErrorInfoFromCustomModifiers(Me.ReturnTypeCustomModifiers)
If typeModifiersErrorInfo IsNot Nothing AndAlso typeModifiersErrorInfo.Code = ERRID.ERR_UnsupportedMethod1 Then
Return typeModifiersErrorInfo
End If
errorInfo = If(errorInfo, If(refModifiersErrorInfo, typeModifiersErrorInfo))
' Check parameters.
Dim result = MergeUseSiteErrorInfo(errorInfo, DeriveUseSiteErrorInfoFromParameters(Me.Parameters))
' If the member is in an assembly with unified references,
' we check if its definition depends on a type from a unified reference.
If result Is Nothing AndAlso Me.ContainingModule.HasUnifiedReferences Then
Dim unificationCheckedTypes As HashSet(Of TypeSymbol) = Nothing
result = If(Me.ReturnType.GetUnificationUseSiteDiagnosticRecursive(Me, unificationCheckedTypes),
If(GetUnificationUseSiteDiagnosticRecursive(Me.RefCustomModifiers, Me, unificationCheckedTypes),
If(GetUnificationUseSiteDiagnosticRecursive(Me.ReturnTypeCustomModifiers, Me, unificationCheckedTypes),
If(GetUnificationUseSiteDiagnosticRecursive(Me.Parameters, Me, unificationCheckedTypes),
GetUnificationUseSiteDiagnosticRecursive(Me.TypeParameters, Me, unificationCheckedTypes)))))
End If
Return result
End Function
''' <summary>
''' Return error code that has highest priority while calculating use site error for this symbol.
''' </summary>
Protected Overrides ReadOnly Property HighestPriorityUseSiteError As Integer
Get
Return ERRID.ERR_UnsupportedMethod1
End Get
End Property
Public NotOverridable Overrides ReadOnly Property HasUnsupportedMetadata As Boolean
Get
Dim info As DiagnosticInfo = GetUseSiteErrorInfo()
Return info IsNot Nothing AndAlso info.Code = ERRID.ERR_UnsupportedMethod1
End Get
End Property
''' <summary>
''' If this method is a reduced extension method, gets the extension method definition that
''' this method was reduced from. Otherwise, returns Nothing.
''' </summary>
Public Overridable ReadOnly Property ReducedFrom As MethodSymbol
Get
Return Nothing
End Get
End Property
''' <summary>
''' Is this a reduced extension method?
''' </summary>
Friend ReadOnly Property IsReducedExtensionMethod As Boolean
Get
Return Me.ReducedFrom IsNot Nothing
End Get
End Property
''' <summary>
''' If this method is a reduced extension method, gets the extension method (possibly constructed) that
''' should be used at call site during ILGen. Otherwise, returns Nothing.
''' </summary>
Friend Overridable ReadOnly Property CallsiteReducedFromMethod As MethodSymbol
Get
Return Nothing
End Get
End Property
''' <summary>
''' If this method can be applied to an object, returns the type of object it is applied to.
''' </summary>
Public Overridable ReadOnly Property ReceiverType As TypeSymbol
Get
Return Me.ContainingType
End Get
End Property
''' <summary>
''' If this method is a reduced extension method, returns a type inferred during reduction process for the type parameter.
''' </summary>
''' <param name="reducedFromTypeParameter">Type parameter of the corresponding <see cref="ReducedFrom"/> method.</param>
''' <returns>Inferred type or Nothing if nothing was inferred.</returns>
''' <exception cref="System.InvalidOperationException">If this is not a reduced extension method.</exception>
''' <exception cref="System.ArgumentNullException">If <paramref name="reducedFromTypeParameter"/> is Nothing.</exception>
''' <exception cref="System.ArgumentException">If <paramref name="reducedFromTypeParameter"/> doesn't belong to the corresponding <see cref="ReducedFrom"/> method.</exception>
Public Overridable Function GetTypeInferredDuringReduction(reducedFromTypeParameter As TypeParameterSymbol) As TypeSymbol
Throw New InvalidOperationException()
End Function
''' <summary>
''' Fixed type parameters for a reduced extension method or empty.
''' </summary>
Friend Overridable ReadOnly Property FixedTypeParameters As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeSymbol))
Get
Return ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeSymbol)).Empty
End Get
End Property
''' <summary>
''' If this is an extension method that can be applied to a instance of the given type,
''' returns the reduced method symbol thus formed. Otherwise, returns Nothing.
'''
''' Name lookup should use this method in order to capture proximity, which affects
''' overload resolution.
''' </summary>
Friend Function ReduceExtensionMethod(instanceType As TypeSymbol, proximity As Integer) As MethodSymbol
Return ReducedExtensionMethodSymbol.Create(instanceType, Me, proximity)
End Function
''' <summary>
''' If this is an extension method that can be applied to a instance of the given type,
''' returns the reduced method symbol thus formed. Otherwise, returns Nothing.
''' </summary>
Public Function ReduceExtensionMethod(instanceType As TypeSymbol) As MethodSymbol
Return ReduceExtensionMethod(instanceType, proximity:=0)
End Function
''' <summary>
''' Proximity level of a reduced extension method.
''' </summary>
Friend Overridable ReadOnly Property Proximity As Integer
Get
Return 0
End Get
End Property
Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind
Get
Return If(Me.ContainingSymbol Is Nothing, EmbeddedSymbolKind.None, Me.ContainingSymbol.EmbeddedSymbolKind)
End Get
End Property
''' <summary>
''' Returns bound block representing method's body. This method is called
''' by 'method compiler' when it is ready to emit IL code for the method.
'''
''' The bound method body is typically a high-level tree - it may contain
''' lambdas, foreach etc... which will be processed in CompileMethod(...)
''' </summary>
''' <param name="compilationState">Enables synthesized methods to create <see cref="SyntheticBoundNodeFactory"/> instances.</param>
''' <param name="methodBodyBinder">Optionally returns a binder, OUT parameter!</param>
''' <remarks>
''' The method MAY return a binder used for binding so it can be reused later in method compiler
''' </remarks>
Friend Overridable Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As DiagnosticBag, <Out()> Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock
Throw ExceptionUtilities.Unreachable
End Function
''' <remarks>
''' True iff the method contains user code.
''' </remarks>
Friend MustOverride ReadOnly Property GenerateDebugInfoImpl As Boolean
Friend ReadOnly Property GenerateDebugInfo As Boolean
Get
' Dev11 generates debug info for embedded symbols.
' There is no reason to do so since the source code is not available to the user.
Return GenerateDebugInfoImpl AndAlso Not IsEmbedded
End Get
End Property
''' <summary>
''' Calculates a syntax offset for a local (user-defined or long-lived synthesized) declared at <paramref name="localPosition"/>.
''' Must be implemented by all methods that may contain user code.
''' </summary>
''' <remarks>
''' Syntax offset is a unique identifier for the local within the emitted method body.
''' It's based on position of the local declarator. In single-part method bodies it's simply the distance
''' from the start of the method body syntax span. If a method body has multiple parts (such as a constructor
''' comprising of code for member initializers and constructor initializer calls) the offset is calculated
''' as if all source these parts were concatenated together and prepended to the constructor body.
''' The resulting syntax offset is then negative for locals defined outside of the constructor body.
''' </remarks>
Friend MustOverride Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
''' <summary>
''' Specifies whether existing, "unused" locals (corresponding to proxies) are preserved during lambda rewriting.
''' </summary>
''' <remarks>
''' This value will be checked by the <see cref="LambdaRewriter"/> and is needed so that existing locals aren't
''' omitted in the EE (method symbols in the EE will override this property to return True).
''' </remarks>
Friend Overridable ReadOnly Property PreserveOriginalLocals As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Is this a method of a tuple type?
''' </summary>
Public Overridable ReadOnly Property IsTupleMethod() As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' If this is a method of a tuple type, return corresponding underlying method from the
''' tuple underlying type. Otherwise, Nothing.
''' </summary>
Public Overridable ReadOnly Property TupleUnderlyingMethod() As MethodSymbol
Get
Return Nothing
End Get
End Property
#Region "IMethodSymbol"
Private ReadOnly Property IMethodSymbol_Arity As Integer Implements IMethodSymbol.Arity
Get
Return Me.Arity
End Get
End Property
Private ReadOnly Property IMethodSymbol_ConstructedFrom As IMethodSymbol Implements IMethodSymbol.ConstructedFrom
Get
Return Me.ConstructedFrom
End Get
End Property
Private ReadOnly Property IMethodSymbol_ExplicitInterfaceImplementations As ImmutableArray(Of IMethodSymbol) Implements IMethodSymbol.ExplicitInterfaceImplementations
Get
Return ImmutableArrayExtensions.Cast(Of MethodSymbol, IMethodSymbol)(Me.ExplicitInterfaceImplementations)
End Get
End Property
Private ReadOnly Property IMethodSymbol_IsExtensionMethod As Boolean Implements IMethodSymbol.IsExtensionMethod
Get
Return Me.IsExtensionMethod
End Get
End Property
Private ReadOnly Property IMethodSymbol_MethodKind As MethodKind Implements IMethodSymbol.MethodKind
Get
Return Me.MethodKind
End Get
End Property
Private ReadOnly Property IMethodSymbol_OriginalDefinition As IMethodSymbol Implements IMethodSymbol.OriginalDefinition
Get
Return Me.OriginalDefinition
End Get
End Property
Private ReadOnly Property IMethodSymbol_OverriddenMethod As IMethodSymbol Implements IMethodSymbol.OverriddenMethod
Get
Return Me.OverriddenMethod
End Get
End Property
Private ReadOnly Property IMethodSymbol_ReceiverType As ITypeSymbol Implements IMethodSymbol.ReceiverType
Get
Return Me.ReceiverType
End Get
End Property
Private ReadOnly Property IMethodSymbol_ReceiverNullableAnnotation As NullableAnnotation Implements IMethodSymbol.ReceiverNullableAnnotation
Get
Return NullableAnnotation.None
End Get
End Property
Private Function IMethodSymbol_GetTypeInferredDuringReduction(reducedFromTypeParameter As ITypeParameterSymbol) As ITypeSymbol Implements IMethodSymbol.GetTypeInferredDuringReduction
Return Me.GetTypeInferredDuringReduction(reducedFromTypeParameter.EnsureVbSymbolOrNothing(Of TypeParameterSymbol)(NameOf(reducedFromTypeParameter)))
End Function
Private ReadOnly Property IMethodSymbol_ReducedFrom As IMethodSymbol Implements IMethodSymbol.ReducedFrom
Get
Return Me.ReducedFrom
End Get
End Property
Private Function IMethodSymbol_ReduceExtensionMethod(receiverType As ITypeSymbol) As IMethodSymbol Implements IMethodSymbol.ReduceExtensionMethod
If receiverType Is Nothing Then
Throw New ArgumentNullException(NameOf(receiverType))
End If
Return Me.ReduceExtensionMethod(receiverType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(receiverType)))
End Function
Private ReadOnly Property IMethodSymbol_Parameters As ImmutableArray(Of IParameterSymbol) Implements IMethodSymbol.Parameters
Get
Return ImmutableArray(Of IParameterSymbol).CastUp(Me.Parameters)
End Get
End Property
''' <summary>
''' Returns true if this symbol is defined outside of the compilation.
''' For instance if the method is <c>Declare Sub</c>.
''' </summary>
Private ReadOnly Property ISymbol_IsExtern As Boolean Implements ISymbol.IsExtern
Get
Return IsExternalMethod
End Get
End Property
''' <summary>
''' If this is a partial method declaration without a body, and the method also
''' has a part that implements it with a body, returns that implementing
''' definition. Otherwise null.
''' </summary>
Public Overridable ReadOnly Property PartialImplementationPart As MethodSymbol
Get
Return Nothing
End Get
End Property
''' <summary>
''' If this is a partial method with a body, returns the corresponding
''' definition part (without a body). Otherwise null.
''' </summary>
Public Overridable ReadOnly Property PartialDefinitionPart As MethodSymbol
Get
Return Nothing
End Get
End Property
Private ReadOnly Property IMethodSymbol_PartialDefinitionPart As IMethodSymbol Implements IMethodSymbol.PartialDefinitionPart
Get
Return PartialDefinitionPart
End Get
End Property
Private ReadOnly Property IMethodSymbol_PartialImplementationPart As IMethodSymbol Implements IMethodSymbol.PartialImplementationPart
Get
Return PartialImplementationPart
End Get
End Property
Private ReadOnly Property IMethodSymbol_ReturnsVoid As Boolean Implements IMethodSymbol.ReturnsVoid
Get
Return Me.IsSub
End Get
End Property
Private ReadOnly Property IMethodSymbol_ReturnsByRef As Boolean Implements IMethodSymbol.ReturnsByRef
Get
Return Me.ReturnsByRef
End Get
End Property
Private ReadOnly Property IMethodSymbol_ReturnsByReadonlyRef As Boolean Implements IMethodSymbol.ReturnsByRefReadonly
Get
Return False
End Get
End Property
Private ReadOnly Property IMethodSymbol_RefKind As RefKind Implements IMethodSymbol.RefKind
Get
Return If(Me.ReturnsByRef, RefKind.Ref, RefKind.None)
End Get
End Property
Private ReadOnly Property IMethodSymbol_ReturnType As ITypeSymbol Implements IMethodSymbol.ReturnType
Get
Return Me.ReturnType
End Get
End Property
Private ReadOnly Property IMethodSymbol_ReturnNullableAnnotation As NullableAnnotation Implements IMethodSymbol.ReturnNullableAnnotation
Get
Return NullableAnnotation.None
End Get
End Property
Private ReadOnly Property IMethodSymbol_TypeArguments As ImmutableArray(Of ITypeSymbol) Implements IMethodSymbol.TypeArguments
Get
Return StaticCast(Of ITypeSymbol).From(Me.TypeArguments)
End Get
End Property
Private ReadOnly Property IMethodSymbol_TypeArgumentsNullableAnnotation As ImmutableArray(Of NullableAnnotation) Implements IMethodSymbol.TypeArgumentNullableAnnotations
Get
Return Me.TypeArguments.SelectAsArray(Function(t) NullableAnnotation.None)
End Get
End Property
Private ReadOnly Property IMethodSymbol_TypeParameters As ImmutableArray(Of ITypeParameterSymbol) Implements IMethodSymbol.TypeParameters
Get
Return StaticCast(Of ITypeParameterSymbol).From(Me.TypeParameters)
End Get
End Property
Private ReadOnly Property IMethodSymbol_AssociatedSymbol As ISymbol Implements IMethodSymbol.AssociatedSymbol
Get
Return Me.AssociatedSymbol
End Get
End Property
Private ReadOnly Property IMethodSymbol_IsGenericMethod As Boolean Implements IMethodSymbol.IsGenericMethod
Get
Return Me.IsGenericMethod
End Get
End Property
Private ReadOnly Property IMethodSymbol_IsAsync As Boolean Implements IMethodSymbol.IsAsync
Get
Return Me.IsAsync
End Get
End Property
Private ReadOnly Property IMethodSymbol_HidesBaseMethodsByName As Boolean Implements IMethodSymbol.HidesBaseMethodsByName
Get
Return True
End Get
End Property
Private ReadOnly Property IMethodSymbol_RefCustomModifiers As ImmutableArray(Of CustomModifier) Implements IMethodSymbol.RefCustomModifiers
Get
Return Me.RefCustomModifiers
End Get
End Property
Private ReadOnly Property IMethodSymbol_ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Implements IMethodSymbol.ReturnTypeCustomModifiers
Get
Return Me.ReturnTypeCustomModifiers
End Get
End Property
Private Function IMethodSymbol_GetReturnTypeAttributes() As ImmutableArray(Of AttributeData) Implements IMethodSymbol.GetReturnTypeAttributes
Return ImmutableArrayExtensions.Cast(Of VisualBasicAttributeData, AttributeData)(Me.GetReturnTypeAttributes)
End Function
Private Function IMethodSymbol_Construct(ParamArray typeArguments() As ITypeSymbol) As IMethodSymbol Implements IMethodSymbol.Construct
Return Construct(ConstructTypeArguments(typeArguments))
End Function
Private Function IMethodSymbol_Construct(typeArguments As ImmutableArray(Of ITypeSymbol), typeArgumentNullableAnnotations As ImmutableArray(Of CodeAnalysis.NullableAnnotation)) As IMethodSymbol Implements IMethodSymbol.Construct
Return Construct(ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations))
End Function
Private ReadOnly Property IMethodSymbol_AssociatedAnonymousDelegate As INamedTypeSymbol Implements IMethodSymbol.AssociatedAnonymousDelegate
Get
Return Me.AssociatedAnonymousDelegate
End Get
End Property
#End Region
#Region "IMethodSymbolInternal"
Private ReadOnly Property IMethodSymbolInternal_IsIterator As Boolean Implements IMethodSymbolInternal.IsIterator
Get
Return Me.IsIterator
End Get
End Property
Private Function IMethodSymbolInternal_CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Implements IMethodSymbolInternal.CalculateLocalSyntaxOffset
Return CalculateLocalSyntaxOffset(localPosition, localTree)
End Function
#End Region
#Region "ISymbol"
Public Overrides Sub Accept(ByVal visitor As SymbolVisitor)
visitor.VisitMethod(Me)
End Sub
Public Overrides Function Accept(Of TResult)(ByVal visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitMethod(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitMethod(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitMethod(Me)
End Function
#End Region
End Class
End Namespace
|
nguerrera/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/MethodSymbol.vb
|
Visual Basic
|
apache-2.0
| 49,986
|
' 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.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class SingleLineIfBlockHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function CreateHighlighter() As IHighlighter
Return New SingleLineIfBlockHighlighter()
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestSinglelineIf1() As Task
Await TestAsync(<Text><![CDATA[
Class C
Sub M()
{|Cursor:[|If|]|} a < b [|Then|] a = b [|Else|] b = a
End Sub
End Class]]></Text>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestSinglelineIf2() As Task
Await TestAsync(<Text><![CDATA[
Class C
Sub M()
[|If|] a < b {|Cursor:[|Then|]|} a = b [|Else|] b = a
End Sub
End Class]]></Text>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestSinglelineIf3() As Task
Await TestAsync(<Text><![CDATA[
Class C
Sub M()
[|If|] a < b [|Then|] a = b {|Cursor:[|Else|]|} b = a
End Sub
End Class]]></Text>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestSinglelineIfNestedInMultilineIf1() As Task
Await TestAsync(<Text><![CDATA[
Class C
Sub M()
If a < b Then
a = b
ElseIf DateTime.Now.Ticks Mod 2 = 0
Throw New RandomException
Else
{|Cursor:[|If|]|} a < b [|Then|] a = b [|Else|] b = a
End If
End Sub
End Class]]></Text>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestSinglelineIfNestedInMultilineIf2() As Task
Await TestAsync(<Text><![CDATA[
Class C
Sub M()
If a < b Then
a = b
ElseIf DateTime.Now.Ticks Mod 2 = 0
Throw New RandomException
Else
[|If|] a < b {|Cursor:[|Then|]|} a = b [|Else|] b = a
End If
End Sub
End Class]]></Text>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestSinglelineIfNestedInMultilineIf3() As Task
Await TestAsync(<Text><![CDATA[
Class C
Sub M()
If a < b Then
a = b
ElseIf DateTime.Now.Ticks Mod 2 = 0
Throw New RandomException
Else
[|If|] a < b [|Then|] a = b {|Cursor:[|Else|]|} b = a
End If
End Sub
End Class]]></Text>)
End Function
End Class
End Namespace
|
mseamari/Stuff
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/SingleLineIfBlockHighlighterTests.vb
|
Visual Basic
|
apache-2.0
| 2,811
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module ArgumentSyntaxExtensions
<Extension()>
Public Function DetermineType(argument As ArgumentSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As ITypeSymbol
' If a parameter appears to have a void return type, then just use 'object' instead.
Return argument.GetArgumentExpression().DetermineType(semanticModel, cancellationToken)
End Function
<Extension()>
Public Function DetermineParameter(
argument As ArgumentSyntax,
semanticModel As SemanticModel,
Optional allowParamArray As Boolean = False,
Optional cancellationToken As CancellationToken = Nothing
) As IParameterSymbol
Dim argumentList = TryCast(argument.Parent, ArgumentListSyntax)
If argumentList Is Nothing Then
Return Nothing
End If
Dim invocableExpression = TryCast(argumentList.Parent, ExpressionSyntax)
If invocableExpression Is Nothing Then
Return Nothing
End If
Dim symbol = semanticModel.GetSymbolInfo(invocableExpression, cancellationToken).Symbol
If symbol Is Nothing Then
Return Nothing
End If
Dim parameters = symbol.GetParameters()
' Handle named argument
If argument.IsNamed Then
Dim namedArgument = DirectCast(argument, SimpleArgumentSyntax)
Dim name = namedArgument.NameColonEquals.Name.Identifier.ValueText
Return parameters.FirstOrDefault(Function(p) p.Name = name)
End If
' Handle positional argument
Dim index = argumentList.Arguments.IndexOf(argument)
If index < 0 Then
Return Nothing
End If
If index < parameters.Length Then
Return parameters(index)
End If
If allowParamArray Then
Dim lastParameter = parameters.LastOrDefault()
If lastParameter Is Nothing Then
Return Nothing
End If
If lastParameter.IsParams Then
Return lastParameter
End If
End If
Return Nothing
End Function
<Extension()>
Public Function GetArgumentExpression(argument As ArgumentSyntax) As ExpressionSyntax
Return argument.GetExpression()
End Function
End Module
End Namespace
|
davkean/roslyn
|
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/ArgumentSyntaxExtensions.vb
|
Visual Basic
|
apache-2.0
| 3,051
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports Desktop.Analyzers
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Namespace Desktop.VisualBasic.Analyzers
''' <summary>
''' CA2239: Provide deserialization methods for optional fields
''' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public NotInheritable Class BasicProvideDeserializationMethodsForOptionalFieldsFixer
Inherits ProvideDeserializationMethodsForOptionalFieldsFixer
End Class
End Namespace
|
qinxgit/roslyn-analyzers
|
src/Desktop.Analyzers/VisualBasic/BasicProvideDeserializationMethodsForOptionalFields.Fixer.vb
|
Visual Basic
|
apache-2.0
| 684
|
Public Class PostEventArgs
Inherits EventArgs
Public Sub New(ByVal aPostType As Integer, ByVal aCancel As Boolean, Optional ByVal aTransaction As IDbTransaction = Nothing)
Me.PostType = aPostType
Me.Cancel = aCancel
Me.Transaction = aTransaction
End Sub 'New
Public PostType As Integer
Public Cancel As Boolean
Public Transaction As IDbTransaction
End Class
Public Delegate Sub PostHandler(ByVal sender As Object, ByVal e As PostEventArgs)
Public Class DataRowEventArgs
Inherits EventArgs
Public Sub New(ByVal aRow As DataRow)
Me.Row = aRow
Me.Cancel = False
End Sub 'New
Public Row As DataRow
Public Cancel As Boolean
End Class
Public Delegate Sub RowCollectionChangedHandler(ByVal sender As Object, ByVal e As DataRowEventArgs)
|
EIDSS/EIDSS-Legacy
|
EIDSS v6/vb/Shared/bv_common/Core/Delegates.vb
|
Visual Basic
|
bsd-2-clause
| 842
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Classification.Classifiers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers
Friend Class OperatorOverloadSyntaxClassifier
Inherits AbstractSyntaxClassifier
Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(
GetType(BinaryExpressionSyntax),
GetType(UnaryExpressionSyntax))
Public Overrides Sub AddClassifications(
syntax As SyntaxNode,
semanticModel As SemanticModel,
options As ClassificationOptions,
result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken)
Dim symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken)
If TypeOf symbolInfo.Symbol Is IMethodSymbol AndAlso
DirectCast(symbolInfo.Symbol, IMethodSymbol).MethodKind = MethodKind.UserDefinedOperator Then
If TypeOf syntax Is BinaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, BinaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
ElseIf TypeOf syntax Is UnaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, UnaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
End If
End If
End Sub
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/OperatorOverloadSyntaxClassifier.vb
|
Visual Basic
|
mit
| 1,882
|
' 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
Public Overrides Function VisitFieldInitializer(node As BoundFieldInitializer) As BoundNode
Return VisitFieldOrPropertyInitializer(node, ImmutableArray(Of Symbol).CastUp(node.InitializedFields))
End Function
Public Overrides Function VisitPropertyInitializer(node As BoundPropertyInitializer) As BoundNode
Return VisitFieldOrPropertyInitializer(node, ImmutableArray(Of Symbol).CastUp(node.InitializedProperties))
End Function
''' <summary>
''' Field initializers need to be rewritten multiple times in case of an AsNew declaration with multiple field names because the
''' initializer may contain references to the current field like in the following example:
''' Class C1
''' Public x, y As New RefType() With {.Field1 = .Field2}
''' End Class
'''
''' in this example .Field2 references the temp that is created for x and y.
'''
''' We moved the final rewriting for field initializers to the local
''' rewriters because here we already have the infrastructure to replace placeholders.
''' </summary>
Private Function VisitFieldOrPropertyInitializer(node As BoundFieldOrPropertyInitializer, initializedSymbols As ImmutableArray(Of Symbol)) As BoundNode
Dim syntax = node.Syntax
Debug.Assert(
syntax.IsKind(SyntaxKind.AsNewClause) OrElse ' Dim a As New C(); Dim a,b As New C(); Property P As New C()
syntax.IsKind(SyntaxKind.ModifiedIdentifier) OrElse ' Dim a(1) As Integer
syntax.IsKind(SyntaxKind.EqualsValue)) ' Dim a = 1; Property P As Integer = 1
Dim rewrittenStatements = ArrayBuilder(Of BoundStatement).GetInstance(initializedSymbols.Length)
' it's enough to create one me reference if the symbols are not shared that gets reused for all following rewritings.
Dim meReferenceOpt As BoundExpression = Nothing
If Not initializedSymbols.First.IsShared Then
' create me reference if needed
Debug.Assert(_currentMethodOrLambda IsNot Nothing)
meReferenceOpt = New BoundMeReference(syntax, _currentMethodOrLambda.ContainingType)
meReferenceOpt.SetWasCompilerGenerated()
End If
Dim objectInitializer As BoundObjectInitializerExpression = Nothing
Dim createTemporary = True
If node.InitialValue.Kind = BoundKind.ObjectCreationExpression OrElse node.InitialValue.Kind = BoundKind.NewT Then
Dim objectCreationExpression = DirectCast(node.InitialValue, BoundObjectCreationExpressionBase)
If objectCreationExpression.InitializerOpt IsNot Nothing AndAlso
objectCreationExpression.InitializerOpt.Kind = BoundKind.ObjectInitializerExpression Then
objectInitializer = DirectCast(objectCreationExpression.InitializerOpt, BoundObjectInitializerExpression)
createTemporary = objectInitializer.CreateTemporaryLocalForInitialization
End If
End If
Dim instrument As Boolean = Me.Instrument(node)
For symbolIndex = 0 To initializedSymbols.Length - 1
Dim symbol = initializedSymbols(symbolIndex)
Dim accessExpression As BoundExpression
' if there are more than one symbol we need to create a field or property access for each of them
If initializedSymbols.Length > 1 Then
If symbol.Kind = SymbolKind.Field Then
Dim fieldSymbol = DirectCast(symbol, FieldSymbol)
accessExpression = New BoundFieldAccess(syntax, meReferenceOpt, fieldSymbol, True, fieldSymbol.Type)
Else
' We can get here when multiple WithEvents fields are initialized with As New ...
Dim propertySymbol = DirectCast(symbol, PropertySymbol)
accessExpression = New BoundPropertyAccess(syntax,
propertySymbol,
propertyGroupOpt:=Nothing,
accessKind:=PropertyAccessKind.Set,
isWriteable:=propertySymbol.HasSet,
receiverOpt:=meReferenceOpt,
arguments:=ImmutableArray(Of BoundExpression).Empty)
End If
Else
Debug.Assert(node.MemberAccessExpressionOpt IsNot Nothing)
' otherwise use the node stored in the bound initializer node
accessExpression = node.MemberAccessExpressionOpt
End If
Dim rewrittenStatement As BoundStatement
If Not createTemporary Then
Debug.Assert(objectInitializer.PlaceholderOpt IsNot Nothing)
' we need to replace the placeholder with it, so add it to the replacement map
AddPlaceholderReplacement(objectInitializer.PlaceholderOpt, accessExpression)
rewrittenStatement = VisitExpressionNode(node.InitialValue).ToStatement
RemovePlaceholderReplacement(objectInitializer.PlaceholderOpt)
Else
' in all other cases we want the initial value be assigned to the member (field or property)
rewrittenStatement = VisitExpression(New BoundAssignmentOperator(syntax,
accessExpression,
node.InitialValue,
suppressObjectClone:=False)).ToStatement
End If
If instrument Then
rewrittenStatement = _instrumenterOpt.InstrumentFieldOrPropertyInitializer(node, rewrittenStatement, symbolIndex, createTemporary)
End If
rewrittenStatements.Add(rewrittenStatement)
Next
Return New BoundStatementList(node.Syntax, rewrittenStatements.ToImmutableAndFree())
End Function
End Class
End Namespace
|
weltkante/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_FieldOrPropertyInitializer.vb
|
Visual Basic
|
apache-2.0
| 7,196
|
' 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.Tasks
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_ExtendedPropertyPattern_FirstPart_Get(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
C CProperty { {|Definition:$$get|}; set; }
int IntProperty { get; set; }
void M()
{
_ = this is { [|CProperty|].IntProperty: 2 };
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_ExtendedPropertyPattern_FirstPart_Set(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
C CProperty { get; {|Definition:$$set|}; }
int IntProperty { get; set; }
void M()
{
_ = this is { CProperty.IntProperty: 2 };
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_ExtendedPropertyPattern_SecondPart_Get(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
C CProperty { get; set; }
int IntProperty { {|Definition:$$get|}; set; }
void M()
{
_ = this is { CProperty.[|IntProperty|]: 2 };
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_Feature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int Prop { {|Definition:$$get|}; set; }
}
class C : IC
{
public virtual int Prop { {|Definition:get|}; set; }
}
class D : C
{
public override int Prop { {|Definition:get|} => base.[|Prop|]; set => base.Prop = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.Prop);
var v1 = ic.[|Prop|];
ic.Prop = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.Prop);
var v2 = c.[|Prop|];
c.Prop = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.Prop);
var v3 = d.[|Prop|];
d.Prop = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_Feature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int Prop { {|Definition:get|}; set; }
}
class C : IC
{
public virtual int Prop { {|Definition:$$get|}; set; }
}
class D : C
{
public override int Prop { {|Definition:get|} => base.[|Prop|]; set => base.Prop = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.Prop);
var v1 = ic.[|Prop|];
ic.Prop = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.Prop);
var v2 = c.[|Prop|];
c.Prop = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.Prop);
var v3 = d.[|Prop|];
d.Prop = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_Feature3(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int Prop { {|Definition:get|}; set; }
}
class C : IC
{
public virtual int Prop { {|Definition:get|}; set; }
}
class D : C
{
public override int Prop { {|Definition:$$get|} => base.[|Prop|]; set => base.Prop = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.Prop);
var v1 = ic.[|Prop|];
ic.Prop = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.Prop);
var v2 = c.[|Prop|];
c.Prop = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.Prop);
var v3 = d.[|Prop|];
d.Prop = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_Feature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int Prop { get; {|Definition:$$set|}; }
}
class C : IC
{
public virtual int Prop { get; {|Definition:set|}; }
}
class D : C
{
public override int Prop { get => base.Prop; {|Definition:set|} => base.[|Prop|] = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.Prop);
var v1 = ic.Prop;
ic.[|Prop|] = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.Prop);
var v2 = c.Prop;
c.[|Prop|] = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.Prop);
var v3 = d.Prop;
d.[|Prop|] = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_Feature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int Prop { get; {|Definition:set|}; }
}
class C : IC
{
public virtual int Prop { get; {|Definition:$$set|}; }
}
class D : C
{
public override int Prop { get => base.Prop; {|Definition:set|} => base.[|Prop|] = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.Prop);
var v1 = ic.Prop;
ic.[|Prop|] = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.Prop);
var v2 = c.Prop;
c.[|Prop|] = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.Prop);
var v3 = d.Prop;
d.[|Prop|] = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_Feature3(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int Prop { get; {|Definition:set|}; }
}
class C : IC
{
public virtual int Prop { get; {|Definition:set|}; }
}
class D : C
{
public override int Prop { get => base.Prop; {|Definition:$$set|} => base.[|Prop|] = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.Prop);
var v1 = ic.Prop;
ic.[|Prop|] = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.Prop);
var v2 = c.Prop;
c.[|Prop|] = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.Prop);
var v3 = d.Prop;
d.[|Prop|] = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Init_Feature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int Prop { get; {|Definition:$$init|}; }
}
class C : IC
{
public virtual int Prop { get; {|Definition:init|}; }
}
class D : C
{
public override int Prop { get => base.Prop; {|Definition:init|} => base.[|Prop|] = value; }
D()
{
this.[|Prop|] = 1;
this.[|Prop|]++;
}
void M()
{
_ = new D() { [|Prop|] = 1 };
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Init_FromProp_Feature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int {|Definition:$$Prop|} { get; set; }
}
class C : IC
{
public virtual int {|Definition:Prop|} { get; set; }
}
class D : C
{
public override int {|Definition:Prop|} { get => base.[|Prop|]; set => base.[|Prop|] = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.[|Prop|]);
var v1 = ic.[|Prop|];
ic.[|Prop|] = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.[|Prop|]);
var v2 = c.[|Prop|];
c.[|Prop|] = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.[|Prop|]);
var v3 = d.[|Prop|];
d.[|Prop|] = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_FromProp_Feature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int {|Definition:Prop|} { get; set; }
}
class C : IC
{
public virtual int {|Definition:$$Prop|} { get; set; }
}
class D : C
{
public override int {|Definition:Prop|} { get => base.[|Prop|]; set => base.[|Prop|] = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.[|Prop|]);
var v1 = ic.[|Prop|];
ic.[|Prop|] = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.[|Prop|]);
var v2 = c.[|Prop|];
c.[|Prop|] = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.[|Prop|]);
var v3 = d.[|Prop|];
d.[|Prop|] = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_FromProp_Feature3(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int {|Definition:Prop|} { get; set; }
}
class C : IC
{
public virtual int {|Definition:Prop|} { get; set; }
}
class D : C
{
public override int {|Definition:$$Prop|} { get => base.[|Prop|]; set => base.[|Prop|] = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.[|Prop|]);
var v1 = ic.[|Prop|];
ic.[|Prop|] = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.[|Prop|]);
var v2 = c.[|Prop|];
c.[|Prop|] = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.[|Prop|]);
var v3 = d.[|Prop|];
d.[|Prop|] = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_FromNameOf1_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int {|Definition:Prop|} { get; set; }
}
class C : IC
{
public virtual int {|Definition:Prop|} { get; set; }
}
class D : C
{
public override int {|Definition:Prop|} { get => base.[|Prop|]; set => base.[|Prop|] = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.[|$$Prop|]);
var v1 = ic.[|Prop|];
ic.[|Prop|] = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.[|Prop|]);
var v2 = c.[|Prop|];
c.[|Prop|] = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.[|Prop|]);
var v3 = d.[|Prop|];
d.[|Prop|] = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_FromNameOf1_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int {|Definition:Prop|} { get; set; }
}
class C : IC
{
public virtual int {|Definition:Prop|} { get; set; }
}
class D : C
{
public override int {|Definition:Prop|} { get => base.[|Prop|]; set => base.[|Prop|] = value; }
}
class Usages
{
void M()
{
IC ic;
var n1 = nameof(ic.[|$$Prop|]);
var v1 = ic.[|Prop|];
ic.[|Prop|] = 1;
ic.[|Prop|]++;
C c;
var n2 = nameof(c.[|Prop|]);
var v2 = c.[|Prop|];
c.[|Prop|] = 1;
c.[|Prop|]++;
D d;
var n3 = nameof(d.[|Prop|]);
var v3 = d.[|Prop|];
d.[|Prop|] = 1;
d.[|Prop|]++;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_ObjectInitializer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual int Prop { {|Definition:$$get|}; set; }
}
class Usages
{
void M()
{
new C
{
Prop = 1
};
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_ObjectInitializer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual int Prop { get; {|Definition:$$set|}; }
}
class Usages
{
void M()
{
new C
{
[|Prop|] = 1
};
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Prop_ObjectInitializer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual int {|Definition:$$Prop|} { get; set; }
}
class Usages
{
void M()
{
new C
{
[|Prop|] = 1
};
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_Indexer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int this[int i] { {|Definition:$$get|} => 0; set { } }
}
class C : IC
{
public virtual int this[int i] { {|Definition:get|} => 0; set { } }
}
class D : C
{
public override int this[int i] { {|Definition:get|} => base[||][i]; set { base[i] = value; } }
}
class Usages
{
void M()
{
IC ic;
var v1 = ic[||][0];
ic[0] = 1;
C c;
var v1 = c[||][0];
c[0] = 1;
D d;
var v1 = d[||][0];
d[0] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_Indexer2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int this[int i] { {|Definition:get|} => 0; set { } }
}
class C : IC
{
public virtual int this[int i] { {|Definition:$$get|} => 0; set { } }
}
class D : C
{
public override int this[int i] { {|Definition:get|} => base[||][i]; set { base[i] = value; } }
}
class Usages
{
void M()
{
IC ic;
var v1 = ic[||][0];
ic[0] = 1;
C c;
var v1 = c[||][0];
c[0] = 1;
D d;
var v1 = d[||][0];
d[0] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_Indexer3(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int this[int i] { {|Definition:get|} => 0; set { } }
}
class C : IC
{
public virtual int this[int i] { {|Definition:get|} => 0; set { } }
}
class D : C
{
public override int this[int i] { {|Definition:$$get|} => base[||][i]; set { base[i] = value; } }
}
class Usages
{
void M()
{
IC ic;
var v1 = ic[||][0];
ic[0] = 1;
C c;
var v1 = c[||][0];
c[0] = 1;
D d;
var v1 = d[||][0];
d[0] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_Indexer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int this[int i] { get => 0; {|Definition:$$set|} { } }
}
class C : IC
{
public virtual int this[int i] { get => 0; {|Definition:set|} { } }
}
class D : C
{
public override int this[int i] { get => base[i]; {|Definition:set|} { base[||][i] = value; } }
}
class Usages
{
void M()
{
IC ic;
var v1 = ic[0];
ic[||][0] = 1;
C c;
var v1 = c[0];
c[||][0] = 1;
D d;
var v1 = d[0];
d[||][0] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_Indexer2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int this[int i] { get => 0; {|Definition:set|} { } }
}
class C : IC
{
public virtual int this[int i] { get => 0; {|Definition:$$set|} { } }
}
class D : C
{
public override int this[int i] { get => base[i]; {|Definition:set|} { base[||][i] = value; } }
}
class Usages
{
void M()
{
IC ic;
var v1 = ic[0];
ic[||][0] = 1;
C c;
var v1 = c[0];
c[||][0] = 1;
D d;
var v1 = d[0];
d[||][0] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_Indexer3(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
int this[int i] { get => 0; {|Definition:set|} { } }
}
class C : IC
{
public virtual int this[int i] { get => 0; {|Definition:set|} { } }
}
class D : C
{
public override int this[int i] { get => base[i]; {|Definition:$$set|} { base[||][i] = value; } }
}
class Usages
{
void M()
{
IC ic;
var v1 = ic[0];
ic[||][0] = 1;
C c;
var v1 = c[0];
c[||][0] = 1;
D d;
var v1 = d[0];
d[||][0] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_Attribute1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class CAttribute : Attribute
{
public virtual int Prop { {|Definition:$$get|} => 0; set { } }
}
[C(Prop = 1)]
class D
{
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_Attribute1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class CAttribute : Attribute
{
public virtual int Prop { get => 0; {|Definition:$$set|} { } }
}
[C([|Prop|] = 1)]
class D
{
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_Cref(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
/// <see cref="Prop"/>
int Prop { {|Definition:$$get|}; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_Cref(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
/// <see cref="Prop"/>
int Prop { get; {|Definition:$$set|}; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Get_ExpressionTree1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Linq.Expressions;
interface I
{
int Prop { {|Definition:$$get|}; set; }
}
class C
{
void M()
{
Expression<Func<I,int>> e = i => i.[|Prop|];
Expression<Action<I>> e = i => i.Prop = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpAccessor_Set_ExpressionTree1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Linq.Expressions;
interface I
{
int Prop { get; {|Definition:$$set|};}
}
class C
{
void M()
{
Expression<Func<I,int>> e = i => i.Prop;
Expression<Action<I>> e = i => i.[|Prop|] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Get_Feature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
property {|Definition:Prop|} as integer
end interface
class C
implements IC
public overridable property Prop as integer implements IC.[|Prop|]
{|Definition:$$get|}
end get
set(value as integer)
end set
end property
end class
class D
inherits C
public overrides property prop as integer
{|Definition:get|}
return mybase.[|prop|]
end get
set(value as integer)
mybase.prop = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim n1 = nameof(ic1.Prop)
dim v1 = ic1.[|Prop|]
ic1.Prop = 1
ic1.[|Prop|] += 1
dim c1 as C
dim n2 = nameof(c1.Prop)
dim v2 = c1.[|Prop|]
c1.Prop = 1
c1.[|Prop|] += 1
dim d1 as D
dim n3 = nameof(d1.Prop)
dim v3 = d1.[|Prop|]
d1.Prop = 1
d1.[|Prop|] += 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Get_Feature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
property {|Definition:Prop|} as integer
end interface
class C
implements IC
public overridable property Prop as integer implements IC.[|Prop|]
{|Definition:get|}
end get
set(value as integer)
end set
end property
end class
class D
inherits C
public overrides property prop as integer
{|Definition:$$get|}
return mybase.[|prop|]
end get
set(value as integer)
mybase.prop = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim n1 = nameof(ic1.Prop)
dim v1 = ic1.[|Prop|]
ic1.Prop = 1
ic1.[|Prop|] += 1
dim c1 as C
dim n2 = nameof(c1.Prop)
dim v2 = c1.[|Prop|]
c1.Prop = 1
c1.[|Prop|] += 1
dim d1 as D
dim n3 = nameof(d1.Prop)
dim v3 = d1.[|Prop|]
d1.Prop = 1
d1.[|Prop|] += 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Set_Feature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
property {|Definition:Prop|} as integer
end interface
class C
implements IC
public overridable property Prop as integer implements IC.Prop
get
end get
{|Definition:$$set|}(value as integer)
end set
end property
end class
class D
inherits C
public overrides property prop as integer
get
return mybase.prop
end get
{|Definition:set|}(value as integer)
mybase.[|prop|] = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim n1 = nameof(ic1.Prop)
dim v1 = ic1.Prop
ic1.[|Prop|] = 1
ic1.[|Prop|] += 1
dim c1 as C
dim n2 = nameof(c1.Prop)
dim v2 = c1.Prop
c1.[|Prop|] = 1
c1.[|Prop|] += 1
dim d1 as D
dim n3 = nameof(d1.Prop)
dim v3 = d1.Prop
d1.[|Prop|] = 1
d1.[|Prop|] += 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Set_Feature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
property {|Definition:Prop|} as integer
end interface
class C
implements IC
public overridable property Prop as integer implements IC.Prop
get
end get
{|Definition:set|}(value as integer)
end set
end property
end class
class D
inherits C
public overrides property prop as integer
get
return mybase.prop
end get
{|Definition:$$set|}(value as integer)
mybase.[|prop|] = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim n1 = nameof(ic1.Prop)
dim v1 = ic1.Prop
ic1.[|Prop|] = 1
ic1.[|Prop|] += 1
dim c1 as C
dim n2 = nameof(c1.Prop)
dim v2 = c1.Prop
c1.[|Prop|] = 1
c1.[|Prop|] += 1
dim d1 as D
dim n3 = nameof(d1.Prop)
dim v3 = d1.Prop
d1.[|Prop|] = 1
d1.[|Prop|] += 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_FromProp_1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
property {|Definition:$$Prop|} as integer
end interface
class C
implements IC
public overridable property {|Definition:Prop|} as integer implements IC.[|Prop|]
get
end get
set(value as integer)
end set
end property
end class
class D
inherits C
public overrides property {|Definition:prop|} as integer
get
return mybase.[|prop|]
end get
set(value as integer)
mybase.[|prop|] = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim n1 = nameof(ic1.[|Prop|])
dim v1 = ic1.[|Prop|]
ic1.[|Prop|] = 1
ic1.[|Prop|] += 1
dim c1 as C
dim n2 = nameof(c1.[|Prop|])
dim v2 = c1.[|Prop|]
c1.[|Prop|] = 1
c1.[|Prop|] += 1
dim d1 as D
dim n3 = nameof(d1.[|Prop|])
dim v3 = d1.[|Prop|]
d1.[|Prop|] = 1
d1.[|Prop|] += 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_FromProp_2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
property {|Definition:Prop|} as integer
end interface
class C
implements IC
public overridable property {|Definition:$$Prop|} as integer implements IC.[|Prop|]
get
end get
set(value as integer)
end set
end property
end class
class D
inherits C
public overrides property {|Definition:prop|} as integer
get
return mybase.[|prop|]
end get
set(value as integer)
mybase.[|prop|] = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim n1 = nameof(ic1.[|Prop|])
dim v1 = ic1.[|Prop|]
ic1.[|Prop|] = 1
ic1.[|Prop|] += 1
dim c1 as C
dim n2 = nameof(c1.[|Prop|])
dim v2 = c1.[|Prop|]
c1.[|Prop|] = 1
c1.[|Prop|] += 1
dim d1 as D
dim n3 = nameof(d1.[|Prop|])
dim v3 = d1.[|Prop|]
d1.[|Prop|] = 1
d1.[|Prop|] += 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_FromProp_3(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
property {|Definition:Prop|} as integer
end interface
class C
implements IC
public overridable property {|Definition:Prop|} as integer implements IC.[|Prop|]
get
end get
set(value as integer)
end set
end property
end class
class D
inherits C
public overrides property {|Definition:$$prop|} as integer
get
return mybase.[|prop|]
end get
set(value as integer)
mybase.[|prop|] = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim n1 = nameof(ic1.[|Prop|])
dim v1 = ic1.[|Prop|]
ic1.[|Prop|] = 1
ic1.[|Prop|] += 1
dim c1 as C
dim n2 = nameof(c1.[|Prop|])
dim v2 = c1.[|Prop|]
c1.[|Prop|] = 1
c1.[|Prop|] += 1
dim d1 as D
dim n3 = nameof(d1.[|Prop|])
dim v3 = d1.[|Prop|]
d1.[|Prop|] = 1
d1.[|Prop|] += 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Get_ObjectInitializer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class C
public property Prop as integer
{|Definition:$$get|}
return 0
end get
set(value as integer)
end set
end class
class Usages
sub M()
dim x = new C with {
.Prop = 1
}
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Set_ObjectInitializer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class C
public property Prop as integer
get
return 0
end get
{|Definition:$$set|}(value as integer)
end set
end class
class Usages
sub M()
dim x = new C with {
.[|Prop|] = 1
}
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Property_ObjectInitializer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class C
public property {|Definition:$$Prop|} as integer
get
return 0
end get
set(value as integer)
end set
end class
class Usages
sub M()
dim x = new C with {
.[|Prop|] = 1
}
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Get_Indexer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
default property {|Definition:Prop|}(a as integer) as integer
end interface
class C
implements IC
public overridable default property Prop(a as integer) as integer implements IC.[|Prop|]
{|Definition:$$get|}
end get
set(value as integer)
end set
end property
end class
class D
inherits C
public overrides default property prop(a as integer) as integer
{|Definition:get|}
return mybase[||](a)
end get
set(value as integer)
mybase(a) = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim v1 = ic1[||](0)
ic1(0) = 1
dim c1 as C
dim v1 = c1[||](0)
c1(0) = 1
dim d1 as D
dim v1 = d1[||](0)
d1(0) = 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Get_Indexer2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
default property {|Definition:Prop|}(a as integer) as integer
end interface
class C
implements IC
public overridable default property Prop(a as integer) as integer implements IC.[|Prop|]
{|Definition:get|}
end get
set(value as integer)
end set
end property
end class
class D
inherits C
public overrides default property prop(a as integer) as integer
{|Definition:$$get|}
return mybase[||](a)
end get
set(value as integer)
mybase(a) = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim v1 = ic1[||](0)
ic1(0) = 1
dim c1 as C
dim v1 = c1[||](0)
c1(0) = 1
dim d1 as D
dim v1 = d1[||](0)
d1(0) = 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Set_Indexer1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
default property {|Definition:Prop|}(a as integer) as integer
end interface
class C
implements IC
public overridable default property Prop(a as integer) as integer implements IC.Prop
get
end get
{|Definition:$$set|}(value as integer)
end set
end property
end class
class D
inherits C
public overrides default property prop(a as integer) as integer
get
return mybase(a)
end get
{|Definition:set|}(value as integer)
mybase[||](a) = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim v1 = ic1(0)
ic1[||](0) = 1
dim c1 as C
dim v1 = c1(0)
c1[||](0) = 1
dim d1 as D
dim v1 = d1(0)
d1[||](0) = 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Set_Indexer2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
interface IC
default property {|Definition:Prop|}(a as integer) as integer
end interface
class C
implements IC
public overridable default property Prop(a as integer) as integer implements IC.Prop
get
end get
{|Definition:set|}(value as integer)
end set
end property
end class
class D
inherits C
public overrides default property prop(a as integer) as integer
get
return mybase(a)
end get
{|Definition:$$set|}(value as integer)
mybase[||](a) = value
end set
end property
end class
class Usages
sub M()
dim ic1 as IC
dim v1 = ic1(0)
ic1[||](0) = 1
dim c1 as C
dim v1 = c1(0)
c1[||](0) = 1
dim d1 as D
dim v1 = d1(0)
d1[||](0) = 1
end sub
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Get_Attribute1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports System
class CAttribute
inherits Attribute
public property Prop as integer
{|Definition:$$get|}
end get
set(value as integer)
end set
end property
end class
<C(Prop:=1)>
class D
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVBAccessor_Set_Attribute1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
imports System
class CAttribute
inherits Attribute
public property Prop as integer
get
end get
{|Definition:$$set|}(value as integer)
end set
end property
end class
<C([|Prop|]:=1)>
class D
end class
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AccessorSymbols.vb
|
Visual Basic
|
mit
| 44,034
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend Partial Class Parser
'
'============ Methods for parsing syntactic terminals ===============
'
' /*********************************************************************
' *
' * Function:
' * Parser::ParseIdentifier
' *
' * Purpose:
' * Parse an identifier. Current token must be at the expected
' * identifer. Keywords are NOT allowed as identifiers.
' *
' **********************************************************************/
' File: Parser.cpp
' Lines: 16939 - 16939
' IdentifierDescriptor .Parser::ParseIdentifier( [ _Inout_ bool& ErrorInConstruct ] [ bool allowNullable ] )
Private Function ParseIdentifier() As IdentifierTokenSyntax
Dim identifier As IdentifierTokenSyntax
If CurrentToken.Kind = SyntaxKind.IdentifierToken Then
identifier = DirectCast(CurrentToken, IdentifierTokenSyntax)
If (identifier.ContextualKind = SyntaxKind.AwaitKeyword AndAlso IsWithinAsyncMethodOrLambda) OrElse
(identifier.ContextualKind = SyntaxKind.YieldKeyword AndAlso IsWithinIteratorContext) Then
identifier = ReportSyntaxError(identifier, ERRID.ERR_InvalidUseOfKeyword)
End If
GetNextToken()
Else
' If the token is a keyword, assume that the user meant it to
' be an identifier and consume it. Otherwise, leave current token
' as is and let caller decide what to do.
If CurrentToken.IsKeyword Then
Dim keyword As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
identifier = _scanner.MakeIdentifier(keyword)
identifier = ReportSyntaxError(identifier, ERRID.ERR_InvalidUseOfKeyword)
GetNextToken()
Else
identifier = InternalSyntaxFactory.MissingIdentifier()
' a preceding "_" will be a BadToken already and there was already a
' ERR_ExpectedIdentifier diagnose message for it
If (CurrentToken.Kind = SyntaxKind.BadToken AndAlso CurrentToken.Text = "_") Then
identifier = identifier.AddLeadingSyntax(CurrentToken, ERRID.ERR_ExpectedIdentifier)
GetNextToken()
Else
identifier = ReportSyntaxError(identifier, ERRID.ERR_ExpectedIdentifier)
End If
End If
End If
Return identifier
End Function
Private Function ParseNullableIdentifier(ByRef optionalNullable As PunctuationSyntax) As IdentifierTokenSyntax
Dim identifier As IdentifierTokenSyntax
identifier = ParseIdentifier()
If SyntaxKind.QuestionToken = CurrentToken.Kind AndAlso Not identifier.ContainsDiagnostics Then
optionalNullable = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken()
End If
Return identifier
End Function
' /*********************************************************************
' *
' * Function:
' * Parser::ParseIdentifierAllowingKeyword
' *
' * Purpose:
' * Parse an identifier. Current token must be at the expected
' * identifer. Keywords are allowed as identifiers.
' *
' **********************************************************************/
' File: Parser.cpp
' Lines: 16998 - 16998
' IdentifierDescriptor .Parser::ParseIdentifierAllowingKeyword( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseIdentifierAllowingKeyword() As IdentifierTokenSyntax
Dim identifier As IdentifierTokenSyntax
If CurrentToken.Kind = SyntaxKind.IdentifierToken Then
identifier = DirectCast(CurrentToken, IdentifierTokenSyntax)
GetNextToken()
ElseIf CurrentToken.IsKeyword() Then
Dim keyword As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
identifier = _scanner.MakeIdentifier(keyword)
GetNextToken()
Else
' Current token is not advanced. Let caller decide what to do.
identifier = InternalSyntaxFactory.MissingIdentifier()
identifier = ReportSyntaxError(identifier, ERRID.ERR_ExpectedIdentifier)
End If
Return identifier
End Function
' File: Parser.cpp
' Lines: 17021 - 17021
' Expression* .Parser::ParseIdentifierExpressionAllowingKeyword( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseIdentifierNameAllowingKeyword() As IdentifierNameSyntax
Dim Name = ParseIdentifierAllowingKeyword()
Return SyntaxFactory.IdentifierName(Name)
End Function
Private Function ParseSimpleNameExpressionAllowingKeywordAndTypeArguments() As SimpleNameSyntax
Dim Name = ParseIdentifierAllowingKeyword()
If Not _evaluatingConditionCompilationExpression AndAlso
BeginsGeneric(allowGenericsWithoutOf:=True) Then
Dim AllowEmptyGenericArguments As Boolean = False
Dim AllowNonEmptyGenericArguments As Boolean = True
Dim Arguments As TypeArgumentListSyntax = ParseGenericArguments(
AllowEmptyGenericArguments,
AllowNonEmptyGenericArguments)
Return SyntaxFactory.GenericName(Name, Arguments)
Else
Return SyntaxFactory.IdentifierName(Name)
End If
End Function
Private Function ParseIntLiteral() As LiteralExpressionSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.IntegerLiteralToken, "Expected Integer literal.")
Dim Literal As LiteralExpressionSyntax = SyntaxFactory.NumericLiteralExpression(CurrentToken)
GetNextToken()
Return Literal
End Function
Private Function ParseCharLiteral() As LiteralExpressionSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.CharacterLiteralToken, "Expected Char literal.")
Dim Literal As LiteralExpressionSyntax = SyntaxFactory.CharacterLiteralExpression(CurrentToken)
GetNextToken()
Return Literal
End Function
Private Function ParseDecLiteral() As LiteralExpressionSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.DecimalLiteralToken, "must be at a decimal literal.")
Dim Literal As LiteralExpressionSyntax = SyntaxFactory.NumericLiteralExpression(CurrentToken)
GetNextToken()
Return Literal
End Function
''' <summary>
''' Parses StringLiteral
''' </summary>
''' <returns>LiteralNode</returns>
''' <remarks>If the current Token is not StringLiteral then returns LiteralNode with missing token.</remarks>
Private Function ParseStringLiteral() As LiteralExpressionSyntax
Dim stringToken As SyntaxToken = Nothing
VerifyExpectedToken(SyntaxKind.StringLiteralToken, stringToken)
Return SyntaxFactory.StringLiteralExpression(stringToken)
End Function
Private Function ParseFltLiteral() As LiteralExpressionSyntax
Debug.Assert(
CurrentToken.Kind = SyntaxKind.FloatingLiteralToken,
"must be at a float literal.")
Dim Literal As LiteralExpressionSyntax = SyntaxFactory.NumericLiteralExpression(CurrentToken)
GetNextToken()
Return Literal
End Function
Private Function ParseDateLiteral() As LiteralExpressionSyntax
Debug.Assert(
CurrentToken.Kind = SyntaxKind.DateLiteralToken,
"must be at a date literal.")
Dim Literal As LiteralExpressionSyntax = SyntaxFactory.DateLiteralExpression(CurrentToken)
GetNextToken()
Return Literal
End Function
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Parser/ParseTerminal.vb
|
Visual Basic
|
apache-2.0
| 8,838
|
' 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.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.ConvertAnonymousTypeToTuple
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToTuple
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=NameOf(VisualBasicConvertAnonymousTypeToTupleCodeFixProvider)), [Shared]>
Friend Class VisualBasicConvertAnonymousTypeToTupleCodeFixProvider
Inherits AbstractConvertAnonymousTypeToTupleCodeFixProvider(Of
ExpressionSyntax,
TupleExpressionSyntax,
AnonymousObjectCreationExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function ConvertToTuple(anonCreation As AnonymousObjectCreationExpressionSyntax) As TupleExpressionSyntax
Return SyntaxFactory.TupleExpression(
SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTriviaFrom(anonCreation.Initializer.OpenBraceToken),
ConvertInitializers(anonCreation.Initializer.Initializers),
SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTriviaFrom(anonCreation.Initializer.CloseBraceToken)).
WithPrependedLeadingTrivia(anonCreation.GetLeadingTrivia())
End Function
Private Function ConvertInitializers(initializers As SeparatedSyntaxList(Of FieldInitializerSyntax)) As SeparatedSyntaxList(Of SimpleArgumentSyntax)
Return SyntaxFactory.SeparatedList(initializers.Select(AddressOf ConvertInitializer), initializers.GetSeparators())
End Function
Private Function ConvertInitializer(field As FieldInitializerSyntax) As SimpleArgumentSyntax
Return SyntaxFactory.SimpleArgument(
GetNameEquals(field),
GetExpression(field)).WithTriviaFrom(field)
End Function
Private Shared Function GetNameEquals(field As FieldInitializerSyntax) As NameColonEqualsSyntax
Dim namedField = TryCast(field, NamedFieldInitializerSyntax)
If namedField Is Nothing Then
Return Nothing
End If
Return SyntaxFactory.NameColonEquals(
namedField.Name,
SyntaxFactory.Token(SyntaxKind.ColonEqualsToken).WithTriviaFrom(namedField.EqualsToken))
End Function
Private Shared Function GetExpression(field As FieldInitializerSyntax) As ExpressionSyntax
Return If(TryCast(field, InferredFieldInitializerSyntax)?.Expression,
TryCast(field, NamedFieldInitializerSyntax)?.Expression)
End Function
End Class
End Namespace
|
ErikSchierboom/roslyn
|
src/Analyzers/VisualBasic/CodeFixes/ConvertAnonymousTypeToTuple/VisualBasicConvertAnonymousTypeToTupleCodeFixProvider.vb
|
Visual Basic
|
apache-2.0
| 3,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
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class LambdaTests
Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim compilationDef =
<compilation name="LambdaTests1">
<file name="a.vb">
Module Program
Sub Main()
Dim y As Object = Function(ParamArray x as Integer()) x
Dim y1 As Object = Function(Optional x As Integer = 0) x
Dim y2 As Object = Function(x As Integer) As Integer x
Dim y3 As Object = Function(x As Integer) As Integer
return x
End Function
Dim y4 As Object = Function(x As Integer)
[Function] = Nothing
return x
End Function
Dim y5 As Object = Sub(x As Integer) As Integer
return x
End Sub
Dim y6 As Object = Sub(x As Integer)
return x
End Sub
Dim y8 As Object = Sub(x As Integer) System.Console.WriteLine(x)
Dim y7 As Object = Sub(x As Integer) As Integer x
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
<![CDATA[
BC30026: 'End Sub' expected.
Sub Main()
~~~~~~~~~~
BC33009: 'Lambda' parameters cannot be declared 'ParamArray'.
Dim y As Object = Function(ParamArray x as Integer()) x
~~~~~~~~~~
BC33010: 'Lambda' parameters cannot be declared 'Optional'.
Dim y1 As Object = Function(Optional x As Integer = 0) x
~~~~~~~~
BC36674: Multiline lambda expression is missing 'End Function'.
Dim y2 As Object = Function(x As Integer) As Integer x
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30205: End of statement expected.
Dim y2 As Object = Function(x As Integer) As Integer x
~
BC36641: Lambda parameter 'x' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim y3 As Object = Function(x As Integer) As Integer
~
BC36641: Lambda parameter 'x' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim y4 As Object = Function(x As Integer)
~
BC30451: 'Function' is not declared. It may be inaccessible due to its protection level.
[Function] = Nothing
~~~~~~~~~~
BC36641: Lambda parameter 'x' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim y5 As Object = Sub(x As Integer) As Integer
~
BC30205: End of statement expected.
Dim y5 As Object = Sub(x As Integer) As Integer
~~~~~~~~~~
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
return x
~~~~~~~~
BC36641: Lambda parameter 'x' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim y6 As Object = Sub(x As Integer)
~
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
return x
~~~~~~~~
BC36641: Lambda parameter 'x' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim y8 As Object = Sub(x As Integer) System.Console.WriteLine(x)
~
BC36641: Lambda parameter 'x' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim y7 As Object = Sub(x As Integer) As Integer x
~
BC30205: End of statement expected.
Dim y7 As Object = Sub(x As Integer) As Integer x
~~~~~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Sub
~
]]>
</expected>)
End Sub
<Fact>
Public Sub Test2()
Dim compilationDef =
<compilation name="LambdaTests2">
<file name="a.vb">
Module Program
Sub Main()
Dim l1 As System.Func(Of Integer, Integer) = Function(x) x
Dim l2 As System.Func(Of Integer, Integer) = Function(x)
Return x
End Function
Dim l3 As System.Action(Of Integer) = Sub(x) System.Console.WriteLine(x)
TakeAction(l3)
Dim l4 As System.Action(Of Integer) = Sub(x)
System.Console.WriteLine(x)
Goto LB1
LB1:
End Sub
Dim l5 As System.Action(Of Integer) = DirectCast(Sub(x)
System.Console.WriteLine(x)
Exit Sub
End Sub, System.Action(Of Integer))
Dim l6 As System.Action(Of Integer) = TryCast(Sub(x)
System.Console.WriteLine(x)
Exit Sub
End Sub, System.Action(Of Integer))
Dim y As Integer = 1
TakeAction(Sub(x)
System.Console.WriteLine(x)
y = y + x
TakeAction(Sub(z)
System.Console.WriteLine(z)
y = y + x
Exit Sub
End Sub)
Exit Sub
End Sub)
System.Console.WriteLine(y)
End Sub
Sub TakeAction(x as System.Action(Of Integer))
x.Invoke(1)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
CompileAndVerify(compilation, <![CDATA[
1
1
1
3
]]>)
End Sub
<Fact>
Public Sub Test3()
Dim compilationDef =
<compilation name="LambdaTests3">
<file name="a.vb">
Module Program
Sub Main()
TakeAction(Sub(x)
System.Console.WriteLine(x)
Exit Function ' 1
End Sub)
TakeAction(Sub(x) Exit Function) ' 2
TakeFunction(Function(x)
System.Console.WriteLine(x)
Exit Sub ' 3
return 34
End Function)
TakeAction(Sub(x)
System.Console.WriteLine(x)
LB2: Goto LB1 ' 4
End Sub)
LB1: Goto LB2
End Sub
Sub TakeAction(x as System.Action(Of Integer))
End Sub
Sub TakeFunction(x as System.Func(Of Integer, Integer))
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30067: 'Exit Function' is not valid in a Sub or Property.
Exit Function ' 1
~~~~~~~~~~~~~
BC30067: 'Exit Function' is not valid in a Sub or Property.
TakeAction(Sub(x) Exit Function) ' 2
~~~~~~~~~~~~~
BC30065: 'Exit Sub' is not valid in a Function or Property.
Exit Sub ' 3
~~~~~~~~
BC30132: Label 'LB1' is not defined.
LB2: Goto LB1 ' 4
~~~
BC30132: Label 'LB2' is not defined.
LB1: Goto LB2
~~~
</expected>)
End Sub
<Fact()>
Public Sub Test4()
Dim compilationDef =
<compilation name="LambdaTests4">
<file name="a.vb">
Module Program
Sub Main()
Dim y1 As System.Func(Of Integer) = Function() As <Out> Integer
Exit Function
End Function ' 0
Dim y2 As System.Func(Of Integer, Integer) = Function(<[In]> a) As Integer
Exit Function
End Function ' 8
Dim y3 As System.Func(Of Integer(), Integer) = Function(x() As Integer)
Exit Function
End Function ' 1
Dim y4 As System.Func(Of Integer()(), Integer) = Function(x() As Integer())
Exit Function
End Function ' 2
Dim y5 As System.Func(Of Integer(), Integer) = Function(x())
Exit Function
End Function '3
Dim y6 As System.Func(Of Integer, Integer) = Function(x?)
Exit Function
End Function ' 4
Dim y7 As System.Func(Of Integer, Integer) = Function(x)
Dim x As Object = Nothing ' 1
Exit Function
End Function ' 5
Dim local1 As Object = Nothing
Dim y8 As System.Func(Of Integer, Integer) = Function(x)
Dim local1 As Integer = 0
End Function ' 6
Dim y9 As System.Func(Of Integer, Integer) = Function(x)
Static local2 As Integer = 0
End Function ' 7
Dim y10 As System.Action(Of Integer) = Sub(local1)
End Sub
End Sub
Sub Main2(Of T)(param As Integer)
Dim y11 As System.Action(Of Integer) = Sub(T)
End Sub
Dim y12 As System.Action(Of Integer) = Sub(param As Integer)
End Sub
Dim y13 As System.Func(Of Integer, System.Action(Of Integer)) = Function(param2)
Return Sub(param2)
End Sub
End Function
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36677: Attributes cannot be applied to return types of lambda expressions.
Dim y1 As System.Func(Of Integer) = Function() As <Out> Integer
~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function ' 0
~~~~~~~~~~~~
BC36634: Attributes cannot be applied to parameters of lambda expressions.
Dim y2 As System.Func(Of Integer, Integer) = Function(<[In]> a) As Integer
~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function ' 8
~~~~~~~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function ' 1
~~~~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
Dim y4 As System.Func(Of Integer()(), Integer) = Function(x() As Integer())
~~~~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function ' 2
~~~~~~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer(), Integer)'.
Dim y5 As System.Func(Of Integer(), Integer) = Function(x())
~~~~~~~~~~~~~~
BC36643: Array modifiers cannot be specified on lambda expression parameter name. They must be specified on its type.
Dim y5 As System.Func(Of Integer(), Integer) = Function(x())
~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function '3
~~~~~~~~~~~~
BC36632: Nullable parameters must specify a type.
Dim y6 As System.Func(Of Integer, Integer) = Function(x?)
~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function ' 4
~~~~~~~~~~~~
BC36667: Variable 'x' is already declared as a parameter of this or an enclosing lambda expression.
Dim x As Object = Nothing ' 1
~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function ' 5
~~~~~~~~~~~~
BC30616: Variable 'local1' hides a variable in an enclosing block.
Dim local1 As Integer = 0
~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function ' 6
~~~~~~~~~~~~
BC36672: Static local variables cannot be declared inside lambda expressions.
Static local2 As Integer = 0
~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function ' 7
~~~~~~~~~~~~
BC36641: Lambda parameter 'local1' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim y10 As System.Action(Of Integer) = Sub(local1)
~~~~~~
BC32089: 'T' is already declared as a type parameter of this method.
Dim y11 As System.Action(Of Integer) = Sub(T)
~
BC36641: Lambda parameter 'param' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim y12 As System.Action(Of Integer) = Sub(param As Integer)
~~~~~
BC36641: Lambda parameter 'param2' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Return Sub(param2)
~~~~~~
]]></expected>)
End Sub
<Fact>
Public Sub Test5()
Dim compilationDef =
<compilation name="LambdaTests5">
<file name="a.vb">
Class TestBase
Public ReadOnly baseInstance As System.Guid
Public Shared ReadOnly baseShared As System.Guid
End Class
Structure TestStruct
Public instance As System.Guid
Public Shared [shared] As System.Guid
Public ReadOnly instanceRO As System.Guid
Public Shared ReadOnly sharedRO As System.Guid
End Structure
Class Test1
Inherits TestBase
Public ReadOnly x As System.Guid
Public ReadOnly x1 As TestStruct
Sub New()
x = New System.Guid()
x1.instance = New System.Guid()
x1.shared = New System.Guid() ' 21
x1.instanceRO = New System.Guid() ' 22
x1.sharedRO = New System.Guid() '23
Dim z As Test1 = New Test1()
z.x = New System.Guid() ' 24
z.x1.instance = New System.Guid() ' 25
z.x1.shared = New System.Guid() '26
z.x1.instanceRO = New System.Guid() '27
z.x1.sharedRO = New System.Guid() '28
Dim y1 As System.Action(Of Integer) = Sub(v)
x = New System.Guid() ' 1
PassByRef(x) ' 2
PassByRef(z.x)
PassByRef(baseInstance)
PassByRef(baseShared)
x1.instance = New System.Guid() '31
x1.shared = New System.Guid() '32
PassByRef(x1.instance) '33
PassByRef(x1.shared) '34
PassByRef(x1.instanceRO)
PassByRef(x1.sharedRO) '35
z.x1.shared = New System.Guid() '36
PassByRef(z.x1.instance)
PassByRef(z.x1.shared) '37
PassByRef(z.x1.instanceRO)
PassByRef(z.x1.sharedRO) '38
End Sub
End Sub
Sub NotAConstructor()
PassByRef(x)
Dim y1 As System.Action(Of Integer) = Sub(v)
x = New System.Guid() ' 5
PassByRef(x)
Dim z1 As Test1 = New Test1()
PassByRef(z1.x)
PassByRef(baseInstance)
PassByRef(baseShared)
PassByRef(x1.instance)
PassByRef(x1.shared) '42
PassByRef(x1.instanceRO)
PassByRef(x1.sharedRO) '43
PassByRef(z1.x1.instance)
PassByRef(z1.x1.shared) '44
PassByRef(z1.x1.instanceRO)
PassByRef(z1.x1.sharedRO) '45
End Sub
End Sub
Shared Sub PassByRef(ByRef v As System.Guid)
End Sub
End Class
Class Test2
ReadOnly x As System.Guid
Sub New()
Dim y1 As System.Action(Of Integer) = Sub(v)
PassByRef(x)
End Sub
End Sub
Shared Sub PassByRef(ByRef v As System.Guid)
End Sub
Shared Sub PassByRef(v As System.Object)
End Sub
End Class
Class Test3
Inherits TestBase
Shared ReadOnly x As System.Guid
Shared Sub New()
x = New System.Guid()
Dim y1 As System.Action(Of Integer) = Sub(v)
x = New System.Guid() ' 3
PassByRef(x) ' 4
Dim z As Test1 = New Test1()
PassByRef(z.x)
PassByRef(baseInstance)
PassByRef(baseShared)
End Sub
End Sub
Sub NotAConstructor()
PassByRef(x)
Dim y1 As System.Action(Of Integer) = Sub(v)
x = New System.Guid() ' 6
PassByRef(x)
Dim z As Test1 = New Test1()
PassByRef(z.x)
PassByRef(baseInstance)
PassByRef(baseShared)
End Sub
End Sub
Shared Sub PassByRef(ByRef v As System.Guid)
End Sub
End Class
Class Test4
Shared ReadOnly x As System.Guid
Sub New()
Dim y1 As System.Action(Of Integer) = Sub(v)
x = New System.Guid() ' 7
PassByRef(x)
End Sub
End Sub
Shared Sub PassByRef(ByRef v As System.Guid)
End Sub
End Class
Class Test5
ReadOnly x As System.Guid
Shared Sub New()
Dim t As New Test5()
Dim y1 As System.Action(Of Integer) = Sub(v)
t.x = New System.Guid() ' 8
PassByRef(t.x)
End Sub
End Sub
Shared Sub PassByRef(ByRef v As System.Guid)
End Sub
End Class
Class Test6
ReadOnly x As System.Guid
Sub New()
Dim y1 As System.Func(Of System.Action(Of Integer)) = Function()
Return Sub(v)
x = New System.Guid() ' 9
PassByRef(x) ' 10
End Sub
End Function
End Sub
Shared Sub PassByRef(ByRef v As System.Guid)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
x1.shared = New System.Guid() ' 21
~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x1.instanceRO = New System.Guid() ' 22
~~~~~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x1.sharedRO = New System.Guid() '23
~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
x1.sharedRO = New System.Guid() '23
~~~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
z.x = New System.Guid() ' 24
~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
z.x1.instance = New System.Guid() ' 25
~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
z.x1.shared = New System.Guid() '26
~~~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
z.x1.instanceRO = New System.Guid() '27
~~~~~~~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
z.x1.sharedRO = New System.Guid() '28
~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
z.x1.sharedRO = New System.Guid() '28
~~~~~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x = New System.Guid() ' 1
~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(x) ' 2
~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x1.instance = New System.Guid() '31
~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
x1.shared = New System.Guid() '32
~~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(x1.instance) '33
~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
PassByRef(x1.shared) '34
~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
PassByRef(x1.sharedRO) '35
~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
z.x1.shared = New System.Guid() '36
~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
PassByRef(z.x1.shared) '37
~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
PassByRef(z.x1.sharedRO) '38
~~~~~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x = New System.Guid() ' 5
~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
PassByRef(x1.shared) '42
~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
PassByRef(x1.sharedRO) '43
~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
PassByRef(z1.x1.shared) '44
~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
PassByRef(z1.x1.sharedRO) '45
~~~~~~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x = New System.Guid() ' 3
~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(x) ' 4
~
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.
PassByRef(baseInstance)
~~~~~~~~~~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x = New System.Guid() ' 6
~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x = New System.Guid() ' 7
~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
t.x = New System.Guid() ' 8
~~~
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
x = New System.Guid() ' 9
~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(x) ' 10
~
</expected>)
End Sub
<Fact>
Public Sub Test6()
Dim compilationDef =
<compilation name="LambdaTests6">
<file name="a.vb">
Module Module1
Sub Main()
Dim y1 As System.Func(Of Integer, Integer) = Function(x) As Integer
Return 1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36674: Multiline lambda expression is missing 'End Function'.
Dim y1 As System.Func(Of Integer, Integer) = Function(x) As Integer
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test7()
Dim compilationDef =
<compilation name="LambdaTests7">
<file name="a.vb">
Module Module1
Function Main() As Integer
Dim y1 As System.Action(Of Integer) = Sub(x)
Return
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36673: Multiline lambda expression is missing 'End Sub'.
Dim y1 As System.Action(Of Integer) = Sub(x)
~~~~~~
BC42353: Function 'Main' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test8()
Dim compilationDef =
<compilation name="LambdaTests8">
<file name="a.vb">
Module Module1
Sub Main()
M1(Function() Value()) '2
M1(Function() '4
Return Value()
End Function)
End Sub
Sub M1(x As System.Func(Of Short))
System.Console.WriteLine(x.GetType())
End Sub
Sub M1(x As System.Func(Of Byte))
System.Console.WriteLine(x.GetType())
End Sub
Function Value() As System.ValueType
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Byte]
System.Func`1[System.Byte]
]]>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'M1' can be called with these arguments:
'Public Sub M1(x As Func(Of Short))': Option Strict On disallows implicit conversions from 'ValueType' to 'Short'.
'Public Sub M1(x As Func(Of Byte))': Option Strict On disallows implicit conversions from 'ValueType' to 'Byte'.
M1(Function() Value()) '2
~~
BC30518: Overload resolution failed because no accessible 'M1' can be called with these arguments:
'Public Sub M1(x As Func(Of Short))': Option Strict On disallows implicit conversions from 'ValueType' to 'Short'.
'Public Sub M1(x As Func(Of Byte))': Option Strict On disallows implicit conversions from 'ValueType' to 'Byte'.
M1(Function() '4
~~
</expected>)
compilationDef =
<compilation name="LambdaTests8">
<file name="a.vb">
Module Module1
Sub Main()
M1(Function() 1) '1
M1(Function() '3
Return 1
End Function)
End Sub
Sub M1(x As System.Func(Of Short))
System.Console.WriteLine(x.GetType())
End Sub
Sub M1(x As System.Func(Of Byte))
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Byte]
System.Func`1[System.Byte]
]]>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Byte]
System.Func`1[System.Byte]
]]>)
End Sub
<Fact>
Public Sub Test9()
Dim compilationDef =
<compilation name="LambdaTests9">
<file name="a.vb">
Module Module1
Sub Main()
M1(Function() 0) '1
M1(Function() Value()) '2
M1(Function()
Return 0
End Function)
M1(Function()
Return Value()
End Function)
End Sub
Sub M1(x As System.Func(Of Integer))
System.Console.WriteLine(x.GetType())
End Sub
Sub M1(x As System.Func(Of System.ValueType))
System.Console.WriteLine(x.GetType())
End Sub
Function Value() As System.ValueType
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int32]
System.Func`1[System.ValueType]
System.Func`1[System.Int32]
System.Func`1[System.ValueType]
]]>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int32]
System.Func`1[System.ValueType]
System.Func`1[System.Int32]
System.Func`1[System.ValueType]
]]>)
End Sub
<Fact>
Public Sub Test10()
Dim compilationDef =
<compilation name="LambdaTests10">
<file name="a.vb">
Module Module1
Sub Main()
Dim a As Integer = 1
M1(Function() a)
M1(Function()
Return a
End Function)
End Sub
Sub M1(x As System.Func(Of Short))
System.Console.WriteLine(x.GetType())
End Sub
Sub M1(x As System.Func(Of Byte))
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Byte]
System.Func`1[System.Byte]
]]>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'M1' can be called with these arguments:
'Public Sub M1(x As Func(Of Short))': Option Strict On disallows implicit conversions from 'Integer' to 'Short'.
'Public Sub M1(x As Func(Of Byte))': Option Strict On disallows implicit conversions from 'Integer' to 'Byte'.
M1(Function() a)
~~
BC30518: Overload resolution failed because no accessible 'M1' can be called with these arguments:
'Public Sub M1(x As Func(Of Short))': Option Strict On disallows implicit conversions from 'Integer' to 'Short'.
'Public Sub M1(x As Func(Of Byte))': Option Strict On disallows implicit conversions from 'Integer' to 'Byte'.
M1(Function()
~~
</expected>)
End Sub
<Fact>
Public Sub Test11()
Dim compilationDef =
<compilation name="LambdaTests11">
<file name="a.vb">
Module Module1
Sub Main()
Dim a As Integer = 1
M1(Function() )
M1(Function()
End Function)
M2(Sub() )
M2(Sub()
End Sub)
End Sub
Sub M1(x As System.Func(Of Short))
End Sub
Sub M2(x As System.Action)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
<![CDATA[
BC30201: Expression expected.
M1(Function() )
~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function)
~~~~~~~~~~~~
BC36918: Single-line statement lambdas must include exactly one statement.
M2(Sub() )
~~~~~~
]]>
</expected>)
End Sub
<Fact>
Public Sub Test12()
Dim compilationDef =
<compilation name="LambdaTests12">
<file name="a.vb">
Module Module1
Sub Main()
M2(1.5)
End Sub
Sub M2(x As Short)
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(x As Single)
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30519: Overload resolution failed because no accessible 'M2' can be called without a narrowing conversion:
'Public Sub M2(x As Short)': Argument matching parameter 'x' narrows from 'Double' to 'Short'.
'Public Sub M2(x As Single)': Argument matching parameter 'x' narrows from 'Double' to 'Single'.
M2(1.5)
~~
</expected>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Single
]]>)
compilationDef =
<compilation name="LambdaTests12">
<file name="a.vb">
Module Module1
Sub Main()
M1(Function()
Return 1.5
End Function)
End Sub
Sub M1(x As System.Func(Of Short))
System.Console.WriteLine(x.GetType())
End Sub
Sub M1(x As System.Func(Of Single))
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int16]
]]>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Single]
]]>)
End Sub
<Fact>
Public Sub Test13()
Dim compilationDef =
<compilation name="LambdaTests13">
<file name="a.vb">
Module Module1
Sub Main()
M1(Function()
Return 1
End Function)
M2(1)
End Sub
Sub M1(x As System.Func(Of Short))
System.Console.WriteLine(x.GetType())
End Sub
Sub M1(x As System.Func(Of Integer))
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(x As Short)
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(x As Integer)
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int32]
System.Int32
]]>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int32]
System.Int32
]]>)
End Sub
<Fact>
Public Sub Test14()
Dim compilationDef =
<compilation name="LambdaTests14">
<file name="a.vb">
Module Module1
Sub Main()
M1(Function()
Return 1
End Function)
M2(1)
End Sub
Sub M1(x As System.Func(Of Short))
System.Console.WriteLine(x.GetType())
End Sub
Sub M1(x As System.Func(Of Long))
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(x As Short)
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(x As Long)
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int64]
System.Int64
]]>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int64]
System.Int64
]]>)
End Sub
<Fact>
Public Sub Test15()
Dim compilationDef =
<compilation name="LambdaTests15">
<file name="a.vb">
Module Module1
Sub Main()
Dim a As Integer = 1
M1(Function()
Return a
End Function,
Function(x)
If x Then
Return 1
Else
Return Value()
End If
End Function)
End Sub
Sub M1(x As System.Func(Of Integer), y As System.Func(Of Boolean, Long))
System.Console.WriteLine(y.GetType())
End Sub
Sub M1(x As System.Func(Of Integer), y As System.Func(Of Boolean, Integer))
System.Console.WriteLine(y.GetType())
End Sub
Function Value() As Long
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`2[System.Boolean,System.Int64]
]]>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompileAndVerify(compilation, <![CDATA[
System.Func`2[System.Boolean,System.Int64]
]]>)
End Sub
<Fact()>
Public Sub Test16()
Dim compilationDef =
<compilation name="LambdaTests15">
<file name="a.vb">
Module Module1
Sub Main()
Dim z As String
Dim a As System.Func(Of Boolean, String) = Function(x As Boolean)
Dim y As String
If x Then
Return ""
ElseIf Not x Then
Return y
ElseIf x Then
Return z
y = ""
End If
End Function
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
<![CDATA[
BC42104: Variable 'y' is used before it has been assigned a value. A null reference exception could result at runtime.
Return y
~
BC42104: Variable 'z' is used before it has been assigned a value. A null reference exception could result at runtime.
Return z
~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
]]>
</expected>)
End Sub
<WorkItem(539777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539777")>
<Fact>
Public Sub TestOverloadResolutionWithStrictOff()
Dim compilationDef =
<compilation name="TestOverloadResolutionWithStrictOff">
<file name="M.vb">
Option Strict Off
Imports System
Module M
Function Goo(ByVal x As Func(Of Object), ByVal y As Integer) As String
Return "ABC"
End Function
Sub Goo(ByVal x As Func(Of String), ByVal y As Long)
End Sub
Sub Main()
Dim x As Object = 1
Dim y As Long = 1
Console.WriteLine(Goo(Function() x, y).ToLower())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompileAndVerify(compilation, expectedOutput:="abc")
End Sub
<WorkItem(539608, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539608")>
<Fact>
Public Sub InvokeOffOfLambda()
Dim compilationDef =
<compilation name="InvokeOffOfLambda">
<file name="M.vb">
Option Strict Off
Module Module1
Sub Main()
Dim x = Function() As String
Return 1
End Function.Invoke & Function() As String
Return 2
End Function.Invoke
System.Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:="12")
End Sub
<WorkItem(539519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539519")>
<Fact>
Public Sub ParseIncompleteMultiLineLambdaWithExpressionAfterAsClause()
' This looks like a single line lambda with an as clause but it is in fact a badly formed multi-line lambda
Dim compilationDef =
<compilation name="IncompleteMultiLineLambdaWithExpressionAfterAsClause">
<file name="M.vb">
<![CDATA[
Module Program
Sub Main()
Dim l1 As System.Func(Of Integer, Integer) = Function(x) As Integer x
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors>
<![CDATA[
BC36674: Multiline lambda expression is missing 'End Function'.
Dim l1 As System.Func(Of Integer, Integer) = Function(x) As Integer x
~~~~~~~~~~~~~~~~~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
Dim l1 As System.Func(Of Integer, Integer) = Function(x) As Integer x
~
BC30205: End of statement expected.
Dim l1 As System.Func(Of Integer, Integer) = Function(x) As Integer x
~
]]>
</errors>)
End Sub
<Fact>
Public Sub Error_BC36532()
Dim compilationDef =
<compilation name="BC36532">
<file name="M.vb">
imports System
Module Module1
Sub Main()
Dim x5 As Func(Of Integer) = Function() As Guid
Return New Guid()
End Function
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer)'.
Dim x5 As Func(Of Integer) = Function() As Guid
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Error_BC36670()
Dim compilationDef =
<compilation name="BC36670">
<file name="M.vb">
imports System
Module Module1
Sub Main()
Dim x6 As Func(Of Integer) = Sub(y As Guid)
End Sub
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of Integer)'.
Dim x6 As Func(Of Integer) = Sub(y As Guid)
~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Error_BC36625()
Dim compilationDef =
<compilation name="BC36625">
<file name="M.vb">
imports System
Module Module1
Sub Main()
Dim x4 As System.Guid = Sub(x0 As Integer) x0 += 1
Dim x41 As Object
x41 = CType(Sub(x0 As Integer) x0 += 1, Guid)
x41 = DirectCast(Sub(x0 As Integer) x0 += 1, Guid)
x41 = TryCast(Sub(x0 As Integer) x0 += 1, Guid)
x41 = TryCast(Sub(x0 As Integer) x0 += 1, String)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36625: Lambda expression cannot be converted to 'Guid' because 'Guid' is not a delegate type.
Dim x4 As System.Guid = Sub(x0 As Integer) x0 += 1
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36625: Lambda expression cannot be converted to 'Guid' because 'Guid' is not a delegate type.
x41 = CType(Sub(x0 As Integer) x0 += 1, Guid)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36625: Lambda expression cannot be converted to 'Guid' because 'Guid' is not a delegate type.
x41 = DirectCast(Sub(x0 As Integer) x0 += 1, Guid)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36625: Lambda expression cannot be converted to 'Guid' because 'Guid' is not a delegate type.
x41 = TryCast(Sub(x0 As Integer) x0 += 1, Guid)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36625: Lambda expression cannot be converted to 'String' because 'String' is not a delegate type.
x41 = TryCast(Sub(x0 As Integer) x0 += 1, String)
~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(540867, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540867")>
<Fact>
Public Sub LambdaForSub2()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Bar(Of T)(ByVal x As T)
Console.WriteLine(x)
End Sub
Sub Main()
Dim x As Func(Of Action(Of String)) = Function() AddressOf Bar
x.Invoke().Invoke("Hello World.")
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="Hello World.")
End Sub
<WorkItem(528344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528344")>
<Fact()>
Public Sub DelegateParametersCanBeOmittedInLambda()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
Dim x As Action(Of Integer) = Sub() Return
End Sub
End Module
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(528346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528346")>
<Fact()>
Public Sub ParameterTypesCanBeRelaxedInLambda()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
Dim a As Action(Of String) = Sub(x As Object) Return
End Sub
End Module
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(528347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528347")>
<Fact()>
Public Sub ReturnTypeCanBeRelaxedInLambda()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
Dim a As Func(Of Object) = Function() As String
Return Nothing
End Function
End Sub
End Module
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(528348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528348")>
<Fact()>
Public Sub ReturnValueOfLambdaCanBeIgnored()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
Dim x As Action = Function() 1
End Sub
End Module
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(528355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528355")>
<Fact()>
Public Sub OverloadResolutionWithNestedLambdas()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C
Shared Sub Main()
Goo(Function() Function() Nothing)
End Sub
Shared Sub Goo(x As Func(Of Func(Of String)))
End Sub
Sub Goo(x As Func(Of Func(Of Object)))
End Sub
End Class
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(541008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541008")>
<Fact>
Public Sub LambdaInFieldInitializer()
Dim source =
<compilation>
<file name="C.vb">
Imports System
Class C
Dim A As Action = Sub() Console.Write(ToString)
Shared Sub Main()
Dim c As New C()
c.A()
End Sub
End Class
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off))
CompileAndVerify(comp1, expectedOutput:="C")
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
CompileAndVerify(comp2, expectedOutput:="C")
End Sub
<WorkItem(541894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541894")>
<Fact()>
Public Sub InvokeLambda01()
Dim source =
<compilation>
<file name="InvokeLambda01.vb">
Imports System
Module MMM
Sub Main()
Dim local = (Function(ap As Byte) As String
Return ap.ToString()
End Function)(123)
Console.Writeline(local)
End Sub
End Module
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off))
CompileAndVerify(comp1, expectedOutput:="123")
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
CompileAndVerify(comp2, expectedOutput:="123")
End Sub
<WorkItem(528678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528678")>
<Fact>
Public Sub LambdaInsideParens()
Dim source =
<compilation>
<file name="LambdaInsideParens.vb">
Imports System
Module Module1
Public Sub Main()
Dim func As Func(Of Long, Long) = (Function(x) x)
End Sub
End Module
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics()
End Sub
<WorkItem(904998, "DevDiv/Personal")>
<Fact>
Public Sub BC36919ERR_DimInSingleLineSubLambda()
Dim source = <compilation>
<file name="BC36919ERR_DimInSingleLineSubLambda"><![CDATA[
Module Module1
Public Sub Main()
Dim x = Sub() Dim y = 2
End Sub
End Module
]]></file></compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_SubDisallowsStatement, "Dim y = 2"))
End Sub
<WorkItem(542665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542665")>
<Fact>
Public Sub DimInSingleLineIfInSingleLineLambda()
Dim compilationDef =
<compilation name="DimInSingleLineIfInSingleLineLambda">
<file name="a.vb">
Imports System
Module M
Sub Main
Dim c = True
Dim z As Action = Sub() If c Then Dim x = 2 : Console.WriteLine(x)
z()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, expectedOutput:="2").VerifyDiagnostics()
End Sub
<Fact>
Public Sub FunctionValueOfLambdaDoesNotHaveAName()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x = Function() as String
dim [Function] as Integer = 23
Return [Function].ToString()
End Function
dim y = Sub()
dim [Sub] as Integer = 23
End Sub
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef).VerifyDiagnostics()
End Sub
<WorkItem(546167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546167")>
<Fact()>
Public Sub ImplicitlyDeclaredVariableInsideLambdaReused()
Dim compilationDef =
<compilation>
<file name="a.vb">
Option Explicit Off
Module Test
Sub Sub1()
Dim a = Function(implicit1) implicit1
Dim b = Function() implicit1 'Creates a new Implicit variable
Dim c = Sub()
Dim a1 = Function(implicit2) implicit2
Dim b2 = Function() implicit2 'Creates a new Implicit variable
End Sub
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36641: Lambda parameter 'implicit1' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim a = Function(implicit1) implicit1
~~~~~~~~~
BC42104: Variable 'implicit1' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim b = Function() implicit1 'Creates a new Implicit variable
~~~~~~~~~
BC36641: Lambda parameter 'implicit2' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim a1 = Function(implicit2) implicit2
~~~~~~~~~
BC42104: Variable 'implicit2' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim b2 = Function() implicit2 'Creates a new Implicit variable
~~~~~~~~~
</expected>)
End Sub
<WorkItem(760094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760094")>
<Fact()>
Public Sub Bug760094_OneTopLevelLambda()
Dim compilationDef =
<compilation>
<file name="a.vb">
Interface IRealBinding
End Interface
Interface IBinderConverter
End Interface
Class EqualityWeakReference
Public IsAlive As Boolean
End Class
Class PropertyInfo
End Class
Friend Delegate Function OnChangeDelegateFactoryDelegate(ByVal currentIndex As Integer, ByVal weakSource As EqualityWeakReference) As System.Action(Of Object)
Friend Delegate Sub OnBindLastItem(ByVal index As Integer, ByVal pi As PropertyInfo, ByVal source As Object)
Class OnePropertyPathBinding
Public Sub Bind(ByVal factory As OnChangeDelegateFactoryDelegate, ByVal OnfinalBind As OnBindLastItem)
factory(1, Nothing)(Nothing)
End Sub
Public Sub RemoveNotify(ByVal currentIndex As Integer)
End Sub
End Class
Friend Class PropertyPathBindingItem
Shared Sub Main()
Dim x = new PropertyPathBindingItem()
System.Console.WriteLine("Done.")
End Sub
Private _DestinationBinding As OnePropertyPathBinding
Friend Sub New()
_DestinationBinding = New OnePropertyPathBinding()
_DestinationBinding.Bind(Function(currentIndex As Integer, weakSource As EqualityWeakReference)
Return Sub(value As Object)
_DestinationBinding.RemoveNotify(currentIndex)
End Sub
End Function, Nothing)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(compilationDef, options:=TestOptions.ReleaseExe)
Dim verifier = CompileAndVerify(compilation,
<![CDATA[
Done.
]]>)
verifier.VerifyIL("PropertyPathBindingItem..ctor",
<![CDATA[
{
// Code size 42 (0x2a)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: newobj "Sub OnePropertyPathBinding..ctor()"
IL_000c: stfld "PropertyPathBindingItem._DestinationBinding As OnePropertyPathBinding"
IL_0011: ldarg.0
IL_0012: ldfld "PropertyPathBindingItem._DestinationBinding As OnePropertyPathBinding"
IL_0017: ldarg.0
IL_0018: ldftn "Function PropertyPathBindingItem._Lambda$__2-0(Integer, EqualityWeakReference) As System.Action(Of Object)"
IL_001e: newobj "Sub OnChangeDelegateFactoryDelegate..ctor(Object, System.IntPtr)"
IL_0023: ldnull
IL_0024: callvirt "Sub OnePropertyPathBinding.Bind(OnChangeDelegateFactoryDelegate, OnBindLastItem)"
IL_0029: ret
}
]]>)
verifier.VerifyIL("PropertyPathBindingItem._Lambda$__2-0",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: newobj "Sub PropertyPathBindingItem._Closure$__2-0..ctor()"
IL_0005: dup
IL_0006: ldarg.0
IL_0007: stfld "PropertyPathBindingItem._Closure$__2-0.$VB$Me As PropertyPathBindingItem"
IL_000c: dup
IL_000d: ldarg.1
IL_000e: stfld "PropertyPathBindingItem._Closure$__2-0.$VB$Local_currentIndex As Integer"
IL_0013: ldftn "Sub PropertyPathBindingItem._Closure$__2-0._Lambda$__1(Object)"
IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)"
IL_001e: ret
}
]]>)
verifier.VerifyIL("PropertyPathBindingItem._Closure$__2-0._Lambda$__1",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld "PropertyPathBindingItem._Closure$__2-0.$VB$Me As PropertyPathBindingItem"
IL_0006: ldfld "PropertyPathBindingItem._DestinationBinding As OnePropertyPathBinding"
IL_000b: ldarg.0
IL_000c: ldfld "PropertyPathBindingItem._Closure$__2-0.$VB$Local_currentIndex As Integer"
IL_0011: callvirt "Sub OnePropertyPathBinding.RemoveNotify(Integer)"
IL_0016: ret
}
]]>)
End Sub
<WorkItem(760094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760094")>
<Fact()>
Public Sub Bug760094_TwoTopLevelLambdas()
Dim compilationDef =
<compilation>
<file name="a.vb">
Interface IRealBinding
End Interface
Interface IBinderConverter
End Interface
Class EqualityWeakReference
Public IsAlive As Boolean
End Class
Class PropertyInfo
End Class
Friend Delegate Function OnChangeDelegateFactoryDelegate(ByVal currentIndex As Integer, ByVal weakSource As EqualityWeakReference) As System.Action(Of Object)
Friend Delegate Sub OnBindLastItem(ByVal index As Integer, ByVal pi As PropertyInfo, ByVal source As Object)
Class OnePropertyPathBinding
Public Sub Bind(ByVal factory As OnChangeDelegateFactoryDelegate, ByVal OnfinalBind As OnBindLastItem)
End Sub
Public Sub RemoveNotify(ByVal currentIndex As Integer)
End Sub
End Class
Friend Class PropertyPathBindingItem
Private _DestinationBinding As OnePropertyPathBinding
Friend Sub New()
_DestinationBinding = New OnePropertyPathBinding()
_DestinationBinding.Bind(Function(currentIndex As Integer, weakSource As EqualityWeakReference)
Return Sub(value As Object)
_DestinationBinding.RemoveNotify(currentIndex)
End Sub
End Function, Nothing)
_DestinationBinding.Bind(Function(currentIndex As Integer, weakSource As EqualityWeakReference)
Return Sub(value As Object)
_DestinationBinding.RemoveNotify(currentIndex)
End Sub
End Function, Nothing)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(compilationDef, options:=TestOptions.ReleaseDll)
Dim verifier = CompileAndVerify(compilation)
verifier.VerifyIL("PropertyPathBindingItem..ctor",
<![CDATA[
{
// Code size 66 (0x42)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: newobj "Sub OnePropertyPathBinding..ctor()"
IL_000c: stfld "PropertyPathBindingItem._DestinationBinding As OnePropertyPathBinding"
IL_0011: ldarg.0
IL_0012: ldfld "PropertyPathBindingItem._DestinationBinding As OnePropertyPathBinding"
IL_0017: ldarg.0
IL_0018: ldftn "Function PropertyPathBindingItem._Lambda$__1-0(Integer, EqualityWeakReference) As System.Action(Of Object)"
IL_001e: newobj "Sub OnChangeDelegateFactoryDelegate..ctor(Object, System.IntPtr)"
IL_0023: ldnull
IL_0024: callvirt "Sub OnePropertyPathBinding.Bind(OnChangeDelegateFactoryDelegate, OnBindLastItem)"
IL_0029: ldarg.0
IL_002a: ldfld "PropertyPathBindingItem._DestinationBinding As OnePropertyPathBinding"
IL_002f: ldarg.0
IL_0030: ldftn "Function PropertyPathBindingItem._Lambda$__1-2(Integer, EqualityWeakReference) As System.Action(Of Object)"
IL_0036: newobj "Sub OnChangeDelegateFactoryDelegate..ctor(Object, System.IntPtr)"
IL_003b: ldnull
IL_003c: callvirt "Sub OnePropertyPathBinding.Bind(OnChangeDelegateFactoryDelegate, OnBindLastItem)"
IL_0041: ret
}
]]>)
verifier.VerifyIL("PropertyPathBindingItem._Lambda$__1-0",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: newobj "Sub PropertyPathBindingItem._Closure$__1-0..ctor()"
IL_0005: dup
IL_0006: ldarg.0
IL_0007: stfld "PropertyPathBindingItem._Closure$__1-0.$VB$Me As PropertyPathBindingItem"
IL_000c: dup
IL_000d: ldarg.1
IL_000e: stfld "PropertyPathBindingItem._Closure$__1-0.$VB$Local_currentIndex As Integer"
IL_0013: ldftn "Sub PropertyPathBindingItem._Closure$__1-0._Lambda$__1(Object)"
IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)"
IL_001e: ret
}
]]>)
verifier.VerifyIL("PropertyPathBindingItem._Lambda$__1-2",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: newobj "Sub PropertyPathBindingItem._Closure$__1-1..ctor()"
IL_0005: dup
IL_0006: ldarg.0
IL_0007: stfld "PropertyPathBindingItem._Closure$__1-1.$VB$Me As PropertyPathBindingItem"
IL_000c: dup
IL_000d: ldarg.1
IL_000e: stfld "PropertyPathBindingItem._Closure$__1-1.$VB$Local_currentIndex As Integer"
IL_0013: ldftn "Sub PropertyPathBindingItem._Closure$__1-1._Lambda$__3(Object)"
IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)"
IL_001e: ret
}
]]>)
verifier.VerifyIL("PropertyPathBindingItem._Closure$__1-0._Lambda$__1",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld "PropertyPathBindingItem._Closure$__1-0.$VB$Me As PropertyPathBindingItem"
IL_0006: ldfld "PropertyPathBindingItem._DestinationBinding As OnePropertyPathBinding"
IL_000b: ldarg.0
IL_000c: ldfld "PropertyPathBindingItem._Closure$__1-0.$VB$Local_currentIndex As Integer"
IL_0011: callvirt "Sub OnePropertyPathBinding.RemoveNotify(Integer)"
IL_0016: ret
}
]]>)
verifier.VerifyIL("PropertyPathBindingItem._Closure$__1-1._Lambda$__3",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld "PropertyPathBindingItem._Closure$__1-1.$VB$Me As PropertyPathBindingItem"
IL_0006: ldfld "PropertyPathBindingItem._DestinationBinding As OnePropertyPathBinding"
IL_000b: ldarg.0
IL_000c: ldfld "PropertyPathBindingItem._Closure$__1-1.$VB$Local_currentIndex As Integer"
IL_0011: callvirt "Sub OnePropertyPathBinding.RemoveNotify(Integer)"
IL_0016: ret
}
]]>)
End Sub
<WorkItem(1207506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1207506"), WorkItem(4899, "https://github.com/dotnet/roslyn/issues/4899")>
<Fact()>
Public Sub InitClosureInsideABlockInAConstructor()
Dim compilationDef =
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim f As New FpB(100, 100)
System.Console.WriteLine(f.FPixels.Length)
End Sub
End Module
Public Class FpB
Public Property FPixels() As FloatPointF(,)
Get
System.Console.WriteLine("In getter")
Return m_FPixels
End Get
Set(value As FloatPointF(,))
m_FPixels = value
End Set
End Property
Private m_FPixels As FloatPointF(,)
Public Sub New(width As Integer, height As Integer)
Try
Dim w As Integer = width
Dim h As Integer = height
Me.FPixels = New FloatPointF(w - 1, h - 1) {}
CallDelegate(Sub(y)
Dim x = Math.Min(0, w - 1)
End Sub)
Catch ex As Exception
System.Console.WriteLine(ex.Message)
End Try
End Sub
Sub CallDelegate(d As Action(Of Integer))
d(1)
End Sub
End Class
Public Structure FloatPointF
Public X As Single
Public Y As Single
End Structure
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
Dim verifier = CompileAndVerify(compilation,
<![CDATA[
In getter
10000
]]>)
End Sub
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Semantics/LambdaTests.vb
|
Visual Basic
|
apache-2.0
| 79,870
|
' 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
Module Module1
Sub Main()
Dim i8 As SByte
Dim i16 As Short
Dim i32 As Integer
Dim i64 As Long
Dim ui8 As Byte
Dim ui16 As UShort
Dim ui32 As UInteger
Dim ui64 As ULong
i8 = 1
i16 = 1
i32 = 1
i64 = 1
ui8 = 1
ui16 = 1
ui32 = 1
ui64 = 1
Console.WriteLine(" << 0")
Console.WriteLine(i8 << 0)
Console.WriteLine(i16 << 0)
Console.WriteLine(i32 << 0)
Console.WriteLine(i64 << 0)
Console.WriteLine(ui8 << 0)
Console.WriteLine(ui16 << 0)
Console.WriteLine(ui32 << 0)
Console.WriteLine(ui64 << 0)
Console.WriteLine(" << 7")
Console.WriteLine(i8 << 7)
Console.WriteLine(i16 << 7)
Console.WriteLine(i32 << 7)
Console.WriteLine(i64 << 7)
Console.WriteLine(ui8 << 7)
Console.WriteLine(ui16 << 7)
Console.WriteLine(ui32 << 7)
Console.WriteLine(ui64 << 7)
Console.WriteLine(" << 15")
Console.WriteLine(i8 << 15)
Console.WriteLine(i16 << 15)
Console.WriteLine(i32 << 15)
Console.WriteLine(i64 << 15)
Console.WriteLine(ui8 << 15)
Console.WriteLine(ui16 << 15)
Console.WriteLine(ui32 << 15)
Console.WriteLine(ui64 << 15)
Console.WriteLine(" << 31")
Console.WriteLine(i8 << 31)
Console.WriteLine(i16 << 31)
Console.WriteLine(i32 << 31)
Console.WriteLine(i64 << 31)
Console.WriteLine(ui8 << 31)
Console.WriteLine(ui16 << 31)
Console.WriteLine(ui32 << 31)
Console.WriteLine(ui64 << 31)
Console.WriteLine(" << 63")
Console.WriteLine(i8 << 63)
Console.WriteLine(i16 << 63)
Console.WriteLine(i32 << 63)
Console.WriteLine(i64 << 63)
Console.WriteLine(ui8 << 63)
Console.WriteLine(ui16 << 63)
Console.WriteLine(ui32 << 63)
Console.WriteLine(ui64 << 63)
Console.WriteLine(" << 64")
Console.WriteLine(i8 << 64)
Console.WriteLine(i16 << 64)
Console.WriteLine(i32 << 64)
Console.WriteLine(i64 << 64)
Console.WriteLine(ui8 << 64)
Console.WriteLine(ui16 << 64)
Console.WriteLine(ui32 << 64)
Console.WriteLine(ui64 << 64)
i8 = System.SByte.MaxValue
i16 = System.Int16.MaxValue
i32 = System.Int32.MaxValue
i64 = System.Int64.MaxValue
ui8 = System.Byte.MaxValue
ui16 = System.UInt16.MaxValue
ui32 = System.UInt32.MaxValue
ui64 = System.UInt64.MaxValue
Console.WriteLine(" >> 0")
Console.WriteLine(i8 >> 0)
Console.WriteLine(i16 >> 0)
Console.WriteLine(i32 >> 0)
Console.WriteLine(i64 >> 0)
Console.WriteLine(ui8 >> 0)
Console.WriteLine(ui16 >> 0)
Console.WriteLine(ui32 >> 0)
Console.WriteLine(ui64 >> 0)
Console.WriteLine(" >> 6")
Console.WriteLine(i8 >> 6)
Console.WriteLine(i16 >> 6)
Console.WriteLine(i32 >> 6)
Console.WriteLine(i64 >> 6)
Console.WriteLine(ui8 >> 6)
Console.WriteLine(ui16 >> 6)
Console.WriteLine(ui32 >> 6)
Console.WriteLine(ui64 >> 6)
Console.WriteLine(" >> 14")
Console.WriteLine(i8 >> 14)
Console.WriteLine(i16 >> 14)
Console.WriteLine(i32 >> 14)
Console.WriteLine(i64 >> 14)
Console.WriteLine(ui8 >> 14)
Console.WriteLine(ui16 >> 14)
Console.WriteLine(ui32 >> 14)
Console.WriteLine(ui64 >> 14)
Console.WriteLine(" >> 30")
Console.WriteLine(i8 >> 30)
Console.WriteLine(i16 >> 30)
Console.WriteLine(i32 >> 30)
Console.WriteLine(i64 >> 30)
Console.WriteLine(ui8 >> 30)
Console.WriteLine(ui16 >> 30)
Console.WriteLine(ui32 >> 30)
Console.WriteLine(ui64 >> 30)
Console.WriteLine(" >> 62")
Console.WriteLine(i8 >> 62)
Console.WriteLine(i16 >> 62)
Console.WriteLine(i32 >> 62)
Console.WriteLine(i64 >> 62)
Console.WriteLine(ui8 >> 62)
Console.WriteLine(ui16 >> 62)
Console.WriteLine(ui32 >> 62)
Console.WriteLine(ui64 >> 62)
Console.WriteLine(" >> 64")
Console.WriteLine(i8 >> 64)
Console.WriteLine(i16 >> 64)
Console.WriteLine(i32 >> 64)
Console.WriteLine(i64 >> 64)
Console.WriteLine(ui8 >> 64)
Console.WriteLine(ui16 >> 64)
Console.WriteLine(ui32 >> 64)
Console.WriteLine(ui64 >> 64)
End Sub
End Module
|
diryboy/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Semantics/BinaryOperatorsTestSource4.vb
|
Visual Basic
|
mit
| 4,892
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Represents Visual Basic parse options.
''' </summary>
Public NotInheritable Class VisualBasicParseOptions
Inherits ParseOptions
Implements IEquatable(Of VisualBasicParseOptions)
Public Shared ReadOnly Property [Default] As VisualBasicParseOptions = New VisualBasicParseOptions()
Private Shared s_defaultPreprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))
Private _features As ImmutableDictionary(Of String, String)
Private _preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))
Private _specifiedLanguageVersion As LanguageVersion
Private _languageVersion As LanguageVersion
''' <summary>
''' Creates an instance of VisualBasicParseOptions.
''' </summary>
''' <param name="languageVersion">The parser language version.</param>
''' <param name="documentationMode">The documentation mode.</param>
''' <param name="kind">The kind of source code.<see cref="SourceCodeKind"/></param>
''' <param name="preprocessorSymbols">An enumerable sequence of KeyValuePair representing preprocessor symbols.</param>
Public Sub New(
Optional languageVersion As LanguageVersion = LanguageVersion.Default,
Optional documentationMode As DocumentationMode = DocumentationMode.Parse,
Optional kind As SourceCodeKind = SourceCodeKind.Regular,
Optional preprocessorSymbols As IEnumerable(Of KeyValuePair(Of String, Object)) = Nothing)
MyClass.New(languageVersion,
documentationMode,
kind,
If(preprocessorSymbols Is Nothing, DefaultPreprocessorSymbols, ImmutableArray.CreateRange(preprocessorSymbols)),
ImmutableDictionary(Of String, String).Empty)
End Sub
Friend Sub New(
languageVersion As LanguageVersion,
documentationMode As DocumentationMode,
kind As SourceCodeKind,
preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object)),
features As ImmutableDictionary(Of String, String))
MyBase.New(kind, documentationMode)
_specifiedLanguageVersion = languageVersion
_languageVersion = languageVersion.MapSpecifiedToEffectiveVersion
_preprocessorSymbols = preprocessorSymbols.ToImmutableArrayOrEmpty
_features = If(features, ImmutableDictionary(Of String, String).Empty)
End Sub
Private Sub New(other As VisualBasicParseOptions)
MyClass.New(
languageVersion:=other._specifiedLanguageVersion,
documentationMode:=other.DocumentationMode,
kind:=other.Kind,
preprocessorSymbols:=other._preprocessorSymbols,
features:=other._features)
End Sub
Public Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Private Shared ReadOnly Property DefaultPreprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))
Get
If s_defaultPreprocessorSymbols.IsDefaultOrEmpty Then
s_defaultPreprocessorSymbols = ImmutableArray.Create(KeyValuePairUtil.Create("_MYTYPE", CObj("Empty")))
End If
Return s_defaultPreprocessorSymbols
End Get
End Property
''' <summary>
''' Returns the specified language version, which is the value that was specified in the call to the
''' constructor, or modified using the <see cref="WithLanguageVersion"/> method, or provided on the command line.
''' </summary>
Public ReadOnly Property SpecifiedLanguageVersion As LanguageVersion
Get
Return _specifiedLanguageVersion
End Get
End Property
''' <summary>
''' Returns the effective language version, which the compiler uses to select the
''' language rules to apply to the program.
''' </summary>
Public ReadOnly Property LanguageVersion As LanguageVersion
Get
Return _languageVersion
End Get
End Property
''' <summary>
''' The preprocessor symbols to parse with.
''' </summary>
''' <remarks>
''' May contain duplicate keys. The last one wins.
''' </remarks>
Public ReadOnly Property PreprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))
Get
Return _preprocessorSymbols
End Get
End Property
''' <summary>
''' Returns a collection of preprocessor symbol names.
''' </summary>
Public Overrides ReadOnly Property PreprocessorSymbolNames As IEnumerable(Of String)
Get
Return _preprocessorSymbols.Select(Function(ps) ps.Key)
End Get
End Property
''' <summary>
''' Returns a VisualBasicParseOptions instance for a specified language version.
''' </summary>
''' <param name="version">The parser language version.</param>
''' <returns>A new instance of VisualBasicParseOptions if different language version is different; otherwise current instance.</returns>
Public Shadows Function WithLanguageVersion(version As LanguageVersion) As VisualBasicParseOptions
If version = _specifiedLanguageVersion Then
Return Me
End If
Dim effectiveVersion = version.MapSpecifiedToEffectiveVersion()
Return New VisualBasicParseOptions(Me) With {._specifiedLanguageVersion = version, ._languageVersion = effectiveVersion}
End Function
''' <summary>
''' Returns a VisualBasicParseOptions instance for a specified source code kind.
''' </summary>
''' <param name="kind">The parser source code kind.</param>
''' <returns>A new instance of VisualBasicParseOptions if source code kind is different; otherwise current instance.</returns>
Public Shadows Function WithKind(kind As SourceCodeKind) As VisualBasicParseOptions
If kind = Me.SpecifiedKind Then
Return Me
End If
Dim effectiveKind = kind.MapSpecifiedToEffectiveKind
Return New VisualBasicParseOptions(Me) With {.SpecifiedKind = kind, .Kind = effectiveKind}
End Function
''' <summary>
''' Returns a VisualBasicParseOptions instance for a specified documentation mode.
''' </summary>
''' <param name="documentationMode"></param>
''' <returns>A new instance of VisualBasicParseOptions if documentation mode is different; otherwise current instance.</returns>
Public Overloads Function WithDocumentationMode(documentationMode As DocumentationMode) As VisualBasicParseOptions
If documentationMode = Me.DocumentationMode Then
Return Me
End If
Return New VisualBasicParseOptions(Me) With {.DocumentationMode = documentationMode}
End Function
''' <summary>
''' Returns a VisualBasicParseOptions instance for a specified collection of KeyValuePairs representing pre-processor symbols.
''' </summary>
''' <param name="symbols">A collection representing pre-processor symbols</param>
''' <returns>A new instance of VisualBasicParseOptions.</returns>
Public Shadows Function WithPreprocessorSymbols(symbols As IEnumerable(Of KeyValuePair(Of String, Object))) As VisualBasicParseOptions
Return WithPreprocessorSymbols(symbols.AsImmutableOrNull())
End Function
''' <summary>
''' Returns a VisualBasicParseOptions instance for a specified collection of KeyValuePairs representing pre-processor symbols.
''' </summary>
''' <param name="symbols">An parameter array of KeyValuePair representing pre-processor symbols.</param>
''' <returns>A new instance of VisualBasicParseOptions.</returns>
Public Shadows Function WithPreprocessorSymbols(ParamArray symbols As KeyValuePair(Of String, Object)()) As VisualBasicParseOptions
Return WithPreprocessorSymbols(symbols.AsImmutableOrNull())
End Function
''' <summary>
''' Returns a VisualBasicParseOptions instance for a specified collection of KeyValuePairs representing pre-processor symbols.
''' </summary>
''' <param name="symbols">An ImmutableArray of KeyValuePair representing pre-processor symbols.</param>
''' <returns>A new instance of VisualBasicParseOptions.</returns>
Public Shadows Function WithPreprocessorSymbols(symbols As ImmutableArray(Of KeyValuePair(Of String, Object))) As VisualBasicParseOptions
If symbols.IsDefault Then
symbols = ImmutableArray(Of KeyValuePair(Of String, Object)).Empty
End If
If symbols.Equals(Me.PreprocessorSymbols) Then
Return Me
End If
Return New VisualBasicParseOptions(Me) With {._preprocessorSymbols = symbols}
End Function
''' <summary>
''' Returns a ParseOptions instance for a specified Source Code Kind.
''' </summary>
''' <param name="kind">The parser source code kind.</param>
''' <returns>A new instance of ParseOptions.</returns>
Public Overrides Function CommonWithKind(kind As SourceCodeKind) As ParseOptions
Return WithKind(kind)
End Function
''' <summary>
''' Returns a ParseOptions instance for a specified Documentation Mode.
''' </summary>
''' <param name="documentationMode">The documentation mode.</param>
''' <returns>A new instance of ParseOptions.</returns>
Protected Overrides Function CommonWithDocumentationMode(documentationMode As DocumentationMode) As ParseOptions
Return WithDocumentationMode(documentationMode)
End Function
Protected Overrides Function CommonWithFeatures(features As IEnumerable(Of KeyValuePair(Of String, String))) As ParseOptions
Return WithFeatures(features)
End Function
''' <summary>
''' Enable some experimental language features for testing.
''' </summary>
Public Shadows Function WithFeatures(features As IEnumerable(Of KeyValuePair(Of String, String))) As VisualBasicParseOptions
' there are currently no parse options for experimental features
If features Is Nothing Then
Return New VisualBasicParseOptions(Me) With {._features = ImmutableDictionary(Of String, String).Empty}
Else
Return New VisualBasicParseOptions(Me) With {._features = features.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase)}
End If
End Function
Public Overrides ReadOnly Property Features As IReadOnlyDictionary(Of String, String)
Get
Return _features
End Get
End Property
Friend Overrides Sub ValidateOptions(builder As ArrayBuilder(Of Diagnostic))
ValidateOptions(builder, MessageProvider.Instance)
' Validate LanguageVersion Not SpecifiedLanguageVersion, after Latest/Default has been converted
If Not LanguageVersion.IsValid Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_BadLanguageVersion, LanguageVersion.ToString))
End If
If Not PreprocessorSymbols.IsDefaultOrEmpty Then
For Each symbol In PreprocessorSymbols
If Not IsValidIdentifier(symbol.Key) OrElse SyntaxFacts.GetKeywordKind(symbol.Key) <> SyntaxKind.None Then
builder.Add(Diagnostic.Create(ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid,
ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier),
symbol.Key)))
Else
Debug.Assert(SyntaxFactory.ParseTokens(symbol.Key).Select(Function(t) t.Kind).SequenceEqual({SyntaxKind.IdentifierToken, SyntaxKind.EndOfFileToken}))
End If
If InternalSyntax.CConst.TryCreate(symbol.Value) Is Nothing Then
builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidPreprocessorConstantType, symbol.Key, symbol.Value.GetType))
End If
Next
End If
End Sub
''' <summary>
''' Determines whether the current object is equal to another object of the same type.
''' </summary>
''' <param name="other">An VisualBasicParseOptions object to compare with this object</param>
''' <returns>A boolean value. True if the current object is equal to the other parameter; otherwise, False.</returns>
Public Overloads Function Equals(other As VisualBasicParseOptions) As Boolean Implements IEquatable(Of VisualBasicParseOptions).Equals
If Me Is other Then
Return True
End If
If Not MyBase.EqualsHelper(other) Then
Return False
End If
If Me.SpecifiedLanguageVersion <> other.SpecifiedLanguageVersion Then
Return False
End If
If Not Me.PreprocessorSymbols.SequenceEqual(other.PreprocessorSymbols) Then
Return False
End If
Return True
End Function
''' <summary>
''' Indicates whether the current object is equal to another object.
''' </summary>
''' <param name="obj">An object to compare with this object</param>
''' <returns>A boolean value. True if the current object is equal to the other parameter; otherwise, False.</returns>
Public Overrides Function Equals(obj As Object) As Boolean
Return Equals(TryCast(obj, VisualBasicParseOptions))
End Function
''' <summary>
''' Returns a hashcode for this instance.
''' </summary>
''' <returns>A hashcode representing this instance.</returns>
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(MyBase.GetHashCodeHelper(), CInt(Me.SpecifiedLanguageVersion))
End Function
End Class
End Namespace
|
physhi/roslyn
|
src/Compilers/VisualBasic/Portable/VisualBasicParseOptions.vb
|
Visual Basic
|
apache-2.0
| 15,217
|
answer = sum [1..100] ^ 2 - foldl (\x y -> y^2 + x) 0 [1..100]
|
tamasgal/haskell_exercises
|
ProjectEuler/p006.hs
|
Haskell
|
mit
| 63
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module DirectoryAPI.API
( directoryAPIProxy
, DirectoryAPI
) where
import Servant
import AuthAPI.API (AuthToken)
import Models (File, Node, NodeId)
type DirectoryAPI = "ls" :> -- List all files
AuthToken :>
Get '[JSON] [File] -- Listing of all files
:<|> "whereis" :> -- Lookup the node for a given file path
AuthToken :>
ReqBody '[JSON] FilePath :> -- Path of file being looked up
Post '[JSON] Node -- Node where the file is kept
:<|> "roundRobinNode" :> -- Next node to use as a file primary
AuthToken :>
ReqBody '[JSON] FilePath :> -- Path of file that will be written
Get '[JSON] Node -- Primary node of the file being stored
:<|> "registerFileServer" :> -- Register a node with the directory service
ReqBody '[JSON] Int :> -- Port file server node is running on
Post '[JSON] NodeId -- Id of the newly created node record
directoryAPIProxy :: Proxy DirectoryAPI
directoryAPIProxy = Proxy
|
houli/distributed-file-system
|
dfs-shared/src/DirectoryAPI/API.hs
|
Haskell
|
mit
| 1,213
|
module BlocVoting.Tally.Resolution where
import qualified Data.ByteString as BS
data Resolution = Resolution {
rCategories :: Int
, rEndTimestamp :: Int
, rName :: BS.ByteString
, rUrl :: BS.ByteString
, rVotesFor :: Integer
, rVotesTotal :: Integer
, rResolved :: Bool
}
deriving (Show, Eq)
updateResolution :: Resolution -> Integer -> Integer -> Resolution
updateResolution (Resolution cats endT name url for total resolved) newForVotes newTotalVotes =
Resolution cats endT name url (for + newForVotes) (total + newTotalVotes) resolved
|
XertroV/blocvoting
|
src/BlocVoting/Tally/Resolution.hs
|
Haskell
|
mit
| 565
|
{-# LANGUAGE CPP #-}
module Database.Orville.PostgreSQL.Plan.Explanation
( Explanation
, noExplanation
, explainStep
, explanationSteps
) where
newtype Explanation =
Explanation ([String] -> [String])
#if MIN_VERSION_base(4,11,0)
instance Semigroup Explanation where
(<>) = appendExplanation
#endif
instance Monoid Explanation where
mempty = noExplanation
mappend = appendExplanation
appendExplanation :: Explanation -> Explanation -> Explanation
appendExplanation (Explanation front) (Explanation back) =
Explanation (front . back)
noExplanation :: Explanation
noExplanation =
Explanation id
explainStep :: String -> Explanation
explainStep str =
Explanation (str:)
explanationSteps :: Explanation -> [String]
explanationSteps (Explanation prependTo) =
prependTo []
|
flipstone/orville
|
orville-postgresql/src/Database/Orville/PostgreSQL/Plan/Explanation.hs
|
Haskell
|
mit
| 800
|
import Data.List (permutations, sort)
solve :: String
solve = (sort $ permutations "0123456789") !! 999999
main = putStrLn $ solve
|
pshendry/project-euler-solutions
|
0024/solution.hs
|
Haskell
|
mit
| 133
|
module Lesson08 where
-- Now let's have some real fun: a two player, online five card stud game,
-- with a full betting system. The betting system is actually the biggest
-- addition versus what we've done previously, so most of our attention
-- will be focused on that. Most of the other code will be very similar
-- to what we had in lesson 7.
import Helper
import Helper.Multiplayer
import Helper.Pretty
import Helper.Winning
import System.Random.Shuffle
import Data.List
import Safe
-- We're going to want to keep track of multiple information per player.
-- A common way to do that is to create a record data type, where each
-- piece of data has its own name. We'll want to have the player and
-- how much money he/she has.
data PokerPlayer = PokerPlayer
{ player :: Player
, chips :: Int
, cards :: [Card]
, hand :: PokerHand
}
data Action = Call | Raise Int | Fold
askAction p allowedRaise = do
str <- askPlayer (player p) "call, raise, or fold?"
case str of
"call" -> return Call
"raise" -> askRaise p allowedRaise
"fold" -> return Fold
_ -> do
tellPlayer (player p) "That was not a valid answer"
askAction p allowedRaise
askRaise p allowedRaise = do
str <- askPlayer (player p) ("Enter amount to raise, up to " ++ show allowedRaise)
case readMay str of
Nothing -> do
tellPlayer (player p) "That was an invalid raise amount"
askRaise p allowedRaise
Just amount
| amount < 0 -> do
tellPlayer (player p) "You cannot raise by a negative value"
askRaise p allowedRaise
| otherwise -> return (Raise amount)
wager p1 p2 pot owed = do
tellAllPlayers $ show (player p1) ++ " has " ++ show (chips p1) ++ " chips"
tellAllPlayers $ show (player p2) ++ " has " ++ show (chips p2) ++ " chips"
tellAllPlayers $ "The pot currently has " ++ show pot ++ " chips"
tellAllPlayers $ "Betting is to " ++ show (player p1) ++ ", who owes " ++ show owed
let allowedRaise = min (chips p2) (chips p1 - owed)
action <- askAction p1 allowedRaise
case action of
Call -> do
tellAllPlayers $ show (player p1) ++ " calls"
let p1' = p1 { chips = chips p1 - owed }
pot' = pot + owed
finishHand p1' p2 pot'
Fold -> do
tellAllPlayers $ show (player p1) ++ " folds"
startGame (player p1) (chips p1) (player p2) (chips p2 + pot)
Raise raise -> do
tellAllPlayers $ show (player p1) ++ " raises " ++ show raise
let p1' = p1 { chips = chips p1 - owed - raise }
wager p2 p1' (pot + owed + raise) raise
finishHand p1 p2 pot = do
tellAllPlayers ("All bets are in, the pot is at: " ++ show pot)
tellAllPlayers (show (player p1) ++ " has " ++ prettyHand (cards p1) ++ ", " ++ show (hand p1))
tellAllPlayers (show (player p2) ++ " has " ++ prettyHand (cards p2) ++ ", " ++ show (hand p2))
(winnings1, winnings2) <-
case compare (hand p1) (hand p2) of
LT -> do
tellAllPlayers (show (player p2) ++ " wins!")
return (0, pot)
EQ -> do
tellAllPlayers "Tied game"
let winnings1 = pot `div` 2
winnings2 = pot - winnings1
return (winnings1, winnings2)
GT -> do
tellAllPlayers (show (player p1) ++ " wins!")
return (pot, 0)
startGame (player p1) (chips p1 + winnings1) (player p2) (chips p2 + winnings2)
startGame player1 0 player2 chips2 = do
tellAllPlayers (show player1 ++ " is out of chips")
tellAllPlayers (show player2 ++ " wins with a total of: " ++ show chips2)
startGame player1 chips1 player2 0 = do
tellAllPlayers (show player2 ++ " is out of chips")
tellAllPlayers (show player1 ++ " wins with a total of: " ++ show chips1)
startGame player1 chips1 player2 chips2 = do
tellAllPlayers "Dealing..."
shuffled <- shuffleM deck
let (cards1, rest) = splitAt 5 shuffled
hand1 = pokerHand cards1
cards2 = take 5 rest
hand2 = pokerHand cards2
p1 = PokerPlayer
{ player = player1
, chips = chips1
, cards = cards1
, hand = hand1
}
-- Always start with a 1 chip ante from player 2
pot = 1
owed = 1
p2 = PokerPlayer
{ player = player2
, chips = chips2 - 1
, cards = cards2
, hand = hand2
}
tellPlayer player1 ("You have " ++ prettyHand cards1 ++ ", " ++ show hand1)
tellPlayer player2 ("You have " ++ prettyHand cards2 ++ ", " ++ show hand2)
wager p1 p2 pot owed
main = playMultiplayerGame "two player five card stud" 2 $ do
tellAllPlayers "Welcome to two player five card stud!"
[player1, player2] <- getPlayers
startGame player1 20 player2 20
-- Let's talk about the betting phase. We'll be alternating between each
-- player. At each player's betting turn, he/she will be allowed to:
--
-- 1. Call, which would be to match whatever bet is on the table.
-- 2. Raise, which would match the current bet and add a little more.
-- 3. Fold
|
snoyberg/haskell-impatient-poker-players
|
src/Lesson08.hs
|
Haskell
|
mit
| 5,286
|
{-# LANGUAGE OverloadedStrings #-}
module Mdb.Status ( doStatus ) where
import Control.Monad ( when )
import Control.Monad.Catch (MonadMask)
import Control.Monad.IO.Class ( MonadIO, liftIO )
import Control.Monad.Logger ( logWarnN, logDebugN, logInfoN )
import Control.Monad.Reader ( ask )
import qualified Database.SQLite.Simple as SQL
import Data.Monoid ( (<>) )
import qualified Data.Text as T
import System.IO.Error ( tryIOError )
import System.Posix.Files ( getFileStatus, modificationTimeHiRes )
import Mdb.CmdLine ( OptStatus(..) )
import Mdb.Database ( MDB, dbExecute, runMDB', withConnection )
import Mdb.Types ( FileId )
doStatus :: (MonadMask m, MonadIO m) => OptStatus -> MDB m ()
doStatus = withFilesSeq . checkFile
type FileInfo = (FileId, FilePath)
withFilesSeq :: (MonadIO m, MonadMask m) => (FileInfo -> MDB IO ()) -> MDB m ()
withFilesSeq f = withConnection $ \c -> do
mdb <- ask
liftIO $ SQL.withStatement c "SELECT file_id, file_name FROM file ORDER BY file_id" $ \stmt ->
let
go = SQL.nextRow stmt >>= \mfi -> case mfi of
Nothing -> return ()
Just fi -> (runMDB' mdb $ f fi) >> go
in go
checkFile :: (MonadIO m, MonadMask m) => OptStatus -> FileInfo -> MDB m ()
checkFile op (fid, fp) = do
efs <- liftIO $ tryIOError $ getFileStatus fp
case efs of
Left ioe -> do
logWarnN $ T.pack ( show ioe )
when (removeMissing op) $ do
logInfoN $ "removing file with ID " <> (T.pack $ show fid)
dbExecute "DELETE FROM file WHERE file_id = ?" (SQL.Only fid)
Right fs -> logDebugN $ T.pack (show $ modificationTimeHiRes fs)
|
waldheinz/mdb
|
src/lib/Mdb/Status.hs
|
Haskell
|
apache-2.0
| 1,802
|
module Serf.Event where
import Serf.Member
import Control.Applicative
import Control.Monad.IO.Class
import System.Environment
import System.Exit
import System.IO
import Text.Parsec
type SerfError = String
data SerfEvent = MemberJoin Member
| MemberLeave Member
| MemberFailed Member
| MemberUpdate Member
| MemberReap Member
| User
| Query
| Unknown String
getSerfEvent :: IO (Either SerfError SerfEvent)
getSerfEvent = getEnv "SERF_EVENT" >>= fromString
where
fromString :: String -> IO (Either SerfError SerfEvent)
fromString "member-join" = readMemberEvent MemberJoin
fromString "member-leave" = readMemberEvent MemberLeave
fromString "member-failed" = readMemberEvent MemberFailed
fromString "member-update" = readMemberEvent MemberUpdate
fromString "member-reap" = readMemberEvent MemberReap
fromString "user" = return $ Right User
fromString "query" = return $ Right Query
fromString unk = return . Right $ Unknown unk
readMemberEvent :: (Member -> SerfEvent) -> IO (Either SerfError SerfEvent)
readMemberEvent f = addMember f <$> readMember
addMember :: (Member -> SerfEvent)
-> Either ParseError Member
-> Either SerfError SerfEvent
addMember _ (Left err) = Left $ show err
addMember f (Right m) = Right $ f m
readMember :: IO (Either ParseError Member)
readMember = memberFromString <$> getLine
isMemberEvent :: SerfEvent -> Bool
isMemberEvent (MemberJoin _) = True
isMemberEvent (MemberLeave _) = True
isMemberEvent (MemberFailed _) = True
isMemberEvent (MemberUpdate _) = True
isMemberEvent (MemberReap _) = True
isMemberEvent _ = False
type EventHandler m = SerfEvent -> m ()
handleEventWith :: MonadIO m => EventHandler m -> m ()
handleEventWith hdlr = do
evt <- liftIO getSerfEvent
case evt of
Left err -> liftIO $ hPutStrLn stderr err >> exitFailure
Right ev -> hdlr ev
|
lstephen/box
|
src/main/ansible/roles/serf/files/Serf/Event.hs
|
Haskell
|
apache-2.0
| 2,110
|
{-# LANGUAGE ExplicitForAll, Rank2Types #-}
-- | An implementation of Reagents (http://www.mpi-sws.org/~turon/reagents.pdf)
-- NOTE: currently this is just a very tiny core of the Reagent design. Needs
-- lots of work.
module Data.Concurrent.Internal.Reagent where
import Data.IORef
import Data.Atomics
import Prelude hiding (succ, fail)
type Reagent a = forall b. (a -> IO b) -> IO b -> IO b
-- | Execute a Reagent.
{-# INLINE react #-}
react :: Reagent a -> IO a
react r = try where
try = r finish try
finish x = return x
-- | Like atomicModifyIORef, but uses CAS and permits the update action to force
-- a retry by returning Nothing
{-# INLINE atomicUpdate #-}
atomicUpdate :: IORef a -> (a -> Maybe (a, b)) -> Reagent b
atomicUpdate r f succ fail = do
curTicket <- readForCAS r
let cur = peekTicket curTicket
case f cur of
Just (new, out) -> do
(done, _) <- casIORef r curTicket new
if done then succ out else fail
Nothing -> fail
atomicUpdate_ :: IORef a -> (a -> a) -> Reagent ()
atomicUpdate_ r f = atomicUpdate r (\x -> Just (f x, ()))
postCommit :: Reagent a -> (a -> IO b) -> Reagent b
postCommit r f succ fail = r (\x -> f x >>= succ) fail
choice :: Reagent a -> Reagent a -> Reagent a
choice _ _ = error "TODO"
|
rrnewton/concurrent-skiplist
|
src/Data/Concurrent/Internal/Reagent.hs
|
Haskell
|
apache-2.0
| 1,287
|
{-# LANGUAGE TemplateHaskell #-}
-- Copyright (C) 2010-2012 John Millikin <john@john-millikin.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module DBusTests.Signature (test_Signature) where
import Test.Chell
import Test.Chell.QuickCheck
import Test.QuickCheck hiding ((.&.), property)
import DBus
import DBusTests.Util
test_Signature :: Suite
test_Signature = suite "Signature"
[ test_BuildSignature
, test_ParseSignature
, test_ParseInvalid
, test_FormatSignature
, test_IsAtom
, test_ShowType
]
test_BuildSignature :: Test
test_BuildSignature = property "signature" prop where
prop = forAll gen_SignatureTypes check
check types = case signature types of
Nothing -> False
Just sig -> signatureTypes sig == types
test_ParseSignature :: Test
test_ParseSignature = property "parseSignature" prop where
prop = forAll gen_SignatureString check
check (s, types) = case parseSignature s of
Nothing -> False
Just sig -> signatureTypes sig == types
test_ParseInvalid :: Test
test_ParseInvalid = assertions "parse-invalid" $ do
-- at most 255 characters
$expect (just (parseSignature (replicate 254 'y')))
$expect (just (parseSignature (replicate 255 'y')))
$expect (nothing (parseSignature (replicate 256 'y')))
-- length also enforced by 'signature'
$expect (just (signature (replicate 255 TypeWord8)))
$expect (nothing (signature (replicate 256 TypeWord8)))
-- struct code
$expect (nothing (parseSignature "r"))
-- empty struct
$expect (nothing (parseSignature "()"))
$expect (nothing (signature [TypeStructure []]))
-- dict code
$expect (nothing (parseSignature "e"))
-- non-atomic dict key
$expect (nothing (parseSignature "a{vy}"))
$expect (nothing (signature [TypeDictionary TypeVariant TypeVariant]))
test_FormatSignature :: Test
test_FormatSignature = property "formatSignature" prop where
prop = forAll gen_SignatureString check
check (s, _) = let
Just sig = parseSignature s
in formatSignature sig == s
test_IsAtom :: Test
test_IsAtom = assertions "IsAtom" $ do
let Just sig = signature []
assertAtom TypeSignature sig
test_ShowType :: Test
test_ShowType = assertions "show-type" $ do
$expect (equal "Bool" (show TypeBoolean))
$expect (equal "Bool" (show TypeBoolean))
$expect (equal "Word8" (show TypeWord8))
$expect (equal "Word16" (show TypeWord16))
$expect (equal "Word32" (show TypeWord32))
$expect (equal "Word64" (show TypeWord64))
$expect (equal "Int16" (show TypeInt16))
$expect (equal "Int32" (show TypeInt32))
$expect (equal "Int64" (show TypeInt64))
$expect (equal "Double" (show TypeDouble))
$expect (equal "UnixFd" (show TypeUnixFd))
$expect (equal "String" (show TypeString))
$expect (equal "Signature" (show TypeSignature))
$expect (equal "ObjectPath" (show TypeObjectPath))
$expect (equal "Variant" (show TypeVariant))
$expect (equal "[Word8]" (show (TypeArray TypeWord8)))
$expect (equal "Dict Word8 (Dict Word8 Word8)" (show (TypeDictionary TypeWord8 (TypeDictionary TypeWord8 TypeWord8))))
$expect (equal "(Word8, Word16)" (show (TypeStructure [TypeWord8, TypeWord16])))
gen_SignatureTypes :: Gen [Type]
gen_SignatureTypes = do
(_, ts) <- gen_SignatureString
return ts
gen_SignatureString :: Gen (String, [Type])
gen_SignatureString = gen where
anyType = oneof [atom, container]
atom = elements
[ ("b", TypeBoolean)
, ("y", TypeWord8)
, ("q", TypeWord16)
, ("u", TypeWord32)
, ("t", TypeWord64)
, ("n", TypeInt16)
, ("i", TypeInt32)
, ("x", TypeInt64)
, ("d", TypeDouble)
, ("h", TypeUnixFd)
, ("s", TypeString)
, ("o", TypeObjectPath)
, ("g", TypeSignature)
]
container = oneof
[ return ("v", TypeVariant)
, array
, dict
, struct
]
array = do
(tCode, tEnum) <- anyType
return ('a':tCode, TypeArray tEnum)
dict = do
(kCode, kEnum) <- atom
(vCode, vEnum) <- anyType
return (concat ["a{", kCode, vCode, "}"], TypeDictionary kEnum vEnum)
struct = do
ts <- listOf1 (halfSized anyType)
let (codes, enums) = unzip ts
return ("(" ++ concat codes ++ ")", TypeStructure enums)
gen = do
types <- listOf anyType
let (codes, enums) = unzip types
let chars = concat codes
if length chars > 255
then halfSized gen
else return (chars, enums)
instance Arbitrary Signature where
arbitrary = do
ts <- gen_SignatureTypes
let Just sig = signature ts
return sig
|
jmillikin/haskell-dbus
|
tests/DBusTests/Signature.hs
|
Haskell
|
apache-2.0
| 4,901
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wall #-}
-- TODO: Complex Numbers
{-|
Embeds Fortran's type system in Haskell via the 'D' GADT.
== Note: Phantom Types and GADTs
Lots of the data types in this module are parameterised by phantom types. These
are types which appear at the type-level, but not at the value level. They are
there to make things more type-safe.
In addition, a lot of the data types are GADTs. In a phantom-type-indexed GADT,
the phantom type often restricts which GADT constructors a particular value may
be an instance of. This is very useful for restricting value-level terms based
on type-level information.
-}
module Language.Fortran.Model.Types where
import Data.Int (Int16, Int32, Int64,
Int8)
import Data.List (intersperse)
import Data.Monoid (Endo (..))
import Data.Typeable (Typeable)
import Data.Word (Word8)
import Data.Singletons.TypeLits
import Data.Vinyl hiding (Field)
import Data.Vinyl.Functor
import Language.Expression.Pretty
import Language.Fortran.Model.Singletons
--------------------------------------------------------------------------------
-- * Fortran Types
{-|
This is the main embedding of Fortran types. A value of type @D a@ represents
the Fortran type which corresponds to the Haskell type @a@. @a@ is a phantom
type parameter. There is at most one instance of @D a@ for each @a@. This means
that a value of type @D a@ acts as a kind of proof that it possible to have a
Fortran type corresponding to the Haskell type @a@ -- and that when you match on
@D a@ knowing the particular @a@ you have, you know which constructor you will
get. This is a nice property because it means that GHC (with
@-fwarn-incomplete-patterns@) will not warn when you match on an impossible
case. It eliminates situations where you'd otherwise write @error "impossible:
..."@.
* @'DPrim' p :: D ('PrimS' a)@ is for primitive types. It contains a value @p@
of type @'Prim' p k a@ for some @p@, @k@, @a@. When matching on something of
type @D ('PrimS' a)@, you know it can only contain a primitive type.
* @'DArray' i v :: D ('Array' i v)@ is for arrays. It contains instances of @'Index'
i@ and @'ArrValue' a@. @'Index' i@ is a proof that @i@ can be used as an index,
and @'ArrValue' a@ is a proof that @a@ can be stored in arrays.
* @'DData' s xs :: D ('Record' name fs)@ is for user-defined data types. The
type has a name, represented at the type level by the type parameter @name@ of
kind 'Symbol'. The constructor contains @s :: 'SSymbol' name@, which acts as a
sort of value-level representation of the name. 'SSymbol' is from the
@singletons@ library. It also contains @xs :: 'Rec' ('Field' D) fs@. @fs@ is a
type-level list of pairs, pairing field names with field types. @'Field' D
'(fname, b)@ is a value-level pair of @'SSymbol' fname@ and @D b@. The vinyl
record is a list of fields, one for each pair in @fs@.
-}
data D a where
DPrim :: Prim p k a -> D (PrimS a)
DArray :: Index i -> ArrValue a -> D (Array i a)
DData :: SSymbol name -> Rec (Field D) fs -> D (Record name fs)
--------------------------------------------------------------------------------
-- * Semantic Types
newtype Bool8 = Bool8 { getBool8 :: Int8 } deriving (Show, Num, Eq, Typeable)
newtype Bool16 = Bool16 { getBool16 :: Int16 } deriving (Show, Num, Eq, Typeable)
newtype Bool32 = Bool32 { getBool32 :: Int32 } deriving (Show, Num, Eq, Typeable)
newtype Bool64 = Bool64 { getBool64 :: Int64 } deriving (Show, Num, Eq, Typeable)
newtype Char8 = Char8 { getChar8 :: Word8 } deriving (Show, Num, Eq, Typeable)
{-|
This newtype wrapper is used in 'DPrim' for semantic primitive types. This means
that when matching on something of type @'D' ('PrimS' a)@, we know it can't be
an array or a record.
-}
newtype PrimS a = PrimS { getPrimS :: a }
deriving (Show, Eq, Typeable)
--------------------------------------------------------------------------------
-- * Primitive Types
{-|
Lists the allowed primitive Fortran types. For example, @'PInt8' :: 'Prim' 'P8
''BTInt' 'Int8'@ represents 8-bit integers. 'Prim' has three phantom type
parameters: precision, base type and semantic Haskell type. Precision is the
number of bits used to store values of that type. The base type represents the
corresponding Fortran base type, e.g. @integer@ or @real@. Constructors are only
provided for those Fortran types which are semantically valid, so for example no
constructor is provided for a 16-bit real. A value of type @'Prim' p k a@ can be
seen as a proof that there is some Fortran primitive type with those parameters.
-}
data Prim p k a where
PInt8 :: Prim 'P8 'BTInt Int8
PInt16 :: Prim 'P16 'BTInt Int16
PInt32 :: Prim 'P32 'BTInt Int32
PInt64 :: Prim 'P64 'BTInt Int64
PBool8 :: Prim 'P8 'BTLogical Bool8
PBool16 :: Prim 'P16 'BTLogical Bool16
PBool32 :: Prim 'P32 'BTLogical Bool32
PBool64 :: Prim 'P64 'BTLogical Bool64
PFloat :: Prim 'P32 'BTReal Float
PDouble :: Prim 'P64 'BTReal Double
PChar :: Prim 'P8 'BTChar Char8
--------------------------------------------------------------------------------
-- * Arrays
-- | Specifies which types can be used as array indices.
data Index a where
Index :: Prim p 'BTInt a -> Index (PrimS a)
-- | Specifies which types can be stored in arrays. Currently arrays of arrays
-- are not supported.
data ArrValue a where
ArrPrim :: Prim p k a -> ArrValue (PrimS a)
ArrData :: SSymbol name -> Rec (Field ArrValue) fs -> ArrValue (Record name fs)
-- | An array with a phantom index type. Mostly used at the type-level to
-- constrain instances of @'D' (Array i a)@ etc.
newtype Array i a = Array [a]
--------------------------------------------------------------------------------
-- * Records
-- | A field over a pair of name and value type.
data Field f field where
Field :: SSymbol name -> f a -> Field f '(name, a)
-- | A type of records with the given @name@ and @fields@. Mostly used at the
-- type level to constrain instances of @'D' (Record name fields)@ etc.
data Record name fields where
Record :: SSymbol name -> Rec (Field Identity) fields -> Record name fields
--------------------------------------------------------------------------------
-- * Combinators
-- | Any Fortran index type is a valid Fortran type.
dIndex :: Index i -> D i
dIndex (Index p) = DPrim p
-- | Anything that can be stored in Fortran arrays is a valid Fortran type.
dArrValue :: ArrValue a -> D a
dArrValue (ArrPrim p) = DPrim p
dArrValue (ArrData nameSym fieldArrValues) =
DData nameSym (rmap (overField' dArrValue) fieldArrValues)
-- | Given a field with known contents, we can change the functor and value
-- type.
overField :: (f a -> g b) -> Field f '(name, a) -> Field g '(name, b)
overField f (Field n x) = Field n (f x)
-- | Given a field with unknown contents, we can change the functor but not the
-- value type.
overField' :: (forall a. f a -> g a) -> Field f nv -> Field g nv
overField' f (Field n x) = Field n (f x)
traverseField' :: (Functor t) => (forall a. f a -> t (g a)) -> Field f nv -> t (Field g nv)
traverseField' f (Field n x) = Field n <$> f x
-- | Combine two fields over the same name-value pair but (potentially)
-- different functors.
zipFieldsWith :: (forall a. f a -> g a -> h a) -> Field f nv -> Field g nv -> Field h nv
zipFieldsWith f (Field _ x) (Field n y) = Field n (f x y)
zip3FieldsWith
:: (forall a. f a -> g a -> h a -> i a)
-> Field f nv
-> Field g nv
-> Field h nv
-> Field i nv
zip3FieldsWith f (Field _ x) (Field _ y) (Field n z) = Field n (f x y z)
--------------------------------------------------------------------------------
-- Pretty Printing
instance Pretty1 (Prim p k) where
prettys1Prec p = \case
PInt8 -> showString "integer8"
PInt16 -> showString "integer16"
PInt32 -> showString "integer32"
PInt64 -> showString "integer64"
PFloat -> showString "real"
PDouble -> showParen (p > 8) $ showString "double precision"
PBool8 -> showString "logical8"
PBool16 -> showString "logical16"
PBool32 -> showString "logical32"
PBool64 -> showString "logical64"
PChar -> showString "character"
instance Pretty1 ArrValue where
prettys1Prec p = prettys1Prec p . dArrValue
instance (Pretty1 f) => Pretty1 (Field f) where
prettys1Prec _ = \case
Field fname x ->
prettys1Prec 0 x .
showString " " .
withKnownSymbol fname (showString (symbolVal fname))
-- | e.g. "type custom_type { character a, integer array b }"
instance Pretty1 D where
prettys1Prec p = \case
DPrim px -> prettys1Prec p px
DArray _ pv -> prettys1Prec p pv . showString " array"
DData rname fields ->
showParen (p > 8)
$ showString "type "
. withKnownSymbol rname (showString (symbolVal rname))
. showString "{ "
. appEndo ( mconcat
. intersperse (Endo $ showString ", ")
. recordToList
. rmap (Const . Endo . prettys1Prec 0)
$ fields)
. showString " }"
|
dorchard/camfort
|
src/Language/Fortran/Model/Types.hs
|
Haskell
|
apache-2.0
| 9,913
|
{-# LANGUAGE TupleSections #-}
module Arbitrary.TestModule where
import Data.Integrated.TestModule
import Test.QuickCheck
import Data.ModulePath
import Control.Applicative
import Arbitrary.Properties
import Test.Util
import Filesystem.Path.CurrentOS
import Prelude hiding (FilePath)
import qualified Arbitrary.ModulePath as MP
import qualified Data.Set as S
testModulePath :: Gen Char -> S.Set ModulePath -> Gen ModulePath
testModulePath subpath avoided =
suchThat
(fromModPath <$> MP.toModulePath subpath)
(not . flip S.member avoided)
where
fromModPath :: ModulePath -> ModulePath
fromModPath (ModulePath pth) =
ModulePath $ take (length pth - 1) pth ++ [testFormat $ last pth]
toTestModule :: ModulePath -> Gen TestModule
toTestModule mp = do
props <- arbitrary :: Gen Properties
return $ TestModule mp (list props)
-- Generate a random test file, care must be taken to avoid generating
-- the same path twice
toGenerated :: Gen Char -> S.Set ModulePath -> Gen (FilePath, TestModule)
toGenerated subpath avoided = do
mp <- testModulePath subpath avoided
(relPath mp,) <$> toTestModule mp
|
jfeltz/tasty-integrate
|
tests/Arbitrary/TestModule.hs
|
Haskell
|
bsd-2-clause
| 1,129
|
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Root where
import Foundation
-- This is a handler function for the GET request method on the RootR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getRootR :: Handler RepHtml
getRootR = do
defaultLayout $ do
h2id <- lift newIdent
setTitle "TierList homepage"
$(widgetFile "homepage")
|
periodic/Simple-Yesod-ToDo
|
Handler/Root.hs
|
Haskell
|
bsd-2-clause
| 625
|
{--
Copyright (c) 2014-2020, Clockwork Dev Studio
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--}
{-# LANGUAGE CPP #-}
module Arguments where
import Prelude hiding (catch)
import LexerData
import Common
import Options
import Data.Char
import System.FilePath.Posix
import System.Directory
import System.IO
import Control.Exception
import System.Exit
import Control.Monad.State
import Control.Monad.Except
import Control.Monad.Identity
import Debug.Trace
import qualified Data.Sequence as Seq
data ConfigFile =
ConfigFile
{
configFileVariableList :: [ConfigFileVariable]
} deriving (Show,Eq)
data ConfigFileVariable =
ConfigFileVariable
{
configFileVariableName :: String,
configFileVariableValue :: String
} deriving (Show, Eq)
loadConfigFile :: Handle -> ConfigFile -> IO ConfigFile
loadConfigFile handle (ConfigFile variables) =
do let endOfFile :: IOError -> IO String
endOfFile e = do return "EOF"
line <- catch (hGetLine handle) endOfFile
if line == "EOF"
then return (ConfigFile variables)
else do let (variable,rest) = span (isAlpha) line
if variable == [] || rest == [] || head rest /= '='
then loadConfigFile handle (ConfigFile variables)
else do loadConfigFile handle (ConfigFile (variables ++ [(ConfigFileVariable variable (tail rest))]))
adjustOptionsBasedOnConfigFile :: Options -> [ConfigFileVariable] -> Options
adjustOptionsBasedOnConfigFile originalOptions (configFileVariable:rest) =
case configFileVariableName configFileVariable of
"backend" -> adjustOptionsBasedOnConfigFile (originalOptions {optionAssembler = configFileVariableValue configFileVariable}) rest
adjustOptionsBasedOnConfigFile originalOptions _ = originalOptions
processArguments :: CodeTransformation ()
processArguments =
do homeDirectory <- liftIO $ getHomeDirectory
let writeDefaultConfigFile :: IOError -> IO Handle
writeDefaultConfigFile _ =
do newConfHandle <- openFile (homeDirectory ++ "/.idlewild-lang.conf") WriteMode
hPutStrLn newConfHandle "backend=nasm"
hClose newConfHandle
newConfHandle <- openFile (homeDirectory ++ "/.idlewild-lang.conf") ReadMode
return newConfHandle
confHandle <- liftIO $ (catch (openFile (homeDirectory ++ "/.idlewild-lang.conf") ReadMode) writeDefaultConfigFile)
configFile <- liftIO $ loadConfigFile confHandle (ConfigFile [])
let customisedOptions = adjustOptionsBasedOnConfigFile defaultOptions (configFileVariableList configFile)
liftIO $ hClose confHandle
arguments <- gets argumentStateArguments
(options, nonOptions) <- liftIO $ processOptions customisedOptions arguments
if optionShowVersion options == True
then do liftIO $ putStrLn "Idlewild-Lang version 0.0.5."
liftIO $ exitSuccess
else return ()
if length nonOptions /= 1
then do liftIO $ putStrLn "Please specify one (and only one) source file name."
liftIO $ exitSuccess
else return ()
let sourceFileName = head nonOptions
asmFileName = replaceExtension sourceFileName ".asm"
#if LINUX==1 || MAC_OS==1
objectFileName = replaceExtension sourceFileName ".o"
#elif WINDOWS==1
objectFileName = replaceExtension sourceFileName ".obj"
#endif
verbose = optionVerbose options
fromHandle <- liftIO $ openFile sourceFileName ReadMode
toHandle <- liftIO $ openFile asmFileName WriteMode
code <- liftIO $ hGetContents fromHandle
put LexState
{lexStateID = LEX_PENDING,
lexStateIncludeFileDepth = 0,
lexStateIncludeFileNameStack = [sourceFileName],
lexStateIncludeFileNames = [],
lexStateCurrentToken = emptyToken,
lexStatePendingTokens = Seq.empty,
lexStateTokens = Seq.singleton (createBOFToken sourceFileName),
lexStateLineNumber = 1,
lexStateLineOffset = 0,
lexStateCharacters = code,
lexStateCompoundTokens = allCompoundTokens,
lexStateConfig = Config {configInputFile = fromHandle,
configOutputFile = toHandle,
configSourceFileName = sourceFileName,
configAsmFileName = asmFileName,
configObjectFileName = objectFileName,
configOptions = options}}
verboseCommentary ("Program arguments okay...\n") verbose
verboseCommentary ("Source file '" ++ sourceFileName ++ "'...\n") verbose
|
clockworkdevstudio/Idlewild-Lang
|
Arguments.hs
|
Haskell
|
bsd-2-clause
| 5,916
|
module Convert.LRChirotope where
-- standard modules
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as Set
-- local modules
import Basics
import Calculus.FlipFlop
import Helpful.General
--import Debug.Trace
{------------------------------------------------------------------------------
- FlipFlop to Chirotope
------------------------------------------------------------------------------}
flipflopsToChirotope :: Network [String] (ARel FlipFlop)
-> Maybe (Network [Int] Int)
flipflopsToChirotope net
| isNothing net5 || isNothing net3 = Nothing
| otherwise = Just $ (fromJust net3)
{ nCons = fst $ Map.foldlWithKey
collectOneCon
(Map.empty, Map.empty)
cons
}
where
collectOneCon (consAcc, mapAcc) nodes rel =
let
(newMap, convertedNodes) = mapAccumL
(\ m node -> let mappedNode = Map.lookup node m in
case mappedNode of
Nothing -> let n = (Map.size m) + 1 in
(Map.insert node n m, n)
otherwise -> (m, fromJust mappedNode)
)
mapAcc
nodes
newRel = case aRel rel of
R -> (-1)
I -> 0
L -> 1
in
( foldl (flip $ uncurry Map.insert) consAcc $
[(x, newRel * y)
| (x,y) <- kPermutationsWithParity 3 convertedNodes
]
, newMap
)
net5 = ffsToFF5s net
net3 = ff5sToFF3s $ fromJust net5
cons = nCons $ fromJust net3
|
spatial-reasoning/zeno
|
src/Convert/LRChirotope.hs
|
Haskell
|
bsd-2-clause
| 1,839
|
{-# LANGUAGE FlexibleContexts #-}
module BRC.Solver.Error where
import Control.Monad.Error (Error(..), MonadError(..))
-- | Solver errors, really just a container for a possibly useful error message.
data SolverError = SolverError String deriving (Eq, Ord)
instance Show (SolverError) where
show (SolverError msg) = "Solver error: " ++ msg
instance Error SolverError where
strMsg = SolverError
-- | Throws an error with a given message in a solver error monad.
solverError :: MonadError SolverError m => String -> m a
solverError = throwError . strMsg
|
kcharter/brc-solver
|
BRC/Solver/Error.hs
|
Haskell
|
bsd-2-clause
| 565
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module NW.Monster where
import NW.Stats
data MonsterClass
= MCFighter
| MCMage
deriving (Eq, Show)
data Monster = Monster
{ mClass :: MonsterClass
, mName :: String
, mStatsBase :: [Stat]
, mLootBonus :: Int
} deriving (Eq, Show)
type MonsterDB = [Monster]
|
listx/netherworld
|
src/NW/Monster.hs
|
Haskell
|
bsd-2-clause
| 338
|
{-# LANGUAGE TemplateHaskell #-}
{-| Contains TemplateHaskell stuff I don't want to recompile every time I make
changes to other files, a pre-compiled header, so to say. Don't know if that
even works.
-}
module FeedGipeda.THGenerated
( benchmarkClosure
, stringDict
, __remoteTable
) where
import Control.Distributed.Process (Closure, Process, Static,
liftIO)
import Control.Distributed.Process.Closure (SerializableDict,
functionTDict, mkClosure,
remotable)
import FeedGipeda.GitShell (SHA)
import FeedGipeda.Repo (Repo)
import qualified FeedGipeda.Slave as Slave
import FeedGipeda.Types (Timeout)
benchmarkProcess :: (String, Repo, SHA, Rational) -> Process String
benchmarkProcess (benchmarkScript, repo, sha, timeout) =
liftIO (Slave.benchmark benchmarkScript repo sha (fromRational timeout))
remotable ['benchmarkProcess]
benchmarkClosure :: String -> Repo -> SHA -> Timeout -> Closure (Process String)
benchmarkClosure benchmarkScript repo commit timeout =
$(mkClosure 'benchmarkProcess) (benchmarkScript, repo, commit, toRational timeout)
stringDict :: Static (SerializableDict String)
stringDict =
$(functionTDict 'benchmarkProcess)
|
sgraf812/feed-gipeda
|
src/FeedGipeda/THGenerated.hs
|
Haskell
|
bsd-3-clause
| 1,466
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Test.PGConstant (
TestPGConstant(..)
, spec
) where
import Data.Proxy (Proxy(..))
import Database.PostgreSQL.Simple.Bind.Parser
import Test.Hspec (Spec, describe)
import Test.QuickCheck (Arbitrary(..), oneof)
import Test.Common (PGSql(..))
import Test.Utils (propParsingWorks)
import Test.PGString (TestPGString(..))
data TestPGConstant
= TPGCString TestPGString
| TPGCNumeric Double
deriving (Show, Eq)
instance Arbitrary TestPGConstant where
arbitrary = oneof [
TPGCString <$> arbitrary
, TPGCNumeric <$> arbitrary]
instance PGSql TestPGConstant where
render (TPGCString s) = render s
render (TPGCNumeric c) = show c
spec :: Spec
spec = do
describe "pgConstant" $ do
propParsingWorks pgConstant (Proxy :: Proxy TestPGConstant)
|
zohl/postgresql-simple-bind
|
tests/Test/PGConstant.hs
|
Haskell
|
bsd-3-clause
| 1,133
|
{-# LANGUAGE OverloadedStrings #-}
module WildBind.SeqSpec (main,spec) where
import Control.Applicative ((<*>))
import Control.Monad (forM_)
import Control.Monad.IO.Class (liftIO)
import qualified Control.Monad.Trans.State as State
import Data.Monoid ((<>))
import Data.IORef (modifyIORef, newIORef, readIORef)
import Test.Hspec
import WildBind.Binding
( binds, on, run, as,
boundActions, actDescription,
boundInputs,
Binding,
justBefore
)
import WildBind.Description (ActionDescription)
import WildBind.Seq
( prefix,
toSeq, fromSeq,
withPrefix, withCancel,
reviseSeq
)
import WildBind.ForTest
( SampleInput(..), SampleState(..),
evalStateEmpty, execAll,
boundDescs, curBoundInputs, curBoundDescs, curBoundDesc,
checkBoundInputs,
checkBoundDescs,
checkBoundDesc,
withRefChecker
)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
spec_prefix
spec_SeqBinding
spec_reviseSeq
spec_prefix :: Spec
spec_prefix = describe "prefix" $ do
let base_b = binds $ do
on SIa `as` "a" `run` return ()
on SIb `as` "b" `run` return ()
specify "no prefix" $ do
let b = prefix [] [] base_b
boundDescs b (SS "") `shouldMatchList`
[ (SIa, "a"),
(SIb, "b")
]
specify "one prefix" $ evalStateEmpty $ do
State.put $ prefix [] [SIc] base_b
checkBoundInputs (SS "") [SIc]
execAll (SS "") [SIc]
checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
execAll (SS "") [SIc]
checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIc]
specify "two prefixes" $ evalStateEmpty $ do
State.put $ prefix [] [SIc, SIb] base_b
checkBoundInputs (SS "") [SIc]
execAll (SS "") [SIc]
checkBoundInputs (SS "") [SIb]
execAll (SS "") [SIb]
checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIc]
specify "cancel binding" $ evalStateEmpty $ do
State.put $ prefix [SIa] [SIc, SIb] base_b
checkBoundInputs (SS "") [SIc]
execAll (SS "") [SIc] -- there is no cancel binding at the top level.
checkBoundInputs (SS "") [SIa, SIb]
checkBoundDesc (SS "") SIa "cancel"
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIc]
execAll (SS "") [SIc, SIb]
checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] -- cancel binding should be weak and overridden.
execAll (SS "") [SIb]
checkBoundInputs (SS "") [SIc]
execAll (SS "") [SIc, SIb]
checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIc]
spec_SeqBinding :: Spec
spec_SeqBinding = describe "SeqBinding" $ do
let b_a = binds $ on SIa `as` "a" `run` return ()
b_b = binds $ on SIb `as` "b" `run` return ()
describe "withPrefix" $ do
it "should allow nesting" $ evalStateEmpty $ do
State.put $ fromSeq $ withPrefix [SIb] $ withPrefix [SIc] $ withPrefix [SIa] $ toSeq (b_a <> b_b)
checkBoundInputs (SS "") [SIb]
execAll (SS "") [SIb]
checkBoundInputs (SS "") [SIc]
execAll (SS "") [SIc]
checkBoundInputs (SS "") [SIa]
execAll (SS "") [SIa]
checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIb]
describe "mappend" $ do
it "should be able to combine SeqBindings with different prefixes." $ evalStateEmpty $ do
State.put $ fromSeq $ withPrefix [SIc] $ ( (withPrefix [SIa, SIc] $ toSeq $ b_a)
<> (withPrefix [SIa] $ toSeq $ b_b)
)
checkBoundInputs (SS "") [SIc]
execAll (SS "") [SIc]
checkBoundInputs (SS "") [SIa]
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIc, SIb]
checkBoundDesc (SS "") SIb "b"
execAll (SS "") [SIb]
checkBoundInputs (SS "") [SIc]
execAll (SS "") [SIc, SIa]
checkBoundInputs (SS "") [SIc, SIb]
execAll (SS "") [SIc]
checkBoundDescs (SS "") [(SIa, "a")]
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIc]
describe "withCancel" $ do
it "should weakly add 'cancel' binding when at least one prefix is kept in the state." $ evalStateEmpty $ do
State.put $ fromSeq $ withPrefix [SIa, SIc] $ withCancel [SIa, SIb, SIc] $ ( toSeq b_a
<> (withPrefix [SIc] $ toSeq b_b)
)
let checkPrefixOne = do
checkBoundInputs (SS "") [SIa]
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIa, SIb, SIc]
forM_ [SIa, SIb] $ \c -> checkBoundDesc (SS "") c "cancel"
checkPrefixOne
execAll (SS "") [SIa]
checkPrefixOne
execAll (SS "") [SIc]
checkBoundInputs (SS "") [SIa, SIb, SIc]
checkBoundDesc (SS "") SIa "a"
checkBoundDesc (SS "") SIb "cancel"
execAll (SS "") [SIa]
checkPrefixOne
execAll (SS "") [SIc, SIb]
checkPrefixOne
execAll (SS "") [SIc, SIc]
checkBoundDescs (SS "") [(SIa, "cancel"), (SIb, "b"), (SIc, "cancel")]
execAll (SS "") [SIb]
checkPrefixOne
spec_reviseSeq :: Spec
spec_reviseSeq = describe "reviseSeq" $ do
it "should allow access to prefix keys input so far" $ evalStateEmpty $ withRefChecker [] $ \out checkOut -> do
act_out <- liftIO $ newIORef ("" :: String)
let sb = withCancel [SIa] $ withPrefix [SIa, SIb, SIc] $ toSeq $ base_b
base_b = binds $ on SIb `as` "B" `run` modifyIORef act_out (++ "B executed")
rev ps _ _ = justBefore $ modifyIORef out (++ [ps])
State.put $ fromSeq $ reviseSeq rev sb
execAll (SS "") [SIa, SIa]
checkOut [[], [SIa]]
execAll (SS "") [SIa, SIb, SIc]
checkOut [[], [SIa], [], [SIa], [SIa, SIb]]
liftIO $ readIORef act_out `shouldReturn` ""
execAll (SS "") [SIb]
checkOut [[], [SIa], [], [SIa], [SIa, SIb], [SIa, SIb, SIc]]
liftIO $ readIORef act_out `shouldReturn` "B executed"
it "should allow unbinding" $ evalStateEmpty $ do
let sb = withPrefix [SIa]
( toSeq ba
<> (withPrefix [SIb] $ toSeq bab)
<> (withPrefix [SIa] $ toSeq baa)
)
ba = binds $ on SIc `as` "c on a" `run` return ()
bab = binds $ on SIc `as` "c on ab" `run` return ()
baa = binds $ do
on SIc `as` "c on aa" `run` return ()
on SIb `as` "b on aa" `run` return ()
rev ps _ i act = if (ps == [SIa] && i == SIb) || (ps == [SIa,SIa] && i == SIc)
then Nothing
else Just act
State.put $ fromSeq $ reviseSeq rev sb
checkBoundInputs (SS "") [SIa]
execAll (SS "") [SIa]
checkBoundInputs (SS "") [SIa, SIc] -- SIb should be canceled
execAll (SS "") [SIa]
checkBoundDescs (SS "") [(SIb, "b on aa")] -- SIc should be canceled
execAll (SS "") [SIb]
checkBoundInputs (SS "") [SIa]
|
debug-ito/wild-bind
|
wild-bind/test/WildBind/SeqSpec.hs
|
Haskell
|
bsd-3-clause
| 7,072
|
{-# LANGUAGE TemplateHaskell #-}
module Data.Comp.Trans.DeriveUntrans (
deriveUntrans
) where
import Control.Lens ( view ,(^.))
import Control.Monad ( liftM )
import Control.Monad.Trans ( lift )
import Data.Comp.Multi ( Alg, cata, (:&:)(..) )
import Language.Haskell.TH
import Data.Comp.Trans.Util
--------------------------------------------------------------------------------
-- |
-- Creates an @untranslate@ function inverting the @translate@ function
-- created by @deriveTrans@.
--
-- @
-- import qualified Foo as F
-- type ArithTerm = Term (Arith :+: Atom :+: Lit)
-- deriveUntrans [''F.Arith, ''F.Atom, ''F.Lit] (TH.ConT ''ArithTerm)
-- @
--
-- will create
--
-- @
-- type family Targ l
-- newtype T l = T {t :: Targ l}
--
-- class Untrans f where
-- untrans :: Alg f t
--
-- untranslate :: ArithTerm l -> Targ l
-- untranslate = t . cata untrans
--
-- type instance Targ ArithL = F.Arith
-- instance Untrans Arith where
-- untrans (Add x y) = T $ F.Add (t x) (t y)
--
-- type instance Targ AtomL = F.Atom
-- instance Untrans Atom where
-- untrans (Var s) = T $ F.Var s
-- untrans (Const x) = T $ F.Const (t x)
--
-- type instance Targ LitL = F.Lit
-- instance Untrans Lit where
-- untrans (Lit n) = T $ F.Lit n
-- @
--
-- Note that you will need to manually provide an instance @(Untrans f, Untrans g) => Untrans (f :+: g)@
-- due to phase issues. (Or @(Untrans (f :&: p), Untrans (g :&: p)) => Untrans ((f :+: g) :&: p)@, if you
-- are propagating annotations.)
--
-- With annotation propagation on, it will instead produce
-- `untranslate :: Term (Arith :&: Ann) l -> Targ l Ann`
deriveUntrans :: [Name] -> Type -> CompTrans [Dec]
deriveUntrans names term = do targDec <- mkTarg targNm
wrapperDec <- mkWrapper wrapNm unwrapNm targNm
fnDec <- mkFn untranslateNm term targNm unwrapNm fnNm
classDec <- mkClass classNm fnNm wrapNm
instances <- liftM concat $ mapM (mkInstance classNm fnNm wrapNm unwrapNm targNm) names
return $ concat [ targDec
, wrapperDec
, fnDec
, classDec
, instances
]
where
targNm = mkName "Targ"
wrapNm = mkName "T"
unwrapNm = mkName "t"
untranslateNm = mkName "untranslate"
classNm = mkName "Untrans"
fnNm = mkName "untrans"
{- type family Targ l -}
mkTarg :: Name -> CompTrans [Dec]
mkTarg targNm = do i <- lift $ newName "i"
return [FamilyD TypeFam targNm [PlainTV i] Nothing]
{- newtype T l = T { t :: Targ l } -}
mkWrapper :: Name -> Name -> Name -> CompTrans [Dec]
mkWrapper tpNm fNm targNm = do i <- lift $ newName "i"
let con = RecC tpNm [(fNm, NotStrict, AppT (ConT targNm) (VarT i))]
return [NewtypeD [] tpNm [PlainTV i] con []]
{-
untranslate :: JavaTerm l -> Targ l
untranslate = t . cata untrans
-}
mkFn :: Name -> Type -> Name -> Name -> Name -> CompTrans [Dec]
mkFn fnNm term targNm fldNm untransNm = sequence [sig, def]
where
sig = do i <- lift $ newName "i"
lift $ sigD fnNm (forallT [PlainTV i] (return []) (typ $ varT i))
typ :: Q Type -> Q Type
typ i = [t| $term' $i -> $targ $i |]
term' = return term
targ = conT targNm
def = lift $ valD (varP fnNm) (normalB body) []
body = [| $fld . cata $untrans |]
fld = varE fldNm
untrans = varE untransNm
{-
class Untrans f where
untrans :: Alg f T
-}
mkClass :: Name -> Name -> Name -> CompTrans [Dec]
mkClass classNm funNm newtpNm = do f <- lift $ newName "f"
let funDec = SigD funNm (AppT (AppT (ConT ''Alg) (VarT f)) (ConT newtpNm))
return [ClassD [] classNm [PlainTV f] [] [funDec]]
{-
type instance Targ CompilationUnitL = J.CompilationUnit
instance Untrans CompilationUnit where
untrans (CompilationUnit x y z) = T $ J.CompilationUnit (t x) (t y) (t z)
-}
mkInstance :: Name -> Name -> Name -> Name -> Name -> Name -> CompTrans [Dec]
mkInstance classNm funNm wrap unwrap targNm typNm = do inf <- lift $ reify typNm
targTyp <- getFullyAppliedType typNm
let nmTyps = simplifyDataInf inf
clauses <- mapM (uncurry $ mkClause wrap unwrap) nmTyps
let conTyp = ConT (transName typNm)
annPropInf <- view annotationProp
let instTyp = case annPropInf of
Nothing -> conTyp
Just api -> foldl AppT (ConT ''(:&:)) [conTyp, api ^. annTyp]
return [ famInst targTyp
, inst clauses instTyp
]
where
famInst targTyp = TySynInstD targNm (TySynEqn [ConT $ nameLab typNm] targTyp)
inst clauses instTyp = InstanceD []
(AppT (ConT classNm) instTyp)
[FunD funNm clauses]
mapConditionallyReplacing :: [a] -> (a -> b) -> (a -> Bool) -> [b] -> [b]
mapConditionallyReplacing src f p reps = go src reps
where
go [] _ = []
go (x:xs) (y:ys) | p x = y : go xs ys
go (x:xs) l | not (p x) = f x : go xs l
go (_:_ ) [] = error "mapConditionallyReplacing: Insufficiently many replacements"
mkClause :: Name -> Name -> Name -> [Type] -> CompTrans Clause
mkClause wrap unwrap con tps = do isAnn <- getIsAnn
nms <- mapM (const $ lift $ newName "x") tps
nmAnn <- lift $ newName "a"
tps' <- applyCurSubstitutions tps
let nmTps = zip nms tps'
Clause <$> (sequence [pat isAnn nmTps nmAnn]) <*> (body nmTps nmAnn) <*> pure []
where
pat :: (Type -> Bool) -> [(Name, Type)] -> Name -> CompTrans Pat
pat isAnn nmTps nmAnn = do isProp <- isPropagatingAnns
if isProp then
return $ ConP '(:&:) [nodeP, VarP nmAnn]
else
return nodeP
where
nonAnnNms = map fst $ filter (not.isAnn.snd) nmTps
nodeP = ConP (transName con) (map VarP nonAnnNms)
body :: [(Name, Type)] -> Name -> CompTrans Body
body nmTps nmAnn = do annPropInf <- view annotationProp
args <- case annPropInf of
Nothing -> return $ map atom nmTps
Just api -> do isAnn <- getIsAnn
let unProp = api ^. unpropAnn
let annVars = filter (isAnn.snd) nmTps
let annExps = unProp (VarE nmAnn) (length annVars)
return $ mapConditionallyReplacing nmTps atom (isAnn.snd) annExps
return $ makeRhs args
where
makeRhs :: [Exp] -> Body
makeRhs args = NormalB $ AppE (ConE wrap) $ foldl AppE (ConE con) args
atom :: (Name, Type) -> Exp
atom (x, t) | elem t baseTypes = VarE x
atom (x, _) = AppE (VarE unwrap) (VarE x)
|
jkoppel/comptrans
|
Data/Comp/Trans/DeriveUntrans.hs
|
Haskell
|
bsd-3-clause
| 8,030
|
module Mistral.Schedule.Value (
Env
, groupEnv
, lookupEnv
, bindType
, bindValue
, bindParam
, NodeTags
, bindNode
, lookupTag, lookupTags
, Value(..)
, SNetwork(..), mapWhen, modifyNode
, SNode(..), addTask
, STask(..), hasConstraints
, SConstraint(..), target
) where
import Mistral.TypeCheck.AST
import Mistral.Utils.PP
import Mistral.Utils.Panic ( panic )
import Mistral.Utils.SCC ( Group )
import qualified Data.Foldable as Fold
import qualified Data.Map as Map
import Data.Monoid ( Monoid(..) )
import qualified Data.Set as Set
sPanic :: [String] -> a
sPanic = panic "Mistral.Schedule.Value"
-- Environments ----------------------------------------------------------------
data Env = Env { envValues :: Map.Map Name Value
, envTypes :: Map.Map TParam Type
}
instance Monoid Env where
mempty = Env { envValues = mempty, envTypes = mempty }
mappend l r = mconcat [l,r]
-- merge the two environments, preferring things from the left
mconcat envs = Env { envValues = Map.unions (map envValues envs)
, envTypes = Map.unions (map envTypes envs) }
lookupEnv :: Name -> Env -> Value
lookupEnv n env =
case Map.lookup n (envValues env) of
Just v -> v
Nothing -> sPanic [ "no value for: " ++ pretty n ]
bindType :: TParam -> Type -> Env -> Env
bindType p ty env = env { envTypes = Map.insert p ty (envTypes env) }
bindValue :: Name -> Value -> Env -> Env
bindValue n v env = env { envValues = Map.insert n v (envValues env) }
bindParam :: Param -> Value -> Env -> Env
bindParam p v env = bindValue (pName p) v env
groupEnv :: (a -> Env) -> (Group a -> Env)
groupEnv = Fold.foldMap
-- Node Tags -------------------------------------------------------------------
newtype NodeTags = NodeTags { getNodeTags :: Map.Map Atom (Set.Set Name) }
instance Monoid NodeTags where
mempty = NodeTags mempty
mappend l r = mconcat [l,r]
mconcat nts = NodeTags (Map.unionsWith Set.union (map getNodeTags nts))
bindNode :: SNode -> NodeTags
bindNode sn = mempty { getNodeTags = foldl add mempty allTags }
where
name = snName sn
allTags = [ (tag, Set.singleton name) | tag <- snTags sn ]
add nodes (tag, s) = Map.insertWith Set.union tag s nodes
-- | Try to resolve a single tag to set of Node names.
lookupTag :: Atom -> NodeTags -> Set.Set Name
lookupTag tag env = case Map.lookup tag (getNodeTags env) of
Just nodes -> nodes
Nothing -> Set.empty
-- | Lookup the nodes that have all of the tags given.
lookupTags :: [Atom] -> NodeTags -> [Name]
lookupTags tags env
| null tags = [] -- XXX maybe all nodes?
| otherwise = Set.toList (foldl1 Set.intersection (map (`lookupTag` env) tags))
-- Values ----------------------------------------------------------------------
data Value = VTFun (Type -> Value)
-- ^ Type abstractions
| VFun (Value -> Value)
-- ^ Value abstractions
| VCon Name [Value]
-- ^ Constructor use
| VLit Literal
-- ^ Literals
| VSched [SNetwork]
-- ^ Evaluted schedules
| VTopo SNetwork
-- ^ Nodes and links
| VNode SNode
-- ^ Nodes
| VLink Link
-- ^ Links
| VTasks (NodeTags -> [STask])
| VTask STask
instance Show Value where
show val = case val of
VTFun _ -> "<function>"
VFun _ -> "<type-function>"
VCon n vs -> "(" ++ unwords (pretty n : map show vs) ++ ")"
VLit lit -> "(VLit " ++ show lit ++ ")"
VSched nets -> show nets
VTopo net -> show net
VNode n -> show n
VLink l -> show l
VTasks _ -> "<tasks>"
VTask t -> show t
-- | Scheduling network.
data SNetwork = SNetwork { snNodes :: [SNode]
, snLinks :: [Link]
} deriving (Show)
instance Monoid SNetwork where
mempty = SNetwork { snNodes = []
, snLinks = [] }
mappend l r = SNetwork { snNodes = Fold.foldMap snNodes [l,r]
, snLinks = Fold.foldMap snLinks [l,r] }
mapWhen :: (a -> Bool) -> (a -> a) -> [a] -> [a]
mapWhen p f = go
where
go as = case as of
a:rest | p a -> f a : rest
| otherwise -> a : go rest
[] -> []
-- | Modify the first occurrence of node n.
--
-- INVARIANT: This relies on the assumption that the renamer has given fresh
-- names to all nodes.
modifyNode :: Name -> (SNode -> SNode) -> (SNetwork -> SNetwork)
modifyNode n f net = net { snNodes = mapWhen nameMatches f (snNodes net) }
where
nameMatches sn = snName sn == n
data SNode = SNode { snName :: Name
, snSpec :: Expr
, snType :: Type
, snTags :: [Atom]
, snTasks :: [STask]
} deriving (Show)
addTask :: STask -> (SNode -> SNode)
addTask task sn = sn { snTasks = task : snTasks sn }
data STask = STask { stName :: Name
, stTask :: Task
, stTags :: [Atom]
, stConstraints :: [SConstraint]
} deriving (Show)
hasConstraints :: STask -> Bool
hasConstraints t = not (null (stConstraints t))
data SConstraint = SCOn Name -- ^ On this node
deriving (Show)
-- XXX This won't work for constraints that specify relative information like:
-- "I need to be able to communicate with X"
target :: SConstraint -> Name
target (SCOn n) = n
|
GaloisInc/mistral
|
src/Mistral/Schedule/Value.hs
|
Haskell
|
bsd-3-clause
| 5,624
|
{-# LANGUAGE ParallelListComp #-}
module OldHMM
(Prob, HMM(..), train, bestSequence, sequenceProb)
where
import qualified Data.Map as M
import Data.List (sort, groupBy, maximumBy, foldl')
import Data.Maybe (fromMaybe, fromJust)
import Data.Ord (comparing)
import Data.Function (on)
import Control.Monad
import Data.Number.LogFloat
type Prob = LogFloat
-- | The type of Hidden Markov Models.
data HMM state observation = HMM [state] [Prob] [[Prob]] (observation -> [Prob])
instance (Show state, Show observation) => Show (HMM state observation) where
show (HMM states probs tpm _) = "HMM " ++ show states ++ " "
++ show probs ++ " " ++ show tpm ++ " <func>"
-- | Perform a single step in the Viterbi algorithm.
--
-- Takes a list of path probabilities, and an observation, and returns the updated
-- list of (surviving) paths with probabilities.
viterbi :: HMM state observation
-> [(Prob, [state])]
-> observation
-> [(Prob, [state])]
viterbi (HMM states _ state_transitions observations) prev x =
deepSeq prev `seq`
[maximumBy (comparing fst)
[(transition_prob * prev_prob * observation_prob,
new_state:path)
| transition_prob <- transition_probs
| (prev_prob, path) <- prev
| observation_prob <- observation_probs]
| transition_probs <- state_transitions
| new_state <- states]
where
observation_probs = observations x
deepSeq ((x, y:ys):xs) = x `seq` y `seq` (deepSeq xs)
deepSeq ((x, _):xs) = x `seq` (deepSeq xs)
deepSeq [] = []
-- | The initial value for the Viterbi algorithm
viterbi_init :: HMM state observation -> [(Prob, [state])]
viterbi_init (HMM states state_probs _ _) = zip state_probs (map (:[]) states)
-- | Perform a single step of the forward algorithm
--
-- Each item in the input and output list is the probability that the system
-- ended in the respective state.
forward :: HMM state observation
-> [Prob]
-> observation
-> [Prob]
forward (HMM _ _ state_transitions observations) prev x =
last prev `seq`
[sum [transition_prob * prev_prob * observation_prob
| transition_prob <- transition_probs
| prev_prob <- prev
| observation_prob <- observation_probs]
| transition_probs <- state_transitions]
where
observation_probs = observations x
-- | The initial value for the forward algorithm
forward_init :: HMM state observation -> [Prob]
forward_init (HMM _ state_probs _ _) = state_probs
learn_states :: (Ord state, Fractional prob) => [(observation, state)] -> M.Map state prob
learn_states xs = histogram $ map snd xs
learn_transitions :: (Ord state, Fractional prob) => [(observation, state)] -> M.Map (state, state) prob
learn_transitions xs = let xs' = map snd xs in
histogram $ zip xs' (tail xs')
learn_observations :: (Ord state, Ord observation, Fractional prob) =>
M.Map state prob
-> [(observation, state)]
-> M.Map (observation, state) prob
learn_observations state_prob = M.mapWithKey (\ (observation, state) prob -> prob / (fromJust $ M.lookup state state_prob))
. histogram
histogram :: (Ord a, Fractional prob) => [a] -> M.Map a prob
histogram xs = let hist = foldl' (flip $ flip (M.insertWith (+)) 1) M.empty xs in
M.map (/ M.fold (+) 0 hist) hist
-- | Calculate the parameters of an HMM from a list of observations
-- and the corresponding states.
train :: (Ord observation, Ord state) =>
[(observation, state)]
-> HMM state observation
train sample = model
where
states = learn_states sample
state_list = M.keys states
transitions = learn_transitions sample
trans_prob_mtx = [[fromMaybe 1e-10 $ M.lookup (old_state, new_state) transitions
| old_state <- state_list]
| new_state <- state_list]
observations = learn_observations states sample
observation_probs = fromMaybe (fill state_list []) . (flip M.lookup $
M.fromList $ map (\ (e, xs) -> (e, fill state_list xs)) $
map (\ xs -> (fst $ head xs, map snd xs)) $
groupBy ((==) `on` fst)
[(observation, (state, prob))
| ((observation, state), prob) <- M.toAscList observations])
initial = map (\ state -> (fromJust $ M.lookup state states, [state])) state_list
model = HMM state_list (fill state_list $ M.toAscList states) trans_prob_mtx observation_probs
fill :: Eq state => [state] -> [(state, Prob)] -> [Prob]
fill states [] = map (const 1e-10) states
fill (s:states) xs@((s', p):xs') = if s /= s' then
1e-10 : fill states xs
else
p : fill states xs'
-- | Calculate the most likely sequence of states for a given sequence of observations
-- using Viterbi's algorithm
bestSequence :: (Ord observation) => HMM state observation -> [observation] -> [state]
bestSequence hmm = (reverse . tail . snd . (maximumBy (comparing fst))) . (foldl' (viterbi hmm) (viterbi_init hmm))
-- | Calculate the probability of a given sequence of observations
-- using the forward algorithm.
sequenceProb :: (Ord observation) => HMM state observation -> [observation] -> Prob
sequenceProb hmm = sum . (foldl' (forward hmm) (forward_init hmm))
|
mikeizbicki/hmm
|
OldHMM.hs
|
Haskell
|
bsd-3-clause
| 5,845
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Test.Hspec.Snap (
-- * Running blocks of hspec-snap tests
snap
, modifySite
, modifySite'
, afterEval
, beforeEval
-- * Core data types
, TestResponse(..)
, SnapHspecM
-- * Factory style test data generation
, Factory(..)
-- * Requests
, delete
, get
, get'
, post
, postJson
, put
, put'
, params
-- * Helpers for dealing with TestResponses
, restrictResponse
-- * Dealing with session state (EXPERIMENTAL)
, recordSession
, HasSession(..)
, sessionShouldContain
, sessionShouldNotContain
-- * Evaluating application code
, eval
-- * Unit test assertions
, shouldChange
, shouldEqual
, shouldNotEqual
, shouldBeTrue
, shouldNotBeTrue
-- * Response assertions
, should200
, shouldNot200
, should404
, shouldNot404
, should300
, shouldNot300
, should300To
, shouldNot300To
, shouldHaveSelector
, shouldNotHaveSelector
, shouldHaveText
, shouldNotHaveText
-- * Form tests
, FormExpectations(..)
, form
-- * Internal types and helpers
, SnapHspecState(..)
, setResult
, runRequest
, runHandlerSafe
, evalHandlerSafe
) where
import Control.Applicative ((<$>))
import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar
,putMVar, readMVar, takeMVar)
import Control.Exception (SomeException, catch)
import Control.Monad (void)
import Control.Monad.State (StateT (..), runStateT)
import qualified Control.Monad.State as S (get, put)
import Control.Monad.Trans (liftIO)
import Data.Aeson (encode, ToJSON)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LBS (ByteString)
import Data.ByteString.Lazy (fromStrict, toStrict)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Snap.Core (Response (..), getHeader)
import qualified Snap.Core as Snap
import Snap.Snaplet (Handler, Snaplet, SnapletInit,
SnapletLens, with)
import Snap.Snaplet.Session (SessionManager, commitSession,
sessionToList, setInSession)
import Snap.Snaplet.Test (InitializerState, closeSnaplet,
evalHandler', getSnaplet, runHandler')
import Snap.Test (RequestBuilder, getResponseBody)
import qualified Snap.Test as Test
import Test.Hspec
import Test.Hspec.Core.Spec
import qualified Text.Digestive as DF
import qualified Text.HandsomeSoup as HS
import qualified Text.XML.HXT.Core as HXT
-- | The result of making requests against your application. Most
-- assertions act against these types (for example, `should200`,
-- `shouldHaveSelector`, etc).
data TestResponse = Html Text
| Json LBS.ByteString
| NotFound
| Redirect Int Text
| Other Int
| Empty
deriving (Show, Eq)
-- | The main monad that tests run inside of. This allows both access
-- to the application (via requests and `eval`) and to running
-- assertions (like `should404` or `shouldHaveText`).
type SnapHspecM b = StateT (SnapHspecState b) IO
-- | Internal state used to share site initialization across tests, and to propogate failures.
-- Understanding it is completely unnecessary to use the library.
--
-- The fields it contains, in order, are:
--
-- > Result
-- > Main handler
-- > Startup state
-- > Startup state
-- > Session state
-- > Before handler (runs before each eval)
-- > After handler (runs after each eval).
data SnapHspecState b = SnapHspecState Result
(Handler b b ())
(Snaplet b)
(InitializerState b)
(MVar [(Text, Text)])
(Handler b b ())
(Handler b b ())
instance Example (SnapHspecM b ()) where
type Arg (SnapHspecM b ()) = SnapHspecState b
evaluateExample s _ cb _ =
do mv <- newEmptyMVar
cb $ \st -> do ((),SnapHspecState r' _ _ _ _ _ _) <- runStateT s st
putMVar mv r'
takeMVar mv
-- | Factory instances allow you to easily generate test data.
--
-- Essentially, you specify a default way of constructing a
-- data type, and allow certain parts of it to be modified (via
-- the 'fields' data structure).
--
-- An example follows:
--
-- > data Foo = Foo Int
-- > newtype FooFields = FooFields (IO Int)
-- > instance Factory App Foo FooFields where
-- > fields = FooFields randomIO
-- > save f = liftIO f >>= saveFoo . Foo1
-- >
-- > main = do create id :: SnapHspecM App Foo
-- > create (const $ FooFields (return 1)) :: SnapHspecM App Foo
class Factory b a d | a -> b, a -> d, d -> a where
fields :: d
save :: d -> SnapHspecM b a
create :: (d -> d) -> SnapHspecM b a
create transform = save $ transform fields
reload :: a -> SnapHspecM b a
reload = return
-- | The way to run a block of `SnapHspecM` tests within an `hspec`
-- test suite. This takes both the top level handler (usually `route
-- routes`, where `routes` are all the routes for your site) and the
-- site initializer (often named `app`), and a block of tests. A test
-- suite can have multiple calls to `snap`, though each one will cause
-- the site initializer to run, which is often a slow operation (and
-- will slow down test suites).
snap :: Handler b b () -> SnapletInit b b -> SpecWith (SnapHspecState b) -> Spec
snap site app spec = do
snapinit <- runIO $ getSnaplet (Just "test") app
mv <- runIO (newMVar [])
case snapinit of
Left err -> error $ show err
Right (snaplet, initstate) ->
afterAll (const $ closeSnaplet initstate) $
before (return (SnapHspecState Success site snaplet initstate mv (return ()) (return ()))) spec
-- | This allows you to change the default handler you are running
-- requests against within a block. This is most likely useful for
-- setting request state (for example, logging a user in).
modifySite :: (Handler b b () -> Handler b b ())
-> SpecWith (SnapHspecState b)
-> SpecWith (SnapHspecState b)
modifySite f = beforeWith (\(SnapHspecState r site snaplet initst sess bef aft) ->
return (SnapHspecState r (f site) snaplet initst sess bef aft))
-- | This performs a similar operation to `modifySite` but in the context
-- of `SnapHspecM` (which is needed if you need to `eval`, produce values, and
-- hand them somewhere else (so they can't be created within `f`).
modifySite' :: (Handler b b () -> Handler b b ())
-> SnapHspecM b a
-> SnapHspecM b a
modifySite' f a = do (SnapHspecState r site s i sess bef aft) <- S.get
S.put (SnapHspecState r (f site) s i sess bef aft)
a
-- | Evaluate a Handler action after each test.
afterEval :: Handler b b () -> SpecWith (SnapHspecState b) -> SpecWith (SnapHspecState b)
afterEval h = after (\(SnapHspecState _r _site s i _ _ _) ->
do res <- evalHandlerSafe h s i
case res of
Right _ -> return ()
Left msg -> liftIO $ print msg)
-- | Evaluate a Handler action before each test.
beforeEval :: Handler b b () -> SpecWith (SnapHspecState b) -> SpecWith (SnapHspecState b)
beforeEval h = beforeWith (\state@(SnapHspecState _r _site s i _ _ _) -> do void $ evalHandlerSafe h s i
return state)
class HasSession b where
getSessionLens :: SnapletLens b SessionManager
recordSession :: HasSession b => SnapHspecM b a -> SnapHspecM b a
recordSession a =
do (SnapHspecState r site s i mv bef aft) <- S.get
S.put (SnapHspecState r site s i mv
(do ps <- liftIO $ readMVar mv
with getSessionLens $ mapM_ (uncurry setInSession) ps
with getSessionLens commitSession)
(do ps' <- with getSessionLens sessionToList
void . liftIO $ takeMVar mv
liftIO $ putMVar mv ps'))
res <- a
(SnapHspecState r' _ _ _ _ _ _) <- S.get
void . liftIO $ takeMVar mv
liftIO $ putMVar mv []
S.put (SnapHspecState r' site s i mv bef aft)
return res
sessContents :: SnapHspecM b Text
sessContents = do
(SnapHspecState _ _ _ _ mv _ _) <- S.get
ps <- liftIO $ readMVar mv
return $ T.concat (map (uncurry T.append) ps)
sessionShouldContain :: Text -> SnapHspecM b ()
sessionShouldContain t =
do contents <- sessContents
if t `T.isInfixOf` contents
then setResult Success
else setResult (Fail $ "Session did not contain: " ++ T.unpack t
++ "\n\nSession was:\n" ++ T.unpack contents)
sessionShouldNotContain :: Text -> SnapHspecM b ()
sessionShouldNotContain t =
do contents <- sessContents
if t `T.isInfixOf` contents
then setResult (Fail $ "Session should not have contained: " ++ T.unpack t
++ "\n\nSession was:\n" ++ T.unpack contents)
else setResult Success
-- | Runs a DELETE request
delete :: Text -> SnapHspecM b TestResponse
delete path = runRequest (Test.delete (T.encodeUtf8 path) M.empty)
-- | Runs a GET request.
get :: Text -> SnapHspecM b TestResponse
get path = get' path M.empty
-- | Runs a GET request, with a set of parameters.
get' :: Text -> Snap.Params -> SnapHspecM b TestResponse
get' path ps = runRequest (Test.get (T.encodeUtf8 path) ps)
-- | A helper to construct parameters.
params :: [(ByteString, ByteString)] -- ^ Pairs of parameter and value.
-> Snap.Params
params = M.fromList . map (\x -> (fst x, [snd x]))
-- | Creates a new POST request, with a set of parameters.
post :: Text -> Snap.Params -> SnapHspecM b TestResponse
post path ps = runRequest (Test.postUrlEncoded (T.encodeUtf8 path) ps)
-- | Creates a new POST request with a given JSON value as the request body.
postJson :: ToJSON tj => Text -> tj -> SnapHspecM b TestResponse
postJson path json = runRequest $ Test.postRaw (T.encodeUtf8 path)
"application/json"
(toStrict $ encode json)
-- | Creates a new PUT request, with a set of parameters, with a default type of "application/x-www-form-urlencoded"
put :: Text -> Snap.Params -> SnapHspecM b TestResponse
put path params' = put' path "application/x-www-form-urlencoded" params'
-- | Creates a new PUT request with a configurable MIME/type
put' :: Text -> Text -> Snap.Params -> SnapHspecM b TestResponse
put' path mime params' = runRequest $ do
Test.put (T.encodeUtf8 path) (T.encodeUtf8 mime) ""
Test.setQueryString params'
-- | Restricts a response to matches for a given CSS selector.
-- Does nothing to non-Html responses.
restrictResponse :: Text -> TestResponse -> TestResponse
restrictResponse selector (Html body) =
case HXT.runLA (HXT.xshow $ HXT.hread HXT.>>> HS.css (T.unpack selector)) (T.unpack body) of
[] -> Html ""
matches -> Html (T.concat (map T.pack matches))
restrictResponse _ r = r
-- | Runs an arbitrary stateful action from your application.
eval :: Handler b b a -> SnapHspecM b a
eval act = do (SnapHspecState _ _site app is _mv bef aft) <- S.get
liftIO $ either (error . T.unpack) id <$> evalHandlerSafe (do bef
r <- act
aft
return r) app is
-- | Records a test Success or Fail. Only the first Fail will be
-- recorded (and will cause the whole block to Fail).
setResult :: Result -> SnapHspecM b ()
setResult r = do (SnapHspecState r' s a i sess bef aft) <- S.get
case r' of
Success -> S.put (SnapHspecState r s a i sess bef aft)
_ -> return ()
-- | Asserts that a given stateful action will produce a specific different result after
-- an action has been run.
shouldChange :: (Show a, Eq a)
=> (a -> a)
-> Handler b b a
-> SnapHspecM b c
-> SnapHspecM b ()
shouldChange f v act = do before' <- eval v
void act
after' <- eval v
shouldEqual (f before') after'
-- | Asserts that two values are equal.
shouldEqual :: (Show a, Eq a)
=> a
-> a
-> SnapHspecM b ()
shouldEqual a b = if a == b
then setResult Success
else setResult (Fail ("Should have held: " ++ show a ++ " == " ++ show b))
-- | Asserts that two values are not equal.
shouldNotEqual :: (Show a, Eq a)
=> a
-> a
-> SnapHspecM b ()
shouldNotEqual a b = if a == b
then setResult (Fail ("Should not have held: " ++ show a ++ " == " ++ show b))
else setResult Success
-- | Asserts that the value is True.
shouldBeTrue :: Bool
-> SnapHspecM b ()
shouldBeTrue True = setResult Success
shouldBeTrue False = setResult (Fail "Value should have been True.")
-- | Asserts that the value is not True (otherwise known as False).
shouldNotBeTrue :: Bool
-> SnapHspecM b ()
shouldNotBeTrue False = setResult Success
shouldNotBeTrue True = setResult (Fail "Value should have been True.")
-- | Asserts that the response is a success (either Html, or Other with status 200).
should200 :: TestResponse -> SnapHspecM b ()
should200 (Html _) = setResult Success
should200 (Other 200) = setResult Success
should200 r = setResult (Fail (show r))
-- | Asserts that the response is not a normal 200.
shouldNot200 :: TestResponse -> SnapHspecM b ()
shouldNot200 (Html _) = setResult (Fail "Got Html back.")
shouldNot200 (Other 200) = setResult (Fail "Got Other with 200 back.")
shouldNot200 _ = setResult Success
-- | Asserts that the response is a NotFound.
should404 :: TestResponse -> SnapHspecM b ()
should404 NotFound = setResult Success
should404 r = setResult (Fail (show r))
-- | Asserts that the response is not a NotFound.
shouldNot404 :: TestResponse -> SnapHspecM b ()
shouldNot404 NotFound = setResult (Fail "Got NotFound back.")
shouldNot404 _ = setResult Success
-- | Asserts that the response is a redirect.
should300 :: TestResponse -> SnapHspecM b ()
should300 (Redirect _ _) = setResult Success
should300 r = setResult (Fail (show r))
-- | Asserts that the response is not a redirect.
shouldNot300 :: TestResponse -> SnapHspecM b ()
shouldNot300 (Redirect _ _) = setResult (Fail "Got Redirect back.")
shouldNot300 _ = setResult Success
-- | Asserts that the response is a redirect, and thet the url it
-- redirects to starts with the given path.
should300To :: Text -> TestResponse -> SnapHspecM b ()
should300To pth (Redirect _ to) | pth `T.isPrefixOf` to = setResult Success
should300To _ r = setResult (Fail (show r))
-- | Asserts that the response is not a redirect to a given path. Note
-- that it can still be a redirect for this assertion to succeed, the
-- path it redirects to just can't start with the given path.
shouldNot300To :: Text -> TestResponse -> SnapHspecM b ()
shouldNot300To pth (Redirect _ to) | pth `T.isPrefixOf` to = setResult (Fail "Got Redirect back.")
shouldNot300To _ _ = setResult Success
-- | Assert that a response (which should be Html) has a given selector.
shouldHaveSelector :: Text -> TestResponse -> SnapHspecM b ()
shouldHaveSelector selector r@(Html body) =
setResult $ if haveSelector' selector r
then Success
else Fail msg
where msg = T.unpack $ T.concat ["Html should have contained selector: ", selector, "\n\n", body]
shouldHaveSelector match _ = setResult (Fail (T.unpack $ T.concat ["Non-HTML body should have contained css selector: ", match]))
-- | Assert that a response (which should be Html) doesn't have a given selector.
shouldNotHaveSelector :: Text -> TestResponse -> SnapHspecM b ()
shouldNotHaveSelector selector r@(Html body) =
setResult $ if haveSelector' selector r
then Fail msg
else Success
where msg = T.unpack $ T.concat ["Html should not have contained selector: ", selector, "\n\n", body]
shouldNotHaveSelector _ _ = setResult Success
haveSelector' :: Text -> TestResponse -> Bool
haveSelector' selector (Html body) =
case HXT.runLA (HXT.hread HXT.>>> HS.css (T.unpack selector)) (T.unpack body) of
[] -> False
_ -> True
haveSelector' _ _ = False
-- | Asserts that the response (which should be Html) contains the given text.
shouldHaveText :: Text -> TestResponse -> SnapHspecM b ()
shouldHaveText match (Html body) =
if T.isInfixOf match body
then setResult Success
else setResult (Fail $ T.unpack $ T.concat [body, "' contains '", match, "'."])
shouldHaveText match _ = setResult (Fail (T.unpack $ T.concat ["Body contains: ", match]))
-- | Asserts that the response (which should be Html) does not contain the given text.
shouldNotHaveText :: Text -> TestResponse -> SnapHspecM b ()
shouldNotHaveText match (Html body) =
if T.isInfixOf match body
then setResult (Fail $ T.unpack $ T.concat [body, "' contains '", match, "'."])
else setResult Success
shouldNotHaveText _ _ = setResult Success
-- | A data type for tests against forms.
data FormExpectations a = Value a -- ^ The value the form should take (and should be valid)
| Predicate (a -> Bool)
| ErrorPaths [Text] -- ^ The error paths that should be populated
-- | Tests against digestive-functors forms.
form :: (Eq a, Show a)
=> FormExpectations a -- ^ If the form should succeed, Value a is what it should produce.
-- If failing, ErrorPaths should be all the errors that are triggered.
-> DF.Form Text (Handler b b) a -- ^ The form to run
-> M.Map Text Text -- ^ The parameters to pass
-> SnapHspecM b ()
form expected theForm theParams =
do r <- eval $ DF.postForm "form" theForm (const $ return lookupParam)
case expected of
Value a -> shouldEqual (snd r) (Just a)
Predicate f ->
case snd r of
Nothing -> setResult (Fail $ T.unpack $
T.append "Expected form to validate. Resulted in errors: "
(T.pack (show $ DF.viewErrors $ fst r)))
Just v -> if f v
then setResult Success
else setResult (Fail $ T.unpack $
T.append "Expected predicate to pass on value: "
(T.pack (show v)))
ErrorPaths expectedPaths ->
do let viewErrorPaths = map (DF.fromPath . fst) $ DF.viewErrors $ fst r
if all (`elem` viewErrorPaths) expectedPaths
then if length viewErrorPaths == length expectedPaths
then setResult Success
else setResult (Fail $ "Number of errors did not match test. Got:\n\n "
++ show viewErrorPaths
++ "\n\nBut expected:\n\n"
++ show expectedPaths)
else setResult (Fail $ "Did not have all errors specified. Got:\n\n"
++ show viewErrorPaths
++ "\n\nBut expected:\n\n"
++ show expectedPaths)
where lookupParam pth = case M.lookup (DF.fromPath pth) fixedParams of
Nothing -> return []
Just v -> return [DF.TextInput v]
fixedParams = M.mapKeys (T.append "form.") theParams
-- | Runs a request (built with helpers from Snap.Test), resulting in a response.
runRequest :: RequestBuilder IO () -> SnapHspecM b TestResponse
runRequest req = do
(SnapHspecState _ site app is _ bef aft) <- S.get
res <- liftIO $ runHandlerSafe req (bef >> site >> aft) app is
case res of
Left err ->
error $ T.unpack err
Right response ->
case rspStatus response of
404 -> return NotFound
200 ->
liftIO $ parse200 response
_ -> if rspStatus response >= 300 && rspStatus response < 400
then do let url = fromMaybe "" $ getHeader "Location" response
return (Redirect (rspStatus response) (T.decodeUtf8 url))
else return (Other (rspStatus response))
parse200 :: Response -> IO TestResponse
parse200 resp =
let body = getResponseBody resp
contentType = getHeader "content-type" resp in
case contentType of
Just "application/json" -> Json . fromStrict <$> body
_ -> Html . T.decodeUtf8 <$> body
-- | Runs a request against a given handler (often the whole site),
-- with the given state. Returns any triggered exception, or the response.
runHandlerSafe :: RequestBuilder IO ()
-> Handler b b v
-> Snaplet b
-> InitializerState b
-> IO (Either Text Response)
runHandlerSafe req site s is =
catch (runHandler' s is req site) (\(e::SomeException) -> return $ Left (T.pack $ show e))
-- | Evaluates a given handler with the given state. Returns any
-- triggered exception, or the value produced.
evalHandlerSafe :: Handler b b v
-> Snaplet b
-> InitializerState b
-> IO (Either Text v)
evalHandlerSafe act s is =
catch (evalHandler' s is (Test.get "" M.empty) act) (\(e::SomeException) -> return $ Left (T.pack $ show e))
{-# ANN put ("HLint: ignore Eta reduce"::String) #-}
|
bitemyapp/hspec-snap
|
src/Test/Hspec/Snap.hs
|
Haskell
|
bsd-3-clause
| 22,986
|
{-# LANGUAGE TypeOperators, MultiParamTypeClasses, FunctionalDependencies
, UndecidableInstances
#-}
-- For ghc 6.6 compatibility
-- {-# OPTIONS -fglasgow-exts -fallow-undecidable-instances #-}
----------------------------------------------------------------------
-- |
-- Module : Data.FunArr
-- Copyright : (c) Conal Elliott 2007-2013
-- License : BSD3
--
-- Maintainer : conal@conal.net
-- Stability : experimental
-- Portability : portable
--
-- Conversion between arrow values and wrapped functions.
----------------------------------------------------------------------
module Data.FunArr
(
FunArr(..) -- , wapl
) where
-- import Control.Monad.Identity
import Control.Compose
infixr 0 $$ -- FunArr application
-- | Convert between an arrow value and a \"wrapped function\". The \"arrow\"
-- doesn't really have to be an arrow. I'd appreciate ideas for names &
-- uses.
class FunArr ar w | ar->w , w->ar where
-- | Convert a @w@-wrapped function to an arrow value
toArr :: w (a->b) -> (a `ar` b)
-- | Apply an arrow to a @w@-wrapped value
($$) :: (a `ar` b) -> w a -> w b
-- -- | Apply a wrapped function to a wrapped value
-- wapl :: FunArr ar w => w (a->b) -> w a -> w b
-- wapl f a = toArr f $$ a
-- The type of wapl matches <*> from Control.Applicative. What about
-- "pure" from the Applicative class, with type a -> w a?
-- Function/Id instance
instance FunArr (->) Id where
toArr (Id f) = f
f $$ Id a = Id (f a)
-- -- Oops! This instance can't work with the mutual functional
-- dependencies. Instead, instantiate it per @h@.
--
-- instance FunArr (FunA h) h where
-- toArr = error "toArr: undefined for FunArr" -- Add FunArrable class & delegate
-- FunA f $$ ha = f ha
-- The following instance violates the "coverage condition" and so
-- requires -fallow-undecidable-instances.
instance (FunArr ar w, FunArr ar' w')
=> FunArr (ar ::*:: ar') (w :*: w') where
toArr (Prod (f,f')) = Prodd (toArr f, toArr f')
Prodd (f,f') $$ Prod (w,w') = Prod (f $$ w, f' $$ w')
|
conal/DeepArrow
|
src/Data/FunArr.hs
|
Haskell
|
bsd-3-clause
| 2,075
|
module Main where
import Build_doctests (flags, pkgs, module_sources)
import Data.Foldable (traverse_)
import Test.DocTest (doctest)
main :: IO ()
main = do
traverse_ putStrLn args
doctest args
where
args = ["-XOverloadedStrings"] ++ flags ++ pkgs ++ module_sources
|
kazu-yamamoto/unix-time
|
test/doctests.hs
|
Haskell
|
bsd-3-clause
| 282
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Configure
-- Copyright : (c) David Himmelstrup 2005,
-- Duncan Coutts 2005
-- License : BSD-like
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- High level interface to configuring a package.
-----------------------------------------------------------------------------
module Distribution.Client.Configure (
configure,
) where
import Distribution.Client.Dependency
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.InstallPlan (InstallPlan)
import Distribution.Client.IndexUtils as IndexUtils
( getSourcePackages, getInstalledPackages )
import Distribution.Client.Setup
( ConfigExFlags(..), configureCommand, filterConfigureFlags )
import Distribution.Client.Types as Source
import Distribution.Client.SetupWrapper
( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.Targets
( userToPackageConstraint )
import Distribution.Simple.Compiler
( CompilerId(..), Compiler(compilerId)
, PackageDB(..), PackageDBStack )
import Distribution.Simple.Program (ProgramConfiguration )
import Distribution.Simple.Setup
( ConfigFlags(..), fromFlag, toFlag, flagToMaybe, fromFlagOrDefault )
import Distribution.Simple.PackageIndex (PackageIndex)
import Distribution.Simple.Utils
( defaultPackageDesc )
import Distribution.Package
( Package(..), packageName, Dependency(..), thisPackageVersion )
import Distribution.PackageDescription.Parse
( readPackageDescription )
import Distribution.PackageDescription.Configuration
( finalizePackageDescription )
import Distribution.Version
( anyVersion, thisVersion )
import Distribution.Simple.Utils as Utils
( notice, info, debug, die )
import Distribution.System
( Platform, buildPlatform )
import Distribution.Verbosity as Verbosity
( Verbosity )
import Data.Monoid (Monoid(..))
-- | Configure the package found in the local directory
configure :: Verbosity
-> PackageDBStack
-> [Repo]
-> Compiler
-> ProgramConfiguration
-> ConfigFlags
-> ConfigExFlags
-> [String]
-> IO ()
configure verbosity packageDBs repos comp conf
configFlags configExFlags extraArgs = do
installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf
sourcePkgDb <- getSourcePackages verbosity repos
progress <- planLocalPackage verbosity comp configFlags configExFlags
installedPkgIndex sourcePkgDb
notice verbosity "Resolving dependencies..."
maybePlan <- foldProgress logMsg (return . Left) (return . Right)
progress
case maybePlan of
Left message -> do
info verbosity message
setupWrapper verbosity (setupScriptOptions installedPkgIndex) Nothing
configureCommand (const configFlags) extraArgs
Right installPlan -> case InstallPlan.ready installPlan of
[pkg@(ConfiguredPackage (SourcePackage _ _ (LocalUnpackedPackage _)) _ _ _)] ->
configurePackage verbosity
(InstallPlan.planPlatform installPlan)
(InstallPlan.planCompiler installPlan)
(setupScriptOptions installedPkgIndex)
configFlags pkg extraArgs
_ -> die $ "internal error: configure install plan should have exactly "
++ "one local ready package."
where
setupScriptOptions index = SetupScriptOptions {
useCabalVersion = maybe anyVersion thisVersion
(flagToMaybe (configCabalVersion configExFlags)),
useCompiler = Just comp,
-- Hack: we typically want to allow the UserPackageDB for finding the
-- Cabal lib when compiling any Setup.hs even if we're doing a global
-- install. However we also allow looking in a specific package db.
usePackageDB = if UserPackageDB `elem` packageDBs
then packageDBs
else packageDBs ++ [UserPackageDB],
usePackageIndex = if UserPackageDB `elem` packageDBs
then Just index
else Nothing,
useProgramConfig = conf,
useDistPref = fromFlagOrDefault
(useDistPref defaultSetupScriptOptions)
(configDistPref configFlags),
useLoggingHandle = Nothing,
useWorkingDir = Nothing
}
logMsg message rest = debug verbosity message >> rest
-- | Make an 'InstallPlan' for the unpacked package in the current directory,
-- and all its dependencies.
--
planLocalPackage :: Verbosity -> Compiler
-> ConfigFlags -> ConfigExFlags
-> PackageIndex
-> SourcePackageDb
-> IO (Progress String String InstallPlan)
planLocalPackage verbosity comp configFlags configExFlags installedPkgIndex
(SourcePackageDb _ packagePrefs) = do
pkg <- readPackageDescription verbosity =<< defaultPackageDesc verbosity
let -- We create a local package and ask to resolve a dependency on it
localPkg = SourcePackage {
packageInfoId = packageId pkg,
Source.packageDescription = pkg,
packageSource = LocalUnpackedPackage "."
}
solver = fromFlag $ configSolver configExFlags
testsEnabled = fromFlagOrDefault False $ configTests configFlags
benchmarksEnabled =
fromFlagOrDefault False $ configBenchmarks configFlags
resolverParams =
addPreferences
-- preferences from the config file or command line
[ PackageVersionPreference name ver
| Dependency name ver <- configPreferences configExFlags ]
. addConstraints
-- version constraints from the config file or command line
-- TODO: should warn or error on constraints that are not on direct deps
-- or flag constraints not on the package in question.
(map userToPackageConstraint (configExConstraints configExFlags))
. addConstraints
-- package flags from the config file or command line
[ PackageConstraintFlags (packageName pkg)
(configConfigurationsFlags configFlags) ]
. addConstraints
-- '--enable-tests' and '--enable-benchmarks' constraints from
-- command line
[ PackageConstraintStanzas (packageName pkg) $ concat
[ if testsEnabled then [TestStanzas] else []
, if benchmarksEnabled then [BenchStanzas] else []
]
]
$ standardInstallPolicy
installedPkgIndex
(SourcePackageDb mempty packagePrefs)
[SpecificSourcePackage localPkg]
return (resolveDependencies buildPlatform (compilerId comp) solver resolverParams)
-- | Call an installer for an 'SourcePackage' but override the configure
-- flags with the ones given by the 'ConfiguredPackage'. In particular the
-- 'ConfiguredPackage' specifies an exact 'FlagAssignment' and exactly
-- versioned package dependencies. So we ignore any previous partial flag
-- assignment or dependency constraints and use the new ones.
--
configurePackage :: Verbosity
-> Platform -> CompilerId
-> SetupScriptOptions
-> ConfigFlags
-> ConfiguredPackage
-> [String]
-> IO ()
configurePackage verbosity platform comp scriptOptions configFlags
(ConfiguredPackage (SourcePackage _ gpkg _) flags stanzas deps) extraArgs =
setupWrapper verbosity
scriptOptions (Just pkg) configureCommand configureFlags extraArgs
where
configureFlags = filterConfigureFlags configFlags {
configConfigurationsFlags = flags,
configConstraints = map thisPackageVersion deps,
configVerbosity = toFlag verbosity,
configBenchmarks = toFlag (BenchStanzas `elem` stanzas),
configTests = toFlag (TestStanzas `elem` stanzas)
}
pkg = case finalizePackageDescription flags
(const True)
platform comp [] (enableStanzas stanzas gpkg) of
Left _ -> error "finalizePackageDescription ConfiguredPackage failed"
Right (desc, _) -> desc
|
alphaHeavy/cabal
|
cabal-install/Distribution/Client/Configure.hs
|
Haskell
|
bsd-3-clause
| 8,529
|
module Text.OpenGL.Xml.ReadRegistry (
readRegistry,
parseRegistry,
PreProcess
) where
import Prelude hiding ((.), id)
import Control.Category
import Text.OpenGL.Types
import Text.OpenGL.Xml.Pickle()
import Text.OpenGL.Xml.PreProcess
import Text.XML.HXT.Core
type PreProcess = Bool
-- TODO RelaxNG validation
readRegistry :: FilePath -> PreProcess -> IO (Either String Registry)
readRegistry fp pp = do
results <- runX (
readDocument readOpts fp >>> preProcess pp >>> parseRegistryArrow
) -- TODO: error handling
return $ handleResults results
where
readOpts :: [SysConfig]
readOpts = [withValidate no, withPreserveComment no]
preProcess :: (ArrowChoice a, ArrowXml a) => PreProcess -> a XmlTree XmlTree
preProcess pp = if pp then preProcessRegistry else id
-- | TODO: make it work (doesn't work with the <?xml ?> header.
parseRegistry :: String -> PreProcess -> Either String Registry
parseRegistry str pp = handleResults $ runLA (
xread >>> preProcess pp >>> parseRegistryArrow
) str
handleResults :: [Either String Registry] -> Either String Registry
handleResults rs = case rs of
[] -> Left "No parse"
(_:_:_) -> Left "Multiple parse"
[rc] -> rc
parseRegistryArrow :: ArrowXml a => a XmlTree (Either String Registry)
parseRegistryArrow =
removeAllWhiteSpace >>> -- This processing is needed for the non IO case.
removeAllComment >>>
arr (unpickleDoc' xpickle)
|
Laar/opengl-xmlspec
|
src/Text/OpenGL/Xml/ReadRegistry.hs
|
Haskell
|
bsd-3-clause
| 1,468
|
{-# Language OverloadedStrings #-}
module XMonad.Actions.XHints.Render where
import XMonad hiding (drawString)
import Data.Text (Text)
import qualified Data.Text as T
import Foreign.C
import Graphics.X11.Xlib.Types
import qualified Data.Text.Foreign as TF
import qualified Data.ByteString as BS
import Codec.Binary.UTF8.String
mkUnmanagedWindow :: Display -> Screen -> Window -> Position
-> Position -> Dimension -> Dimension -> IO Window
mkUnmanagedWindow d s rw x y w h = do
let visual = defaultVisualOfScreen s
attrmask = cWOverrideRedirect
allocaSetWindowAttributes $
\attributes -> do
set_override_redirect attributes True
createWindow d rw x y w h 0 (defaultDepthOfScreen s)
inputOutput visual attrmask attributes
newHintWindow :: Display -> IO (Window,GC)
newHintWindow dpy = do
let win = defaultRootWindow dpy
blk = blackPixel dpy $ defaultScreen dpy
wht = whitePixel dpy $ defaultScreen dpy
scn = defaultScreenOfDisplay dpy
(_,_,_,_,_,x,y,_) <- queryPointer dpy win
nw <- createSimpleWindow dpy win (fromIntegral x) (fromIntegral y) 2 2 1 blk wht
mapWindow dpy nw
gc <- createGC dpy nw
return (nw,gc)
|
netogallo/XHints
|
src/XMonad/Actions/XHints/Render.hs
|
Haskell
|
bsd-3-clause
| 1,227
|
isPrime :: Integral a => a -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime n =
all (\ x -> x /= 0)
[n `mod` x | x <- [2..(truncate $ sqrt (fromIntegral n) + 1)]]
goldbach :: (Integral t, Integral t1) => t1 -> (t, t1)
goldbach n = goldbach' 3 (n - 3)
where
goldbach' a b
| isPrime a && isPrime b = (a, b)
| otherwise = goldbach' (a + 2) (b - 2)
|
m00nlight/99-problems
|
haskell/p-40.hs
|
Haskell
|
bsd-3-clause
| 403
|
module UI.Widget.List (
listWidget
) where
import Reactive.Banana
import Reactive.Banana.Extra
import Reactive.Banana.Frameworks
import UI.TclTk
import UI.TclTk.AST
import UI.TclTk.Builder
import UI.Widget
-- | List widget
listWidget :: Frameworks t => Event t [a] -> GUI t p (TkName, Event t (Int,a))
listWidget eList = do
frame [Fill FillX] $
withPack PackLeft $ do
let toEvt x (_,e) = x <$ e
-- Buttons
spacer
e1 <- toEvt ToBegin <$> button [Text "<|" ] []
e2 <- toEvt (MoveBack 10) <$> button [Text "<<<"] []
e3 <- toEvt (MoveBack 1 ) <$> button [Text "<" ] []
-- Central area
spacer
Widget _ eN finiN <- entryInt [] []
_ <- label [ Text " / " ] []
labN <- label [] []
actimateTcl (length <$> eList) $ do
configure labN $ LamOpt $ Text . show
spacer
-- More buttons
e4 <- toEvt (MoveFwd 1 ) <$> button [Text ">" ] []
e5 <- toEvt (MoveFwd 10) <$> button [Text ">>>"] []
e6 <- toEvt ToEnd <$> button [Text "|>" ] []
spacer
-- OOPS
let events = listEvents eList (unions [JumpTo <$> eN, e1, e2, e3, e4, e5, e6])
finiN $ Bhv 0 $ fst <$> events
return events
-- Commands for a list
data ListCmd
= MoveFwd Int
| MoveBack Int
| JumpTo Int
| ToBegin
| ToEnd
deriving (Show)
-- Cursor for list of values
data Cursor a
= Cursor Int [a] Int -- Length × list × position
| Invalid
listEvents :: Event t [a] -> Event t ListCmd -> Event t (Int,a)
listEvents listEvt command
= filterJust
$ fmap fini
$ scanE acc Invalid
$ listEvt `joinE` command
where
--
fini (Cursor _ xs i) = Just (i, xs !! i)
fini Invalid = Nothing
-- Accumulate data
acc Invalid (Left []) = Invalid
acc Invalid (Left xs) = Cursor (length xs) xs 0
acc Invalid _ = Invalid
acc (Cursor _ _ n) (Left xs) =
Cursor len xs $ clip len n where len = length xs
acc (Cursor len xs n) (Right c) =
case c of
MoveFwd d -> go $ n + d
MoveBack d -> go $ n - d
JumpTo d -> go d
ToBegin -> go 0
ToEnd -> go $ len - 1
where
go = Cursor len xs . clip len
-- Clip out of range indices
clip len i | i < 0 = 0
| i >= len = len -1
| otherwise = i
|
Shimuuar/banana-tcltk
|
UI/Widget/List.hs
|
Haskell
|
bsd-3-clause
| 2,401
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
module React.Flux.Mui.RadioButton.RadioButtonGroup where
import Protolude
import Data.Aeson
import Data.Aeson.Casing
import Data.String (String)
import React.Flux
import React.Flux.Mui.Types
import React.Flux.Mui.Util
data RadioButtonGroup = RadioButtonGroup
{ radioButtonGroupClassName :: !(Maybe Text)
, radioButtonGroupLabelPosition :: !(Maybe (MuiSymbolEnum '[ "left", "right"]))
, radioButtonGroupName :: !Text
} deriving (Generic, Show)
instance ToJSON RadioButtonGroup where
toJSON =
genericToJSON $ aesonDrop (length ("RadioButtonGroup" :: String)) camelCase
defRadioButtonGroup :: Text -> RadioButtonGroup
defRadioButtonGroup radioButtonGroupName_ =
RadioButtonGroup
{ radioButtonGroupClassName = Nothing
, radioButtonGroupLabelPosition = Nothing
, radioButtonGroupName = radioButtonGroupName_
}
radioButtonGroup_ ::
RadioButtonGroup
-> [PropertyOrHandler handler]
-> ReactElementM handler ()
-> ReactElementM handler ()
radioButtonGroup_ args props =
foreign_ "RadioButtonGroup" (fromMaybe [] (toProps args) ++ props)
|
pbogdan/react-flux-mui
|
react-flux-mui/src/React/Flux/Mui/RadioButton/RadioButtonGroup.hs
|
Haskell
|
bsd-3-clause
| 1,165
|
-- |
-- Module: Threshold
-- Description: Time integrated threshold functions
-- Copyright: (c) 2013 Tom Hawkins & Lee Pike
--
-- Time integrated threshold functions typically used in condition monitoring.
module Language.Atom.Common.Threshold
( boolThreshold
, doubleThreshold
) where
import Language.Atom.Expressions
import Language.Atom.Language
import Data.Int (Int32)
-- | Boolean thresholding over time. Output is set when internal counter hits
-- limit, and cleared when counter is 0.
boolThreshold :: Name -> Int32 -> Bool -> E Bool -> Atom (E Bool)
boolThreshold name_ num init_ input = atom name_ "" $ do
--assert "positiveNumber" $ num >= 0
state <- bool "state" init_
count <- int32 "count" (if init_ then num else 0)
atom "update" "" $ do
cond $ value count >. Const 0 &&. value count <. Const num
count <== value count + mux input (Const 1) (Const (-1))
atom "low" "" $ do
cond $ value count ==. Const 0
state <== false
atom "high" "" $ do
cond $ value count ==. Const num
state <== true
return $ value state
-- | Integrating threshold. Output is set with integral reaches limit, and
-- cleared when integral reaches 0.
doubleThreshold :: Name -> Double -> E Double -> Atom (E Bool)
doubleThreshold name_ lim input = atom name_ "" $ do
--assert "positiveLimit" $ lim >= 0
state <- bool "state" False
sum_ <- double "sum" 0
-- TODO: Figure out what the below translates to in the newer library
-- (high,low) <- priority
atom "update" "" $ do
sum_ <== value sum_ + input
-- low
atom "clear" "" $ do
cond $ value sum_ <=. 0
state <== false
sum_ <== 0
-- high
atom "set" "" $ do
cond $ value sum_ >=. Const lim
state <== true
sum_ <== Const lim
-- high
return $ value state
|
Copilot-Language/atom_for_copilot
|
Language/Atom/Common/Threshold.hs
|
Haskell
|
bsd-3-clause
| 1,806
|
import Control.Monad (when)
import Distribution.Simple
import System.Directory (doesFileExist)
import System.Process (readProcess)
import Data.ByteString.Char8 as BS
gitVersion :: IO ()
gitVersion = do
let filename = "app/Internal/Version.hs"
versionSh = "./version.sh"
hasVersionSh <- doesFileExist versionSh
when hasVersionSh $ do
ver <- fmap BS.pack $ readProcess "bash" [versionSh] ""
let override = BS.writeFile filename ver
e <- doesFileExist filename
if e then do orig_ver <- BS.readFile filename
when (ver /= orig_ver) $ do
override
else override
main :: IO ()
main = gitVersion >> defaultMain
|
da-x/fancydiff
|
Setup.hs
|
Haskell
|
bsd-3-clause
| 780
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.