-

- -

Monday, September 5, 2022

Writing C# and VB Console Project On DotNet Core Platform

 .


Create C# Console Project

Create VB Console Project

We will start at the root of ALL OUR PROJECTS

c:\ZT\>

We will start at the root of ALL OUR PROJECTS

c:\ZT\>

CLI: dotnet new console -lang C# -o cstest1

CLI: dotnet new console -lang VB -o vbtest1

CLI: cd  cstest1

CLI: cd vbtest1

CLI: dotnet build

CLI: dotnet build

CLI: dotnet run

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 (C#)

1) Print Hello World Program (VB)

Pseudo Code:

1. BEGIN

2. PRINT "Hello World"

3. END

Pseudo Code:

1. BEGIN

2. PRINT "Hello World"

3. END

using System;

namespace cstest1 {

  class Program {

    static void Main(string[] args) {

      Console.WriteLine("Hello World!");

    }

  }

}

Imports System

Module Program

Sub Main(args As String())

    Console.WriteLine("Hello World!")

End Sub

End Module

2) Sum Numbers Program (C#)

2) Sum Numbers Program (VB)

Pseudo Code:

1. BEGIN

2. PRINT 1 + 2

3. END

Pseudo Code:

1. BEGIN

2. PRINT 1 + 2

3. END

CLUE:

Console.WriteLine(1+2);

CLUE:

Console.WriteLine(1+2);

using System;

namespace cstest1 {

  class Program {

    static void Main(string[] args) {

      Console.WriteLine(1 + 2);

      Console.ReadKey();

    }

  }

}

Imports System

Module Program

Sub Main(args As String())

    Console.WriteLine(1 + 2)

    Console.ReadKey()

End Sub

End Module

3) Sum Variables Program (C#)

3) Sum Variables Program (VB)

Pseudo Code:

1. BEGIN

2. INPUT var1var2

3. PRINT var1+var2

4. END

Pseudo Code:

1. BEGIN

2. INPUT var1var2

3. PRINT var1+var2

4. END

CLUE:

CLUE:

using System;

namespace cstest1 {

  class Program {

    static void Main(string[] args) {

      int var1 = Convert.ToInt32(Console.ReadLine());

      int var2 = Convert.ToInt32(Console.ReadLine());

      Console.WriteLine(var1 + var2);

      Console.ReadKey();

    }

  }

}

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 (C#)

4) Multiply Variables Program (VB)

Pseudo Code:

1. BEGIN

2. INPUT var1var2

3. PRINT var1 * var2

4. END

Pseudo Code:

1. BEGIN

2. INPUT var1var2

3. PRINT var1 * var2

4. END

CLUE:

using System;

namespace cstest1 {

  class Program {

