Wednesday, September 25, 2019

[Tutorial] VB Console Projects On ASP.NET Core Platform

 .


Create VB Console Project

We will start at the root of ALL OUR PROJECTS

c:\ZT\>

CLI: dotnet new console -lang VB -o vbtest1

CLI: cd vbtest1

CLI: dotnet build

CLI: dotnet run

See Appendix 1 for Screenshot of VB Console Project Based On DotNet Framework

Online code beautifier tool:

https://codebeautify.org/csharpviewer 

https://www.xhcode.com/vbscriptformat/ 

1) Print Hello World Program (VB)

Pseudo Code:

1. BEGIN

2. PRINT "Hello World"

3. END

Imports System

Module Program

Sub Main(args As String())

    Console.WriteLine("Hello World!")

End Sub

End Module

2) Sum Numbers Program (VB)

Pseudo Code:

1. BEGIN

2. PRINT 1 + 2

3. END

CLUE:

Console.WriteLine(1+2);

Imports System

Module Program

Sub Main(args As String())

    Console.WriteLine(1 + 2)

    Console.ReadKey()

End Sub

End Module

3) Sum Variables Program (VB)

Pseudo Code:

1. BEGIN

2. INPUT var1var2

3. PRINT var1+var2

4. END

CLUE:

Imports System

Module Program

Sub Main(args As String())

   

    Dim var1 As Integer = Console.ReadLine()

   

    Dim var2 As Integer = Console.ReadLine()

   

    Console.WriteLine(var1 + var2)

   

    Console.ReadKey()

   

End Sub

End Module

4) Multiply Variables Program (VB)

Pseudo Code:

1. BEGIN

2. INPUT var1var2

3. PRINT var1 * var2

4. END

Imports System

Module Program

Sub Main(args As String())

   

    Dim var1 As Integer = Console.ReadLine()

   

    Dim var2 As Integer = Console.ReadLine()

   

    Console.WriteLine(var1 * var2)

   

    Console.ReadKey()

   

End Sub

End Module

5) Divide Variables Program (VB)

Pseudo Code:

1. BEGIN

2. INPUT var1var2

3. IF var2=0

4. THEN PRINT "Error. Division by zero."

5. ELSE PRINT var1/var2

6. END

CLUE:

Try input for 2 rounds.

For round1 => var1=4, var2=2

For round2=> var1=2, var2=0

Imports System

Module Program

Sub Main(args As String())

   

    Dim var1 As Double = Console.ReadLine()

   

    Dim var2 As Double = Console.ReadLine()

   

    If var2 = 0 Then

       

        Console.WriteLine("Error. Division by zero")

    Else

       

        Console.WriteLine(var1 / var2)

       

    End If

   

    Console.ReadKey()

   

End Sub

End Module

6) Count Numbers Program (VB)

Pseudo Code:

1. BEGIN

2. PRINT "Start counting."

3. FOR i LOOP := 1 to 3 STEP 1

4.     PRINT i

5. END LOOP

6. PRINT "Done."

7. END

CLUE:

Note:loop index number starts with 0.

Imports System

Module Program

Sub Main(args As String())

   

    Console.WriteLine("Start Counting.")

   

    For i As Integer = 0 To 2 Step 1

       

        Console.WriteLine(i)

    Next

   

    Console.WriteLine("Start Done.")

   

End Sub

End Module

7) Display Array Values Program (VB)

1. BEGIN

2. INITIALISE ARRAY arr[5] TO CONTAIN VALUES a,b,c,d,e

3. PRINT "Displaying array values."

4. FOR i := 1 to 5

5.    PRINT arr[i]

6. END FOR LOOP

7. PRINT "Done."

8. END

CLUE:

Plan your data type for array carefully

char[] arr = new char[] {'a', 'b', 'c', 'd', 'e'};

string[] arr = new string[] {"a""b""c""d""e"};

string[] arr =  {"a""b""c""d""e"};

Imports System

Module Program

Sub Main(args As String())

   

    Dim arr() As String = {"a", "b", "c", "d", "e"}

   

    Console.WriteLine("Displaying array values.")

   

    For i As Integer = 0 To 4 Step 1

       

        Console.WriteLine(arr(i))

       

    Next

   

    Console.WriteLine("Start Done.")

   

End Sub

End Module

Imports System

Module Program

Sub Main(args As String())

   

    Dim arr() As Char = {"a", "b", "c", "d", "e"}

   

    Console.WriteLine("Displaying array values.")

   

    For i As Integer = 0 To 4 Step 1

       

        Console.WriteLine(arr(i))

       

    Next

   

    Console.WriteLine("Start Done.")

   

End Sub

End Module

8) Edit Array Values Program (VB)

Pseudo Code:

1. BEGIN

