Search This Blog

Wednesday, June 30, 2021

Csharp: Garbage Collector

Confusing Terms:
  1. IDispose -- unmanaged, user can call
  2. Difference between Close and Dispose
  3. GC.Collect -- managed, user can call
  4. Finalize -- unamanged, user can not call
  5. Destructor
  6. SupressFinalize
  7. Close
================================================================================
IDispose : 
  • Used for disposing unmanaged resources 
  • When we implement IDispose interface, Dispose is the method where we dispose the umanged resource. 
  • In some objects we have two options 1. dispose and 2. Close. For file streaming both options are same. 
Void dispose()
{
this.close();
Dispose(true);
GC.SupressFinalize(this);
}
===============================================================================
Difference between Close and Dispose

Close
1. Disconnected with DB
2. Release resources.
3. SQL Connection object not released, it is just close and can be open again. 

Dispose
1. Disconnected with DB
2. Release resources.
3. Release SQL connection object as well. 

Example: 
try 
    
        string constring = "Server=(local);Database=my; User Id=sa; Password=sa";                             SqlConnection sqlcon = new SqlConnection(constring); 
        sqlcon.Open(); // here connection is open 
        // some code here which will be execute 
    
catch // code will be execute when error occurred in try block } 
finally 
    
        sqlcon.Close(); // close the connection 
        sqlcon.Dispose(); // desroy the connection object 
    }

===============================================================================
GC.Collect:

1. this method is used to clear manged resources. 
2. Unlike Finalize which can not be called by user, GC.Collect can be called by user. 
3. Also GC.Collect is to work on managed resrouce while GC.Finalize is for unmanaged resources. 
4. It will force the GC generations to start. 

===============================================================================
Finalize():

1. This method is used to clear the unmanaged resource like IDispose. 
2. This method can only be called by GC as a part of destructor. 
3. We can not call it explicitly. We have to implemetn IDispose instead, if we want to take care of un managead resource. 

===============================================================================
Destructor:

1. Finalize also called as destructor of the class. Finalize()
2. It can not be explicitly called except for the destructor calling itself behind the scene. 
3. Finalize can be used to clean unmanged resource in C# with the help of GC. 

~myclass()
{
this.Dispose(); // behind the scene finalize would also be called
}

===============================================================================
SupressFinalize()

1. This method is to tell the CLR that we have already taken care of releasing unmanged resources and GC need not to act on it. 

===============================================================================

Tuesday, June 29, 2021

Ctor: Base class, Child class

  class baseclass
    {
        public baseclass()
        {
            Console.WriteLine("--base class ctor--");
        }
    }

    class childclass1 : baseclass
    {
        public childclass1()
        {
            Console.WriteLine("--Child class ctor--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            baseclass b = new childclass1();
            Console.ReadKey();
        }

    }

output of above both lines will be same. below o/p will be printed twice. 
--base class ctor--
--Child class ctor--

Base class Child Class relation

Case 1
    class baseclass
    {
        public void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            c.childmethod1();
            c.basemethod(); // is this possible? error, warning, nothing?

            Console.ReadKey();
        }

    }

c.childmethod1() -- output would be "--Child Method1--"
c.basemethod(); -- No error, no warning, o/p would be "--base method--". Child class has access to its parent public and protected members. 

----------------------------------------------------------------------------------------------------------------------------------------
Case 2

    class baseclass
    {
        public virtual void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            c.basemethod(); // is this possible? error, warning, nothing?

            Console.ReadKey();
        }

    }

c.basemethod(); -- No error, no warning, o/p would be "--base method--" as nothing is override in child method. and code flow is from parent to child as waterfall. So parent method will be called. 
----------------------------------------------------------------------------------------------------------------------------------------
Case 3:

class baseclass
    {
        public virtual void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }

        public new / <<space>> / virtual / override void basemethod()
        {
            Console.WriteLine("--base method from child--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            c.basemethod(); // is this possible? error, warning, nothing?

            Console.ReadKey();
        }

    }
c.basemethod(); -- No error, no warning, o/p would be "--base method from child--" as object is pure form of child class.it wont simply look at parent method. 
----------------------------------------------------------------------------------------------------------------------------------------
Case 4:

class baseclass
    {
        public virtual void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }

        public new / <<space>> / virtual void basemethod()
        {
            Console.WriteLine("--base method from child--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            baseclass b = new childclass1();
            b.basemethod();

            Console.ReadKey();
        }

    }
c.basemethod(); -- o/p would be "--base method--" now method will be from parent to child as waterfall. Since there is no override keyword. basemethod of parent will be called in above case. 
Even if parent doent have virtual keyword then still only parent method would have called. 

----------------------------------------------------------------------------------------------------------------------------------------
Case 5:

 class baseclass
    {
        public virtual void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }

        public override void basemethod()
        {
            Console.WriteLine("--base method from child--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            baseclass b = new childclass1();
            b.basemethod();

            Console.ReadKey();
        }

    }

