#include <iostream>
#include <string>
#include <winsock2.h>
#include "msclr/marshal_cppstd.h"
#include <nlohmann/json.hpp>
#include <fstream>
#include <sstream>
#pragma comment(lib, "Ws2_32.lib")
using namespace msclr::interop;
using namespace System;
using namespace System::Windows::Forms;
using namespace System::ServiceProcess;
using json = nlohmann::json;
using namespace System::Diagnostics;
using namespace System::Security::Principal;
// Convert std::filesystem::path to System::String^
System::String^ ConvertPathToString(const std::filesystem::path& path) {
return msclr::interop::marshal_as<System::String^>(path.string());
}
namespace DataConnectorGUI {
using namespace System::Collections::Generic;
public ref class Form : public System::Windows::Forms::Form {
public:
Form(void) {
InitializeComponent();
this->Icon = nullptr;
this->gatewayData = gcnew Dictionary<int, array<String^>^>();
LoadGatewayConfig();
// Create a timer to refresh service status
System::Windows::Forms::Timer^ serviceStatusTimer = gcnew
System::Windows::Forms::Timer();
serviceStatusTimer->Interval = 5000; // 5 seconds
serviceStatusTimer->Tick += gcnew System::EventHandler(this,
&Form::UpdateServiceStatuses);
serviceStatusTimer->Start();
protected:
~Form() {
if (components) {
delete components;
}
}
private:
System::Windows::Forms::TabControl^ tabControl;
System::Windows::Forms::TabPage^ gatewayTab;
System::Windows::Forms::Button^ addButton;
System::Windows::Forms::TabPage^ securityTab;
System::Windows::Forms::TabPage^ detailsTab;
System::Collections::Generic::List<System::Windows::Forms::Panel^>^
dynamicPanels;
int addedFieldCount;
Dictionary<int, array<String^>^>^ gatewayData;
System::ComponentModel::Container^ components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void) {
this->components = gcnew System::ComponentModel::Container();
this->Size = System::Drawing::Size(640, 560);
this->Text = L"DataConnector";
this->Padding = System::Windows::Forms::Padding(10, 0, 8, 40);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->tabControl = gcnew System::Windows::Forms::TabControl();
this->tabControl->Dock = System::Windows::Forms::DockStyle::Fill;
// Gateway Tab for maintain the data form Services(Create, Start, Stop
and Delete)
this->gatewayTab = gcnew System::Windows::Forms::TabPage();
this->gatewayTab->Text = L"Gateway";
this->gatewayTab->BackColor = System::Drawing::Color::White;
// Add Button
this->addButton = gcnew System::Windows::Forms::Button();
this->addButton->Text = L"Add";
this->addButton->Location = System::Drawing::Point(20, 20);
this->addButton->Size = System::Drawing::Size(65, 23);
this->addButton->Click += gcnew System::EventHandler(this,
&Form::OnAddButtonClick);
this->gatewayTab->Controls->Add(this->addButton);
// Create and configure OK button
Button^ okButton = gcnew Button();
okButton->Text = L"OK";
okButton->Size = System::Drawing::Size(65, 23);
okButton->Location = System::Drawing::Point(this->ClientSize.Width -
240, this->ClientSize.Height - 35);
okButton->Click += gcnew System::EventHandler(this,
&Form::OnOkButtonClick);
okButton->Anchor = AnchorStyles::Bottom | AnchorStyles::Right;
// Add OK button to the form
this->Controls->Add(okButton);
// Create and configure Cancel button
Button^ cancelButton = gcnew Button();
cancelButton->Text = L"Cancel";
cancelButton->Size = System::Drawing::Size(65, 23);
cancelButton->Location = System::Drawing::Point(this->ClientSize.Width
- 160, this->ClientSize.Height - 35);
cancelButton->Click += gcnew System::EventHandler(this,
&Form::OnOkButtonClick);
cancelButton->Anchor = AnchorStyles::Bottom | AnchorStyles::Right;
// Create and configure Apply button
Button^ applyButton = gcnew Button();
applyButton->Text = L"Apply";
applyButton->Size = System::Drawing::Size(65, 23);
applyButton->Location = System::Drawing::Point(this->ClientSize.Width -
80, this->ClientSize.Height - 35);
applyButton->Click += gcnew System::EventHandler(this,
&Form::OnOkButtonClick);
applyButton->Anchor = AnchorStyles::Bottom | AnchorStyles::Right;
// Add buttons to the form
this->Controls->Add(okButton);
this->Controls->Add(cancelButton);
this->Controls->Add(applyButton);
// Security Tab
this->securityTab = gcnew System::Windows::Forms::TabPage();
this->securityTab->Text = L"Security";
this->securityTab->BackColor = System::Drawing::Color::White;
// Details Tab
this->detailsTab = gcnew System::Windows::Forms::TabPage();
this->detailsTab->Text = L"Details";
this->detailsTab->BackColor = System::Drawing::Color::White;
this->tabControl->Controls->Add(this->gatewayTab);
this->tabControl->Controls->Add(this->securityTab);
this->tabControl->Controls->Add(this->detailsTab);
this->Controls->Add(this->tabControl);
this->dynamicPanels = gcnew
System::Collections::Generic::List<System::Windows::Forms::Panel^>();
this->addedFieldCount = 0;
}
#pragma endregion
// Add button event handler
void OnAddButtonClick(System::Object^ sender, System::EventArgs^ e) {
int startX = 30;
int startY = 50 + (addedFieldCount * 35);
auto panel = gcnew System::Windows::Forms::Panel();
panel->Location = System::Drawing::Point(startX, startY);
panel->Size = System::Drawing::Size(550, 60);
array<System::Windows::Forms::TextBox^>^ textBoxes = gcnew
array<System::Windows::Forms::TextBox^>(3);
for (int i = 0; i < 3; ++i) {
// Only create TextBox controls
auto textBox = gcnew System::Windows::Forms::TextBox();
textBox->Location = System::Drawing::Point(10 + (i * 100), 30);
textBox->Size = System::Drawing::Size(80, 20);
textBoxes[i] = textBox;
if (i == 0) {
textBox->Name = "aliasTextBox";
textBox->Text = L"Gateway" + (addedFieldCount + 1).ToString();
textBox->ReadOnly = true;
textBox->TextChanged += gcnew System::EventHandler(this,
&Form::OnAliasTextChanged);
}
else if (i == 1) {
textBox->Name = "nameTextBox";
textBox->Text = L"Gateway" + (addedFieldCount + 1).ToString();
textBox->TextChanged += gcnew System::EventHandler(this,
&Form::OnNameTextChanged);
}
else if (i == 2) {
textBox->Name = "portTextBox";
// Generate the default port number
String^ generatedPort = L"500" + (addedFieldCount +
1).ToString();
// Validate the generated port number (only numeric)
bool isValidPort = true;
for (int j = 0; j < generatedPort->Length; ++j) {
if (!Char::IsDigit(generatedPort[j])) {
isValidPort = false;
break;
}
}
if (isValidPort) {
textBox->Text = generatedPort;
}
else {
textBox->Text = L"500";
}
textBox->MaxLength = 4;
// Attach the KeyPress event to restrict input to numbers only
and handle length limit
textBox->KeyPress += gcnew
System::Windows::Forms::KeyPressEventHandler(this, &Form::OnPortKeyPress);
}
panel->Controls->Add(textBox);
}
// Create Button
auto createButton = gcnew System::Windows::Forms::Button();
createButton->Text = L"Create";
createButton->Location = System::Drawing::Point(320, 32);
createButton->Size = System::Drawing::Size(60, 20);
createButton->Tag = textBoxes;
createButton->Click += gcnew System::EventHandler(this,
&Form::OnCreateButtonClick); // OnClick Event
panel->Controls->Add(createButton);
this->gatewayTab->Controls->Add(panel);
this->dynamicPanels->Add(panel);
addedFieldCount++;
}
// Existing Services show in UI
void AddGatewayPanel(String^ alias, String^ name, String^ port, String^
status) {
int startX = 30;
int startY = 50 + (addedFieldCount * 35);
auto panel = gcnew System::Windows::Forms::Panel();
panel->Location = System::Drawing::Point(startX, startY);
panel->Size = System::Drawing::Size(550, 50);
array<String^>^ labelsText = { L"Alias:", L"Service Name:", L"Port:" };
array<System::Windows::Forms::TextBox^>^ textBoxes = gcnew
array<System::Windows::Forms::TextBox^>(3);
for (int i = 0; i < 3; ++i) {
if (addedFieldCount == 0) {
auto label = gcnew System::Windows::Forms::Label();
label->Text = labelsText[i];
label->Location = System::Drawing::Point(10 + (i * 100), 10);
panel->Controls->Add(label);
}
auto textBox = gcnew System::Windows::Forms::TextBox();
textBox->Location = System::Drawing::Point(10 + (i * 100), 30);
textBox->Size = System::Drawing::Size(80, 20);
textBoxes[i] = textBox;
if (i == 0) {
textBox->Name = "aliasTextBox";
textBox->Text = alias;
textBox->ReadOnly = true;
}
else if (i == 1) {
textBox->Name = "nameTextBox";
textBox->Text = name;
textBox->TextChanged += gcnew System::EventHandler(this,
&Form::OnNameTextChanged);
textBox->ReadOnly = true;
}
else if (i == 2) {
textBox->Name = "portTextBox";
textBox->Text = port;
textBox->ReadOnly = true;
}
panel->Controls->Add(textBox);
}
// Add buttons based on the status
if (status->Equals(L"Running", StringComparison::OrdinalIgnoreCase)) {
auto stopButton = gcnew System::Windows::Forms::Button();
stopButton->Text = L"Stop";
stopButton->Location = System::Drawing::Point(320, 30);
stopButton->Size = System::Drawing::Size(60, 20);
stopButton->Click += gcnew System::EventHandler(this,
&Form::OnStopButtonClick);
panel->Controls->Add(stopButton);
}
else if (status->Equals(L"Stopped",
StringComparison::OrdinalIgnoreCase)) {
auto startButton = gcnew System::Windows::Forms::Button();
startButton->Text = L"Start";
startButton->Location = System::Drawing::Point(320, 30);
startButton->Size = System::Drawing::Size(60, 20);
startButton->Click += gcnew System::EventHandler(this,
&Form::OnStartButtonClick);
panel->Controls->Add(startButton);
}
// Add Restart button (only once)
auto restartButton = gcnew System::Windows::Forms::Button();
restartButton->Text = L"Restart";
restartButton->Location = System::Drawing::Point(390, 30);
restartButton->Size = System::Drawing::Size(60, 20);
restartButton->Tag = panel;
restartButton->Click += gcnew System::EventHandler(this,
&Form::OnRestartButtonClick);
panel->Controls->Add(restartButton);
// Add Delete button (only once)
auto deleteButton = gcnew System::Windows::Forms::Button();
deleteButton->Text = L"Delete";
deleteButton->Location = System::Drawing::Point(460, 30);
deleteButton->Size = System::Drawing::Size(60, 20);
deleteButton->Tag = panel;
deleteButton->Click += gcnew System::EventHandler(this,
&Form::OnDeleteButtonClick);
panel->Controls->Add(deleteButton);
this->gatewayTab->Controls->Add(panel);
this->dynamicPanels->Add(panel);
addedFieldCount++;
}
// Port textBox Conditions
void OnPortKeyPress(System::Object^ sender,
System::Windows::Forms::KeyPressEventArgs^ e) {
// Only allow digits and control characters like Backspace
if (!Char::IsDigit(e->KeyChar) && e->KeyChar != 8) {
e->Handled = true;
}
// Prevent the input if the length of the TextBox exceeds 5 characters
auto textBox = dynamic_cast<System::Windows::Forms::TextBox^>(sender);
if (textBox != nullptr && textBox->Text->Length >= 5 && e->KeyChar !=
8) {
e->Handled = true;
}
}
std::string send_query_to_data_handler(const std::string& query, const
std::string& ip, int port) {
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
int result;
std::string response;
// Initialize Winsock
result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
throw std::runtime_error("WSAStartup failed with error: " +
std::to_string(result));
}
// Create a socket
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
WSACleanup();
throw std::runtime_error("Socket creation failed with error: " +
std::to_string(WSAGetLastError()));
}
// Set up the sockaddr_in structure
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr(ip.c_str());
clientService.sin_port = htons(port);
// Connect to the server
result = connect(ConnectSocket, (SOCKADDR*)&clientService,
sizeof(clientService));
if (result == SOCKET_ERROR) {
closesocket(ConnectSocket);
WSACleanup();
throw std::runtime_error("Connection failed with error: " +
std::to_string(WSAGetLastError()));
}
// Send the query
result = send(ConnectSocket, query.c_str(), query.length(), 0);
if (result == SOCKET_ERROR) {
closesocket(ConnectSocket);
WSACleanup();
throw std::runtime_error("Send failed with error: " +
std::to_string(WSAGetLastError()));
}
// Receive the response
char recvbuf[512];
int bytesReceived;
while ((bytesReceived = recv(ConnectSocket, recvbuf, sizeof(recvbuf) -
1, 0)) > 0) {
recvbuf[bytesReceived] = '\0';
response += recvbuf;
}
if (bytesReceived == SOCKET_ERROR) {
closesocket(ConnectSocket);
WSACleanup();
throw std::runtime_error("Receive failed with error: " +
std::to_string(WSAGetLastError()));
}
// Clean up
closesocket(ConnectSocket);
WSACleanup();
return response;
}
// Function to convert std::string to std::wstring
std::wstring ConvertToWideString(const std::string& str) {
int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.c_str(),
(int)str.length(), nullptr, 0);
std::wstring wstr(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.length(),
&wstr[0], size_needed);
return wstr;
}
bool ServiceExists(const std::string& serviceName) {
SC_HANDLE scManager = OpenSCManager(nullptr, nullptr,
SC_MANAGER_CONNECT);
if (!scManager) {
std::cerr << "Failed to open Service Control Manager." <<
std::endl;
return false;
}
// Convert serviceName from std::string to std::wstring
std::wstring wideServiceName = ConvertToWideString(serviceName);
SC_HANDLE service = OpenServiceW(scManager, wideServiceName.c_str(),
SERVICE_QUERY_STATUS);
if (service) {
CloseServiceHandle(service);
CloseServiceHandle(scManager);
return true; // Service already exists
}
CloseServiceHandle(scManager);
return false; // Service does not exist
}
void LoadGatewayConfig() {
try {
std::string handler_ip = "127.0.0.1";
int handler_port = 8084;
std::string sql_query = "SELECT service_name, status, port FROM
services;";
// Send the SQL query and get the response
std::string response = send_query_to_data_handler(sql_query,
handler_ip, handler_port);
// Log the raw response for debugging
std::cout << "Raw Response: " << response << std::endl;
if (response.empty()) {
throw std::runtime_error("Error: Received an empty response
from the server.");
}
std::istringstream stream(response);
std::string service_name, status, port;
int entryCount = 0;
while (stream >> service_name >> status >> port) {
if (status.empty() || status == "Stopped") {
status = "Running";
}
entryCount++;
std::cout << "Processing Service - " << service_name <<
std::endl;
if (!ServiceExists(service_name)) {
std::cout << "Creating and Starting Service: " <<
service_name << std::endl;
InstallService(gcnew String(service_name.c_str()), gcnew
String(service_name.c_str()));
// Start the service
StartService(gcnew String(service_name.c_str()));
}
else {
std::cout << "Service " << service_name << " already
exists. Skipping installation." << std::endl;
}
// Add the service to the UI panel
AddGatewayPanel(gcnew String(service_name.c_str()), gcnew
String(service_name.c_str()), gcnew String(port.c_str()), gcnew
String(status.c_str()));
}
if (entryCount == 0) {
throw std::runtime_error("Error: No valid entries found in the
response.");
}
}
catch (const std::exception& ex) {
MessageBox::Show(gcnew String(ex.what()), "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
}
}
// Save the Service Configuration (Create Button Click)
void SaveGatewayConfig(String^ alias, String^ name, String^ port) {
try {
std::string aliasStr = marshal_as<std::string>(alias);
std::string nameStr = marshal_as<std::string>(name);
std::string portStr = marshal_as<std::string>(port);
// Check if the service with the same Name already exists
if (ServiceExists(nameStr)) {
MessageBox::Show("Service with this name already exists.",
"Information", MessageBoxButtons::OK, MessageBoxIcon::Information);
return;
}
InstallService(gcnew String(nameStr.c_str()), gcnew
String(aliasStr.c_str()));
StartService(gcnew String(nameStr.c_str()));
// Add the service to the UI panel
AddGatewayPanel(gcnew String(nameStr.c_str()), gcnew
String(aliasStr.c_str()), gcnew String(portStr.c_str()), "Running");
MessageBox::Show("Service created successfully.", "Success",
MessageBoxButtons::OK, MessageBoxIcon::Information);
}
catch (const std::exception& ex) {
MessageBox::Show(gcnew String(ex.what()), "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
}
}
void InstallService(String^ name, String^ alias) {
try {
// Check if the application is running with administrator
privileges
WindowsIdentity^ identity = WindowsIdentity::GetCurrent();
WindowsPrincipal^ principal = gcnew WindowsPrincipal(identity);
bool isAdmin = principal-
>IsInRole(WindowsBuiltInRole::Administrator);
if (!isAdmin) {
// Silent admin privilege escalation using Task Scheduler
method
try {
String^ taskCommand = "schtasks /create
/tn \"SilentAdminTask\" /tr \"" + Application::ExecutablePath + "\" /sc once /st
00:00 /rl highest /f";
ProcessStartInfo^ taskInfo = gcnew
ProcessStartInfo("cmd.exe", "/c " + taskCommand);
taskInfo->WindowStyle = ProcessWindowStyle::Hidden;
taskInfo->UseShellExecute = true;
taskInfo->Verb = "runas"; // Request admin silently
Process^ taskProcess = Process::Start(taskInfo);
taskProcess->WaitForExit();
// Run the scheduled task immediately
Process::Start("cmd.exe", "/c schtasks /run
/tn \"SilentAdminTask\"");
return;
}
catch (Exception^) {
MessageBox::Show("Failed to start with administrator
privileges.", "Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
return;
}
}
// Check if the service already exists
for each (ServiceController ^ service in
ServiceController::GetServices()) {
if (service->ServiceName->Equals(name,
StringComparison::OrdinalIgnoreCase)) {
MessageBox::Show("Service already exists.", "Information",
MessageBoxButtons::OK, MessageBoxIcon::Information);
return;
}
}
// Use "cmd.exe" as the service binPath (alternative to .exe)
String^ command = String::Format("sc create \"{0}\"
binPath= \"cmd.exe\" start= auto", name);
// Execute the command
Process^ process = gcnew Process();
process->StartInfo->FileName = "cmd.exe";
process->StartInfo->Arguments = "/c " + command;
process->StartInfo->WindowStyle = ProcessWindowStyle::Hidden;
process->StartInfo->UseShellExecute = false;
process->StartInfo->RedirectStandardOutput = true;
process->StartInfo->RedirectStandardError = true;
process->Start();
// Capture output for debugging
String^ output = process->StandardOutput->ReadToEnd();
String^ errorOutput = process->StandardError->ReadToEnd();
process->WaitForExit();
// Show installation success or error messages
if (!String::IsNullOrEmpty(errorOutput)) {
MessageBox::Show("Error: " + errorOutput, "Service Installation
Failed", MessageBoxButtons::OK, MessageBoxIcon::Error);
}
else {
MessageBox::Show("Service installed successfully.", "Success",
MessageBoxButtons::OK, MessageBoxIcon::Information);
}
}
catch (Exception^ ex) {
MessageBox::Show("An error occurred: " + ex->Message, "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
}
}
// Event handler for check updated service status
void Form::UpdateServiceStatuses(Object^ sender, EventArgs^ e) {
for each (Panel ^ panel in dynamicPanels) {
String^ serviceName = nullptr;
// Find the TextBox containing the service name
for each (Control ^ control in panel->Controls) {
TextBox^ textBox = dynamic_cast<TextBox^>(control);
if (textBox != nullptr && textBox->Name == "nameTextBox") {
serviceName = textBox->Text;
break;
}
}
if (!String::IsNullOrEmpty(serviceName)) {
ServiceControllerStatus status = GetServiceStatus(serviceName);
// Find Start/Stop button
Button^ serviceButton = nullptr;
for each (Control ^ control in panel->Controls) {
Button^ button = dynamic_cast<Button^>(control);
if (button != nullptr && (button->Text == "Start" ||
button->Text == "Stop")) {
serviceButton = button;
break;
}
}
// Update button text and event handler
if (serviceButton != nullptr) {
if (status == ServiceControllerStatus::Running) {
serviceButton->Text = "Stop";
serviceButton->Click -= gcnew
System::EventHandler(this, &Form::OnStartButtonClick);
serviceButton->Click += gcnew
System::EventHandler(this, &Form::OnStopButtonClick);
}
else if (status == ServiceControllerStatus::Stopped) {
serviceButton->Text = "Start";
serviceButton->Click -= gcnew
System::EventHandler(this, &Form::OnStopButtonClick);
serviceButton->Click += gcnew
System::EventHandler(this, &Form::OnStartButtonClick);
}
}
}
}
}
// Service controller service status check
ServiceControllerStatus Form::GetServiceStatus(String^ serviceName) {
try {
ServiceController^ service = gcnew ServiceController(serviceName);
return service->Status;
}
catch (Exception^ ex) {
return ServiceControllerStatus::Stopped;
}
}
// Start button event handler
void Form::OnStartButtonClick(Object^ sender, EventArgs^ e) {
Button^ startButton = safe_cast<Button^>(sender);
Panel^ panel = safe_cast<Panel^>(startButton->Parent);
// Find the TextBox containing the service name
String^ serviceName = nullptr;
for each (Control ^ control in panel->Controls) {
TextBox^ textBox = dynamic_cast<TextBox^>(control);
if (textBox != nullptr && textBox->Name == "nameTextBox") {
serviceName = textBox->Text;
break;
}
}
if (String::IsNullOrEmpty(serviceName)) {
MessageBox::Show("Service name is required.", "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
return;
}
// Start the actual Windows Service
if (StartService(serviceName)) {
// Update the UI button dynamically
startButton->Text = L"Stop"; // Change button text to "Stop"
// Change the event handler to stop functionality
startButton->Click -= gcnew System::EventHandler(this,
&Form::OnStartButtonClick);
startButton->Click += gcnew System::EventHandler(this,
&Form::OnStopButtonClick);
}
}
bool StartService(String^ serviceName) {
try {
// Create a ServiceController object for the service
ServiceController^ service = gcnew ServiceController(serviceName);
// Check if the service is already running
if (service->Status != ServiceControllerStatus::Running) {
// Start the service if it is not running
service->Start();
service->WaitForStatus(ServiceControllerStatus::Running,
TimeSpan::FromSeconds(30)); // Wait for up to 30 seconds
}
// If the service is running, return true
if (service->Status == ServiceControllerStatus::Running) {
return true;
}
else {
MessageBox::Show("Service is not running after attempting to
start.", "Warning", MessageBoxButtons::OK, MessageBoxIcon::Warning);
return false; // Failed to start the service
}
}
// Catching general invalid operations (e.g., if the service doesn't
exist)
catch (InvalidOperationException^ ex) {
MessageBox::Show("Invalid operation: " + ex->Message, "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
return false;
}
// Catching any general exceptions
catch (Exception^ ex) {
MessageBox::Show("Failed to start service: " + ex->Message,
"Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
return false;
}
}
void Form::OnRestartButtonClick(Object^ sender, EventArgs^ e) {
Button^ restartButton = safe_cast<Button^>(sender);
Panel^ panel = safe_cast<Panel^>(restartButton->Parent);
// Get the service name from the panel
String^ serviceName = nullptr;
for each (Control ^ control in panel->Controls) {
TextBox^ textBox = dynamic_cast<TextBox^>(control);
if (textBox != nullptr && textBox->Name == "nameTextBox") {
serviceName = textBox->Text;
break;
}
}
if (String::IsNullOrEmpty(serviceName)) {
MessageBox::Show("Service name is required.", "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
return;
}
}
bool Form::RestartService(String^ serviceName) {
try {
ServiceController^ service = gcnew ServiceController(serviceName);
// If service is running, stop it first
if (service->Status == ServiceControllerStatus::Running) {
service->Stop();
service->WaitForStatus(ServiceControllerStatus::Stopped,
TimeSpan::FromSeconds(5)); // Wait up to 5 sec
}
// Start the service again
service->Start();
service->WaitForStatus(ServiceControllerStatus::Running,
TimeSpan::FromSeconds(5)); // Wait up to 5 sec
return true;
}
catch (Exception^ ex) {
MessageBox::Show("Failed to restart service: " + ex->Message,
"Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
return false;
}
}
// Stop button Event handler
void Form::OnStopButtonClick(Object^ sender, EventArgs^ e) {
Button^ stopButton = safe_cast<Button^>(sender);
Panel^ panel = safe_cast<Panel^>(stopButton->Parent);
// Get the service name from the panel (e.g., from a TextBox control)
String^ serviceName = nullptr;
for each (Control ^ control in panel->Controls) {
TextBox^ textBox = dynamic_cast<TextBox^>(control);
if (textBox != nullptr && textBox->Name == "nameTextBox") {
serviceName = textBox->Text;
break;
}
}
// Stop the service
if (StopService(serviceName)) {
// Successfully stopped, update button and UI
stopButton->Text = L"Start"; // Change button text to "Start"
stopButton->Click -= gcnew System::EventHandler(this,
&Form::OnStopButtonClick); // Remove stop handler
stopButton->Click += gcnew System::EventHandler(this,
&Form::OnStartButtonClick); // Add start handler
}
else {
MessageBox::Show("Failed to stop the service.", "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
}
}
// Stop the service on service.msc
bool StopService(String^ serviceName) {
try {
ServiceController^ service = gcnew ServiceController(serviceName);
// Stop the service if it is running
if (service->Status == ServiceControllerStatus::Running) {
service->Stop(); // Stops the service
service->WaitForStatus(ServiceControllerStatus::Stopped);
}
if (service->Status == ServiceControllerStatus::Stopped) {
return true; // Successfully stopped
}
else {
return false; // Failed to stop the service
}
}
catch (Exception^ ex) {
MessageBox::Show("Error stopping service: " + ex->Message, "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
return false;
}
}
void OnAliasTextChanged(System::Object^ sender, System::EventArgs^ e) {
auto aliasTextBox =
dynamic_cast<System::Windows::Forms::TextBox^>(sender);
if (aliasTextBox != nullptr) {
String^ currentText = aliasTextBox->Text;
// Check if the current text contains any spaces
if (currentText->Contains(" ")) {
// Remove spaces by replacing them with an empty string
aliasTextBox->Text = currentText->Replace(" ", "");
// Move the cursor to the end of the text
aliasTextBox->SelectionStart = aliasTextBox->Text->Length;
}
}
}
void OnNameTextChanged(System::Object^ sender, System::EventArgs^ e) {
auto nameTextBox =
dynamic_cast<System::Windows::Forms::TextBox^>(sender);
if (nameTextBox != nullptr) {
auto panel = nameTextBox->Parent;
for each (auto control in panel->Controls) {
auto textBox =
dynamic_cast<System::Windows::Forms::TextBox^>(control);
if (textBox != nullptr) {
if (textBox->Name == "aliasTextBox") {
textBox->Text = nameTextBox->Text;
}
}
}
}
}
// Save service to database
void SaveServiceToDatabase(String^ serviceName, String^ alias, String^
port, String^ status) {
try {
std::string handler_ip = "127.0.0.1";
int handler_port = 8084;
// Construct SQL INSERT query
std::string sql_query = "INSERT INTO services (service_name, port,
status) VALUES ('" +
msclr::interop::marshal_as<std::string>(serviceName) + "', '" +
msclr::interop::marshal_as<std::string>(port) + "', '" +
msclr::interop::marshal_as<std::string>(status) + "');";
// Send the query to the Data Handler
std::string response = send_query_to_data_handler(sql_query,
handler_ip, handler_port);
// Log the response
std::cout << "Database Response: " << response << std::endl;
}
catch (const std::exception& ex) {
MessageBox::Show(gcnew String(ex.what()), "Error Saving to
Database", MessageBoxButtons::OK, MessageBoxIcon::Error);
}
}
// Create button event handler to create or save configration
void OnCreateButtonClick(System::Object^ sender, System::EventArgs^ e) {
auto button = safe_cast<System::Windows::Forms::Button^>(sender);
auto panel = dynamic_cast<System::Windows::Forms::Panel^>(button-
>Parent);
auto textBoxes =
safe_cast<array<System::Windows::Forms::TextBox^>^>(button->Tag);
String^ alias = textBoxes[0]->Text;
String^ name = textBoxes[1]->Text;
String^ port = textBoxes[2]->Text;
// Run DataConnector.exe silently without using cmd.exe
String^ executablePath = "C:\\Users\\hp\\source\\repos\\DataConnector
GUI\\DataConnector GUI\\DataConnector.exe";
System::Diagnostics::ProcessStartInfo^ processStartInfo = gcnew
System::Diagnostics::ProcessStartInfo(executablePath);
processStartInfo->WindowStyle =
System::Diagnostics::ProcessWindowStyle::Hidden;
processStartInfo->CreateNoWindow = true;
processStartInfo->UseShellExecute = false;
processStartInfo->RedirectStandardOutput = false;
processStartInfo->RedirectStandardError = false;
System::Diagnostics::Process::Start(processStartInfo);
// Install and start the service
InstallService(name, alias);
StartService(name);
// Save the service information to the database
SaveServiceToDatabase(name, alias, port, "Running");
// Update the UI panel
panel->Controls->Remove(button);
auto stopButton = gcnew System::Windows::Forms::Button();
stopButton->Text = L"Stop";
stopButton->Location = System::Drawing::Point(320, 30);
stopButton->Size = System::Drawing::Size(60, 20);
stopButton->Click += gcnew System::EventHandler(this,
&Form::OnStopButtonClick);
panel->Controls->Add(stopButton);
auto restartButton = gcnew System::Windows::Forms::Button();
restartButton->Text = L"Restart";
restartButton->Location = System::Drawing::Point(390, 30);
restartButton->Size = System::Drawing::Size(60, 20);
restartButton->Click += gcnew System::EventHandler(this,
&Form::OnRestartButtonClick);
panel->Controls->Add(restartButton);
auto deleteButton = gcnew System::Windows::Forms::Button();
deleteButton->Text = L"Delete";
deleteButton->Location = System::Drawing::Point(460, 30);
deleteButton->Size = System::Drawing::Size(60, 20);
deleteButton->Tag = panel;
deleteButton->Click += gcnew System::EventHandler(this,
&Form::OnDeleteButtonClick);
panel->Controls->Add(deleteButton);
}
void CreateServiceControlButtons(System::Windows::Forms::Panel^ panel,
String^ serviceName) {
auto stopButton = gcnew System::Windows::Forms::Button();
stopButton->Text = L"Stop";
stopButton->Location = System::Drawing::Point(10, 40);
stopButton->Size = System::Drawing::Size(60, 20);
stopButton->Click += gcnew System::EventHandler(this,
&Form::OnStopButtonClick);
panel->Controls->Add(stopButton);
auto restartButton = gcnew System::Windows::Forms::Button();
restartButton->Text = L"Restart";
restartButton->Location = System::Drawing::Point(80, 40);
restartButton->Size = System::Drawing::Size(60, 20);
restartButton->Click += gcnew System::EventHandler(this,
&Form::OnRestartButtonClick);
panel->Controls->Add(restartButton);
auto deleteButton = gcnew System::Windows::Forms::Button();
deleteButton->Text = L"Delete";
deleteButton->Location = System::Drawing::Point(150, 40);
deleteButton->Size = System::Drawing::Size(60, 20);
deleteButton->Tag = serviceName;
deleteButton->Click += gcnew System::EventHandler(this,
&Form::OnDeleteButtonClick);
panel->Controls->Add(deleteButton);
}
// Delete event handler
void Form::OnDeleteButtonClick(System::Object^ sender, System::EventArgs^
e) {
auto button = safe_cast<System::Windows::Forms::Button^>(sender);
auto panel = dynamic_cast<System::Windows::Forms::Panel^>(button->Tag);
// Get the alias, name, and port from the panel's TextBox controls
String^ alias = nullptr;
String^ name = nullptr;
String^ port = nullptr;
for each (auto control in panel->Controls) {
auto textBox =
dynamic_cast<System::Windows::Forms::TextBox^>(control);
if (textBox != nullptr) {
if (textBox->Name == "aliasTextBox") {
alias = textBox->Text;
}
else if (textBox->Name == "nameTextBox") {
name = textBox->Text;
}
else if (textBox->Name == "portTextBox") {
port = textBox->Text;
}
}
}
// Show confirmation dialog before deleting the service
System::Windows::Forms::DialogResult result = MessageBox::Show(
"Are you sure you want to delete this service?",
"Confirm Deletion",
MessageBoxButtons::OKCancel,
MessageBoxIcon::Warning
);
// If the user clicks "Cancel", stop the deletion process
if (result != System::Windows::Forms::DialogResult::OK) {
return;
}
// Stop the service before deleting (if applicable)
if (!String::IsNullOrEmpty(name)) {
StopService(name);
}
// Remove the panel from the UI
this->gatewayTab->Controls->Remove(panel);
int panelIndex = dynamicPanels->IndexOf(panel);
dynamicPanels->Remove(panel);
// Reposition remaining panels after deletion
for (int i = panelIndex; i < dynamicPanels->Count; ++i) {
auto currentPanel = dynamicPanels[i];
System::Drawing::Point newLocation = currentPanel->Location;
newLocation.Y -= 35;
currentPanel->Location = newLocation;
}
// Delete the service from services.msc
DeleteService(name);
// Delete the service record from the database
DeleteServiceFromDatabase(alias, name, port);
}
//Delete Service to Database
void DeleteServiceFromDatabase(String^ serviceName, String^ alias, String^
port) {
try {
std::string handler_ip = "127.0.0.1";
int handler_port = 8084;
// Construct SQL DELETE query
std::string sql_query = "DELETE FROM services WHERE service_name =
'" +
msclr::interop::marshal_as<std::string>(serviceName) + "' AND
port = '" +
msclr::interop::marshal_as<std::string>(port) + "';";
// Send the query to the Data Handler
std::string response = send_query_to_data_handler(sql_query,
handler_ip, handler_port);
// Log the response
std::cout << "Database Response: " << response << std::endl;
}
catch (const std::exception& ex) {
MessageBox::Show(gcnew String(ex.what()), "Error Deleting from
Database", MessageBoxButtons::OK, MessageBoxIcon::Error);
}
}
// Delete the service from services.msc
bool Form::DeleteService(String^ serviceName) {
try {
// Use 'sc delete' command to delete the service
String^ command = String::Format("sc delete \"{0}\"", serviceName);
// Execute the command
System::Diagnostics::Process^ process = gcnew
System::Diagnostics::Process();
process->StartInfo->FileName = "cmd.exe";
process->StartInfo->Arguments = "/c " + command;
process->StartInfo->WindowStyle =
System::Diagnostics::ProcessWindowStyle::Hidden;
process->Start();
process->WaitForExit();
// Check if the service was deleted successfully
if (process->ExitCode == 0) {
return true;
}
else {
MessageBox::Show("Failed to delete service.", "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
return false;
}
}
catch (Exception^ ex) {
MessageBox::Show("Error deleting service: " + ex->Message, "Error",
MessageBoxButtons::OK, MessageBoxIcon::Error);
return false;
}
}
// Event handler function to close the form
void Form::OnOkButtonClick(System::Object^ sender, System::EventArgs^ e) {
this->Close(); // Closes the form
}
};
}
in the above code service not created in the service.msc but without description
and status and also try to create or start or stop or restart or delete it also not
working please check what is issue in that and resolve all issue and reshare full
code in same structure which is maintained like storing and retriving from db and
according to that run services in service.msc
check all possible condition and solve all issue