Wednesday, January 31, 2024

Introduction toWindows Services in C#

 Creating Windows Services in C# .Net for coders & students

Introduction to Windows Services?

  • Definition of Windows services

  • Where can we see Windows Services?

    • Show SCM and describe its contents.

  • What are some critical Windows Services?

    • Printer spooler, remote desktop, various software update services.

My course about Windows Service Programming(link)

engine-mustang.jpg


Definition: What are Windows Services?


It is a long-running executable application software that runs in the background. Services run in their own Windows session.

Windows operating system can automatically start a Windows service when the system starts up.


Windows services are like the engine people typically don’t see; programmers, you know, are different than the common folk, so we often get to see such scary stuff. Microsoft is trying to weave Docker into its ecosystem so that it could someday replace Windows Services. But it still seems far-fetched. Until that happens, you can continue using Windows Services. Many legacy applications rely on Windows Services, so it won't be easy to get rid of them entirely anytime soon.


Where can we see Windows Services if they don’t have any interface?


You can see the services by going to Windows Service Control Manager. To do this, press

Windows + R

Type Services.msc

run-services-msc.png


Windows Service Control Manager will show up. 

windows-service-control-center-annotated.png


There are many exciting pieces of information on this screen, like the name of the service, its description, and its status. 

To see more options, right-click a service name and select ‘Properties.’

windows-service-properties.png


A couple of essential pieces of information on the general tab are the path to the executable and startup type. 


There are four service startup types:

  1. Automatic, the service starts as soon as the system is powered on.

  2. Manual: the service does not start when the computer is turned on. It stays in a stop state until you, the user, go and start it manually.

  3. Automatic (delayed start): The service starts shortly after the PC is turned on.

  4. Disabled: The service does not start at all.


It is possible to start, stop, or restart a Windows service if you are logged in from an appropriate user—an administrator, for example.


You can also see services installed on a PC through the task manager.

Press Ctrl + Esc key

Click on the ‘Services’ tab.

task-manager-windows-services.png

task-manager-windows10.png


You can see essential services like Windows Defender and SkypeUpdate in the screenshot above.


Clicking the Open Services link below the list of services will open the service control manager, which we opened through a keyboard shortcut earlier.


IMPORTANT NOTES:

  1. The developer command prompt is used in VS 2015 instead of the visual studio command prompt.

  2. Run DCP as administrator; otherwise, the service installation will fail.

  3. The service only starts up successfully when the service process installer property Account is set to LocalSystem.

  4. If the service fails to start, Event Viewer can be used to see the events. Windows Logs -> System can be used to see the following types of events:

    1. Service failed to start

    2. Service installed

  5. The event can be seen in Windows Log -> Application when a service is started or stopped.


Anatomy & Lifecycle of a Windows Service

A Windows service must be installed on a computer to run it. The complete lifecycle of the service is shown in the flow chart.


  • Installed

  • Stopped

  • Started

  • Paused


A Windows service can be started manually through the SCM or automatically started by the Operating System when the system starts up.


A Windows Service must inherit from the .Net framework class ServiceBase

A Windows service contains methods that are called in response to each of its lifecycle states.

Some of these methods are:

  • OnStart

  • OnStop

  • OnPause

  • OnContinue


An example piece of code that can handle these events is shown below.

windows-service-methods.png


Difference between debugging Windows Services and “Normal” Windows applications

Notable differences between a Windows Service and other applications like Windows Forms, WPF, ASP.Net, and command-line applications are shown in the table below.


Serial

Normal Windows Applications

Windows Services

1

Press F5 in Visual Studio, and the application will start dancing in front of you.

No, you can’t do that with a Windows Service.

3

Debugging can be started without making any code changes straight inside Visual Studio.

Debugging cannot be started without some code changes(next section)

2

You don’t need to install the application to run it. Just double-clicking the .exe file is sufficient.

You must install the service using InstallUtil.exe to run it.


Windows-service-start-failure.png

If you try to hit F5 and run a Windows Service directly from the code, the message box shown above will be displayed to you by the system.


Live examples are shown in my video course.


Friday, September 8, 2023

Does it make sense to use the Page object in a project with API tests?

 


