Press "Enter" to skip to content

Posts published in “.net core”

New features in .net core 3.0 – Take a look!

In this article, I would like to share with you the new features in .Net Core 3.0 version.



run dotnet -version to see the which version you are using.

All templates that come with .Net Core 3.0 are listed with the command dotnet help – as shown below.

From the new templates, 2 of my most noticeable are the following.

  • WPF Application
  • Windows Forms Application
.net core 3.0 new features

First, the .Net Framework 4.8 is installed from the following link. Thus, innovations coming with C # 8.0 will be examined.

You can download from this link: https://blogs.msdn.microsoft.com/dotnet/2018/11/28/announcing-net-framework-4-8-early-access-build-3694/

Windows Application over .Net Core 3.0:

The following command creates the .Net Core Windows Application.

dotnet new winforms -o core3

Ranges and indices :

On Windows Forms, put a button called Test Sequences.



private void buttonArray_Click(object sender, EventArgs e)
        {
            Index i1 = 2;
            Index i2=^5;
            int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            MessageBox.Show($"{a[i1]}, {a[i2]}"); // "2, 5"
            var array = a[i1..i2];
            var arrayString=String.Join(",", array.Select(p=>p.ToString()).ToArray());
            MessageBox.Show(arrayString); // 2,3,4
        }
  • Index i1 takes the second element from the beginning of the array. ==> a [i1] 2.
  • Because of Index i2 ^, it takes the last element from the end. ==> a [i2] is 5.
  • In the range a [i1..i2], all elements in the array are taken. ==> 2,3,4

Asynchronous Streams:

The goal can be considered as an asynchronous method to navigate with the foreach.

GetUserAsync (): The following method is written from GitHub, which pulls the user information asynchronously. Using github api!

public async Task<IEnumerable<string>> GetUserAsync()
        {
            string url = "https://api.github.com/users/blabla";
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "http://developer.github.com/v3/#user-agent-required");
 
                using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
                {
                    using (HttpContent content = response.Content)
                    {
                        var result = await content.ReadAsStringAsync();
                        string[] resultlist = result.Split(',');
                        return resultlist;
                    }
                }
            }
        }

WriteResultsAsync (): In this method, the sequence of asynchronous returning string [] from GetUserAsync () is printed on the screen.

public async Task WriteResultsAsync()
        {
            await foreach (var result in GetUserAsync())
            {
                Console.WriteLine(result);
            }
        }

There is a bug for .Net Core 3.0. For the moment it is stated that it only works in C # 8.0. But it will soon come to .Net Core 3.0. Since it cannot be tested fully, the code will be edited if necessary!

Cryptography:

The encryption algorithms AES GCM and AES-CCM are included in Net Core 3.0. These are necessary namespaces to use cryptography algorithms: System.Security.Cryptography.AesGcm & System.Security.Cryptography.AesCcm

I got the below code from blogs.msdn.microsoft.com and i changed a bit.

public void WriteCrypto()
        {
            byte[] key = new byte[16];
            RandomNumberGenerator.Fill(key);
 
            byte[] nonce = new byte[12];
            RandomNumberGenerator.Fill(nonce);
 
            byte[] dataToEncrypt = new byte[1234];
            byte[] associatedData = new byte[333];
            RandomNumberGenerator.Fill(dataToEncrypt);
            RandomNumberGenerator.Fill(associatedData);
 
            byte[] tag = new byte[16];
            byte[] ciphertext = new byte[dataToEncrypt.Length];
 
            using (AesGcm aesGcm = new AesGcm(key))
            {
                aesGcm.Encrypt(nonce, dataToEncrypt, ciphertext, tag, associatedData);
            }
 
 
            byte[] decryptedData = new byte[ciphertext.Length];
 
            using (AesGcm aesGcm = new AesGcm(key))
            {
                aesGcm.Decrypt(nonce, ciphertext, tag, decryptedData, associatedData);
            }
 
            Console.WriteLine($"AES-GCM: Decrypted data, {(dataToEncrypt.SequenceEqual(decryptedData) ? "same" : "different")} original data.");
        }

