1 / 22

SQL .Net Consultation Session 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur

SQL .Net Consultation Session 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location: 1st Széchenyi str. 7666 Pogány, Hungary Tel: +36-309-015-488 E-mail: pauler@t-online.hu. Content of Presentation.

nay
Download Presentation

SQL .Net Consultation Session 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SQL .Net Consultation Session 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location: 1st Széchenyi str. 7666 Pogány, Hungary Tel: +36-309-015-488 E-mail: pauler@t-online.hu

  2. Content of Presentation .Net Visual Basic syntax • Primitive variable types • Compound variable types • List-based containers • Declaring methods of classes: • Functions • Procedures • General code editing rules • Process flow control commands • Selections • Cycles • Error handling • Traditional onion-skin model • Error handlig with exception handlers • Operators • Built-in functions • Innovations in .Net 2.0 Visual Basic References

  3. Visual Basic syntax 1: Primitive variable types Primitive variable types (Pirimitív Változótípusok) can be seen in the table attached: • It is important to note that Date is stored as 8 byte-fixed point fraction number, where 0.000 is 1900.01.00 00:00:00 and +1day = +1.0 (+1 hour = +1/24, etc.), Negative values mean da- tes before the starting date. One date can be subtracted (Kivon) from other date returning their difference in days, and numbers can also be added/subtracted from dates Declaring primitive-typed constants and variables: ConstConstNameAsConstType=Value DimVariableNameAsVariableType • These reserve fixed number of bytes accor- ding to their types in stack (Verem) memory Using primitive typed constants and variables in coding: • At passing values, information allways streams from right to left: Variable=Constant, Variable1=Variable2, but cannot beConstant=Variable • Comparing them at conditions (Feltétel), both variables and constants can be in any side Declaring array (Tömb) variables containing multiple values of same type in indexed format: DimArrayName(StartIndexToEndIndex) AsElementType ‘1 dimensional array DimArray(Start1ToEnd1, Start2 To End2) AsElementType ‘Multi dimensional array • These reserve element number × type bytes amount of memory in stack, even if they are empty! DimDinamArray() AsElementType ‘Dynamic sized array • This reserves only 4bytes when it is empty, but at this stage is unusable. We can reserve its actual sized working memory in the more sizeable heap (Halom) memory with Redim command: RedimDinamArray(1ToActualRows,1 To ActualColumns) • If we do not need it anymore, we can free its reserved memory in heap with command RedimDinamTomb(0) Its content will be lost • Last index range of dynamic array can be increased preserving its content also: Redim PreserveDinamArray(1ToRows,1ToManyMoreColumns)

  4. Visual Basic syntax 2: Compound variable types Using elements of an array in code: ArrayName(Index1,Index2) • Usually, we do not process elements of an array one-by-one. Instead of it, they are processed by For cycles where indices are expressions computed from cycle variables (Usually named I, J, K, L…) • Multi-dimensional arrays are usually processed with more, nested (Beágyazott) For cycles, each representing a dimension index • Using indices out of index range will result „Out of index range” runtime error Declaring record types: • We frequently need a special container called record (Rekord) which contains several primitive typed fields (Mező) (eg. Name, Address, Age) describing one entity (Egyed) (pl. Human) with numerous occourences (Előfordulás) (eg. John Doe, Jane Doe, etc.): StructureRecordType Field1NameAsField1Type Field2NamAsField2Type End Structure • Please note that in earlier versions of Visual Basic Type … End Type statement was used for this pupose, which is no longer valid! Declaring single record variable: DimRecordVariableAsRecordType Using single record-typed variable in code: Recordvariable.FieldName=Something A record can contain arrays, even dynamic ones: StructureArrayedRecordType NameAs String SomeArray(1To10,1To2) As Integer End Structure DimArrayedRecordAsArrayedRecordType ArrayedRecord.SomeArray(RowIndex,ColumnIndex) =Something Any array – even dynamic – can contain records: DimDataBaseTable() AsRecordType RedimDataBaseTable(1ToActualRecordCount) DataBaseTable(RecordIndex).Field1Name=Something RedimDataBaseTable(0)

  5. Visual Basic syntax 3: Compound variable types • Eg. We can emulate database tables in memory with dynamic arrays consist of records – working more fast than database tables (their content can be buffered (Pufferelve) in memory) Further nesting rules: • Record type can contain nested any pre-declared record type • Any array can contain array type nested (but, it is easier to use multi-dymensional array instead of that) Two methods of passing values between compound variables: • Passing By Value (Értékek átadása): stored data of a container will be copied in a totally different place in memory. The original and the copy are totally independent (Független), deleting the original will not affect the copy: • Record variable can pass its values directly to another record variable, it is not necessary to do it field-by-field: RecordVariable2=RecordVariable1 • We can pass between them field-by-field if we want to pass only one part of the fields: Rec2.Field1 =Rec1.Field1 • An array can get all values of an array with the same type and indexing directly: Tomb2=Tomb1 • Passing By Reference (Hivatkozás átadása) the new container (Variable2) will not consume separate place in memory. Its starting memory address will be defined on starting memory address of the old container (variable1) showing its content. The two containers are totally interdependent (Függő): Variable2=Variable1 • Please note that in old versions of Visual Basic, passing by reference required starting it with Set keyword. This is no longer valid here! • Types of the two variables are not required to be the same, but recommended, otherwise Variable2 will show undezipherable (Értelmezhetetlen) data • Detaching a variable from the memory address it shows (it will not consume memory and will be inoperable): Variable2=Nothing • Creating a new object instance of a pre-declared class and defining an object variable with a given name on that in one step: Dim MyNewObjectAs New GeneralClassOfMyObject ‘Simpler format Dim MyNewObjectAs ActualClass = New GeneralClassOfMyObject Most of the cases, general and actual classes are the same, but .Net Visual Basic allows actual class being a specialized subversion of the general class

  6. Visual Basic syntax 4: List-based containers • Array containers have a serious disadvantage: intermediary (Közbülső) elements cannot be deleted from them, only final n elements of the last dimension/index of dynamic arrays with Redim Preserve described above • To overcome this difficulty, we can use list-based container objects (Listák): List and Collection are 1-dimensional indexed container objects, where the following rules apply: • List contains removable items of a single pre-declared type, but slower than arrays: DimMyListAs NewList (Of String)() • A Collection is slower than List, but can contain several types of objects as items: DimMyListAs NewCollection • New list/collection item can be added to the list with the following method: MyList.Add(„ItemName”)‘New items automatically receive index increasing by 1 • It is possible to remove item from list/collection with the following method: MyList.Remove(„ItemName”)‘Indices of items after removed item decrease by 1 • Any item in a list/collection can be accessed directly by its index: MyList(Index) =Something • As indices of items may change rapidly because of deletions, items should be preferably be referenced by their .Name property, which remains unchanged: MyList(„ItemName”) =Something • For iterating through all elements of a list/collection, we should use For Each .. Next: For Each Item As ItemType In MyList Item = Something Next • There are more difficult list-based container objects also: Dictionary/SortedDictionary are adding a string/integer .Key property to items before their .Value property. This way .Value can store repeating values, while .Key or .Name property of list cannot store that: DimMyDictAs New[Sorted]Dictionary(Of String[Integer], String) • Items can be added/removed by: MyDict.Add/Remove(„KeyValue”, „ItemName”) • Both keys and values of items can be iterated by the following way: For Each Item As KeyType/ItemType In MyDict.Key/.Value Item = Something Next • If possible values of a variable form list of named integer codes (eg. 1:Male, 2:Female), it should be represented by Enum type: EnumGender Male=1 Female=2 End Enum Dim MyGender As Gender MyGender = Male

  7. Content of Presentation .Net Visual Basic syntax • Primitive variable types • Compound variable types • List-based containers • Declaring methods of classes: • Functions • Procedures • General code editing rules • Process flow control commands • Selections • Cycles • Error handling • Traditional onion-skin model • Error handlig with exception handlers • Operators • Built-in functions • Innovations in .Net 2.0 Visual Basic References

  8. Visual Basic syntax 5: Declaring methods of classes: functions Declaring user defined functions (Függvények): • At the header (Fejléc) of the function: • Visibility (Láthatóság) options are before function name, controlling who can use it: • Public: function can be called in any other class unlimited (not recommended!!!) • /Private: function can be called only within its class (cannot reuse elsewhere!!!) • /Protected: function can be called only by descendant classes of declaring class • /Friend: function can be called by any class within the same Assembly (Szerelvény): set of class- and resurce files grouped in one installation package • /Protected Friend: can be seen in same assembly by descendants • Visibility can be regulated the same way at classes and variables also • Visibility setting of a higher-level code component overrules the lower one • Memory usage (Memóriahasználat) options are also before function name: • Static: local variables of the function remain in stack memory even after its end • /Shared:local variables are stored in a shared work memory instead of stack, can be seen by any class, and remain there even if the declaring class destructed! • After function name, parameter/argument list (Paraméter lista) follows in brackets, giving parameter name, then its type after As keyword. Before name, there is value pass switch: • ByVal: passsing value to parameter, being independent copy of memory content • ByRef: setting starting memory address of parameter to the original data • Then type of return value (Visszatérő érték) of the function is defined [Visibility][Memory]FunctionFunctName(ByRefParamByRefAsParType,_ ByValParamByvalAsParType) AsReturnValType DimLocalVariableAsLocalVarType‘Local variables of the function ‘Function computes here… FunctName= AnyExpression‘Don’t forget to compute return value! [Exit Function]‘With this, we can jump out from function even befeore its end End Function‘FunctName  it is recommended to write function name here Using user defined functions from code: • Within same class: Variable1=FunctName(ActParam1,ActParam2) • From another class (if function is visible there): Variable1=NameSpace.ClassName.FunctName(ActParam1,ActParam2) • If the function has multiple parameters, and it is not necessary to give them all, we can reference to them by their name: Variable1=FunctName(Param1Name:=Value,Param26Name:=Value)

  9. PRACTICE 2-1: Examples of variables with different visibility Shortly you will be called in random sequence to present this in 3 minute speech: (1pts) • Find examples of variables with the following visibility in your object programmed in Home Assignment 1-1 (see Lesson1): • Public • Shared • Protected • Please give a reasoning why would you assign a given variable into a given visibility! Example solution (incomplete): Class Toaster ‘Data field declarations--------------------------------- Public Enum tPowerPlug PowerPlugDisconnected = 0 PowerPlugConnected = 1 End Enum ‘Enum declaration can be fully reusable by anybody Shared PowerPlug As tPowerPlug ’Can be seen by anybody else using the power plug Public Enum tPowerSwitch PowerSwitchOff = 0 PowerSwitchOn = 1 End Enum ‘Enum declaration can be fully reusable by anybody Protected PowerSwitch As tPowerSwitch ’Can be controlled by descendants Protected ProgTemp As Single’Can be controlled by descendants Private ActualTemp As Single’Actual temp is measured internally End Class

  10. Visual Basic syntax 6: Declaring procedures and general code editing rules Syntax of user defined procedures: • Declaration is pretty much the same as functions, exept that we have to use keyword Sub instead of Function and there is no return value • Calling procedures (please note that no brackets are required): • Within the same class: ProcNameActParam1,ActParam2 • From other class (if visibility applies): NameSpace.ClassName.ProcName _ ActParam1,ActParam2 Selecting unique identifier names of classes, variables, procedures, functions: • They cannot contain space and special characters, and cannot start with number • Their recommended length is 8±3 characters for easier coding • They should be meaningful English abbreviations (Rövidítés) (NOT V1, V2, V3, etc.!!!), names consist of more members should be delimited by capitals (Nagybetű) (eg. DistanceMatrix), but there is no any difference between uppercase (Nagybetű) and lowercase letters in coding. • Although Visual Basic editor of .Net offers a utility to rename identifier names globally in the code (see Lesson1), names should be carefully and systematically selected at first, setting up and keeping our own naming conventions! • Identifier names are always represented in the code editor in Black color • Identifier names cannot be reserved words (eg. Sub, Exit, etc.), which are represented in the code editor in Blue color • If a local variable name in a function has the same name as a global/shared variable, its name will „cover” the global variable, which cannot be used there. To avoid this, it is recommended to start local variable names with prefix „lc” (eg. lcPartialSum) except cycle variables, which can be allways I, J, K etc. • It is a frequent problem that we try to give the same name to a record variable as its record type, which will cuse syntax error. To avoid this, it is recommended to use „t” prefix before the record type name, to keep names similar but different: DimFlightDataAstFlightData Rules of tabulation: • Visual Basic code should be written tabulated to ensure easy overview: only one command or statement should be written in one row, and nested parts should be indented (Beljebb húzva) with one tabulator position as the main part • Do NOT use Space instead of Tab for tabulation! • If we want to tabulate multiple rows inward/outward in the same time, we should select first them with Shift+Cursor and press Tab for inward /Shift+Tab for outward tabulation

  11. Visual Basic syntax 7: General code editing rules Line breaking: • Visual Basic editor can handle max 1024 characters in a row. If we have a longer expression or we do not want to see such a long rows we cannot overview on screen, we can break up lines with „ _” (Space+Underscore) line breaker character combination and continue in the next line. • However identifier names, keywords, and string constants cannot be broken up, break should be between them • To break up very long string constant into lines, we can use array function: String1=Array(„This is the fu”, _ „cking long stri”, _ „ng constant”) • String constants are represented in code editor in Brown color Commenting: • Whatever taxing work it is, all classes, functions, procedures, statements, commands, and variables in the code should be commented to create self-contained documentation (Öndokumentáló) which is essential for reusability of the code. Work invested initially in commenting will return many times later! • Comments can be written after apostrof (‘) signs at the end of the lines, they are marked in code editor with Dark Green color Visual Basic Foolishness: comments cannot be written in the middle of the line, so is it not possible to comment parameters immediately in a parameter list of a function: ‘Computing Euclidean distance of 2 coordinate points Protected FunctionEuclDist(ByValX1As Single, _ ‘Startpoint X ByValY1As Single, _ ‘Startpoint Y ByValX2As Single, _ ‘Endpoint X ByValY2As Single)As Single‘Endpoint Y This will result in a syntax error because of mid-line commenting!

  12. Content of Presentation .Net Visual Basic syntax • Primitive variable types • Compound variable types • List-based containers • Declaring methods of classes: • Functions • Procedures • General code editing rules • Process flow control commands • Selections • Cycles • Error handling • Traditional onion-skin model • Error handlig with exception handlers • Operators • Built-in functions • Innovations in .Net 2.0 Visual Basic References

  13. Visual Basic syntax 8: Process flow control commands Selections (shown with recommended commenting): they handle branches of an algorithm • Single[Dual] branching (Elágaztatás): IfConditionalExpressionThen DoThisIfTrue [Else‘If not ConditionalExpression DoThisIfFalse] End If‘ConditionalExpression  should be written here to avoid confusing End Ifs! • Multiplex (Többszörös) branching: Select CaseConditionalExpression CaseValue1:‘If ConditionalExpression = Value1 DoThisInCaseOfValue1 CaseValue2 To Value3:‘If ConditionalExpression is in Value2..Value3 DoThisInCaseOfBetweenValue2AndValue3 CaseElse‘If ConditionalExpression is other DoThisInAnyOtherCase End Case‘ConditionalExpression  should be written here to avoid confusion Cycles (shown with recommended commenting): iterated execution of commands contained by cycle core (Ciklusmag): • Fix Iterations (Rögzített pörgészámú), pretesting (Elöltesztelő) before running cycle core: ForCycleVar=StartValToEndValue[StepStepSize]‘StepSize can be negative in downward iteration, but in this case StartVal>EndVal should hold Something=CycleVar‘Cycle variable can take part in computations, indices [Exit For]‘With this, it jumps out from the cycle before reaching EndVal Next‘CycleVar No cycle variable after Next like in old VB versions, but comment it! • Iterating on actual number of elements of an array, collection or list: [DimIAs Long]‘No cycle counter here, we have to create manually, if we need it [I=0]‘Initiate cycle counter, if we need it For EachItemAs ItemType InArrayOrCollectionOrList [I = I + 1]‘Increase cycle counter, if we need it Something=Item‘We can work with the actual item in the cycle core [Exit For]‘With this, it jumps out from the cycle before reaching last item Next‘Item No item variable after Next like in old VB versions, but comment it!

  14. Visual Basic syntax 9: Process flow control commands • Variable iteration (Nem rögzített pörgésszámú) cycles: • Pretesting (Elöltesztelő), variable iteration (Nem rögzített pörgésszámú) cycles: • Iterate on true condition (Igaz feltételre iteráló): [DimIAs Long]‘No cycle counter here, we have to create manually [I=0]‘Initiate cycle counter, if we need it Do WhileConditionTrue‘Usually depends on counter,eg. I<=Endval [I = I + 1]‘Increase cycle counter, if we need it CycleCore [Exit Do]‘With this, it jumps out from the cycle regardless the condition Loop ‘To ConditionTrue Comment here to avoid confusing several Loops • Iterate on false condition (Hamis feltételre iteráló): [DimIAs Long]‘No cycle counter here, we have to create manually [I=0]‘Initiate cycle counter, if we need it Do UntilConditionFalse‘Usually depends on counter,eg. I>Endval [I = I + 1]‘Increase cycle counter, if we need it CycleCore [Exit Do]‘With this, it jumps out from the cycle regardless the condition Loop ‘To ConditionFalse Comment here to avoid confusing several Loops • Post testing (Hátultesztelő), variable iteration (Nem rögzített pörgésszámú) cycles: • Iterate on true condition (Igaz feltételre iteráló): [DimIAs Long]‘No cycle counter here, we have to create manually [I=0]‘Initiate cycle counter, if we need it Do ‘Feedback from ConditionTrue Comment here to avoid confusing Dos [I = I + 1]‘Increase cycle counter, if we need it CycleCore ‘It will run once for sure, because it is before the test! [Exit Do]‘With this, it jumps out from the cycle regardless the condition Loop WhileConditionTrue‘Usually depends on counter,eg. I<=Endval • Iterate on false condition (Hamis feltételre iteráló): [DimIAs Long]‘No cycle counter here, we have to create manually [I=0]‘Initiate cycle counter, if we need it Do ‘Feedback from ConditionFalse Comment here to avoid confusing Dos [I = I + 1]‘Increase cycle counter, if we need it CycleCore ‘It will run once for sure, because it is before the test! Loop UntilConditionFalse‘Usually depends on counter,eg. I>Endval

  15. PRACTICE 2-2: Translation from English into .Net Visual Basic (-------------------------PRACTICE 2-1 Should be performed here!!!-------------------------) Shortly you will be called in random sequence to translate a short story written in plain English into .Net Visual Basic code, giving a reasoning why you selected the specific types of flow control commands and variables. Present this in a 3 minute speech: (1pts) Short stories to translate: Student 1: While Mary cooks the potatoe, George parallely should put wood on fire but only if water is not boiling yet Student 2: Mary and George both adding up weight of two separate group of people paralelly in their own notebook. Whoever first reaches 2000 pounds of total weight should stop measuring people and will be the winner Student 3: Cranckaxle should be rotated continuosly by one degree until the spark plug number 1 ignites, but it should be started only after battery voltage reached 11.5V in continuos charging Student 4: At overtake, you should continuosly check traffic in the opposite lane and traffic at your back. If opposite vehicle is just left and there is at least 80 yards of gap from the next opposite vehicle, and back vehicle did not start to overtake also, you can start overtaking Student 5: If your wallet is stolen, you cannot get driving license until you do not have personal ID card. However, without driving license you cannot make official drivers life insurance. Without drivers life insurance, you cannot drive heavy wehicles. Times ar uncertain when you can get these papaers you should continously watch Student 6: Squares in a chess table should be colored alternated white and black even in rows and columns Student 7: Mary and George are dating. If George moves his hand towards Mary on the table more than 1 inches from last observed situation, Mary will move her hand also the same distance as George moved. However if George moves his hand more than 2 inches in one step, Mary gets angry and leaves. It goes until their hands are touching Student 8: We are mixing set of playcards. If we find a red one, we will place it on the bottom of card stack. It goes until all red cards are at the bottom of the stack Student 9: A mouse is moving in a labyrinth. At every corner it turns the leftmost corridor it did not checked before. If there is no one, mose turns back and checks the last crossing. It goes until he finds the cheese, but it is not sure there is a cheese Student 10: „I cannot eat Little Red Riding Hood until I did not eat grandmother. However I should eat her before the hunter arrives” – thought the wolf

  16. Visual Basic syntax 10: Error handling methods A program code should be written foolproof (Hülyebiztos): it has two alternative methods: EXAMPLE 2-1: to introduce them, lets assume that we have to perform 3 activities (Act1, Act2, Act3) in a function, each of them being the precondition of the next one. All 3 activities have binary status flag variables signaling that they are completed (OK1,..OK3). All activites reserve memory (Mem1..Mem3) A, Traditional error handling: the onion-skin model (Hagymahéj-modell): we perform the following tasks of each activity in nested onion-skins: 1.Checking precondition, 2.Reserve memory, 3.Perform computation, 4.Free memory, 5.Error handling: FunctionTest(ByRefOK1,OK2,OK3As Boolean) As String DimMem1(), Mem2(), Mem3()As Long Redim Mem1(1000) Act1 OK1 If OK1 Then Redim Mem2(1000) Act2 OK2 If OK2 Then Redim Mem3(1000) Act3 OK3 If OK3 Then Test = „Act1, Act2, Act3 are fine and working!” Else Test = „Act1, Act2 completed, Act3 failed!” End If Redim Mem3(0) Else Test = „Act1 completed, Act2 failed, Act3 cancelled!” End If Redim Mem2(0) Else Test = „Act1 failed, Act2 and Act3 cancelled!” End If Redim Mem1(0) End Function • Evaluation: this is safe and precise solution but takes long time to write

  17. Visual Basic syntax 11: Error handling methods B, Microsoft bullshit-styled, exception handler-based (Kifogás kezelő) error handling: with Try command, we open an error-tolerant shell, where we do not check any preconditions in advance, just reserve memory and launch the 3 activities sequentially. If any runtime error happens, we analyze it afterwards in the Catch part. However, it is not allways possible to really detect what went wrong in a complex process, therefore we usually can give only a silly, general error message. Moreover it is hard to detect which memory was reserved, therefore we do not free anything but relay on central garbage cleaning of .Net CLR (see Session1) Thats how „modern” applications tend to freeze and „blue death” comes: FunctionTest() As String Try‘Open error-tolerant shell. In case of runtime error jump to Catch part RedimMem1(1000) Act1 RedimMem2(1000) Act2 RedimMem3(1000) Act3 Test=„Everything working!” RedimMem3(0) RedimMem2(0) RedimMem1(0) Catch‘Error handling part Test=Error(Err)‘Query type of the error IfTest = „Fatal error” Then‘If error is too serious to handle… MsgBox „Suck you, I’m dying!”‘Silly error message Throw‘Function stops without freeing reserved memory Else ‘If error is not serious handle here End If ‘End of error handling Finally‘If error is fixed, continue with this part End Try ‘End of error-tolerant shell End Function ‘Test • Evaluation: this is really simple and fast to write, even by „indian programmers”, but try to use any Microsoft product under demandig conditions and you will really see yourself!

  18. Content of Presentation .Net Visual Basic syntax • Primitive variable types • Compound variable types • List-based containers • Declaring methods of classes: • Functions • Procedures • General code editing rules • Process flow control commands • Selections • Cycles • Error handling • Traditional onion-skin model • Error handlig with exception handlers • Operators • Built-in functions • Innovations in .Net 2.0 Visual Basic References

  19. Visual Basic syntax 12: Operators and built-in functions Arithmetic operators: • X+Y, X-Y, X*Y, X/Y, X\Y:division with modulus (Maradékos osztás), X mod Y:modulus, =, <, >, <>, <=, >= String operators: • A+B: concatenation (Összefűzés) • True/False = CompareString Like MaskString: partial string matching with a mask string consist of wildcards (Joker karakter): ?: 1 character, *: many characters, #: 1 number, [acef]: string contains any of the a,c,e,f characters anywhere, [!acef]: string cannot contain a,c,e,f characters anywhere Logic operators: • U And V, U Or V, U Xor V, Not U Type conversion functions: Visual Basic auto converts different primitive types used together, whenever it is possible: BooleanLong, IntegerLong, SingleDouble, Integer Single, LongDouble, CurrencyDouble or • String can be translated into number(eg. „-123”, „-123.3”, „-0.123e-8”)  Long, Double • Stringcan be translated into date-time (eg. „1971.05.11 22:30:14”)  Date  Double (because dates are stored as fraction numbers). However, date constats written directly in code should be put between Sharp characters: Date1= #1/11/1999 12:30:00 PM# • If it cannot convert different types, it will give compilation error „Type Mismatch” To control the conversions manually, we can use conversion functions: • Integer = CInt(AnyThingItCanBe), Double = CDouble(AnyThingItCanBe) • String = CStr(AnyThing), formatted: String = CStr(Format(Expression,FormatCode)) • A FormatCode can be:Fixed, Standard, Percent, Scientific, LongDate, LongTime, etc. As a new innovation in .Net Visual Basic, primitive types are also defined as objects, so they can have methods: .ToString, .ToInt, etc. methods give an alternative way of manually controlled type conversion Math functions: • The usual: Abs(), Atn(), Cos(), Exp(), Log(), Rnd(), Sgn(), Sin(), Sqr(), Tan() • Fix():makes integer from fraction, at negative numbers it results the lower integer (eg. -4 from -3.6) Int(): the same as the last except that at negative numbers it gives the higher integer (eg. -3 from -3.6)

  20. Visual Basic syntax 13: Built-in functions, Innovations in .Net 2.0 Visual basic String functions: • Byte = Asc(String): 1 characters ASCII code • Char = Chr(Byte): ASCII character from byte • Long = Len(String): length of string • True/False = Instr(StartChar,WhereToSearchString,WhatToSearchString,0/1): searching WhatToSearchString in WhereToSearchString, 0:exact match, 1:uppercase/lowercase are the same • String = Mid(String,StartChar,Length): getting mid-section of a string • String = Left/Right(String,CharacterCount): left/right end of a string • String = L/RTrim(String): cutting off Space characters from left/right end of string • String = L/UCase(String): lower/uppercase conversion of string Date-time functions: • Date = Now(): actual date and time of system • Wait Date: running should wait until a given point of time • Wait Now()+1/24/3600: running should wait 1 second • Integer = Year/Month/Day/Hour/Minute/Second(Date): parts of date as number • Integer = WeekDay(Date): number of day in a week Built-in controls: • MsgBox „MessageString”: write message in a textbox with OK button • Variable = InputBox(„Question”,”Title”, Type:=1): modal (Modális) input box for single variable with title, question, OK, Close: user cannot access other windows until it is open Generic types (Paraméterezhető típusok): Type of classes / parameters of methods / collections can be given dynamically. It enables us to use the same code on different classes without defining it several times • Generic class: class type can be parameterized runtime Private/Public ClassClassName (OfClassType) End Class • Generic methods of a class: type of method parameters can be parameterized, chosen runtime dynamically. Eg. we can range-check (Értékhatár-ellenőrzés) different type of numeric variables with the same method: PrivateSubSubName(OfParamType)(ByValParamNameAsParamType) End Sub SubName (of Integer) (VarInteger) ’Starting with Integer type SubName (of Double) (VarDouble) ’Starting with double type

  21. Visual Basic syntax 14: Innovations in .Net 2.0 Visual basic • Generic typed collections/lists: Instead of assembling collection from general Objecttype containers, it creates collection/list from primitive types, but the type can be parameterized: DimMyCollectionAs NewCollection (Of Date) It works more fast than object collection but slower than strongly typed (Fix típusmegadású) arrays. Comparison of ratio of items/elements processed in a given amount of time: • Object collection: 5% - very flexible container, but slow • Generic typed list/collection: 50% • Strongly typed array: 100% - the least flexible container, but very fast Myobject: It contains the most important classes from the many 1000 classes of .Net frame-work grouped into easy to overview categories:Application, Computer, Forms, User, Web Overriding operators: It defines extra meaning to conventional math-log operators (=, <>, <, >, <=, >=, Not, IsNot, Is) used on classes as operands. Eg. BossEmployee > SubordinateEmployee should have a meaning comparing their .RankNumber property: Operator>(ByValLeftOperandAsOperandClass, _ ByValRightOperandAsOperandClass)As Boolean IfLeftOperand.RankNumber>RightOperand.RankNumberThen ReturnTrue Else ReturnFalse End If End Operator‘> New keywords in VB syntax: • Global.: points to the root namespace from any namespace environment set up by Imports statement of class declaration • Using (ObjectName) … End Using: foced dispose of the object at the end of usage block, if developer does not trust on CLR’s automatic dispose and cleanup (mistrust is highly recommended!!!). It makes the same effect as calling the .Dispose method of the object, just we don’t have to do it manually at any little branch of our algorithm! • Continue: can be placed in core of any cycle. It will jump out from current iteration and goes to the beginning of next iteration of the cycle

  22. References (------------------------Practice 2-2 should be performed here----------------------) .Net Visual Basic reference: http://msdn.microsoft.com/en-us/library/sh9ywfdk.aspx

More Related