Programování pro (Arc)GIS I KMA/AGI Karel Jedlička
[email protected] http://www.kma.zcu.cz/Jedlicka Vznik materiálu byl podpořen z projektu FRVŠ č. 584/2011
Programování pro (Arc)GIS • • • • • •
Výběr z referenční příručky jazyka Visual Basic Objektová orientace (ve Visual Basic a .NET) Component Object Model (COM) ArcObjects .NET Rozšiřování ArcGIS Desktop – Model Builder (APA) – Python (APA) – Add-ins
Visual Basic Reference • Proč právě Visual Basic? • Syntaxe – Proměnné, procedury a jejich rozsah působnosti – datové typy – programové bloky (procedury a funkce) – předávání parametrů – struktury pro tvorbu a kontrolu běhu programu (větvení, cykly, přerušení) – interakce s uživatelem (základní, formuláře)
Visual Basic Reference • Referenční příručka jazyka Visual Basic (pro Visual Studio v. 2010)
Visual Basic Reference • Proměnné – Proměnná je ukazatel na část paměti, kde se nachází její hodnota. – Jméno proměnné nesmí být klíčovým slovem v programovacím jazyce (např.: if .. then, ..), musí začínat na písmeno, nesmí obsahovat tečky (tečková notace)! – Implicitní deklarace proměnné – typ je jí přiřazen při prvním výskytu. • Explicitní – vyžaduje deklaraci, pro práci s ArcObjects (viz dále) silně doporučováno! Option Explicit On Dim [nazevPromenne] As [typPromenne]
Visual Basic Reference • Definice rozsahu proměnných a procedur – The scope of a variable, sometimes referred to as accessibility of a variable, refers to where the variable can be read from and/or written to, and the variable's lifetime, or how long it stays in memory. – The scope of a procedure or method refers to where a procedure can be called from or under what context you are allowed to call a method. – There are many different ways you can declare variables and procedures.
Visual Basic Reference • Definice rozsahu proměnných a procedur Term
Used With…
Visibility
Public
Variables/Properties/Methods/Types
Anywhere in or outside of a project
Private
Variables/Properties/Methods/Types
Only in the block where defined
Protected
Variables/Properties/Methods
Can be used in the class where defined. Can be used within any inherited class.
Friend
Variables/Properties/Methods
Can only be accessed by code in the same project/assembly.
ProtectedFriend
Variables/Properties/Methods
Combination of Protected and Friend
Visual Basic Reference • Proměnné – Správné používání rozsahu působnosti proměnných: • zpřehledňuje kód, • šetří paměť, • zlepšuje stabilitu programu.
Visual Basic Reference • Datové typy – – – – – – – –
Integers decimal and numeric Approximate Numerics datetime and smalldatetime Character Strings Unicode Character Strings Binary Strings Other Data Types • …
Visual Basic Reference • Programové bloky – Procedury [ scope ] Sub name [ (Of typeparamlist) ] [ (parameterlist) ] [ Implements implementslist | Handles eventlist ] [ statements ] [ Exit Sub ] [ statements ] End Sub Sub computeArea(ByVal length As Double, ByVal width As Double) ' Declare local variable. Dim area As Double If length = 0 Or width = 0 Then ' If either argument = 0 then exit Sub immediately. Exit Sub End If ' Calculate area of rectangle. area = length * width ' Print area to Immediate window. ! Debug.WriteLine(area) End Sub
Visual Basic Reference • Programové bloky – Funkce [scope] Function name [ (Of typeparamlist) ] [ (parameterlist) ] [ As returntype ] [ Implements implementslist | Handles eventlist ] [ statements ] [ Exit Function ] [ statements ] End Function
Function myFunction(ByVal j As Integer) As Double myFunction = 3.87 * j End Function
Visual Basic Reference • Předávání parametrů – Odkazem Sub x End Sub
Increment (ByRef x As Integer) = x + 1 Sub Main () Dim a As Integer a = 1 MsgBox a ! Call Increment (a) MsgBox a End Sub
– Hodnotou Sub Increment (ByVal x As Integer) …
Visual Basic Reference • Struktury pro tvorbu a kontrolu běhu programu – Podmínka If If condition [ Then ] [ statements ] [ ElseIf elseifcondition [ Then ] [ elseifstatements ] ] [ Else [ elsestatements ] ] End If Dim number, digits As Integer Hodnotu získejte od uživatele Dim myString As String number = 53 If number < 10 Then digits = 1 ElseIf number < 100 Then digits = 2 Else digits = 3 End If If digits = 1 Then myString = "One" Else myString = "More than one"
Visual Basic Reference •
Struktury pro tvorbu a kontrolu běhu programu – Select Case Select [ Case ] testexpression [ Case expressionlist [ statements ] ] [ Case Else [ elsestatements ] ] End Select Dim number As Integer = 8 Select Case number Case 1 To 5 Debug.WriteLine("Between 1 and 5, inclusive") ' The following is the only Case clause that evaluates to True. Case 6, 7, 8 Debug.WriteLine("Between 6 and 8, inclusive") Case 9 To 10 Debug.WriteLine("Equal to 9 or 10") Case Else Debug.WriteLine("Not between 1 and 10, inclusive") End Select
Visual Basic Reference • Struktury pro tvorbu a kontrolu běhu programu – Smyčky • While Loops – The While...End While construction runs a set of statements as long as the condition specified in the While statement is True, see more in While...End While Statement (Visual Basic).
• Do Loops – The Do...Loop construction allows you to test a condition at either the beginning or the end of a loop structure. You can also specify whether to repeat the loop while the condition remains True or until it becomes True, see more in Do...Loop Statement (Visual Basic).
• For Loops – The For...Next construction performs the loop a set number of times. It uses a loop control variable, also called a counter, to keep track of the repetitions. You specify the starting and ending values for this counter, and you can optionally specify the amount by which it increases from one repetition to the next, see more in For...Next Statement (Visual Basic).
• For Each Loops – The For Each...Next construction runs a set of statements once for each element in a collection. You specify the loop control variable, but you do not have to determine starting or ending values for it, see more in For Each...Next Statement (Visual Basic).
Visual Basic Reference • Struktury pro tvorbu a kontrolu běhu programu – Cyklus While While condition [ statements ] [ Exit While ] [ statements ] End While Dim counter As Integer = 0 While counter < 20 counter += 1 ' Insert code to use current value of counter. End While MsgBox("While loop ran " & CStr(counter) & " times")
!
Visual Basic Reference • Struktury pro tvorbu a kontrolu běhu programu – Cyklus For ... Next For counter [ As datatype ] = start To end [ Step step ] [ statements ] [ Exit For ] [ statements ] Next [ counter ] Dim words, digit As Integer Dim thisString As String = "" For words = 10 To 1 Step -1 For digit = 0 To 9 thisString &= CStr(digit) Next digit thisString &= " " Next words
Visual Basic Reference • Struktury pro tvorbu a kontrolu běhu programu – Cyklus For ... Each For Each element [ As datatype ] In group [ statements ] [ Exit For ] [ statements ] Next [ element ] Dim found As Boolean = False Dim thisCollection As New Collection For Each thisObject As String In thisCollection If thisObject = "Hello" Then found = True Exit For End If Next thisObject
Visual Basic Reference • Interakce s uživatelem – Základní – vstup Public Function InputBox( _ ByVal Prompt As String, _ Optional ByVal Title As String Optional ByVal DefaultResponse Optional ByVal Xpos As Integer Optional ByVal YPos As Integer ) As String
= "", _ As String = "", _ = -1, _ = -1 _
odpovedUzivatele = InputBox("Text k zobrazení", "Dialog pro získání vstupu od uživatele", "Hello World!")
Visual Basic Reference • Interakce s uživatelem – Základní – výstup Public Function MsgBox( _ ByVal Prompt As Object, _ Optional ByVal Buttons As MsgBoxStyle = _ MsgBoxStyle.OKOnly, _ Optional ByVal Title As Object = Nothing _ ) As MsgBoxResult MsgBox(odpovedUzivatele, MsgBoxStyle.Information, "Odpověď uživatele")
Visual Basic Reference • Interakce s uživatelem – Pokročilá • Formuláře – Introduction to Windows Forms
• Vyžaduje událostmi řízené programování! – Strukturované x událostmi řízené programování
Visual Basic Reference • Interakce s uživatelem – Událostmi řízené programování • Základním principem tvorby aplikací s GUI je řízení programu událostmi. – Netýká se však pouze GUI, je to obecnější pojem označující typ asynchronního programování, kdy je: – tok programu řízen událostmi; – události nastávají obvykle určitou uživatelskou akcí – klik či pohyb myši, stisk tlačítka, ...;
– Event-driven programming
Přinuťte Visual Studio mocnit • Cvičení – Konzolový mód • Ukázka tvorby jednoduchého prográmku s voláním podprocedury. • Samostatná práce – přinuťte Visual Studio mocnit
Přinuťte Visual Studio mocnit • Samostatná práce – přinuťte Visual Studio mocnit – Zajistěte nutnost explicitní deklarace proměnných. – Vytvořte proceduru „Hello World“. – Vytvořte kód, který spočte druhou mocninu čísla uloženého v proměnné cislo. – Hodnotu proměnné cislo získejte od uživatele. – Kód, který počítá druhou mocninu volejte z hlavního kódu jako funkci mocnina(). – Zobecněte funkci mocnina() pro n-tou mocninu. Hodnotu n získejte také od uživatele. – Vytvořený kód ať s uživatelem komunikuje přes: • InputBox a MsgBox • Formuláře
Přinuťte Visual Studio mocnit • Samostatná práce – přinuťte Visual Studio mocnit – Řešení • Zajistěte nutnost explicitní deklarace proměnných. Option Explicit On
• Vytvořte kód, který spočte druhou mocninu čísla uloženého v proměnné cislo. Sub Main() Dim cislo As Double cislo = 4 cislo = cislo * cislo MsgBox cislo End Sub
Přinuťte Visual Studio mocnit • Samostatná práce – přinuťte Visual Studio mocnit – Řešení • Hodnotu proměnné cislo získejte od uživatele. cislo = Val(InputBox("Mocnenec:", "Funkce umocneni", "5"))
Přinuťte Visual Studio mocnit • Samostatná práce – přinuťte Visual Studio mocnit – Řešení • Kód, který počítá druhou mocninu volejte z hlavního kódu jako funkci mocnina(). Option Explicit On Private Function mocnina(mocnenec As Double) As Double mocnina = mocnenec * mocnenec End Function Sub Main() Dim cislo As Double Dim vysledek As Double cislo = Val(InputBox("Mocnenec:", "Funkce umocneni", "5")) vysledek = mocnina(cislo) MsgBox vysledek End Sub
Přinuťte Visual Studio mocnit • Samostatná práce – přinuťte Visual Studio mocnit – Řešení • Zobecněte funkci mocnina() pro n-tou mocninu. Hodnotu n získejte také od uživatele. Private Function nta_mocnina(mocnenec As Double, mocnitel As Integer) As Double Dim i As Integer Alternativně: Dim mezivysledek As Double mezivysledek = mocnenec Nt_mocnina = mocnenec^mocnitel For i = 2 To mocnitel mezivysledek = mezivysledek * mocnenec Next i nta_mocnina = mezivysledek End Function Sub Main() Dim cislo As Double Dim dalsi_cislo As Integer Dim vysledek As Double cislo = Val(InputBox("Mocnenec:", "Funkce umocneni", "2")) dalsi_cislo = Val(InputBox("Mocnitel:", "Funkce umocneni", "4")) vysledek = nta_mocnina(cislo, dalsi_cislo) MsgBox vysledek End Sub
Přinuťte Visual Studio mocnit • Formuláře – Vytvořte formulář pro umocňování, formulář bude obsahovat následující prvky (viz obr): • Zadávací pole pro mocněnec i mocnitel s předvyplněnými hodnotami. • Tlačítko pro umocnění. • Prostor pro výpis výsledku operace. • Při každém stisku tlačítka pro umocnění, bude přednastavená hodnota pro mocnitele zvednuta o 1.
Přinuťte Visual Studio mocnit • Formuláře (řešení)
FormMocneni.Text = "Mocneni"
Přinuťte Visual Studio mocnit • Formuláře ' pseudokód Label1.Text = "Mocnenec:" Label2.Text = "Mocnitel:" TextBoxMocnenec.Text = "2" TextBoxMocnenec.TextAlign = Right TextBoxMocnitel. … ButtonMocni.Text = "Mocni" GroupBoxVysledek.Text = "Vysledek" LabelVysledek.Text = " " Private Sub ButtonMocni_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles ButtonMocni.Click LabelVysledek.Text = (Val((TextBoxMocnenec.Text) ^ _ Val(TextBoxMocnitel.Text))) TextBoxMocnitel.Text = Val(TextBoxMocnitel.Text) + 1 End Sub
Zdroje • Všechny použité zdroje jsou k dispozici on-line a jsou dostupné přímo formou odkazů z jednotlivých snímků