Default implementations of interface members :

Not supported in C # 8.0 and .Net Core 3.0 yet. Tested with Microsoft Visual Studio Enterprise 2019 Preview 2.0.

Default method can be assigning to the interface as follows.

  • The IMessage interface, the method “WriteMessage ()” and the default “WriteMessageMultiTimes ()” method are defined in the corresponding interface.
  • MessageNote: Although it did not implement the WriteMessageMultiTimes () method derived from the IMessage interface, no error was encountered. Because this method is defined as default in the IMessage interface.
using System;
 
interface IMessage
{
    void WriteMessage(string message);
    void WriteMessageMultiTimes(string message, int repeatCount = 3)
    {
        for (int i = 0; i < repeatCount; i++)
        {
            Console.WriteLine(message);
        }
    }
}
 
class MessageNote : IMessage
{
    public void WriteMessage(string message) { Console.WriteLine("MessageNoteClass:"+message); }
}
 
//Usage:
MessageNote mNote= new MessageNote ();
var messageText= ((IMessage)mNote).WriteMessageMultiTimes("Default Interface Method",2);

So what’s the advantage of this? For example, the following interface should be implemented by 3 different methods. As seen below, the IFighter interface contains 4 methods.

public interface IFighterBuilder
{
 void SetKick();
 void SetDefance();
 void SetCombo(); 
 
 Fighter GetFighter();
}

Now there is 3 other classes that derives from this interface:

using System.Diagnostics;
public class Ken: IFighterBuilder
{
   void SetKick(){Debug.WriteLine("Hit, Kick!");}
   void SetDefance(){Debug.WriteLine("Blocke");}
   void SetCombo(){Debug.WriteLine("Hit, Combo!");}
   Fighter GetFighter(){return new Ken();}
   
   void SetFlyPunch(){Debug.WriteLine("Hit, Kick!");}
}
 
public class Ryu: IFighterBuilder
{
   void SetKick(){Debug.WriteLine("Hit, Kick!");}
   void SetDefance(){Debug.WriteLine("Blocke");}
   void SetCombo(){Debug.WriteLine("Hit, Combo!");}
   Fighter GetFighter(){return new Ryu();}
 
   void SetHaduucat(){Debug.WriteLine("Throw Haduuucat");}
}
 
public class Honda: IFighterBuilder+
{
   void SetKick(){Debug.WriteLine("Hit, Kick!");}
   void SetDefance(){Debug.WriteLine("Blocke");}
   void SetCombo(){Debug.WriteLine("Hit, Combo!");}
   Fighter GetFighter(){return new Honda();}
 
   void SetFlyHead(){Debug.WriteLine("Head, Kick!");}
}

Now let’s say we need to add a new method to the IFighterBuilder interface. SetSpecialMove () method The SetFlyPunch () method is defined in the Interface as a default method so that all classes using this interface are not changed.

public interface IFighterBuilder
{
 void SetKick();
 void SetDefance();
 void SetCombo(); 
 
 Fighter GetFighter();
 SetSpecialMove(){Debug.WriteLine("Move, Your Special!");}
}

Windows Desktop Support

In previous versions of .Net Core, the main target was web applications and web api. Desktop support is also included with this version. But since this is only available for Windows developers, I don’t think that it will create much excitement for people like us who have been using .NetCore for web projects.

In-Box Json Reader

This version comes with Json.Utf8JsonReader under System.Text namespace. Json.Net will be 2 times faster than the reader. In the first stage, Json read (sequential access) support will be available, in later versions, Json write, DOM (random access), poco serializer, poco deserializer will be added.

Sources for this blog:

Thanks for reading.. I will be update this blog often! Keep on following you .net core lovers!

See you on next post!

Did you read solid principles?

