Wednesday, April 22, 2020

Xamarin.Forms - Controlling Your PC 🖥️ With Your Phones📱Using TCP/IP Protocol - Part One


The misuse of official computers is a common practice among users in many work environments where proper monitoring mechanisms do not exist. It results in the waste of resources and is not meeting the overall objectives of an organization. So, to achieve the maximum and desired results in a work environment, an effective mechanism through which the administrator can monitor and control the workstations under the use of employees is needed.
The purpose of this project is to develop a Xamarin.Forms based application which will serve the administrator with on-demand remote surveillance and controlling of workstations of the workplace. The project will involve the development of two applications, one will run on workstations and the other one will run on the mobile phone of the administrator. Both the applications will be connected through Wi-Fi. The implementation of such a mechanism will allow the administrator, to not only have an eye on the activities of users but also, will make him/her able to remotely control the specific workstation(s).

Scope of Project

There will be two applications in this project,
  1. Server Application
    Server Application will continuously run on each workstation in workplace. The server application will be connected with the Client Application through a Wi-Fi connection. It will take a screenshot of user activity on the demand of the administrator and will transfer the same to client/mobile application. This application will interpret and execute commands received from the Client/mobile application.
  1. Client / Xamarin.Forms Application
    Android application will run on Administrator’s smart mobile phone and will provide an effective interface through which the Administrator will be able to connect it with the Server Application. Through this application, the Administrator will be able to instruct the Server Application to take the screenshot(s) and send to this application. Through this application, the Administrator will also be able to control any workstation and perform the activities such as sending a message, turning the workstation into sleep mode and shutting down any workstation etc.
  • Creating Connection Between Computer and Mobile
  • Screenshot taking and sending to Client / Xamarin.Forms Mobile Application
    Server Application will take the screenshot(s) of user activity on any workstation on demand of the Administrator through Client/mobile Application. Screenshot(s) will be transferred to the client/mobile application.
  • Controlling Work Stations
    The administrator will be able to control any workstation through sending commands. Administrator will be able to perform sending a message to the workstation turning that into sleep mode, locking the workstation, and shutting down the workstation.

Server Application

Step 1 - Create Console Application
Let’s create a console app project with .NET framework.
Xamarin.Android – Build Real Life Application-using TCP/IP
Step 2 - Add Appropriate Namespace
Create an instance of TcpClient and TcpListener inside your Program class by using appropriate namespaces. Also, declare a local variable type string with the name ipString.
  1. public static TcpClient client;  
  2. private static TcpListener listener;  
  3. private static string ipString;  
Step 3 - Get Your Machine IP Address
Let’s write a method inside your Main function that will catch and return your machine's IP Address.
  1. IPAddress[] localIp = Dns.GetHostAddresses(Dns.GetHostName());  
  2. foreach(IPAddress address in localIp) {  
  3.     if (address.AddressFamily == AddressFamily.InterNetwork) {  
  4.         ipString = address.ToString();  
  5.     }  
  6. }  
Step 4 - Start Listening On 1234 Port
Now, in this step, we are ready to start listening. I am using 1234 as my port number and I will use the current machine's local IP address and my port number for endpoints. After following all these steps, now, we can accept any TCP client and connect with clients.
  1. IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipString), 1234);  
  2. listener = new TcpListener(ep);  
  3. listener.Start();  
  4. Console.WriteLine(@"  
  5. ===================================================  
  6. Started listening requests at: {0}:{1}  
  7. ===================================================",  
  8. ep.Address, ep.Port);  
  9. client = listener.AcceptTcpClient();  
  10. Console.WriteLine("Connected to client!" + " \n");  
Xamarin.Android – Build Real Life Application-using TCP/IP
Step 5 - Build Connection With Client
After connecting with the client, I will perform my first function that will sleep the workstations using client command. While the client is connected with the Server, if a client will send SLP2 command, then the server will execute the sleep function that I will write in the next step.
  1. while (client.Connected) {  
  2.     try {  
  3.         const int bytesize = 1024 * 1024;  
  4.         byte[] buffer = new byte[bytesize];  
  5.         string x = client.GetStream().Read(buffer, 0, bytesize).ToString();  
  6.         var data = ASCIIEncoding.ASCII.GetString(buffer);  
  7.         if (data.ToUpper().Contains("SLP2")) {  
  8.             Console.WriteLine("Pc is going to Sleep Mode!" + " \n");  
  9.             Sleep();  
  10.         }  
  11.     } catch (Exception exc) {  
  12.         client.Dispose();  
  13.         client.Close();  
  14.     }  
  15. }  
