Tuesday, September 24, 2019

[Tutorial] C# Console Projects On ASP.NET Core Platform

 .

Create C# Console Project

We will start at the root of ALL OUR PROJECTS

c:\ZT\>

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

CLI: cd  cstest1

CLI: dotnet build

CLI: dotnet run

Online code beautifier tool:

https://codebeautify.org/csharpviewer 

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

1) Print Hello World Program (C#)

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!");

    }

  }

}

2) Sum Numbers Program (C#)

Pseudo Code:

1. BEGIN

2. PRINT 1 + 2

3. END

CLUE:

Console.WriteLine(1+2);

using System;

namespace cstest1 {

  class Program {

    static void Main(string[] args) {

      Console.WriteLine(1 + 2);

      Console.ReadKey();

    }

  }

}

3) Sum Variables Program (C#)

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();

    }

  }

}

4) Multiply Variables Program (C#)

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();

    }

  }

}

5) Divide Variables Program (C#)

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

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();

    }

  }

}

6) Count Numbers Program (C#)

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.

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.");

    }

  }

}

7) Display Array Values Program (C#)

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

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.");

    }

  }

}

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.");

    }

  }

}

8) Edit Array Values Program (C#)

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

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.");

    }

  }

}

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

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){

        {...}

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;

     

    }

  }

}

cd /

cd ZT

cd cstest1

10) Program Parameter (C#)

using System;

namespace cstest1 {

   

  class Program {

     

    static void Main(string[] args) {

       

      Console.WriteLine(args[0]);

     

    }

  }

}

Type console command:

dotnet run hello

Output:

TRY CATCH BLOCK (C#)

    try {

             /* try to do something here */

    } catch (Exception e) {

      Console.WriteLine(e.Message);

    }

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

Get back to root of projects

C:\ZT>

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

Type command: cd cstrycatch

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

Edit Program.cs by replacing the existing codes with the following codes. Make sure that your namespace is correct i.e. trycatch:

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();

    }

  }

}

C:\ZT\cstrycatch>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\trycatch>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*/

13) SQL Server Connection (C#)

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

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();

    }

  }

}

CLI: cd csdbcon1

CLI: dotnet build

CLI: dotnet run


.

No comments:

Post a Comment