How to deploy .Net core application on Ubuntu (Google Cloud)

We can run an application developed with Net Core on Windows, Linux, and Mac systems. In this article we will publish an application developed with Net Core 2.1 version on Ubuntu 16.04 using nginx.

It is pretty easy but there is no good documentation on internet. I want to write an article about this. Here are my steps to deploy .net core application on google cloud! Thanks for reading..

Deploying .Net Core App on Google Cloud (ubuntu)

  • Create Ubuntu instance from Google Cloud
    • Ubuntu 18.04 LTS version
  • Set firewall rules to instance’s Network Tags (Following tags should be exist in the Google Cloud “Network Services/Firewall Rules”)
    • http-server
    • https-server
    • default-allow-ssh
    • vnc-server (if you want RDP)
  • Login gcloud
    • gcloud auth login
  • Open ssh console
    • gcloud compute ssh YOUR_INSTANCE_NAME –project YOUR_PROJECT_NAME –zone europe-west4-a –ssh-flag “-L 22:localhost:22”
  • File transfer to ubuntu pc
    • gcloud compute scp C:\Users\YOURNAME\Desktop\publish\*.* YOUR_INSTANCE_NAME 
      YOUR_PROJECT_NAME YOUR_ZONE (example: zone europe-west4-a)
  • Install .Net Core SDK and Runtime to the Ubuntu 18.04 instance 
    • Update Ubuntu
      • sudo apt-get update
      • sudo apt-get upgrade
    • Install .net core package
  • Set firewall settings
    • sudo ufw enable
    • sudo ufw allow https
    • sudo ufw allow ssh
    • sudo ufw allow http
  • Create Folder on Ubuntu Instance
    • sudo mkdir YOUR_FOLDER_NAME
    • sudo chown YOUR_NAME YOUR_FOLDER_NAME
  • Copy project files to instance (in the Google Cloud SDK Command Line Toot, not ubuntu shell)
    • gcloud compute scp C:\ProjectFolder\*.* 
      YOUR_INSTANCE_NAME  –project 
      YOUR_PROJECT_NAME –zone YOUR_ZONE
  • Create .ppk file
    • you need to create .ppk file with PuTTY Key Generator
    • Create a .ppk file with a same name with the instance of linux machine. For Example; your linux machine name: sample-ubuntu, and your .ppk file name must be ‘sample-ubuntu.ppk’
    • Key Comment: Your sample-ubuntu machine user name
      Key passphrase: Your password& save private key as  sample-ubuntu.ppk
  • Create sh file (yourproject.sh file in the Your publish folder)

                                  #! /bin/sh

                                  sudo dotnet /YourProject/YourProject.dll

  • Create service file (yourproject.service file in the Your publish folder)

                                 [Unit]
                                 Description= yourproject daemon service
                                 After=basic.target syslog.target network.target

                                 [Service]
                                 ExecStart=/ YourProject/yourproject.sh
                                 Restart=always

                                 StandardOutput=syslog
                                 StandardError=inherit
                                 SyslogFacility=daemon
                                 SyslogLevel=err
                                 SyslogIdentifier=yourproject

                                 [Install]
                                 WantedBy=multi-user.target

  • Set permission
    • sudo chmod +x YourProject.dll
    • sudo chmod +x yourproject.sh
  • Copy service file to linux system folder
    • sudo cp yourproject.service /lib/systemd/system
  • Reload SystemD and enable the service
    • sudo systemctl daemon-reload
    • sudo systemctl enable yourproject
  • Start service
    • sudo systemctl start yourproject
      • sudo systemctl stop yourproject
  • View service status
    • systemctl status yourproject

Your application is now running on your linux machine. You can check your server by entering the IP address of your server. The service definition file that we created will start automatically even when our server restarts or the dotnet runtime collapses.

As you, if you can follow steps deploying .net core app on google cloud, it is so easy.

you can ask every thing to us from instagram.com/DeveloperKafasiOfficial