There may be more suitable approaches than using the Page Object pattern in an API testing project. The Page Object pattern is used in web UI automation testing(with libraries like Selenium, Cypress, and PlayWright). You abstract web pages into objects to make the test code more readable, maintainable, and reusable. It helps interact with and manipulate web elements like buttons, forms, and links.


In API testing, you deal with an application's backend, Sending HTTP requests and validating the responses. The concepts of web pages and UI elements do not apply in the same way as they do in UI automation testing. Instead, in API testing, you work with the following:


1. HTTP Requests: You send HTTP requests (e.g., GET, POST, PUT, DELETE) to specific API endpoints to interact with the backend services.


2. Response Validation: You confirm the responses received from the API endpoints. You check for expected status codes, headers, and response data structures.


3. Data Manipulation: You might need to manipulate and process data returned by the API. For example, you are extracting values for further use or transforming data for testing.


In API testing, it's more common to organize your code around HTTP request libraries or frameworks (e.g., using tools like Postman, RestAssured, or Python's requests library). Yet, you can still apply some best practices to make your API tests maintainable:


Modularization: Organize your API requests and response validation code into reusable functions or modules. This makes it easier to maintain and update your tests.


Configuration Management: Store API endpoints, request headers, and other configuration settings in a central location or configuration files to ensure consistency and ease of maintenance.


Test Data Management: Handle test data from test code so you can change data inputs and expected outputs without modifying your test scripts.


Test Reporting: Implement a reporting mechanism to track test results and monitor the health of your API endpoints.


In summary, while the Page Object pattern is valuable for UI automation testing, it does not apply to API testing. Instead, prioritize organizing your API testing code to make it readable, maintainable, and efficient for working with HTTP requests and responses.

Wednesday, April 26, 2023

TCP Socket Programming on Windows in C#

The.NET Framework's Socket class can program TCP/IP sockets in C# on Windows. The Socket class provides methods and attributes for creating, connecting, sending, and receiving data through TCP/IP sockets.

Discount coupon for my TCP/IP socket programming course:

https://www.udemy.com/course/tcpip-socket-programming-for-coders-using-csharp-net/?couponCode=CHATGPT_TCP_SOCKETS

In C#, here's a simple example of how to create a client that connects to a server over TCP/IP sockets:


using System;

using System.Net;

using System.Net.Sockets;

using System.Text;


class Program {

  static void Main(string[] args) {

    // Establish the remote endpoint for the socket.

    IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");

    IPAddress ipAddress = ipHostInfo.AddressList[0];

    IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, 11000);


    // Create a TCP/IP socket.

    Socket client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


    // Connect to the remote endpoint.

    client.Connect(remoteEndPoint);


    Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());


    // Encode the data string into a byte array.

    byte[] data = Encoding.ASCII.GetBytes("Hello, server!");


    // Send the data through the socket.

    int bytesSent = client.Send(data);


    // Receive the response from the server.

    byte[] buffer = new byte[1024];

    int bytesRec = client.Receive(buffer);

    Console.WriteLine("Server response: {0}", Encoding.ASCII.GetString(buffer, 0, bytesRec));


    // Release the socket.

    client.Shutdown(SocketShutdown.Both);

    client.Close();

  }

}

This example implements a TCP/IP client that connects to a server operating on the same computer (localhost) on port 11000. The client sends the server a "Hello, server!" message and receives a return message.

You can use the following code to construct a TCP/IP server:


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class Program {
  static void Main(string[] args) {
    // Establish the local endpoint for the socket.
    IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

    // Bind the socket to the local endpoint and listen for incoming connections.
    listener.Bind(localEndPoint);
    listener.Listen(10);

    Console.WriteLine("Waiting for a connection...");

    // Accept incoming connections and start a new socket to handle communication with the client.
    Socket handler = listener.Accept();
    Console.WriteLine("Connection established with {0}", handler.RemoteEndPoint.ToString());

    // Receive data from the client and send a response.
    byte[] buffer = new byte[1024];
    int bytesRec = handler.Receive(buffer);
    Console.WriteLine("Client message: {0}", Encoding.ASCII.GetString(buffer, 0, bytesRec));

    byte[] response = Encoding.ASCII.GetBytes("Hello, client!");
    handler.Send(response);

    // Release the socket.
    handler.Shutdown(SocketShutdown.Both);
    handler.Close();
  }
}