2. INITIALISE ARRAY arr[i] WITH VALUES 1,2,3,4,5

3. FOR := 1 to 5

4.   PRINT arr[i]

5. END FOR LOOP

6. INPUT indexnumber

7. INPUT arrayvalue

8. arr[indexnumber] = arrayvalue

9. FOR i := 1 to 5

10.   PRINT arr[i]

11. END FOR LOOP

12. END

CLUE:

Try input 1 and f

What is the output?

a

b

c

d

e

Input indexNumber = 1

Input arrayValue = f

Let arr[1]=f

a

f

c

d

e

Imports System

Module Program

Sub Main(args As String())

   

    Dim arr() As Char = {"a", "b", "c", "d", "e"}

   

    Console.WriteLine("Displaying array values.")

    For i As Integer = 0 To 4 Step 1

        Console.WriteLine(arr(i))

    Next

    Console.WriteLine("Start Done.")    

   

    Console.WriteLine("Enter index number and new value:")

    Dim indexNumber As Integer = Console.ReadLine()

    Dim arrayValue As String = Console.ReadLine()

    arr(indexNumber) = arrayValue

   

    Console.WriteLine("Displaying array values.")

    For i As Integer = 0 To 4 Step 1

        Console.WriteLine(arr(i))

    Next

    Console.WriteLine("Start Done.")

       

End Sub

End Module

SEBELUM INPUT

arr[0]=a

arr[1]=b

arr[2]=c

arr[3]=d

arr[4]=e

INPUT

indexNumber? Cth 1

arrayValue? Cth f

KEMASKINI NILAI DALAM ARRAY

arr[1]=f

SELEPAS INPUT

arr[0]=a

arr[1]=f

arr[2]=c

arr[3]=d

arr[4]=e

9) Modular Program (VB)

Pseudo Code:

1. BEGIN displaydata

2.   FOR all item in array PRINT item values

3. END displaydata

1. BEGIN updatedata

2.   INPUT indexnumber, arrayvalue

3.   arr[indexnumber]=arrayvalue

4.   CALL displaydata

4. END updatedata

1. BEGIN main

2.   CALL displaydata

3.   CALL updatedata

4. END main

CLUE:

        Main

        {

                Dim arr() as Char={"a","b","c","d","e"};

                displayData(arr);

                updateData(arr);

                displayData(arr);

        }

        Sub displayData(ByVal arr() as Char)

        …

        End Sub

        Sub updateData(ByRef arr() as Char){

        …

        End Sub

Imports System

Module Program

Sub Main(args As String())

   

    Dim arr() As Char = {"a", "b", "c", "d", "e"}

    displayData(arr)

    updateData(arr)

    displayData(arr)

   

End Sub

Sub displayData(ByVal arr() As Char)

    Console.WriteLine("Displaying array values.")

    For i As Integer = 0 To 4 Step 1

        Console.WriteLine(arr(i))

    Next

    Console.WriteLine("Start Done.")

End Sub

Sub updateData (ByRef arr() As Char)

    Console.WriteLine("Enter index number and new value:")

    Dim indexNumber As Integer = Console.ReadLine()

    Dim arrayValue As Char = Console.ReadLine()

    arr(indexNumber) = arrayValue

End Sub

End Module

cd /

cd ZT

cd cstest1

10) Program Parameter (VB)

Imports System

Module Program

Sub Main(args As String())

   

    Console.WriteLine(args(0))

   

End Sub

End Module

Type console command:

dotnet run hello

Output:

TRY CATCH BLOCK (VB)

      Try

            ‘Try to do something here

      Catch e As Exception

         Console.WriteLine(e.Message)

      End Try

11) Working With Text File (VB)

Get back to root of projects

C:\ZT>

Type command: dotnet new console -lang vb -o vbtrycatch

Type command: cd vbtrycatch

In the VC project explorer panel, find the vbtrycatch folder.

You will see Program.vb 

Create a text file data.txt in the project root folder (i.e. vbtrycatch folder).

Type following text into the file (i.e. data.txt):

this is a test

Edit Program.vb by replacing the existing codes with the following codes.

Imports System

Imports System.IO

Module Program

Sub Main()

    Dim fileName As String = "data.txt"

    Try

    Using writer As StreamReader = New StreamReader(fileName)

    Dim line As String

    line = sr.ReadLine()

    While ( line <> Nothing)

        Console.WriteLine(line)

        line = sr.ReadLine()

    End While

End Using

Catch e As Exception

    Console.WriteLine(e.Message)

End Try

Console.ReadKey()

End Sub

End Module

C:\ZT\vbtrycatch>dotnet run

This is a test

Try changing the content of data.txt (e.g. this is another test).

Run again your program.

Check that new data is displayed.