Step 6 - Sleep Method
First, add the following namespaces to your project; then write the sleep function inside your Main function.
  1. using System.Windows.Forms;  
  2. void Sleep() {  
  3.     Application.SetSuspendState(PowerState.Suspend, truetrue);  
  4. }  

Client Application

The steps given below are required to be followed in order to create a Xamarin.Forms Application, using Visual Studio.
Step 1 - Create a Xamarin.Forms Project
Open Visual Studio and go to New Project-> Cross-platform-> Xamarin.Forms-> Blank app. give it a name, like XamarinFormsClient.
Step 2 - Create Connection Class
We need to define a connection class in our project for creating a TCP Client instance. Create a new class with the name Connection.cs and write the following code into it.
(FileName: Connection.cs)
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Net.Sockets;    
  5. namespace XamarinForms.Client    
  6. {    
  7.     public class Connection    
  8.     {    
  9.         private static Connection _instance;    
  10.         public static Connection Instance    
  11.         {    
  12.             get    
  13.             {    
  14.                 if (_instance == null) _instance = new Connection();    
  15.                 return _instance;    
  16.             }    
  17.         }    
  18.         public TcpClient client { getset; }    
  19.     }    
  20. }    
Step 2 - Creating User Interface for Connection
We need two edit texts boxs for IP address & port and one button for connecting with the server. Open MainPage layout file inside your layout and replace the following code into it.
  1. <?xml version="1.0" encoding="utf-8" ?>    
  2. <ContentPage xmlns=""    
  3.              xmlns:x=""    
  4.              xmlns:local="clr-namespace:XamarinForms.Client"    
  5.              x:Class="XamarinForms.Client.MainPage">    
  6.     <StackLayout>    
  7.     <Label Text="Connect to Server"     
  8.            FontSize="Medium"    
  9.            HorizontalOptions="Center" />    
  10.     <Entry x:Name="IPAddress" Placeholder="IP Address"/>    
  11.     <Entry x:Name="Port" Placeholder="Port Number"/>    
  12.     <Button x:Name="Connect" Text="Connect" Clicked="Connect_Clicked"/>    
  13.     </StackLayout>    
  14. </ContentPage>    
Xamarin.Android – Build Real Life Application-using TCP/IP
Step 3 - Create Connection Method
On this page, first, we will bind our UI controls with this MainPage class. Then, we will connect with the server application using the workstation IP address and port. Write the following code in your connect activity.
(FileName: MainPage.xaml)
  1. using System;    
  2. using System.Net.Sockets;    
  3. using Xamarin.Forms;    
  6. namespace XamarinForms.Client    
  7. {    
  8.     public partial class MainPage : ContentPage    
  9.     {    
  10.         public MainPage()    
  11.         {    
  12.             InitializeComponent();    
  13.         }    
  15.         private async void Connect_Clicked(object sender, EventArgs e)    
  16.         {    
  17.             try    
  18.             {    
  19.                 TcpClient client = new TcpClient();     
  20.                     await client.ConnectAsync(IPAddress.Text, Convert.ToInt32(Port.Text));    
  21.                 if (client.Connected)    
  22.                 {    
  23.                     Connection.Instance.client = client;    
  24.                     Application.Current.MainPage = new NavigationPage(new OperationsPage());    
  26.                    await DisplayAlert("Connected""Connected to server successfully!""Ok");    
  27.                 }    
  28.                 else    
  29.                 {    
  30.                     await DisplayAlert("Error""Connection unsuccessful!""Ok");    
  31.                 }    
  32.             }    
  33.             catch (Exception ex)    
  34.             {    
  35.                 await DisplayAlert("Error"""+ex.ToString(), "Ok");    
  36.             }    
  37.         }    
  38.     }    
  39. }    
Step 4 - Update App Class
Just open your App.xaml file inside this class adds the following code in the constructor of the App class.
  1. MainPage = new NavigationPage(new MainPage());     
We have completed our first module of client and server application that will hit the request to the server for building a connection. Then, we will be able to send any kind of commands to our server and also receive the response from the server.

Test Connection

Let’s test the connection of the server and client app that we have just built. However, the main launcher of Xamarin.Forms application will display the Main page. Start your server application and copy the IP address & port of workstation from the server app. Put this required parameter into the client application and hit Connect.
Xamarin.Android – Build Real Life Application-using TCP/IP
For simplicity, I am splitting the article into two parts. In the next part, I will complete the pending functionalities of Server and Client Applications. So, please stay tuned for my next article of this series.

Ahsan Siddique

Author & Editor

Experienced Microsoft Certified Azure Developer and Trainer with a demonstrated history of working in the computer software industry. Skilled in .NET, .NET Core, C#, Xamarin, Azure, Kubernetes, Docker Containers, Microservices, CI/CD, and Universal Windows Platform with Strong engineering professional.


Post a Comment