This example establishes a TCP/IP server that waits for incoming connections on port 11000. When a client joins, the server accepts the connection and opens a new socket to handle client communication. The server gets a message from the client and responds with its own message.

It should be noted that these are relatively basic examples that do not include error handling or advanced capabilities such as asynchronous socket communication. When working with exceptions and problems, it is critical to handle them correctly.

Wednesday, April 5, 2023

Top 42 Kubernetes Interview Questions and Answers with Tips



Kubernetes and the Cloud-Native Ecosystem Interview Questions

Question 1: Where can a container run?

  1. on an LXD system with Docker installed
  2. on a Linux machine with no other prerequisites
  3. on a Windows machine with a container engine installed(correct answer)
  4. on a cloud-based Docker Hub deployment

Kubernetes tip: A container requires an engine (container engine) installed on any operating system on which it is expected to work.

Question 2: One goal of cloud-native technologies is to increase the speed of application deployments.

True(correct anwer)

False

Kubernetes tip: Other goals include making applications highly available, scalable, and portable across environments.


Question 3: What assumption is at the foundation of cloud-native technology?

  1. Software should be released in slow cycles to enable proper testing.
  2. Cloud-native projects should provide isolated solutions with less cross-integration.
  3. It is good to remove silos between ops teams and software development teams. (correct)
  4. Bonus: By removing these silos, cloud technology can help expedite code pushes to production.

Question 4: Which statement is true regarding Kubernetes?

  1. It is written in Java or C++.
  2. It originates in a Facebook system called Go.
  3. It is an open-source project. (Correct)
  4. Kubernetes Tip: Kubernetes is an open-source system with many active developers. It is maintained by Google.

Question 5: Kubernetes is the Greek word for helmsman of a ship. Why did the creators of the project choose this name?

Answer: 

Kubernetes ranks containers in the order in which they were deployed.

Kubernetes oversees a set of servers and decides where to deploy containerized applications, when to scale up and down the number of application replicas, and what to do when an application or server stops working. (correct answer)

K8S Bonus: 

Kubernetes negotiates with other servers and trades containers when it has run out of space.

Kubernetes moves containers from one cloud provider to another.


Questions about setting up and getting oriented with Kubernetes

Question#6: Which installer type is not offered for Minikube on Windows through the official Minikube site?

  1. .exe download
  2. Windows Package Manager
  3. .zip portable download(correct answer)
  4. Chocolatey


KubeCTL Bonus: A Chocolatey installer type is offered through the official Minikube site. A Windows Package Manager installer type is offered.


Question 7: Which command installs Minikube on macOS using Homebrew?

  1. Homebrew install minikube
  2. sudo install minikube
  3. brew install minikube (correct answer)
  4. brew minikube install

Question 8: Which statement is true regarding Docker installation on Windows?

  1. Docker Desktop for Windows is a free application.
  2. Docker is a requirement to run a Minikube Kubernetes cluster. (correct answer)
  3. Docker Desktop installs the container engine required by Kubernetes.
  4. It does not require a restart.

K8S Bonus:

A Docker Desktop installation requires a machine restart.

Docker Desktop actually requires a paid subscription for commercial use in larger enterprises.


Question 9 Which kubectl command lists the pods from all the namespaces?

kubectl get pods -A (correct answer)

kubectl get pods -N

kubectl get namespaces -P

kubectl list pods -all-namespaces


Question 10: For what purpose will you use Minikube?

  1. Run a Kubernetes cluster on your computer. (correct answer)
  2. Run a Kubernetes cluster on AWS
  3. Interact with a Kubernetes cluster

Question 11: Which shell command can you use on Linux at the end of the Docker installation process to confirm that Docker is properly installed?

  1. docker-ce
  2. docker (correct answer)
  3. lsb-release
  4. docker-compose-plugin


Question 12: Which package is not a prerequisite to install Docker on Linux?

  1. gnupg
  2. keyrings (correct answer)
  3. curl
  4. lsb-release