C:\ZT\vbycatch>dotnet run

This is a another test

Sending And Receiving Data Through Internet HyperText Transfer Protocol

Suppose that we want to send data to a target server at the URL https://httpbin.org/post 

For illustration purposes, we will use the REST demo application at https://resttesttest.com as a form tool for data submission to the target server.

The target server URL is specifically allocated for the POST method.

Sending a FORM method will result with HTTP 200 success code.

On the other hand, sending a GET method will result in an HTTP 400 error code.

In the next part, we are going to write a DotNet Console application to work similar to the RestTestTest web site.

12) Working With Web Request (VB)

Imports System

Imports System.text

Imports System.Web

Imports System.Net

Imports System.IO

Module Program

Sub Main()

    Try

    Dim postdata As String = "comments=good&custemail=harry@porter.com&custname=harry+porter&custtel=0123456789&delivery=jnt"

    WebrequestWithPost("https://httpbin.org/post",Encoding.UTF8,postdata,"application/x-www-form-urlencoded")

    Catch e As Exception

    Console.WriteLine(e.Message)

End Try

Console.ReadKey()

End Sub

Function WebrequestWithPost(ByVal url As String, ByVal dataEncoding As Encoding, ByVal dataToPost As String, ByVal contentType As String) As String

Dim postDataAsByteArray As Byte() = dataEncoding.GetBytes(dataToPost)

Dim returnValue As String = String.Empty

Try

Dim webRequest As HttpWebRequest = WebRequest.CreateHttp(url)  'change to: dim webRequest as var = DirectCast(WebRequest.Create(url), HttpWebRequest) if you are your .NET Version is lower than 4.5

If (Not (webRequest) Is Nothing) Then

    webRequest.AllowAutoRedirect = False

    webRequest.Method = "POST"

    webRequest.ContentType = contentType

    webRequest.ContentLength = postDataAsByteArray.Length

    Dim requestDataStream As Stream = webRequest.GetRequestStream

    requestDataStream.Write(postDataAsByteArray, 0, postDataAsByteArray.Length)

    requestDataStream.Close

    Dim response As Webresponse = webRequest.GetResponse

    Dim responseDataStream As Stream = response.GetResponseStream

    If (Not (responseDataStream) Is Nothing) Then

        Dim responseDataStreamReader As StreamReader = New StreamReader(responseDataStream)

        returnValue = responseDataStreamReader.ReadToEnd

        Console.WriteLine(returnValue)

        responseDataStreamReader.Close

        responseDataStream.Close

    End If

    response.Close

    requestDataStream.Close

End If

Catch ex As WebException

If (ex.Status = WebExceptionStatus.ProtocolError) Then

    Dim response As HttpWebResponse = CType(ex.Response,HttpWebResponse)

    'handle this your own way.

    Console.WriteLine("Webexception! Statuscode: {0}, Description: {1}", CType(response.StatusCode,Integer), response.StatusDescription)

End If

Catch ex As Exception

'handle this your own way, something serious happened here.

Console.WriteLine(ex.Message)

End Try

Return returnValue

End Function

End Module

https://codesnippets.fesslersoft.de/send-data-using-a-webrequest/ 

13) SQL Server Connection (VB)

CLI: dotnet new console -lang c# -o vbdbcon1

CLI: dotnet add package Microsoft.Data.SqlClient --version 5.0.0

Imports System

Imports Microsoft.Data.SqlClient

Module Program

Sub Main(args As String())

    Try

   

    Dim builder As New Microsoft.Data.SqlClient.SqlConnectionStringBuilder()

   

    builder.DataSource = "smacomdb.mssql.somee.com"

    builder.UserID = "smarcompu_SQLLogin_1"

    builder.Password = ""

    builder.InitialCatalog = "smacomdb"

    builder.TrustServerCertificate = True

   

    Using connection As New SqlConnection(builder.ConnectionString)

   

    Console.WriteLine(vbCrLf & "Query data example:")

    Console.WriteLine("=========================================" & vbCrLf)

   

    connection.Open()

   

    Dim sql As String = "SELECT name, collation_name FROM sys.databases"

   

    Using command As New SqlCommand(sql,connection)

   

    Using reader As SqlDataReader = command.ExecuteReader()

    If reader.HasRows Then

        Do Whilereader.Read

            'Console.WriteLine("{0}", reader.GetString(0))

            Console.WriteLine($"{reader.GetString(0)}")

        Loop

    End If

End Using

End Using

connection.Close()

End Using

Catch ex As Exception

End Try

Console.WriteLine(vbCrLf & "Done. Press enter.")

Console.ReadLine()

End Sub

End Module

CLI: cd vbdbcon1

CLI: dotnet build

CLI: dotnet run

.

No comments:

Post a Comment