Visual Basic.netJust some notesThese are my personal notes that I use as a quick help in my work.
|
|
Just in case some things have changed, see the old page of notes for VB6.
vb.net IDE:
' comment |
Comments |
safdasfd _ asdf |
Continue line |
|
Two forms of do..loop |
While cond |
While |
If cond Then ... [Else ...] |
Statement on one line |
If cond Then |
|
For i=start_i to end_i [step n] |
|
For Each element In group |
|
Call procedure(arg1, arg2) |
Call procedure (note that parentheses are needed with "call"). Use empty parentheses after array parameter. |
ChDir |
|
|
Note: use Get and Put together |
console.writeline(..) |
Display on console Message box for windows applications Gives string representation |
Date = ... |
Set date / time |
Dim varname |
|
[Public | Private] Enum name |
|
[Private | Public] Type varname |
|
Erase arraylist |
release memory |
|
|
[Public] Event procedurename [(arglist)] |
|
[Public | Private | Friend] [Static] Function name [(arglist)]
|
|
[Private | Public | Friend] [Static] Sub name [(arglist)]
|
|
[Public | Private | Friend] [Static] Property Get name
[(arglist)] |
|
[Public | Private | Friend] [Static] Property Let name
([arglist,] value) |
|
[Public | Private | Friend] [Static] Property Set name
([arglist,] reference) |
|
[Optional] [ByVal | ByRef] [ParamArray] varname[( )]
[As type] [= defaultvalue] |
Argument list for functions and subs |
GoSub line |
|
Implements [InterfaceName | Class] |
|
[Let] varname = expression |
The "let" is not necessary |
|
|
Mid(stringvar, start[, length]) = string |
|
Option Base {0 | 1} |
Default lower bound for arrays, at start of module |
Option Compare {Binary | Text | Database} |
|
Option Explicit |
All variables must be explicitely defined |
Option Private Module |
|
RaiseEvent eventname [(argumentlist)] |
|
Randomize [number] |
|
SavePicture picture, stringexpression |
|
SaveSetting appname, section, key, setting |
|
Select Case testexpression |
|
SendKeys string[, wait] |
|
Stop |
Stops execution Exit application |
Try |
|
Throw New Exception("This is a custom exception") |
Stops execution Exit application |
[Public | Private] Const constname [As type] = expression
[Public | Private] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])]
[Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])]
[As type]
& | Concatenation |
+ - * / | |
a \ b a Mod b |
Division with integer result Integer remainder |
a ^ b | a raised to power of b (a^2 is square) |
AddressOf procedurename | Address of a procedure |
a Is b | Returns true if a and b refer to the same object |
Like | |
Eqv | |
Imp | Logical implication |
Mod | |
And Or Xor |
Explicit conversions:
Format or Val functions (formats to string, and val gives number equivalent of string)
In .NET: something = system.convert.toInt32(somethingElse) where ToInt32 can be any data type.
The My
namespace contains both .NET framework classes and
the classes
The Me object corresponds to the current window.
Data source is what the application sees. The data source connects through
a connection to the database. The data source is stored as an .xsd file.
Four objects: binding source, binding navigator, typed dataset, table adapter.
Each combo also has a binding source and a table adapter.
The table adapters hold the queries that are used on the table. By default four
queries are built in: insert, update, select and delete. Add query if needed.
Example: search with " (t.col LIKE '%' + @A_label + '%')
".
Then add "FillBy" queries to the table adapter component of the form.
Combo box for reference tables: drag and drop the table from the "Data Source" window onto the combo.
Main page
Settings: allows storage of custom settings, such as username. The names of web services are kept here too. Get settings with "My.Settings.theNameOfTheSetting". Save settings with My.Settings.Save
right-click on project, choose add web reference. VB then adds all the necessary files, including a proxy of the web service so that some off-line development work can be done. The data source is added too.
Drag the data set onto the form. A binding source and a binding navigator are added.
BackGroundWorker component: launches a separate thread so as to give the control
back to the user. Program the DoWork event to call the web service:
Dim OneArg = e.Argument
Dim theWebService As New nameOfWebService.Service
e.Result = theWebService.aMethodOfWebService(arg as defined for web service)
Start the background worker with:
If Not TheBackgroundWorkerObject.IsBusy() then
TheBackgroundWorkerObject.RunWorkerAsync(whatever args)
End If
Imports System
Imports System.Web.Services
Imports Microsoft.VisualBasic
Public Class the_name : Inherits WebService
Public Function <WebMethod()> a_function (strWhatEver as String) as
String
...
End Function
End Class
Render Blocks:
<% %>
<% Dim I As Integer
For I = 0 to 7 %>
<font size="<%=I%>"> Growing display </font> <br>
<% Next %>
All controls are mapped to one of the controls in the
"System.Web.UI.HtmlControls" namespace.
Non-standard controls map to "System.Web.UI.HtmlControls.HtmlGenericControl"
List of controls:
http://samples.gotdotnet.com/quickstart/aspplus/doc/webcontrolsref.aspx
If possible, use the System.DateTime
data type which allows interoperation with the .NET framework.
The Date type (in VB) or System.DateTime (in .NET) contains IEEE (8-byte) values that represent dates from year 0001 to 9999.
The date object without the constructor new
contains the current date and time.
The two static methods are UTC and parse.
Create a date with (hours, minutes, seconds and milliseconds are optional):
Dim MyDate As New System.DateTime(2007, 2, 13, 10, 32, 0, 0)
Then display it with a format:
MyString = MyDate.ToString("dd/MM/yyyy gg HH:mm:ss (zzz)")
The previous line is equivalent to:
MyString = Format(MyDate, "dd/MM/yyyy gg HH:mm:ss (zzz)")
Get the current time and date:
Dim theMoment as DateTime = Now()
Custom date formats:
Differing options refer to the format with/without leading zeros or abbreviated/full names
The use of the date formats requires: Imports System.Globalization
.
See the TimeSpan object for representing positive and negative time spans. See the calendar class for handling Gregorian and other calendars.
Pre-defined format names for the format function:
VB Script constants (also for .NET?):
Use the methods System.DateTime.FromOADate
and System.DateTime.ToOADate
to convert to or from
OLE Automation dates.
Example of the use of parsing:
Imports System.Globalization
Dim MyCultureInfo As CultureInfo = new CultureInfo("de-DE")
Dim MyString As String = "12 April 2006"
Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo)
Console.WriteLine(MyDateTime)
The ParseExact method allows specification of one and only of the possible formats (see list above).
Sample code:
dim aTimeSpan as TimeSpan = New TimeSpan(3, 12, 0, 0) ' 3 days, 12 hours
aTimeSpan = aDatetime.Subtract(anotherDateTime)
Sample timing operation:
dim StartTime, EndTime as DateTime
dim theDuration as TimeSpan
StartTime = Now()
.....
EndTime = Now()
theDuration = EndTime - StartTime
Debug.Write("Duration is " & theDuration.duration )
tcpServer.Protocol = sckTCPProtocol ' Set the protocol
tcpServer.LocalPort = 1001 ' Set local port
tcpServer.Listen ' Now wait
Private Sub tcpServer_ConnectionRequest _ (ByVal requestID As Long) '
Event ConnectionRequest
If tcpServer.State <> sckClosed Then tcpServer.Close
' Close previous connection first
tcpServer.Accept requestID
End Sub
tcpClient.RemoteHost = "the remote computer name"
tcpClient.RemotePort = 1001
tcpClient.Connect ' Initiate a connection.
tcpServerOrClient.SendData "a text"
Private Sub tcpServerOrClient_DataArrival (ByVal bytesTotal As Long)
' Event DataArrival
Dim strData As String
tcpServerOrClient.GetData strData
End Sub
Handle multiple connection requests:
intMax = 0
sckServer(0).LocalPort = 1001
sckServer(0).Listen
Private Sub sckServer_ConnectionRequest (Index As Integer, ByVal requestID As
Long)
If Index = 0 Then
intMax = intMax + 1
Load sckServer(intMax)
sckServer(intMax).LocalPort
= 0
sckServer(intMax).Accept requestID
End If
End Sub
object.BytesReceived
object.LocalHostName
object.LocalIP
object.LocalPort = long
object.Protocol n
object.RemoteHost = string
object.RemoteHostIP
object.RemotePort = port
object.SocketHandle
object.State
object.Tag [= expression]
Winsock.Accept requestID
object.Bind LocalPort, LocalIP
object.Close
object.GetData (format)
object.GetData data, [type,] [maxLen]
object.PeekData data, [type,] [maxLen]
object.SendData data
Close
Connect()
Object_ConnectionRequest (requestID As Long)
object_DataArrival (bytesTotal As Long)
object_Error(number As Integer, Description As String, Scode As Long,
Source As String,
HelpFile as String, HelpContext As Long, CancelDisplay As Boolean)
object_SendComplete
object_SendProgress (bytesSent As Long, bytesRemaining As Long)
Confirmation of each change to the data (deletion or insertion):
menu tools > options > tab edit/find > confirm: record changes, document deletions and action queries
At the beginning of each module
Option Compare Database 'Utilise l'ordre de la base pour les comparaisons
de chaƮnes
Option Explicit
Minimum for a sub
Private Sub whatever(params)
On Error GoTo whateverError
...
whateverExit:
Exit Sub
whateverError:
msgbox "Error number " & err & " in sub-routine 'whatever'" & Chr$(13)
& Error(err)
' undo or rollback here
Resume whateverExit
End Sub
Code for opening a form with parameter
Private Sub xyz_Click()
Dim stDocName As String
Dim stLinkCriteria As String
stDocName = "a_form_name"
stLinkCriteria = "[AccountNo]=" & Me![AccountNo]
DoCmd.OpenForm stDocName, A_NORMAL, A_EDIT , stLinkCriteria
End Sub
Private Sub SEARCH_Enter()
or: Private Sub SEARCH_LostFocus()
DocName = "Filtre de recherche"
DoCmd.OpenQuery DocName, A_NORMAL, A_EDIT
End Sub
Prompt user to confirm changes
Called Sub CheckUnsavedData() in Form_BeforeUpdate() and Form_Unload()
' Use this with an OK button
Private AskToSaveRecord As Boolean
' Put AskToSaveRecord = True in the Form_Current and save events
' Put AskToSaveRecord = False in the cmdOK_Click event so that the user is not
prompted
' However, in some of my notes, I do NOT use the variable AskToSaveRecord.
Private Sub CheckUnsavedData(theForm as form)
' AskToSaveRecord is set to no when user clicks on OK, otherwise
yes. Don't use if no OK button
...
If theform.Dirty And AskToSaveRecord Then
If vbNo = MsgBox("The data has changed" & Chr$(13)
& "Do you want to save the changes?", vbYesNo) Then
theform.Undo ' Undo the changes here
End If
End If
AskToSaveRecord = True
...
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
Call CheckUnsavedData(me)
End Sub
Private Sub Form_Unload(Cancel As Integer)
Call CheckUnsavedData(me)
End Sub
Private Sub fieldName_AfterUpdate()
Forms!xyz.Refresh
End Sub
Private Sub Form_Close()
DoCmd.Quit
End Sub
Private Sub Form_Open(Cancel As Integer)
Forms!Accounts.Caption = "the accounts"
Forms!Accounts!Abc.Form.Filter = "a condition"
End Sub
Put this in general module
Public Sub ErrMsg(TheError, SubName As String)
Dim ErrorLine1$, ErrorLine2$
Dim ErrNum As Long
If IsNumeric(TheError) Then
'ErrNum = TheError
ErrorLine1$ = "Error number " & TheError & " in sub-routine
'" & SubName & "'"
ErrorLine2$ = Error(TheError) 'Error$ ' The error number
is ignored because of a bug.
' Take the current error
' or use object err: err.description
Else
ErrorLine1$ = "Custom error in sub-routine '" & SubName
& "'"
ErrorLine2$ = TheError
End If
If 0 < Len(ErrorLine1$) + Len(ErrorLine2$) Then MsgBox ErrorLine1$
& Chr$(13) & ErrorLine2$
End Sub
DoCmd.Close
DoCmd.Quit
DoCmd.GoToControl "a_control"
Execute immediate: create a module with
Option Compare Database
Sub a_sub()
DoCmd.RunSQL "update table set ....;"
End Sub
Then do F5 or Run. Optionally compile beforehand (menu debug > compile)
Option Compare Database
Option Explicit
Private Sub Command53_Click()
On Error GoTo Err_Command53_Click
DoCmd.GoToRecord , , acFirst
Exit_Command53_Click:
Exit Sub
Err_Command53_Click:
MsgBox Err.Description
Resume Exit_Command53_Click
End Sub
' commands
DoCmd.GoToRecord , , acFirst ' goto first
DoCmd.GoToRecord , , acPrevious
DoCmd.GoToRecord , , acNext
DoCmd.GoToRecord , , acLast
DoCmd.Close
DoCmd.GoToRecord , , acNewRec
DoCmd.PrintOut
' Delete:
DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70
DoCmd.DoMenuItem acFormBar, acEditMenu, 6, , acMenuVer70
' Search :
Screen.PreviousControl.SetFocus
DoCmd.DoMenuItem acFormBar, acEditMenu, 10, , acMenuVer70
' Also:
Private Sub Descriptor_DblClick(Cancel As Integer)
DoCmd.OpenForm "tbl_descriptors"
End Sub
' open a form
DoCmd.OpenForm "Maintenanceform", , , , , acNormal
' or
Dim stDocName As String
Dim stLinkCriteria As String
stDocName = "lkp_Descriptors"
DoCmd.OpenForm stDocName, , , stLinkCriteria
' open a report
DoCmd.OpenReport stDocName, acViewPreview
Private Sub Form_Activate()
DoCmd.Maximize
DoCmd.ShowToolbar "Reference", acToolbarYes
End Sub
Private Sub Form_Close()
DoCmd.ShowToolbar "Reference", acToolbarNo
End Sub
Private Sub control_BeforeUpdate(Cancel As Integer)
asdf
If intCountDuplicate > 0 Then
MsgBox " Found a duplicate record"
End If
End Sub
Private Sub Control_LostFocus()
asdf
End Sub
DoCmd.Hourglass True
' Build search query
If Not IsNull(Me!cboCountry) Then
strFilter = strFilter & " Country = '" & Me!cboCountry
& "' AND"
End If
If Me!ExpertisePolicy = True Then
strFilter = strFilter & " ExpertisePolicy = True AND"
End If
' fill a list with the results of a search
strFilter = strFilter & " " & mcmdSort.ControlTipText ' Add ORDER
BY clause
Me!lstOrder.RowSource = mcstrSQL & strFilter ' Put SQL in the list
box
Me!lstOrder.Requery
DoCmd.Hourglass False
If Not IsNull(Me!lstOrder) Then
Me!lstOrder.Tag = Me!lstOrder.Column(0)
DoCmd.OpenForm "ViewContact"
End If
' clear:
Me![cboGeoExp] = Null
Me![ExpertisePolicy] = False
' what is this
mcmdSort.FontWeight = mcintNormal
Set mcmdSort = Me!cmdLocation
mcmdSort.FontWeight = mcintBold
Call cbfRequery ' Rebuild the list
expression builder for validation rule: to see fields, first save text.
Sort reports in "Sorting and Grouping"
trim(str)
left(str,3)
link table
Primary key is made of both foreign keys
Combo
Displays options from a reference table TR. The data is stored in the main table MT.
control source | main-table.id |
Row source type | Table/Query |
Row source | SELECT id, label FROM TR; order by id |
Bound column | 1 |
Limit to list | Yes |
column count | 2 |
Column widths | 0;3cm (trick to hide the ID) |
Sub-form
On the form is a combo-box, as described above
Default view | continuous forms |
data source | Link form to the link table (the table representing the m-to-n relationship) order by id of TR |
Record Selectors | yes |
Navigation Buttons | no |
Main form
Add a child form. Link child field id1 with master field id1.
Integrate these notes:
prototype for M-n relationship:
Create a sub-form (wizard, columnar view) on the table representing the m-n
relationship
this is correct:
Create a sub-form (wizard, autoformat-datasheet) on the table representing the
m-n relationship When inserting sub-form, choose "use an existing form"
and for linked fields, choose "define my own"
enforce Referential integrity for the m-to-n relationships: "cascade delete related records" for other relationships, do NOT cascade delete
for BackgroundInformation, no referential integrity is enforced.
What if records in the main table are deleted?
Test this.
Integrity error when inserting: set the default values for columns with lookups to null or to a valid value in the lookup table
date() --> current date
docmd.requery
Handle unsaved data |
---|
|
To add an object on the page, first open VB editor, then go into design mode "menu Run > design mode" and return to the document.
To manage security for macros in Word: menu tools > macro > security. Set security to medium so that macros can be enabled.
Insert a date-time in current cell. Define a macro that uses this procedure.
Sub InsertDateInCurrentCell()
ActiveCell.Value = Now
End Sub
Use "lock-modify-unlock" mode (only one user can change one file at time) --> minimizes the need for merging files.
Check in a copy of all files at the end of the day, but they must compile.
Use labels with version information and comments. Implement keyword expansion in SourceSafe and add the appropriate comments to all SQL scripts.
Label projects with version name --> allows identification of projects and files for particular milestones.
Encrypt in the root folder using EFS. Remove permissions from the Everyone user for these folders, and assign specific permission to SourceSafe users or groups.