Upload
allison-cole
View
231
Download
7
Tags:
Embed Size (px)
Citation preview
1
Visual Basic “Whidbey”:Advanced Language andIDE FeaturesSteven Lees, [email protected] Silver, [email protected] ManagersMicrosoft Corporation
Session Code: TLS300
2
AgendaAgenda
Advanced IDE FeaturesLots of new language featuresFull platform support
Advanced IDE FeaturesLots of new language featuresFull platform support
3
Advanced IDE FeaturesAdvanced IDE Features
Application DesignerSettings
Extensible code snippetsRename SymbolNew Async calling convention
Application DesignerSettings
Extensible code snippetsRename SymbolNew Async calling convention
4
Configuration and SettingsConfiguration and Settings
Basic support in VS 2002 and 2003App.config contains settings in XMLFramework class for reading settingsCan extend with additional capabilities
Straightforward, but not really easy
Basic support in VS 2002 and 2003App.config contains settings in XMLFramework class for reading settingsCan extend with additional capabilities
Straightforward, but not really easy
5
Configuration and SettingsConfiguration and Settings
Huge improvements in WhidbeyFramework classes support read/writeStrongly-typed access to settingsIntelliSense for settingsChoose app-scoped or user-scoped settingsWorks in partial trustValidation modelExtensible provider modelShared infrastructure across client and web
Huge improvements in WhidbeyFramework classes support read/writeStrongly-typed access to settingsIntelliSense for settingsChoose app-scoped or user-scoped settingsWorks in partial trustValidation modelExtensible provider modelShared infrastructure across client and web
6
Settings ArchitectureSettings Architecture
SettingsBaseSettingsBase
ApplicationSettingsBaseApplicationSettingsBase
WindowsApp1SettingsWindowsApp1Settings
Provider InterfaceProvider Interface
LocalLocalSettingsSettings
RemoteRemote SqlSql CustomCustomAccessAccessCustomCustom
My.SettingsMy.Settings
7
Settings ArchitectureSettings Architecture
CustomizableAt the provider levelBy writing custom settings classes
CustomizableAt the provider levelBy writing custom settings classes
8
9
SettingsSettings
Designer allowsCreating / modifying / deleting entriesType of entry (for strong typing)Choosing user-scoped or app-scopedDefault valueDifferent “profiles”
Special support forConnection StringsWeb service proxiesVS will automatically create settings
Designer allowsCreating / modifying / deleting entriesType of entry (for strong typing)Choosing user-scoped or app-scopedDefault valueDifferent “profiles”
Special support forConnection StringsWeb service proxiesVS will automatically create settings
10
Settings ArchitectureSettings Architecture
App settingsApp settings User SettingsUser Settings
Myapp.exe.config
<applicationSettings>…
</applicationSettings>
fred.config
<userSettings>…
</userSettings>
ethel.config
<userSettings>…
</userSettings>
gladys.config
<userSettings>…
</userSettings>
11
Code SamplesCode Samples
Load
Save
Handling events for validation
Load
Save
Handling events for validation
MyMy.Settings.UseHighQuality = .Settings.UseHighQuality = TrueTrue‘ Settings automatically loaded on first access‘ Settings automatically loaded on first access
Private SubPrivate Sub Settings_SettingChanging(ByVal sender Settings_SettingChanging(ByVal sender AsAs Object, Object, ByValByVal e e AsAs SettingsArg) SettingsArg) HandlesHandles MyBaseMyBase.SettingChanging.SettingChanging
IfIf e.SettingName = “SignatureFile” e.SettingName = “SignatureFile” ThenThen If NotIf Not My.Computer.FileSystem.FileExists(e.Setting.Value) My.Computer.FileSystem.FileExists(e.Setting.Value) ThenThen ‘ ‘ Cancel eventCancel event End IfEnd If End IfEnd IfEnd SubEnd Sub
MyMy.Settings.UseHighQuality = .Settings.UseHighQuality = TrueTrueMyMy.Settings.Save().Settings.Save()
12
Advanced IDE FeaturesAdvanced IDE Features
Application DesignerSettings
Extensible code snippetsRename SymbolNew Async calling convention
Application DesignerSettings
Extensible code snippetsRename SymbolNew Async calling convention
13
Application DesignerApplication Designer
One stop shopping for app settingsResourcesApp and user settingsReferencesVersion InfoDeployment
Easier to findNon-modal window for better usability
One stop shopping for app settingsResourcesApp and user settingsReferencesVersion InfoDeployment
Easier to findNon-modal window for better usability
14
Application DesignerApplication Designer
New Application EventsStartupShutdownUnhandled exceptionNetwork connectedNetwork disconnected
New Application EventsStartupShutdownUnhandled exceptionNetwork connectedNetwork disconnected
15
Advanced IDE FeaturesAdvanced IDE Features
Application DesignerSettings
Extensible code snippetsRename SymbolNew Async calling convention
Application DesignerSettings
Extensible code snippetsRename SymbolNew Async calling convention
16
Extensible Code SnippetsExtensible Code Snippets
Code snippets have standard schemaYou can add items to the right-click menuSnippet editor
For creating, editing snippets
Multiple snippet storesLocal or network share
Easy way to package code for reuseSharing is encouraged!
Code snippets have standard schemaYou can add items to the right-click menuSnippet editor
For creating, editing snippets
Multiple snippet storesLocal or network share
Easy way to package code for reuseSharing is encouraged!
17
Rename SymbolQuick way to change identifiersRename SymbolQuick way to change identifiers
Rename all cases of “TextBox1”Type declarationVariable declarationsEvents
More precise than text replacementDoesn’t affect commentsWorking on other “refactoring” features
Create method
Rename all cases of “TextBox1”Type declarationVariable declarationsEvents
More precise than text replacementDoesn’t affect commentsWorking on other “refactoring” features
Create method
18
Advanced IDE FeaturesAdvanced IDE Features
Application DesignerSettings
Extensible code snippetsRename SymbolNew Async calling convention
Application DesignerSettings
Extensible code snippetsRename SymbolNew Async calling convention
19
Asynchronous callingAsynchronous calling
Easier way to call slow background tasksModel asynchronous calls as events
PictureBox1.LoadAsync(url)PictureBox1_LoadCompleted(…, …)
Completion routine is on main threadWeb service proxiesSupports progress, cancellationBackground worker component
Easier way to call slow background tasksModel asynchronous calls as events
PictureBox1.LoadAsync(url)PictureBox1_LoadCompleted(…, …)
Completion routine is on main threadWeb service proxiesSupports progress, cancellationBackground worker component
20
Background WorkerBackground WorkerStructure BackgroundArgsStructure BackgroundArgs Dim arg1 As IntegerDim arg1 As Integer Dim arg2 As StringDim arg2 As StringEnd StructureEnd Structure
Private Sub Button1_Click(…) Handles Button1.ClickPrivate Sub Button1_Click(…) Handles Button1.Click Dim args As BackgroundArgsDim args As BackgroundArgs BackgroundWorker1.RunWorkerAsync(args)BackgroundWorker1.RunWorkerAsync(args)End SubEnd Sub
Private Sub BackgroundWorker1_DoWork(…) Handles Private Sub BackgroundWorker1_DoWork(…) Handles BackgroundWorker1.DoWorkBackgroundWorker1.DoWork ‘ ‘ This is run on a background threadThis is run on a background thread Dim args As BackgroundArgsDim args As BackgroundArgs args = CType(e.Argument, BackgroundArgs)args = CType(e.Argument, BackgroundArgs) ‘ ‘ Now do something on the background threadNow do something on the background thread e.Result = <some object>e.Result = <some object>End SubEnd Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(…) Handles Private Sub BackgroundWorker1_RunWorkerCompleted(…) Handles Background…Background… result = e.Resultresult = e.ResultEnd SubEnd Sub
21
Advanced IDE Features
22
New Language FeaturesNew Language Features
Explicit array boundsUsing statementContinue statementGlobal keywordAccessor accessibilityPartial typesUnsigned typesOperator OverloadingGenericsWarnings
Explicit array boundsUsing statementContinue statementGlobal keywordAccessor accessibilityPartial typesUnsigned typesOperator OverloadingGenericsWarnings
23
Explicit Array BoundsExplicit Array Bounds
Arrays are still zero basedYou can now specify the lower and upper bounds in the declaration
Arrays are still zero basedYou can now specify the lower and upper bounds in the declaration
‘‘In VS 2002 and 2003, you did it this wayIn VS 2002 and 2003, you did it this wayDim x(10) As IntegerDim x(10) As Integer
‘‘Now you can also declare it like thisNow you can also declare it like thisDim y(0 To 10) As IntegerDim y(0 To 10) As Integer
24
Using StatementAcquire, Execute, ReleaseUsing StatementAcquire, Execute, Release
Fast way correctly release resources Easier to read than Try, Catch, Finally
Couple with Dispose Pattern stub gen
Fast way correctly release resources Easier to read than Try, Catch, Finally
Couple with Dispose Pattern stub gen
‘‘Using block disposes of resourceUsing block disposes of resourceUsing fStr As New FileStream(path, FileMode.Append)Using fStr As New FileStream(path, FileMode.Append) For i As Integer = 0 To fStr.LengthFor i As Integer = 0 To fStr.Length fStr.ReadByte()fStr.ReadByte() NextNext
‘ ‘End of block will close streamEnd of block will close streamEnd UsingEnd Using
25
Continue StatementSkips to next iteration of loopContinue StatementSkips to next iteration of loop
Loop logic is concise, easier to read Loop logic is concise, easier to read
For j As Integer = 0 to 5000For j As Integer = 0 to 5000 While matrix(j) IsNot thisValueWhile matrix(j) IsNot thisValue If matrix(j) Is thatValueIf matrix(j) Is thatValue
‘ ‘ Continue to next jContinue to next j Continue ForContinue For
End IfEnd If
Graph(j)Graph(j) End WhileEnd WhileNext jNext j
26
Global KeywordAccess to root (empty) namespaceGlobal KeywordAccess to root (empty) namespace
Complete name disambiguation Better choice for code generationComplete name disambiguation Better choice for code generation
Namespace HeadTraxNamespace HeadTrax Class Form1Class Form1
Inherits Windows.Forms.FormsInherits Windows.Forms.Forms
Sub LastName(nm As String)Sub LastName(nm As String) Global.Microsoft.VisualBasic.Left(nm)Global.Microsoft.VisualBasic.Left(nm) End SubEnd Sub End ClassEnd ClassEnd NamespaceEnd Namespace
27
Accessor AccessibilityGranular accessibility on Get and Set
Accessor AccessibilityGranular accessibility on Get and Set
Forces calls to always use get, setEasy way to enforce validationForces calls to always use get, setEasy way to enforce validation
Property Salary() As IntegerProperty Salary() As Integer GetGet
Return mSalaryReturn mSalary End GetEnd Get
Private Set( value As Integer)Private Set( value As Integer)If value < 0 ThenIf value < 0 Then Throw New Exception(“Mistake”)Throw New Exception(“Mistake”)End IfEnd If
End SetEnd SetEnd PropertyEnd Property
28
Partial TypesSingle Structure, Class in Multiple Files
Partial TypesSingle Structure, Class in Multiple Files
Used to separate designer gen into another fileFactor implementation
Used to separate designer gen into another fileFactor implementation
Public Class Form1Public Class Form1 Inherits Windows.Forms.FormInherits Windows.Forms.Form
‘ ‘ Your CodeYour CodeEnd ClassEnd Class
Partial Class Form1Partial Class Form1‘ ‘ Designer codeDesigner codeSub InitializeComponent()Sub InitializeComponent() ‘ ‘ Your controlsYour controlsEnd SubEnd Sub
End ClassEnd Class
29
Unsigned TypesFull support in the languageUnsigned TypesFull support in the language
Full platform parityEasier Win32 Api calls and translationMemory and performance win
Full platform parityEasier Win32 Api calls and translationMemory and performance win
Dim sb As SByte = -4 ‘Error:negativeDim sb As SByte = -4 ‘Error:negativeDim us As UShortDim us As UShortDim ui As UIntegerDim ui As UIntegerDim ul As ULongDim ul As ULong
‘‘Full support in VisualBasic modulesFull support in VisualBasic modulesIf IsNumeric(uInt) ThenIf IsNumeric(uInt) Then
‘ ‘ Will now return true Will now return true End IfEnd If
30
New Language Features
31
Operator OverloadingCreate your own base typesOperator OverloadingCreate your own base typesClass AddrClass Addr Private mString As StringPrivate mString As String
Property Value() As StringProperty Value() As String GetGet Return mStringReturn mString End GetEnd Get Set (value As String)Set (value As String) If Valid(value) ThenIf Valid(value) Then mString = valuemString = value End IfEnd If End SetEnd Set
Shared Operator &(ad1 As Addr, ad2 As Addr) _Shared Operator &(ad1 As Addr, ad2 As Addr) _ As AddrAs Addr
Return New Addr(ad1.Value & ad2.Value)Return New Addr(ad1.Value & ad2.Value) End Operator End Operator
32
Operator Overloading
33
List intList = new List()List intList = new List()
intList.Add(1) intList.Add(1) ‘ Argument is boxed‘ Argument is boxedintList.Add(2) intList.Add(2) ‘ Argument is boxed‘ Argument is boxedintList.Add("Three") intList.Add("Three") ‘ Should be an error‘ Should be an error
int i = CInt(intList(0)) int i = CInt(intList(0)) ‘ Cast required‘ Cast required
GenericsGenericsPublic Class ListPublic Class List<ItemType><ItemType> Private elements() As Private elements() As ItemTypeItemType Private count As IntegerPrivate count As Integer
Public Sub Add(element As Public Sub Add(element As ItemTypeItemType) ) If (count = elements.Length) Then _If (count = elements.Length) Then _ Resize(count * 2)Resize(count * 2) count += 1count += 1 elements(count) = elementelements(count) = element End SubEnd Sub
Public Property default(index As Integer) As Public Property default(index As Integer) As ItemTypeItemType Get : Return elements(index) : End GetGet : Return elements(index) : End Get Set : elements(index) = value : End SetSet : elements(index) = value : End Set End PropertyEnd Property
Public Property Count As IntegerPublic Property Count As Integer Get : Return count : End GetGet : Return count : End Get End PropertyEnd PropertyEnd ClassEnd Class
Public Class ListPublic Class List Private elements() As ObjectPrivate elements() As Object Private mCount As IntegerPrivate mCount As Integer
Public Sub Add(element As Object) Public Sub Add(element As Object) If (mCount = elements.Length) Then _If (mCount = elements.Length) Then _ Resize(mCount * 2)Resize(mCount * 2) mCount += 1mCount += 1 elements(mCount) = elementelements(mCount) = element End SubEnd Sub
Default Public Property i(index As Integer) As ObjectDefault Public Property i(index As Integer) As Object Get Get Return elements(index) Return elements(index) End GetEnd Get Set Set elements(index) = value elements(index) = value End SetEnd Set End PropertyEnd Property
Public Property Count() As IntegerPublic Property Count() As Integer Get : Return mCount : End GetGet : Return mCount : End Get End PropertyEnd PropertyEnd ClassEnd Class
Dim intList As New ListDim intList As New List
intList.Add(1)intList.Add(1)intList.Add(2)intList.Add(2)intList.Add("Three")intList.Add("Three")
Dim i As Integer = intList(0)Dim i As Integer = intList(0)
Dim intList As New ListDim intList As New List(Of Integer)(Of Integer)
intList.Add(1) ‘ No boxingintList.Add(1) ‘ No boxingintList.Add(2) ‘ No boxingintList.Add(2) ‘ No boxingintList.Add("Three") ‘ Compile-time errorintList.Add("Three") ‘ Compile-time error
int i = intList(0) ‘ No cast requiredint i = intList(0) ‘ No cast required
34
Generics (Specifics)Generics (Specifics)
Compile Time CheckingEliminates runtime errors
PerformanceNo casting or boxing overhead
Code reuseEasy to create strongly typed collections
Generic Collection classes in Framework
Dictionary, HashTable, List, Stack, etc.
Compile Time CheckingEliminates runtime errors
PerformanceNo casting or boxing overhead
Code reuseEasy to create strongly typed collections
Generic Collection classes in Framework
Dictionary, HashTable, List, Stack, etc.
35
Generics
36
Visual Basic WarningsEarly warning of bad runtime behavior
Visual Basic WarningsEarly warning of bad runtime behavior
Overlapping catch blocks or cases Recursive property accessUnused Imports statementUnused local variableFunction, operator without returnReference on possible null referenceOption Strict broken down
“Late binding”VB Style ConversionsEtc.
Overlapping catch blocks or cases Recursive property accessUnused Imports statementUnused local variableFunction, operator without returnReference on possible null referenceOption Strict broken down
“Late binding”VB Style ConversionsEtc.
37
Warnings
38
Additional ResourcesAdditional Resources
Related sessionsTLS343 – Visual Studio “Whidbey”: Advanced Debugging Techniques (Tuesday 5:15 Room 408 AB)TLS344 – Visual Studio “Whidbey”: Deploying Applications Using ClickOnce (Wednesday 10:00 Room 511 ABC)ARC413 – CLR Under the Covers: “Whidbey” CLR Internals (Wednesday 5:00 Room 152/153)
Related sessionsTLS343 – Visual Studio “Whidbey”: Advanced Debugging Techniques (Tuesday 5:15 Room 408 AB)TLS344 – Visual Studio “Whidbey”: Deploying Applications Using ClickOnce (Wednesday 10:00 Room 511 ABC)ARC413 – CLR Under the Covers: “Whidbey” CLR Internals (Wednesday 5:00 Room 152/153)
39
Additional ResourcesAdditional Resources
PanelsAsk The Experts (Tonight)Languages Panel (Thursday)
Send us [email protected]: microsoft.public.dotnet.vbhttp://msdn.microsoft.com/vstudio/whidbeypdc
Other resourcesPaul Vick’s blog: www.panopticon.net
PanelsAsk The Experts (Tonight)Languages Panel (Thursday)
Send us [email protected]: microsoft.public.dotnet.vbhttp://msdn.microsoft.com/vstudio/whidbeypdc
Other resourcesPaul Vick’s blog: www.panopticon.net
40
SummarySummary
Ease of use is built on solid infrastructureMany points of extensibilityVery powerful new language features
And some cool fit and finish ones too
Full access to the platform
Please fill out the eval!(Thank you!)
Ease of use is built on solid infrastructureMany points of extensibilityVery powerful new language features
And some cool fit and finish ones too
Full access to the platform
Please fill out the eval!(Thank you!)
41© 2003-2004 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.