KubeCTL Bonus: "Keyrings" is not a Linux package for a name of a folder used during installation. The GNUPG(GNU Privacy Guard) package is required to add the Docker GPG key.


Question 13: Which statement is true about Minikube?

  1. It is designed to run production clusters.
  2. It is as secure as a complete Kubernetes installation.
  3. It is free software. (correct answer)

KubeCTL Bonus: Minikube is not designed to run production systems.

Question 13: What is different about Docker installation for macOS compared to Windows?

  1. The Docker engine installation on macOS requires a restart.
  2. The macOS installation process considers the chip family on the machine. (correct answer)
  3. The Docker installation package for macOS is different for Intel and Apple chips.
  4. The macOS Docker engine only has a graphical user interface.
  5. The macOS Docker engine has a different name.

K8S Bonus: The Docker installation on macOS does not require a restart.

Questions about application deployment with Kubernetes

Question 14: Using the DESCRIBE POD command, what will the event log show for a pod running for a long time?

  1. If a pod has been running for a while, Kubernetes will assume it is healthy and not show its events.
  2. The command is not expected to show pod events.
  3. The event log will show all events from the launch.
  4. Old events are less interesting for a pod running for a while.
  5. The event log will show as empty. (correct answer)

Question 15: Which KUBECTL command can you use to list all the pods in a specific namespace?

  1. kubectl apply -f mynamespace
  2. kubectl get pods -n mynamespace (correct answer)
  3. kubectl list pods -n mynamespace
  4. kubectl mynamespace -l deployments

Question 16: What will be the outcome of the following command?

kubectl get pods

  1. All pods in all namespaces will be listed.
  2. All pods in the default namespace will be listed (correct answer)
  3. With no specified namespace, the command will list all the default namespace pod.
  4. The command will cause an error.

Question 17: Pod A runs a web server with an IP address of 172.17.0.3. On pod B on the cluster, running wget 172.17.0.3 results in a refused connection. What is one immediate thing to check?

  1. Pod B is exposing port 80.
  2. Pods A and B are exposing port 3000.
  3. Pod A is exposing port 8080.
  4. Pod A is exposing port 80 (correct answer)

k8s Bonus Tip: Pod A should expose the port that the "wget" command is trying to call (defaulting to 80). Remember that "wget" defaults to port 80 if no port is specified.

Question 18: What is the syntax issue in the following YAML file?

items:

- bananas

- tomatoes

  1. The colon needs to be placed correctly.
  2. The indentation is wrong (correct answer)
  3. Nested items must be indented.
  4. Some lines are missing a colon.

Question 18: Which character or sequence of characters will you use in YAML to represent a sequence?

  1. #
  2. - (correct answer)
  3. ---
  4. :

Question 19: When the -o wide option is added to the kubectl get pods to command, what additional information will show?

  1. IP address (correct answer)
  2. The IP address will show for all listed pods.
  3. port
  4. status

Question 20: Which path in the deployment YAML file specifies the number of instances to run?

  1. spec -> template -> spec -> containers
  2. spec -> instances
  3. metadata -> replicas
  4. spec -> replicas (correct answer)

Question 20: What represents a valid namespace YAML?

---

apiVersion: v1

kind: Namespace  name: mynamespace

---

apiVersion: v1

kind: Namespace

metadata:

  name: mynamespace (correct answer)

---

apiVersion: v1

metadata:

  kind: Namespace

  name: mynamespace

---

apiVersion: v1

metadata:

  name: mynamespace

Question 21: What is the immediate parent of the following line?

  1. - containerPort: 8080
  2. template:
  3. spec:
  4. ports: (correct answer)
  5. containers:

Complex Application Deployment in Kubernetes

Question 22: Your deployment YAML has the following configuration. What should your service YAML include so traffic is directed correctly?

metadata:

  labels:

    app: pod-info

spec:

  selector:

    app: pod-service

spec:

  selector:

    app: pod-info

(correct)

spec:

  selector:

    service: pod-info

Question 22: What is not a type of service that Kubernetes offers?

  1. AddressPool (correct answer)
  2. AddressPool is not a service type that Kubernetes supports.
  3. ClusterIP
  4. LoadBalancer
  5. NodePort