    static void Main(string[] args) {

      int var1 = Convert.ToInt32(Console.ReadLine());

      int var2 = Convert.ToInt32(Console.ReadLine());

      Console.WriteLine(var1 * var2);

      Console.ReadKey();

    }

  }

}

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 (C#)

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

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

CLUE:

Try input for 2 rounds.

For round1 => var1=4, var2=2

For round2=> var1=2, var2=0

using System;

namespace cstest1 {

  class Program {

    static void Main(string[] args) {

      double var1 = Convert.ToDouble(Console.ReadLine());

      double var2 = Convert.ToDouble(Console.ReadLine());

      if (var2 == 0) {

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

      } else {

        Console.WriteLine(var1 / var2);

      }

      Console.ReadKey();

    }

  }

}

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 (C#)

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

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.

CLUE:

Note:loop index number starts with 0.

using System;

namespace cstest1 {

   

  class Program {

     

    static void Main(string[] args) {

      Console.WriteLine("Start Counting.");

     

      for (int i = 0; i < 3; i++) {

         

        Console.WriteLine(i);

       

      }

      Console.WriteLine("Counting Done.");

    }

  }

}

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 (C#)

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

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"};

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"};

using System;

namespace cstest1 {

   

  class Program {

     

    static void Main(string[] args) {

       

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

       

        Console.WriteLine("Displaying array values.");

       

        for (int i = 0; i < 5; i++) {

         

            Console.WriteLine(arr[i]);

       

        }

     

      Console.WriteLine("Done.");

    }

  }

}

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

using System;

namespace cstest1 {

   

  class Program {

     

    static void Main(string[] args) {

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

     

      Console.WriteLine("Displaying array values.");

     

      for (int i = 0; i < 5; i++) {

         

          Console.WriteLine(arr[i]);

         

      }

     

      Console.WriteLine("Done.");

    }

  }

}

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 (C#)

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

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

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

using System;

namespace cstest1 {

   

  class Program {

     

    static void Main(string[] args) {

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

      Console.WriteLine("Displaying array values.");

     

      for (int i = 0; i < 5; i++) {

         

        Console.WriteLine(arr[i]);

       

      }

     

      Console.WriteLine("Done.");

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

     

      int indexNumber = Convert.ToInt32(Console.ReadLine());

     

      string arrayValue = Console.ReadLine();

     

      arr[indexNumber] = arrayValue;

      Console.WriteLine("Displaying array values.");

     

      for (int i = 0; i < 5; i++) {

         

        Console.WriteLine(arr[i]);

       

      }

     

      Console.WriteLine("Done.");

    }

  }

}

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

9) Modular Program (C#)

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

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:

        public static void Main()

        {

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

                displayData(arr);

                updateData(arr);

                displayData(arr);

        }

        private static void displayData(string[] arr1)

        {...}

        private static void updateData(string[] arr2){

        {...}

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

using System;

namespace cstest1 {

   

  class Program {

    static void Main(string[] args) {

     

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

     

      displayData(arr);

     

      updateData(arr);

     

      displayData(arr);

     

    }

   

    private static void displayData(string[] arr1) {

     

      Console.WriteLine("Displaying array values.");

     

      for (int i = 0; i < 5; i++) {

         

        Console.WriteLine(arr1[i]);

       

      }

     

      Console.WriteLine("Done.");

     

    }

    private static void updateData(string[] arr2) {

     

      int indexNumber = Convert.ToInt32(Console.ReadLine());

     

      string arrayValue = Console.ReadLine();

     

      Console.WriteLine("Updating...");

     

      arr2[indexNumber] = arrayValue;

     

    }

  }

}

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

10) Program Parameter (C#)

10) Program Parameter (VB)

using System;

namespace cstest1 {

   

  class Program {

     

    static void Main(string[] args) {

       

      Console.WriteLine(args[0]);

     

    }

  }

}

Imports System

Module Program

Sub Main(args As String())

   

    Console.WriteLine(args(0))

   

End Sub

End Module

Type console command:

Type console command:

dotnet run hello

dotnet run hello

Output:

Output:

TRY CATCH BLOCK (C#)

TRY CATCH BLOCK (VB)

    try {

             /* try to do something here */

    } catch (Exception e) {

      Console.WriteLine(e.Message);

    }

      Try

            ‘Try to do something here

      Catch e As Exception

         Console.WriteLine(e.Message)

      End Try

When do we use the TRY CATCH block?

  1. read/write text file
  2. Connecting to db
  3. Connecting to web resources

11) Working With Text File (C#)

11) Working With Text File (VB)

Get back to root of projects

C:\ZT>

Type command: dotnet new console -lang c# -o cstrycatch

Type command: cd cstrycatch

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 cstrycatch folder.

You will see Program.cs 

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

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

this is a test

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.cs by replacing the existing codes with the following codes. Make sure that your namespace is correct i.e. trycatch:

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

using System;

using System.IO;

namespace csrycatch {

   

  class Program {

     

    static void Main(string[] args) {

       

      string fileName = "data.txt";

     

      try {

         

        using(StreamReader reader = new StreamReader(fileName)) {

         

          string line;

         

          line = reader.ReadLine();

         

          while (line != null) {

           

            Console.WriteLine(line);

           

            line = reader.ReadLine();

          }

        }

      } catch (Exception e) {

       

        Console.WriteLine(e.Message);

       

      }

     

      Console.ReadKey();

    }

  }

}

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\cstrycatch>dotnet run

This is a test

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.

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\trycatch>dotnet run

This is a another test

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 (C#)

Create New Project

C:\ZT>dotnet new console -o mywebrequest

C:\ZT>cd mywebrequest

C:\ZT\mywebrequest>

Replace the content of Program.cs with the following codes:

using System;

namespace mywebrequest

{

    class Program

    {

        static void Main(string[] args)

        {

    var postdata ="comments=good&custemail=harry@porter.com&custname=harry+porter&custtel=0123456789&delivery=jnt";

      try{

     

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

      }

      catch(Exception e){

        Console.WriteLine(e.Message);

      }        

     

    Console.ReadKey();

        } /* Main end */

    } /* Program end */

} /*namespace end*/

We will get 2 errors during build process:

C:\ZT\mywebrequest\Program.cs(12,7): error CS0103: The name 'WebrequestWithPost' does not exist in the current context [C:\ZT\mywebrequest\mywebrequest.csproj]

C:\ZT\mywebrequest\Program.cs(12,53): error CS0103: The name 'Encoding' does not exist in the current context [C:\ZT\mywebrequest\mywebrequest.csproj]

using System;

namespace mywebrequest

{

    class Program

    {

        static void Main(string[] args)

        {

    var postdata ="comments=good&custemail=harry@porter.com&custname=harry+porter&custtel=0123456789&delivery=jnt";

      try{

     

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

      }

      catch(Exception e){

        Console.WriteLine(e.Message);

      }        

     

    Console.ReadKey();

        } /* Main end */

private static string WebrequestWithPost(string url, Encoding dataEncoding, string dataToPost, string contentType = @"application/x-www-form-urlencoded")

{

     // to do something here

} /* WebrequestWithPost end */

    } /* Program end */

} /*namespace end*/

We will get 1 error during build process:

C:\ZT\mywebrequest\Program.cs(12,53): error CS0103: The name 'Encoding' does not exist in the current context [C:\ZT\mywebrequest\mywebrequest.csproj]

using System;

using System.Text;

namespace mywebrequest

{

    class Program

    {

        static void Main(string[] args)

        {

    var postdata ="comments=good&custemail=harry@porter.com&custname=harry+porter&custtel=0123456789&delivery=jnt";

      try{

     

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

      }

      catch(Exception e){

        Console.WriteLine(e.Message);

      }        

     

    Console.ReadKey();

        } /* Main end */

private static string WebrequestWithPost(string url, Encoding dataEncoding, string dataToPost, string contentType = @"application/x-www-form-urlencoded")

{

     // to do something here

} /* WebrequestWithPost end */

    } /* Program end */

} /*namespace end*/

We will get 1 error during build process:

C:\ZT\mywebrequest\Program.cs(22,23): error CS0161: 'Program.WebrequestWithPost(string, Encoding, string, string)': not all code paths return a value [C:\ZT\mywebrequest\mywebrequest.csproj]

using System;

using System.Text;

namespace mywebrequest

{

    class Program

    {

        static void Main(string[] args)

        {

    var postdata ="comments=good&custemail=harry@porter.com&custname=harry+porter&custtel=0123456789&delivery=jnt";

      try{

     

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

      }

      catch(Exception e){

        Console.WriteLine(e.Message);

      }        

     

    Console.ReadKey();

        } /* Main end */

private static string WebrequestWithPost(string url, Encoding dataEncoding, string dataToPost, string contentType = @"application/x-www-form-urlencoded")

{

     var returnValue = String.Empty;

     return returnValue;

} /* WebrequestWithPost end */

    } /* Program end */

} /*namespace end*/

Lessons learned:

1) if we get name not found, we may need to declare our custom function/method (e.g. WebrequestWithPost) or we may need to use other libraries/namespace (using System.Text)

2) if we get an error regarding the return value, check that our function/method returns the expected value.

private static string WebrequestWithPost(

string url,

Encoding dataEncoding,

string dataToPost,

string contentType = @"application/x-www-form-urlencoded"

)

{

}

string url, = url to get the web resource

Encoding dataEncoding, = text encoding format for character data transfer

Encoding is the process of transforming a set of Unicode characters into a sequence of bytes. In contrast, decoding is the process of transforming a sequence of encoded bytes into a set of Unicode characters.
E.g. UTF-8

string dataToPost = data to be sent to destination

E.g.  

var postdata ="comments=good&custemail=harry@porter.com&custname=harry+porter&custtel=0123456789&delivery=jnt";

Serialised data i.e. data that has been arranged in sequence so that they can travelled through communication line

https://resttesttest.com/ 

 string contentType = @"application/x-www-form-urlencoded"

This is to tell the computer that our serialized data follows the format application/x-www-form-urlencoded

Use restesttest.com to send your form to https://httpbin.org/post  

The final complete codes for Program.cs is as follows:

using System;

using System.Text;

using System.Web;

using System.Net;

using System.IO;

namespace mywebrequest

{

    class Program

    {

        static void Main(string[] args)

        {

    var postdata ="comments=good&custemail=harry@porter.com&custname=harry+porter&custtel=0123456789&delivery=jnt";

      try{

     

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

      }

      catch(Exception e){

        Console.WriteLine(e.Message);

      }        

     

    Console.ReadKey();

        } /* Main end */

private static string WebrequestWithPost(string url, Encoding dataEncoding, string dataToPost, string contentType = @"application/x-www-form-urlencoded")

{

    var postDataAsByteArray = dataEncoding.GetBytes(dataToPost);

    var returnValue = String.Empty;

    try

    {

        var webRequest = WebRequest.CreateHttp(url);  //change to: var webRequest = (HttpWebRequest)WebRequest.Create(url); if you are your .NET Version is lower than 4.5

        if (webRequest != null)

        {

            webRequest.AllowAutoRedirect = false;

            webRequest.Method = "POST";

            webRequest.ContentType = contentType;

            webRequest.ContentLength = postDataAsByteArray.Length;

            using (var requestDataStream = webRequest.GetRequestStream())

            {

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

                requestDataStream.Close();

                using (var response = webRequest.GetResponse())

                {

                    using (var responseDataStream = response.GetResponseStream())

                    {

                        if (responseDataStream != null)

                        {

                            using (var responseDataStreamReader = new StreamReader(responseDataStream))

                            {

                                returnValue = responseDataStreamReader.ReadToEnd();

                                Console.WriteLine(returnValue);

                                responseDataStreamReader.Close();

                            }

                            responseDataStream.Close();

                        }

                    }

                    response.Close();

                }

                requestDataStream.Close();

            }

        }

    }

    catch (WebException ex)

    {

        if (ex.Status == WebExceptionStatus.ProtocolError)

        {

            var response = ((HttpWebResponse)ex.Response);

            //handle this your own way.

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

        }

    }

    catch(Exception ex)

    {

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

        Console.WriteLine(ex.Message);

    }

    return returnValue;

} /* WebrequestWithPost end */

    } /* Program end */

} /*namespace end*/

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 (C#)

13) SQL Server Connection (VB)

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

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

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

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

using System;

using Microsoft.Data.SqlClient;

namespace csdbcon1 {

  class Program {

    static void Main(string[] args) {

      try {

        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

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

        builder.UserID = "smarcompu_SQLLogin_1";

        builder.Password = "";

        builder.InitialCatalog = "smacomdb";

        builder.TrustServerCertificate = true;

        using(SqlConnection connection = new SqlConnection(builder.ConnectionString)) {

          Console.WriteLine("\nQuery data example:");

          Console.WriteLine("=========================================\n");

          connection.Open();

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

          using(SqlCommand command = new SqlCommand(sql, connection)) {

            using(SqlDataReader reader = command.ExecuteReader()) {

              if (reader.HasRows) {

                while (reader.Read()) {

                  /*Console.WriteLine("{0}", reader.GetString(0));*/

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

                }

              }

            }

          }

        }

      } catch (SqlException e) {

        Console.WriteLine(e.ToString());

      }

      Console.WriteLine("\nDone. Press enter.");

      Console.ReadLine();

    }

  }

}

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 csdbcon1

CLI: dotnet build

CLI: dotnet run

CLI: cd vbdbcon1

CLI: dotnet build

CLI: dotnet run

zpx6ci6uu6


.