I am creating a WPF application to use at work. I am a Studio QA Analyst for a Software/Game Development company and we do automation testing on our test racks. I am looking for a way to have the application connect to the server based on the IP Address the user inputs. Once the application connects to the server, then connect to the SQL Server. My UI has 3 Textbox's: Server IP, Device IP and Balance amount. I keep getting an error that it can't connect with the username provided and then shuts down once I click ok on the error message. I am learning as I go and understand my code may not look the best or be the most pretty and structured so please no comments of "You are doing that completely wrong" or "Why are you doing this when it is so much easier to do this". I am completely open to listen to people genuinely trying to help me or guide me. I just need a nudge in the right direction and I'll get it from there!
I tried to use RDP but could not get it setup to work. Currently I am trying to use Remote Desktop Connection to open a connection and it seems that has worked possibly. It's saying cannot connect but it's using the username for the SQL Server. I am not sure if somehow it is confused and trying to connect to the server with the SQL login or if it has connected to the server and is now failing the login for SQL. It errors out and crashes. I expected the username and password to work and log into SQL and then run my query but that has not happened. A couple times I have had the connection timed out message come up as well. My code will be listed below, please don't attack me.
using System.Windows;
using System.Windows.Threading;
using System.Windows.Input;
using System.Windows.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Threading;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
namespace BalanceUpdater
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
DragMove();
}
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void ExitButton_Click(Object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private bool ConnectToServer(string serverIp, string username, string password)
{
try
{
ConnectToServerViaRDP(serverIp, username, password);
using (SqlConnection serverConnection = new SqlConnection($"Data Source={serverIp};User ID=;Password=;"))
{
serverConnection.Open();
}
if (ConnectToSQLServer(serverIp, "", "", ""))
{
return true;
}
else
{
LogMessage($"{DateTime.Now} - Failed to connect to SQL Server on {serverIp}");
return false;
}
}
catch (Exception ex)
{
LogMessage($"{DateTime.Now} - Error connecting to {serverIp}: {ex.Message}\nStackTrace: {ex.StackTrace}");
return false; // Failed to connect to the server
}
}
private bool ConnectToSQLServer(string serverIp, string username, string password, string databaseName)
{
try
{
// Connection to the SQL Server
string connectionString = $"Data Source={serverIp};Initial Catalog=;User ID=;Password=";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
return true; // Successfully connected to the SQL Server
}
}
catch (Exception ex)
{
MessageBox.Show($"Error connecting to the SQL Server: {ex.Message}\nStackTrace: {ex.StackTrace}");
LogMessage($"Error connecting to the SQL Server: {ex.Message}\nStackTrace: {ex.StackTrace}");
return false; // Failed to connect to the SQL Server
}
}
private void ConnectToServerViaRDP(string serverIp, string user_name, string pass_word)
{
try
{
Process.Start("mstsc.exe", $"/v:{serverIp} /u:s /p:");
LogMessage($"Remote Desktop Connection launched to {serverIp}");
}
catch (Exception ex)
{
LogMessage($"{DateTime.Now} - Error launching Remote Desktop Connection to {serverIp}: {ex.Message}\nStackTrace: {ex.StackTrace}");
}
}
private void UpdateBalances_Click(object sender, RoutedEventArgs e)
{
try
{
string serverIp = ServerIpTextBox.Text;
string username = "";
string password = "";
using (SqlConnection serverConnection = new SqlConnection($"Data Source={serverIp};User ID={username};Password={password}"))
{
serverConnection.Open();
if (ConnectToSQLServer(serverIp, "", "", ""))
{
string ipAddressInput = DeviceListTextBox.Text;
string balanceInput = BalanceAmountTextBox.Text;
using (SqlConnection sqlConnection = new SqlConnection($"Data Source={serverIp};Initial Catalog=;User ID=;Password="))
{
sqlConnection.Open();
if (UpdateBalances(sqlConnection, ipAddressInput, balanceInput))
{
MessageBox.Show("Balances updated successfully.");
LogMessage("Balances updated successfully.");
}
else
{
MessageBox.Show("Failed to update balances. Verify IP's and balance is correct.");
LogMessage("Failed to update balances. Verify IP's and balance is correct.");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}");
LogMessage($"Error: {ex.Message}\nStackTrace: {ex.StackTrace}");
}
}
private bool UpdateBalances(SqlConnection connection, string ipAddressInput, string balanceInput)
{
string[] ipAddressArray = ipAddressInput.Split(',');
if (decimal.TryParse(balanceInput, out decimal newBalance))
{
try
{
connection.Open();
foreach (string ipAddress in ipAddressArray)
{
SqlCommand command = new SqlCommand($" USE UPDATE dbo. SET current_balance = @NewBalance WHERE machine_name = @IPAddress", connection);
command.Parameters.AddWithValue("@NewBalance", newBalance);
command.Parameters.AddWithValue("@IPAddress", ipAddress.Trim());
command.ExecuteNonQuery();
}
return true;
}
catch (Exception ex)
{
LogMessage($"Error: {ex.Message}\nStackTrace: {ex.StackTrace}");
MessageBox.Show($"Error: {ex.Message}");
return false;
}
}
else
{
MessageBox.Show("Invalid balance input. Please enter a numeric value.");
LogMessage($"Error: {"Invalid balance input. Please enter a numeric value."}");
return false;
}
}
private void LogMessage(string message)
{
string logDirectory = "C:;
string logFileName = "BalanceUpdaterLog.txt";
if (!Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
string logFilePath = Path.Combine(logDirectory, logFileName);
// This logs to the application log
File.AppendAllText(logFilePath, $"{DateTime.Now}: {message}\n");
// This logs to Event Viewer
EventLog eventLog = new EventLog("Application");
eventLog.Source = "BalanceUpdater";
eventLog.WriteEntry($"{DateTime.Now}: {message}", EventLogEntryType.Error);
}
}
}