Question 23: "resources" refers to a worker node's available bandwidth and memory.

FALSE (correct)

TRUE

K8s Bonus Tip: "resources" refers to a worker node's available CPU and memory.

Question 24: In a deployment YAML file, what is the immediate parent under which the resource request and limit specifications should be placed?

  1. the template block
  2. the env block
  3. the container block (correct answer)

Since the resources apply to a container, they should be specified under the container's block.

Question 25: What do resources refer to in the context of resource requests and limits to a pod?

  1. available storage space for the pod
  2. available CPU and memory for the cluster
  3. available CPU and memory on the worker node (correct answer)

Question 26: What is the result of the following command?

Minikube delete

  1. Delete all objects added using YAML manifests.
  2. Delete the namespaces.
  3. Delete the entire Minikube Kubernetes cluster. (correct answer)

This command will delete the entire Minikube Kubernetes cluster.

Question 27: How would you delete a Kubernetes deployment created with a YAML manifest called api.yaml?

  1. kubectl destroy -f api.yaml
  2. kubectl delete -f api.yaml (correct answer)
  3. kubectl delete deployment
  4. kubectl delete API

Question 28: If you need someone to access an application deployed in your Kubernetes cluster, you'll set up a Kubernetes _____ Service.

  1. NAT Gateway
  2. ClusterIP
  3. LoadBalancer (correct answer)
  4. NodePort

Kubernetes Architecture Interview Questions

Question 29: What is an instance of Kubernetes called?

  1. a worker node
  2. a cluster (correct answer)
  3. a deployment
  4. a server

Question 30: What component communicates directly with the etcd component?

  1. Scheduler component
  2. The API Server (correct answer)
  3. Only the Kube API Server component can communicate directly with etcd.
  4. The Kubelet

Question 31: Which control plane component stores the data about the state of the cluster?

  1. API Server
  2. etcd (correct answer)
  3. scheduler
  4. controller manager

Question 32: What function does the Kubelet component perform on a worker load?

  1. Create containers using a supported engine.
  2. This function is actually handled by the Container Runtime.
  3. Check that pods and services can communicate.
  4. Check that the containers are healthy. (correct answer)

Question 32: What are the three components of every worker node?

  1. container runtime interface, kubelet, and kube-proxy (correct answer)
  2. kube-apiserver, container runtime interface, and kube-proxy
  3. kubelet, cloud-controller-manager, and kube-proxy
  4. kubelet, kube-scheduler, and kube-proxy

Question 33: The kube-proxy is the only worker node component that communicates with the kube-apiserver.

  1. FALSE (correct answer)
  2. TRUE

Question 34: Dockershim was removed from Kubernetes v1.24 . How did this change impact Kubernetes?

  1. Kubernetes can no longer use the Docker engine to run containers.(correct answer)
  2. Kubernetes can no longer be installed on a Docker server host.
  3. Kubernetes can no longer use Docker images to instantiate containers.

Question 35: Which component pulls the image from the image repository, when you launch a pod with a new container image?

  1. api-server
  2. controller manager
  3. kubelet (correct answer)

Question 36: Which two Kubernetes components bind a pod to a node when the user applies a new deployment?

  1. controller manager and scheduler
  2. kubelet and container-runtime
  3. api-server and kubelet (correct answer)
  4. api-server and etcd

Kubernetes tip: The controller manager is only involved in checking for changes. These two components are involved in starting a container.

Question 37: Which of these is not a component of the Kubernetes Control Plane?

  1. kubelet (correct answer)
  2. etcd
  3. kube-apiserver
  4. cloud-controller-manager

Kubernetes Advanced Topics

Question 38:  What is the best way to run these application pods if you need to run an application that performs a one-time extract, transform, load (ETL) operation that transfers data from a SQL database to a data warehouse. ?

  1. StatefulSet
  2. DaemonSet
  3. Job (correct answer)
  4. Deployment

Kubernetes tip: A Kubernetes Job will spin up a pod, run the container until its task is complete, and terminate it. A Job is best for applications that perform one-time operations, like an ETL.