c.basemethod(); -- o/p would be "--base method from child--" here method will be called from parent to child. since parent has virtual keyword and child has override keyword, method of child would be called. 

----------------------------------------------------------------------------------------------------------------------------------------
Case 6:

 class baseclass
    {
        public void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public override void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            c.basemethod(); // is this possible? error, warning, nothing?

            Console.ReadKey();
        }

    }

Compile time error: Override can not exists without virtual/abstract keyword. While virtual can exists without override. 

----------------------------------------------------------------------------------------------------------------------------------------





----------------------------------------------------------------------------------------------------------------------------------------





----------------------------------------------------------------------------------------------------------------------------------------

Thursday, June 17, 2021

Host ASP.NET Core on azure Linux with Nginx

 This can be done in two ways 1) with out creating docker image 2) creating docker image from the published folder
3) create image and download it from azure container registry

Approach 1: Without creating Docker image

 Basic steps to host a .net core application on azure linux mahince with nginx
1. Create a resource group
2. Create a Linux virtual machine on azure. (may be ubutu server). Make sure port:80 is open as we are going to use it for http request. 
3. Login to Linux virtual machine using PUTTY. 
4. Install Docker
sudo apt install docker-ce

5. download nginx docker image
docker pull nginx:1.17.0

6. check if new downloaded image is avalible or not
docker images

7. Run default page of nginx. This will launch the default page of welcome to docker 
docker run -d -p 80:80 nginx:1.17.0

--- from here approach 2 can be used ---------
8. install .net core SDK on linux vm
9. publish the .net core code from Visual studio locally and copy the publish folder from local to VM using WINSCP tool 
10. run application on linum vm using .net core. it will run kestral web server by default. 
dotnet projectfile.dll

11. Now we have to configure nginx configuration file to transafer all request to kestral server and we will hit nginx port to access application. 

Approach 2: creating docker image from the published folder

1. create a docker file and write below content into it. 

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 -- this tell the default image to take reference
WORKDIR /app -- working directory for ur application
COPY  . .  -- copy from publish folder to working directory
ENV ASPNETCORE_URLS http://*:5000 -- open the port 
EXPOSE 5000
ENTRYPOINT ["dotnet", "coreproj.dll"] -- dotnet application with applicpation name as 'coreproj'

2. Run following command. this command will run the above file 
sudo docker build -t dotnetapp .

3. Run the application 
sudo docker run -d -p 5000:5000 dotnetapp

Since here we are mentioning 5000 we have to open inbound port for 5000 as well. 

4. Stop the application 
sudo docker stop dotnetapp

Wednesday, June 16, 2021

Kubernetes

Kafka: Introduction

 KAFKA

  • Kafka can be used to send and receive messages in microservices. 
  • It is a middleware and can handle millions of messages. 
  • Azure service bus and Rabbit MQ are substitute messaging service to Kafka. 
  • Kafka work on Topic- Subscription model of messages not on queues. 
  • Kafka was created by Linked in. 
  • Kafka has concept of publisher, Broker, Consumer
    • Broker - Kafka cluster and kafka ecosystem. 
    • Publisher, Consumer - Microservices 
  • We also have to up and run zookeeper and its main purpose is
    • Maintain list of topics and messages 
    • Track status of nodes in distributed system
    • Manage Kafka brokers on distributed system. 
=================================================================================

How to work with KAFKA and use it to communicate between .net core microservices. 

Step1. Install Java if not already install on server. check by java -version
Step2. Download Kafka and unzip it. let say folderA
Step3. Download Zookeeper and unzip it. let say Folder B
Step4. Start Zookeeper. Go to bin and double click on exe file. We can start it with cmd also. 
Step5. Start Kafka. with CMD which will act as a broker. 
Step6. Create a Topic
Step7. Create a publisher. it could be console application or a Microservice
Step8. Create a subscriber.  it could be console application or a Microservice


===============================================================================
.net Microservice to create a publisher and a subscriber  

Publisher
Step1. Install nuget pakcage "Confluent.kafka" in api project created on .net core. which we will treat as microservice. 
Step2. In appsettings.json create producer by mentioning bootstrap server.
    value of bootstrap server like below :
BootstrapServers = "localhost:9092"
Step3. Add above producer in Starup.configureservice method. .

Step4. Create an API controller do some coding like below:
                await producer.Produce.Async(topic, message); 
Where message is json serialized object. 

Step5. now if you send something from postman then that thing must come in above api method. 

Post:
http://localhost/api/producer/send?topic=temp-topic
{"id":1,"name":"test"}

Subscriber
1. Create a microservice and install the above nuget package. 
2. in main.cs subscribe to the same topic mentioned above. 
=============================================================================