public MainWindow() { PerfectWardAPI.Debug.Log("Connector started."); PerfectWardAPI.Debug.Log($"Version: {Assembly.GetExecutingAssembly().GetName().Version}"); var args = Environment.GetCommandLineArgs(); if (args.Length == 2) { if (args[1] == "-uninstall") { PerfectWardAPI.Debug.Log("Uninstall flag received."); PerfectWardAPI.Debug.Close(); PerfectWardAPI.Debug.Uninstall(); try { SetEnvironmentVariables(null, null, null, null, null); ManageService(false); var ts = Microsoft.Win32.TaskScheduler.TaskService.Instance; ts.RootFolder.DeleteTask(TaskName, false); } catch (Exception ex) { MessageBox.Show(ex.Message); } Environment.Exit(0); } } InitializeComponent(); TextChangedEventHandler pwTestCondition = (s, e) => { btnInstall.IsEnabled = false; btnTestPw.IsEnabled = txtEmail.Text.Length > 0 && txtAPIToken.Text.Length > 0; }; txtEmail.TextChanged += pwTestCondition; txtAPIToken.TextChanged += pwTestCondition; txtConnStr.TextChanged += (s, e) => { btnInstall.IsEnabled = false; btnTestSql.IsEnabled = txtConnStr.Text.Length > 0; }; RoutedEventHandler cc = (s, e) => { grpProxy.IsEnabled = chkPxyEnabled.IsChecked.Value; }; chkPxyEnabled.Checked += cc; chkPxyEnabled.Unchecked += cc; btnTestPw.Click += (s, e) => { var credentials = new StringCredentials(txtEmail.Text, txtAPIToken.Text); PerfectWardClient pwc; if (chkPxyEnabled.IsChecked.Value) { pwc = new PerfectWardClient(credentials, new System.Net.NetworkCredential(txtPxyUser.Text, txtPxyPass.Text)); } else { pwc = new PerfectWardClient(credentials); } grpPw.IsEnabled = false; txtPwStatus.Content = "Testing..."; txtPwStatus.Foreground = Brushes.Black; Task.Factory.StartNew(async() => { PerfectWardAPI.Debug.Log("Test API clicked."); try { SuccessAPI = await pwc.TestApi(); PerfectWardAPI.Debug.Log($"API test: {SuccessAPI}"); Dispatcher.Invoke(() => { if (SuccessAPI) { txtPwStatus.Content = "Success!"; txtPwStatus.Foreground = bruPwGreen; } else { grpPw.IsEnabled = true; txtPwStatus.Content = "Authentication failed"; txtPwStatus.Foreground = bruError; } btnInstall.IsEnabled = SuccessAPI && SuccessSQL; }); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); PerfectWardAPI.Debug.Log("Error in test API:\n" + ex); Environment.Exit(0); } }); }; btnTestSql.Click += (s, e) => { PerfectWardAPI.Debug.Log("Test SQL clicked."); try { var driver = DbDriver.Create(txtConnStr.Text); grpSql.IsEnabled = false; txtSqlStatus.Content = "Testing..."; txtSqlStatus.Foreground = Brushes.Black; Task.Factory.StartNew(() => { SuccessSQL = driver.TestConnection(); PerfectWardAPI.Debug.Log($"SQL test: {SuccessSQL}"); Dispatcher.Invoke(() => { if (SuccessSQL) { txtSqlStatus.Content = "Success!"; txtSqlStatus.Foreground = bruPwGreen; //driver.DropTables(); driver.CreateTables(); } else { grpSql.IsEnabled = true; txtSqlStatus.Content = "Connection failed"; txtSqlStatus.Foreground = bruError; } btnInstall.IsEnabled = SuccessAPI && SuccessSQL; }); }); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); PerfectWardAPI.Debug.Log("Error in test SQL:\n" + ex); Environment.Exit(0); } }; btnInstall.Click += (s, e) => { PerfectWardAPI.Debug.Log("Install clicked."); try { PerfectWardAPI.Debug.Log("Setting environment variables..."); SetEnvironmentVariables(txtEmail.Text, txtAPIToken.Text, txtPxyUser.Text, txtPxyPass.Text, txtConnStr.Text); ManageService(true); var cmd = $"{Environment.GetFolderPath(Environment.SpecialFolder.System)}\\cmd.exe"; PerfectWardAPI.Debug.Log("Scheduling task..."); var ts = Microsoft.Win32.TaskScheduler.TaskService.Instance; ts.RootFolder.DeleteTask(TaskName, false); var t = ts.AddTask( TaskName, new Microsoft.Win32.TaskScheduler.DailyTrigger(), new Microsoft.Win32.TaskScheduler.ExecAction(cmd, $"/c net start {ServiceName}"), "NT AUTHORITY\\SYSTEM", null, Microsoft.Win32.TaskScheduler.TaskLogonType.ServiceAccount, "Perfect Ward API Connector Task" ); MessageBox.Show("The API was connected.", "Success", MessageBoxButton.OK, MessageBoxImage.Information); PerfectWardAPI.Debug.Log($"Starting task..."); t.Run(); //Process.Start(new ProcessStartInfo(cmd, $"/c net start {ServiceName}")); MessageBox.Show("The reporting task has begun and will run in the background.", string.Empty, MessageBoxButton.OK, MessageBoxImage.Information); PerfectWardAPI.Debug.Log($"Quitting..."); Environment.Exit(0); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); PerfectWardAPI.Debug.Log("Error in install:\n" + ex); Environment.Exit(0); } }; Closed += (s, e) => { PerfectWardAPI.Debug.Log("Closing connector."); }; }
private async void DoWork() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException); Debug.Log("Background task started."); Debug.Log($"Version: {Assembly.GetExecutingAssembly().GetName().Version}"); var connStr = EnvironmentVariables.Get(EnvironmentVariables.SQLConnectionString); //Debug.Log($"{nameof(connStr)}: {connStr}"); if (string.IsNullOrEmpty(connStr)) { Debug.Log($"{nameof(connStr)} is null, quitting..."); Environment.Exit(-1); return; } var pwEmail = EnvironmentVariables.Get(EnvironmentVariables.PerfectWardEmail); //Debug.Log($"{nameof(pwEmail)}: {pwEmail}"); if (string.IsNullOrEmpty(pwEmail)) { Debug.Log($"{nameof(pwEmail)} is null, quitting..."); Environment.Exit(-1); return; } var pwToken = EnvironmentVariables.Get(EnvironmentVariables.PerfectWardToken); //Debug.Log($"{nameof(pwToken)}: {pwToken}"); if (string.IsNullOrEmpty(pwToken)) { Debug.Log($"{nameof(pwToken)} is null, quitting..."); Environment.Exit(-1); return; } Environment.CurrentDirectory = new FileInfo(Assembly.GetExecutingAssembly().CodeBase.Substring(8)).DirectoryName; var driver = DbDriver.Create(connStr); if (driver == null) { Debug.Log("No DB driver found, quitting."); Environment.Exit(-1); return; } Debug.Log($"DB driver found: {driver.GetType()}"); if (!driver.TestConnection()) { Debug.Log("Failed to connect to the database."); Environment.Exit(-1); return; } var creds = new StringCredentials(pwEmail, pwToken); var pwc = new PerfectWardClient(creds); if (!await pwc.TestApi()) { Debug.Log("Failed to connect to the API."); Environment.Exit(-1); return; } driver.CreateTables(); var existingIDs = driver.ListReportIDs(); var maxTimestamp = driver.GetLatestStartDate().ToTimeStamp(); var reportsResponse = await pwc.ListReportsSince(maxTimestamp); var reports = reportsResponse.Reports; if (reportsResponse.Meta != null) { int currentPage = reportsResponse.Meta.CurrentPage; int totalPages = reportsResponse.Meta.TotalPages; while (currentPage < totalPages) { if (AnnounceCancel()) { break; } reportsResponse = await pwc.ListReportsSince(maxTimestamp, ++currentPage); reports.AddRange(reportsResponse.Reports); } } reports = reports.Distinct(new ReportEqualityComparer()).Where(x => !existingIDs.Contains(x.Id)).OrderBy(x => x.Id).ToList(); Debug.Log($"Query returned reports: {reports.Count}"); var conn = driver.OpenConnection(); var reportsStack = new Queue <Report>(reports); while (reportsStack.Any()) { if (AnnounceCancel()) { break; } var report = reportsStack.Peek(); var drr = pwc.ReportDetails(report.Id).Result; driver.UploadReport(ref conn, drr); reportsStack.Dequeue(); } Debug.Log($"Finished uploading reports, terminating..."); conn.Close(); conn.Dispose(); TaskComplete.Set(); if (!AnnounceCancel()) { Stop(); } }