Question 39: How to set up data storage inside a Kubernetes cluster?

  1. Docker volume
  2. a managed SQL database
  3. persistent volume (correct)

Question 40: Which option will work best to run containers that are agents?

  1. Job
  2. Deployment
  3. DaemonSet (correct)

Kubernetes tip: DaemonSets allow you to run one pod per node, which works well for running pods implementing background processes such as agents.

Question 41: What is the immediate parent under which the securityContext definition should be placed?

  1. the env block
  2. the container name
  3. the metadata section
  4. the container block(correct)

Kubernetes tip: Since the security context is defined per container, it must be placed inside its block.

Question 42: Which service or object is associated with Kubernetes persistent volumes?

  1. Amazon RDS
  2. stateless application
  3. statefulSet (correct)

Kubernetes tip: A statefulSet is an object that lets an updated Kubernetes application communicate with the same volume as the previous pod.

Tuesday, October 18, 2022

How to Hide Kubernetes and System Containers in Docker Desktop



Containers have been around in kitchens and shipping docks for a long time. But in the software world, containers have taken over just recently through technologies like Docker and PodMan.

What is a Docker Container?

A Container is a basic package "containing" everything needed to run specific software or a more extensive software system component. Docker is the technology used to create containers. Taking care of your Docker containers is easy when their count is negligible. But in the case of large software systems, the number of containers can swell real quick. Kubernetes is the technology used to manage your container sprawl. There are other technologies, but Kubernetes comes built-in with Docker Desktop. This article is written using Docker Desktop for Windows. You can download the Docker Desktop from this link. This article is not concerned with the Docker Desktop settings file.

Docker itself is built using containers. It uses containers to take care of its internal operation.

Kubernetes on Docker Desktop

When we install Docker Desktop, Kubernetes is not enabled by default. You can install and enable Kubernetes later. Kubernetes is the king of container orchestration technologies. Having Kubernetes installed with Docker Desktop means you don't need to install tools like MiniKube.

One day, you may open Docker Desktop, and a terrifying list of containers will greet you on the Containers screen. 

Docker Desktop Kubernetes Containers

Please take a look at the screenshot shown above. You can see the list of Kubernetes containers in a red box. An arrow is added on the bottom left of the same screenshot, and the vast green tile contains a tiny Kubernetes icon. It is easy to miss for newbies, and there is room for UX improvement in Docker Desktop.

How to optimize the number of containers shown by Docker Desktop UI

The list of containers displayed by the Docker Desktop contains the containers used by the Docker system to keep the "lights on." These containers are called system containers. The name of Docker system containers is hard to remember for humans, at least in the current Docker Desktop version. You may not enjoy seeing them again and again. It is possible to hide the system containers through Docker desktop settings. 

The Docker Desktop settings can be opened through an icon on the top right corner of the Docker window. 

Docker Desktop Settings Icon
The Docker Desktop Settings icon is shown above. The Docker Settings icon could've been slightly more prominent, and the tiny bug nearby makes it less visible. Clicking it is going to lead us to the Docker Settings UI.

Show system containers - Docker Desktop

The Kubernetes settings are hidden in a tab on the Docker Desktop settings UI. By default, you can see the option "Show system containers (advanced)" is enabled. This tiny checkbox contributes to the long list of items from where we started the chase. It is time to uncheck the setting "Show system containers (advanced)" and click the button "Apply & Restart." The apply button is below the settings UI, towards the right side.

Settings Docker Desktop


The screenshot above shows the Docker Desktop (for Windows) settings after unchecking the option "Show system containers (advanced)." Clicking the "Apply & Restart" button will not do much on the surface but will change the relevant settings behind the scenes. You must close the Docker Desktop window and reopen it to see the results.
 
Docker Desktop No System Containers


The screenshot above shows how the Docker Desktop for Windows. The containers UI section will look when the system containers are not displayed.

Conclusion:
It is straightforward to enable/disable whether you want to see the Docker system containers. The number can be large, and most of the time, you don't need to look at the list all the time. My personal preference is to hide the system containers from Docker settings. I'll be writing more about containerization and Docker in the future. Please stay tuned. Please do share your feedback about the post as well. It is most welcome.