.EXE getting stuck after closing program with red X button built in to WPF program - exit

I'm sure this is being caused by one of the loops not shutting down right but i could be wrong. i know the X should close it all the way but it just gets stuck open.
I have tried to make it exit with out using the default X built in but it does not work, I would like to use the normal exit function but it just hangs open on my pc. I am having to reboot to get it to close. not even closing the process tree will close it out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data;
using System.Text.RegularExpressions;
using System.IO;
using System.Timers;
using System.Threading;
namespace Verifone_note_secure {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
richTextBox1.SpellCheck.IsEnabled = true;
richTextBox2.SpellCheck.IsEnabled = true;
richTextBox3.SpellCheck.IsEnabled = true;
richTextBox4.SpellCheck.IsEnabled = true;
richTextBox5.SpellCheck.IsEnabled = true;
richTextBox6.SpellCheck.IsEnabled = true;
textBox1.SpellCheck.IsEnabled = true;
Style noSpaceStyle = new Style(typeof(Paragraph));
noSpaceStyle.Setters.Add(new Setter(Paragraph.MarginProperty, new Thickness(0)));
richTextBox1.Resources.Add(typeof(Paragraph), noSpaceStyle);
richTextBox2.Resources.Add(typeof(Paragraph), noSpaceStyle);
richTextBox3.Resources.Add(typeof(Paragraph), noSpaceStyle);
richTextBox4.Resources.Add(typeof(Paragraph), noSpaceStyle);
richTextBox5.Resources.Add(typeof(Paragraph), noSpaceStyle);
richTextBox6.Resources.Add(typeof(Paragraph), noSpaceStyle);
textBox1.FontSize = 20;
Application.Current.MainWindow.Closing += new CancelEventHandler(MainWindow_Closing);
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 140);
dispatcherTimer.Start();
}
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private int iScroll;
private string strString;
StreamReader reader;
StreamWriter writer;
private void dispatcherTimer_Tick(object sender, EventArgs e) {
try {
reader = File.OpenText(#"ScrollingText.txt");
strString = reader.ReadToEnd();
if (strString.Length <= 1) {
reader.Close();
writer = File.CreateText(#"ScrollingText.txt");
writer.Write(" Please Enter your text into ScrollingText.txt for it to give you your personal messages ");
writer.Close();
reader = File.OpenText(#"ScrollingText.txt");
strString = reader.ReadToEnd();
}
} catch {
writer = File.CreateText(#"ScrollingText.txt");
writer.Write(" Please Enter your text into ScrollingText.txt for it to give you your personal messages ");
writer.Close();
reader = File.OpenText(#"ScrollingText.txt");
strString = reader.ReadToEnd();
}
iScroll = iScroll + 1;
int iLmt = strString.Length - iScroll;
if (iLmt < 56) {
iScroll = 0;
}
string str = strString.Substring(iScroll, 56);
label2.Content = str;
}
void MainWindow_Closing(object sender, CancelEventArgs e) {// when form closes
reader.Close();
}
private void KB_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void VeriWeb_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void Critrix_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void AmDocs_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void preescalationchecklist_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void Clearpumpsonhold_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void Clearreservedpumps_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void DCRPollError_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void DCRHold_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void Topazstuckonwhitescreen_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void UnabletologintoTopaz_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void Remoteserviceisdown_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void MX8xxpinpadcommunications_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void Monthlyclosestopsprinting_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void CommanderPuTTYcommands_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void COMMANDERECpleasechecksystemwdt_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("[enter image description here][1]");
}
private void fuelcommerrornofuelfunctionsnow_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void posfuelandsalesquickreference_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void commanderfueldcrconfiguration_Click(object sender, RoutedEventArgs e) {
System.Diagnostics.Process.Start("");
}
private void T3_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void ResponsetoVASCreturningcall_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void PinPadERS_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void ValeroCSTdispatchrequest_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void PantryDispatchRequest_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void GeneralDispatchTemplate_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void sppdispatch_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void DialInT2Template_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void VantageTemplate_Click(object sender, RoutedEventArgs e) {
richTextBox1.Document.Blocks.Clear();
richTextBox1.AppendText("");
}
private void exxon_Click(object sender, RoutedEventArgs e) {
Clipboard.SetText(Regex.Replace(exxon.Header.ToString(), "[A-Za-z : ]", ""));
}
private void ShellVantage_Click(object sender, RoutedEventArgs e) {
Clipboard.SetText(Regex.Replace(ShellVantage.Header.ToString(), "[A-Za-z : ]", ""));
}
private void Shell_Click(object sender, RoutedEventArgs e) {
Clipboard.SetText(Regex.Replace(Shell.Header.ToString(), "[A-Za-z : ]", "").Remove(12));
}
private void Plenti_Click(object sender, RoutedEventArgs e) {
Clipboard.SetText(Regex.Replace(Plenti.Header.ToString(), "[A-Za-z : ]", ""));
}
private void Worldpay_Click(object sender, RoutedEventArgs e) {
Clipboard.SetText(Regex.Replace(Worldpay.Header.ToString(), "[A-Za-z : ]", ""));
}
private void Hughe_Click(object sender, RoutedEventArgs e) {
Clipboard.SetText(Regex.Replace(Hughe.Header.ToString(), "[A-Za-z : ]", ""));
}
private void Chevron_Click(object sender, RoutedEventArgs e) {
Clipboard.SetText(Regex.Replace(Chevron.Header.ToString(), "[A-Za-z : ]", "").Remove(12));
}
private void Mako_Click(object sender, RoutedEventArgs e) {
Clipboard.SetText(Regex.Replace(Mako.Header.ToString(), "[A-Za-z : ]", ""));
}
private void PCcommander_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Power cycled Commander ");
}
private void PCFCI_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Power cycled Forecourt Controller ");
}
private void PCEZR_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Power cycled Enhanced Zone Router ");
}
private void PCsapphire_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Power cycle Sapphire ");
}
private void initDCR_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Initialized Dispenser Card reader ");
}
private void initFuel_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Initialized Fuel ");
}
private void reseatCables_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Reseated Cables ");
}
private void accessedPutty_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Accessed site via PuTTY # ");
}
private void configCheck_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("Check Configuration Client ");
}
private void CNG_Click(object sender, RoutedEventArgs e) {
richTextBox6.AppendText("Case number Given ");
}
private void CND_Click(object sender, RoutedEventArgs e) {
richTextBox6.AppendText("Case number Declined ");
}
private void CFcheckTR_Click(object sender, RoutedEventArgs e) {
richTextBox5.AppendText("CFcheck on Topaz/Ruby ");
}
private void button1_Click(object sender, RoutedEventArgs e) { //copy all button
string CopyAll = "";
string NewLine = "\n";
richTextBox2.SelectAll();
richTextBox3.SelectAll();
richTextBox4.SelectAll();
richTextBox5.SelectAll();
richTextBox6.SelectAll();
CopyAll += richTextBox2.Selection.Text + NewLine + richTextBox3.Selection.Text + NewLine + richTextBox4.Selection.Text + NewLine + richTextBox5.Selection.Text + NewLine + richTextBox6.Selection.Text;
Clipboard.SetText(CopyAll);
}
private void button7_Click(object sender, RoutedEventArgs e) {//clear all button
//if (System.DateTime.Now > new System.DateTime(2015, 10, 30)) {
// MessageBox.Show("Please contact tech support, for new trial version", "Trial Expired!!", MessageBoxButton.OK, MessageBoxImage.Warning);
// Application.Current.Shutdown();
//}
if (MessageBox.Show("Do you really want to Clear All?\nThis includes the clipboard", "Warning!", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) {
richTextBox1.Document.Blocks.Clear();
richTextBox2.Document.Blocks.Clear();
richTextBox3.Document.Blocks.Clear();
richTextBox4.Document.Blocks.Clear();
richTextBox5.Document.Blocks.Clear();
richTextBox6.Document.Blocks.Clear();
textBox1.Clear();
Clipboard.Clear();
}
}
private void button8_Click(object sender, RoutedEventArgs e) {//copy name
textBox1.SelectAll();
textBox1.Copy();
}
private void button9_Click(object sender, RoutedEventArgs e) {//copy template area
richTextBox1.SelectAll();
richTextBox1.Copy();
}
private void button2_Click(object sender, RoutedEventArgs e) {//copy box 1
richTextBox2.SelectAll();
richTextBox2.Copy();
}
private void button3_Click(object sender, RoutedEventArgs e) {//copy box 2
richTextBox3.SelectAll();
richTextBox3.Copy();
}
private void button4_Click(object sender, RoutedEventArgs e) {//copy box 3
richTextBox4.SelectAll();
richTextBox4.Copy();
}
private void button5_Click(object sender, RoutedEventArgs e) {//copy box 4
richTextBox5.SelectAll();
richTextBox5.Copy();
}
private void button6_Click(object sender, RoutedEventArgs e) {//copy box 5
richTextBox6.SelectAll();
richTextBox6.Copy();
}
private void button10_Click(object sender, RoutedEventArgs e) {
RichTextBox[] rTextBox = { richTextBox1, richTextBox2, richTextBox3, richTextBox4, richTextBox5, richTextBox6 };
overallTextReplace(rTextBox);
}
public void overallTextReplace(RichTextBox[] rtb) {
string[] keyword = { "FCI", "CND", "CNG", "DCR", "EZR", "VASC", "PC", "SFC" };
string[] newString = { "Forecourt Controller", "Case Number Declined ", "Case Number Given", "Dispenser Card reader", "Enhanced Zone Router", "Verifone Authorized Service Contractor", "Power cycle", "Smart Fuel Controller" };
for (int i = 0; i < rtb.Length; i++) {
RichTextBox rtb_wording = rtb[i];
var textRange = new TextRange(rtb_wording.Document.ContentStart, rtb_wording.Document.ContentEnd);
string rtf;
using (var memoryStream = new MemoryStream()) {
textRange.Save(memoryStream, DataFormats.Rtf);
rtf = ASCIIEncoding.Default.GetString(memoryStream.ToArray());
}
for (int j = 0; j < keyword.Length; j++) {
rtf = rtf.Replace(keyword[j], newString[j]);
}
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(rtf));
rtb_wording.SelectAll();
rtb_wording.Selection.Load(stream, DataFormats.Rtf);
}
}
}
}

Related

How to control DC motor via Arduino and Visual C++

I have the following situation. I try to control a DC motor via arduino IDE and window application made in Visual C++ 2017. I'm using a serial port to process the data from Visual Studio into Arduino. Here's the things I want to achieve:
I'm using mouse_down event (when I click the button with a mouse, something happens), but it sends just one sign (U, D, R, L) during a pressing, causing a DC motor to move just a little bit. How do I make it run and send the char untill the button is released? Should I use some kind of a loop?
I try to control it the same way, using a num keys on keyboard. The thing is, keys are not functional, untill the focus is put on them (they are pressed by/hovered by mouse). Is there a way to get rid of focus?
Thank you for your help.
Control panel
Code snippet for
arduino code
data=Serial.read();
analogWrite(motorPin1,motorSpeed);
analogWrite(motorPin2,motorSpeed);
xValues=analogRead(xPin);
if((xValues>xIdleHigh) or (data=='R')) {
motorSpeed=map(xValues,xIdleHigh,xRight,motorSpeedLow,motorSpeedHigh);
analogWrite(motorPin1,motorSpeed);
analogWrite(motorPin2,motorSpeedLow);
Serial.print("TURNING RIGHT...");
Serial.print("\n");
delay(50);
}
xValues=analogRead(xPin);
if((xValues<xIdleLow) or (data=='L')) {
motorSpeed=map(xValues,xIdleLow,xLeft,motorSpeedLow,motorSpeedHigh);
analogWrite(motorPin1,motorSpeedLow);
analogWrite(motorPin2,motorSpeed);
Serial.print("TURNING LEFT...");
Serial.print("\n");
delay(50);
}
yValues=analogRead(yPin);
if((yValues<=yUp) or (data=='U')) {
if(pos<150) {
pos+=1;
}
Serial.print("BARREL UP");
Serial.print("\n");
delay(50);
} else if((yValues>=yDown) or (data=='D')) {
if(pos>30) {
pos-=1;
}
Serial.print("BARREL DOWN");
Serial.print("\n");
delay(50);
}
servo.write(pos);
delay(50);`
Code snippet for
visual studio code
private: System::Void button1_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
if (e->KeyCode == Keys::NumPad6) {
serialPort1->Open();
serialPort1->Write("R");
serialPort1->Close();
}
}
private: System::Void button1_KeyUp(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
if (e->KeyCode == Keys::NumPad6) {
serialPort1->Open();
serialPort1->Write("X");
serialPort1->Close();
}
}
private: System::Void button1_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
serialPort1->Open();
serialPort1->Write("R");
serialPort1->Close();
}
private: System::Void button1_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
serialPort1->Open();
serialPort1->Write("X");
serialPort1->Close();
}
private: System::Void button2_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
if (e->KeyCode == Keys::NumPad4) {
serialPort1->Open();
serialPort1->Write("L");
serialPort1->Close();
}
}
private: System::Void button2_KeyUp(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
if (e->KeyCode == Keys::NumPad4) {
serialPort1->Open();
serialPort1->Write("X");
serialPort1->Close();
}
}
private: System::Void button2_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
serialPort1->Open();
serialPort1->Write("L");
serialPort1->Close();
}
private: System::Void button2_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
serialPort1->Open();
serialPort1->Write("X");
serialPort1->Close();
}
private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button3_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
serialPort1->Open();
serialPort1->Write("U");
serialPort1->Close();
}
private: System::Void button4_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
serialPort1->Open();
serialPort1->Write("D");
serialPort1->Close();
}`

How to call a request to a server with period and send it again if response was invalid?

I'm writing a simple client for a web service for my personal training. And I decided to do it with Qt. I'm using version 5.7. I managed to overcome troubles with sending and receiving requests from a server. But there is still a problem.
I have a slot on_scanButton_click() which, depending on what radio button is checked calls some request to a server. My problem is how to send another request to a server after first one with a period so that I could check if response_code in valid and I can call separate window for it.
This is my mainwindow.cpp
#include "mainwindow.h"
#include "networkmanager.h"
#include "commentdialog.h"
#include "rescanfiledialog.h"
#include "filebrowser.h"
#include "program_exceptions.h"
#include "overlaywidget.h"
#include <QMessageBox>
#include <regex>
MainWindow::MainWindow(QWidget* parent) :
QMainWindow{parent} {
ui.setupUi(this);
ui.fileRadioButton->setFixedWidth(100);
ui.urlRadioButton->setFixedWidth(100);
ui.searchRadioButton->setFixedWidth(100);
ui.stringFormater->setFixedSize(500, 30);
ui.stringFormater->setPlaceholderText("No file selected");
ui.uploadButton->setFixedHeight(30);
ui.scanButton->setFixedSize(120, 50);
ui.rescanButton->setFixedSize(120, 50);
ui.commentButton->setFixedSize(120, 50);
}
void MainWindow::changeEvent(QEvent* e) {
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui.retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::on_scanButton_clicked() {
NetworkManager* network_manager{new NetworkManager};
QString input_string = ui.stringFormater->text();
try {
if (ui.fileRadioButton->isChecked()) {
if (std::regex_match(input_string.toStdString(), std::regex("^(.*/)([^/]*)$"))) {
network_manager->scanFileRequest(input_string);
} else {
throw InvalidFilePathException();
}
} else if (ui.urlRadioButton->isChecked()) {
if (std::regex_match(input_string.toStdString(),
std::regex("^(ht{2}ps?:\\/{2})?(w{3}\\.)?([^:\\/\\.\\s]+)\\.([^:\\/\\.\\s]+)$"))) {
network_manager->scanUrlRequest(input_string);
} else {
throw InvalidUrlNameException();
}
} else if (ui.searchRadioButton->isChecked()) {
if (!std::regex_match(input_string.toStdString(), std::regex("([^:\\/\\.\\s]+)\\.([^:\\/\\.\\s]+)$"))) {
if (!std::regex_match(input_string.toStdString(), std::regex("^(([0-9]{1,3})\\.){3}([0-9]{1,3})$"))) {
throw InvalidIpAddressException();
} else {
network_manager->retrieveIpReportRequest(input_string);
}
throw InvalidDomainNameException();
} else {
network_manager->retrieveDomainReportRequest(input_string);
}
}
} catch (std::exception& ex) {
QString exception_message{ex.what()};
QMessageBox::warning(this, "Warning", exception_message);
}
ui.stringFormater->clear();
}
void MainWindow::on_fileRadioButton_clicked() {
ui.stringFormater->setPlaceholderText("No file selected");
ui.uploadButton->setText("Choose File");
ui.scanButton->setText("Scan it!");
ui.stringFormater->clear();
}
void MainWindow::on_urlRadioButton_clicked() {
ui.stringFormater->setPlaceholderText("http://example.com");
ui.uploadButton->setText("Enter URL");
ui.scanButton->setText("Scan it!");
ui.stringFormater->clear();
}
void MainWindow::on_searchRadioButton_clicked() {
ui.stringFormater->setPlaceholderText("hash, URL, domain, IP address...");
ui.uploadButton->setText("Enter Term");
ui.scanButton->setText("Search it!");
ui.stringFormater->clear();
}
void MainWindow::on_uploadButton_clicked() {
if (ui.fileRadioButton->isChecked()) {
FileBrowser* file_browser{new FileBrowser(this)};
file_browser->exec();
ui.stringFormater->setText(file_browser->getFilePath());
file_browser->setFilePath("");
}
}
void MainWindow::on_rescanButton_clicked() {
RescanFileDialog* rescan_file_doalog{new RescanFileDialog(this)};
rescan_file_doalog->exec();
}
void MainWindow::on_commentButton_clicked() {
CommentDialog* comment_dialog{new CommentDialog(this)};
comment_dialog->exec();
}
Here goes networkmanager.h.
#ifndef NETWORKMANAGER_H
#define NETWORKMANAGER_H
#include <QtNetwork>
class NetworkManager : public QObject {
Q_OBJECT
private:
QString api_address{"https://www.virustotal.com/vtapi/v2"};
QByteArray api_key{"API KEY HERE"};
QNetworkAccessManager* network_manager{new QNetworkAccessManager(this)};
static QJsonObject json_response;
public:
explicit NetworkManager() {
connect(network_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
}
virtual ~NetworkManager() = default;
void scanFileRequest(const QString&);
void rescanFileRequest(const QString&);
void retrieveFileReportRequest(const QString&);
void scanUrlRequest(const QString&);
void retrieveUrlReportRequest(const QString&);
void retrieveIpReportRequest(const QString&);
void retrieveDomainReportRequest(const QString&);
void makeCommentRequest(const QString&, const QString&);
const static QJsonObject getJsonResponse() {
return json_response;
}
private slots:
void requestFinished(QNetworkReply*);
};
#endif // NETWORKMANAGER_H
And networkmanager.cpp.
#include "networkmanager.h"
#include "responses.h"
#include "status_codes.h"
#include "program_exceptions.h"
#include <QMessageBox>
#include <QTimer>
QJsonObject NetworkManager::json_response{};
void NetworkManager::scanFileRequest(const QString& absolute_file_path) {
const QFileInfo file_info{absolute_file_path};
QHttpMultiPart* multi_part{new QHttpMultiPart(QHttpMultiPart::FormDataType)};
QHttpPart api_key_part{};
api_key_part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"apikey\""));
api_key_part.setBody(api_key);
QHttpPart file_part{};
QMimeDatabase db{};
QMimeType mime_message{db.mimeTypeForFile(file_info)};
file_part.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(mime_message.name()));
file_part.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"file\"; filename=\"" + file_info.fileName() + "\""));
QFile* file{new QFile(absolute_file_path)};
try {
if (!file->open(QIODevice::ReadOnly)) {
throw FileDoesNotExistException();
}
} catch (std::exception& ex) {
QMessageBox message_box{QMessageBox::Warning, "Warning", QObject::tr(ex.what()),
QMessageBox::NoButton, 0, Qt::FramelessWindowHint};
message_box.exec();
}
file_part.setBodyDevice(file);
file->setParent(multi_part);
multi_part->append(api_key_part);
multi_part->append(file_part);
QNetworkRequest request{QUrl{api_address + "/file/scan"}};
network_manager->post(request, multi_part);
}
void NetworkManager::rescanFileRequest(const QString& resource) {
QUrlQuery query_set{};
query_set.addQueryItem("apikey", api_key);
query_set.addQueryItem("resource", resource);
QUrl post_params{};
post_params.setQuery(query_set);
QByteArray post_data{post_params.toEncoded(QUrl::RemoveFragment)};
post_data.remove(0, 1);
QNetworkRequest request{QUrl{api_address + "/file/rescan"}};
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
network_manager->post(request, post_data);
}
void NetworkManager::retrieveFileReportRequest(const QString& resource) {
QUrl url{api_address + "/file/report"};
QUrlQuery query_set{};
query_set.addQueryItem("apikey", api_key);
query_set.addQueryItem("resource", resource);
url.setQuery(query_set.query());
QNetworkRequest request{url};
network_manager->get(request);
}
void NetworkManager::scanUrlRequest(const QString& url) {
QUrlQuery query_set{};
query_set.addQueryItem("apikey", api_key);
query_set.addQueryItem("url", url);
QUrl post_params{};
post_params.setQuery(query_set);
QByteArray post_data{post_params.toEncoded(QUrl::RemoveFragment)};
post_data.remove(0, 1);
QNetworkRequest request{QUrl{api_address + "/url/scan"}};
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
network_manager->post(request, post_data);
}
void NetworkManager::retrieveUrlReportRequest(const QString& resource) {
QUrlQuery query_set{};
query_set.addQueryItem("apikey", api_key);
query_set.addQueryItem("resource", resource);
QUrl post_params{};
post_params.setQuery(query_set);
QByteArray post_data{post_params.toEncoded(QUrl::RemoveFragment)};
post_data.remove(0, 1);
QNetworkRequest request{QUrl{api_address + "/url/report"}};
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
network_manager->post(request, post_data);
}
void NetworkManager::retrieveIpReportRequest(const QString& ip) {
QUrl url{api_address + "/ip-address/report"};
QUrlQuery query_set{};
query_set.addQueryItem("apikey", api_key);
query_set.addQueryItem("ip", ip);
url.setQuery(query_set.query());
QNetworkRequest request{url};
network_manager->get(request);
}
void NetworkManager::retrieveDomainReportRequest(const QString& domain) {
QUrl url{api_address + "/domain/report"};
QUrlQuery query_set{};
query_set.addQueryItem("apikey", api_key);
query_set.addQueryItem("domain", domain);
url.setQuery(query_set.query());
QNetworkRequest request{url};
network_manager->get(request);
}
void NetworkManager::makeCommentRequest(const QString& resource, const QString& comment) {
QUrlQuery query_set{};
query_set.addQueryItem("apikey", api_key);
query_set.addQueryItem("resource", resource);
query_set.addQueryItem("comment", comment);
QUrl post_params{};
post_params.setQuery(query_set);
QByteArray post_data{post_params.toEncoded(QUrl::RemoveFragment)};
post_data.remove(0, 1);
QNetworkRequest request{QUrl{api_address + "/comments/put"}};
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
network_manager->post(request, post_data);
}
void NetworkManager::requestFinished(QNetworkReply* reply) {
try {
http_status_code_t server_reply{static_cast<http_status_code_t>(
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt())};
if (server_reply == OK) {
QJsonObject json_object = QJsonDocument::fromJson(reply->readAll()).object();
response_code_t response_code{static_cast<response_code_t>(json_object["response_code"].toInt())};
std::string verbose_msg{json_object["verbose_msg"].toString().toStdString()};
if (response_code == ITEM_IS_PRESENT) {
json_response = json_object;
qDebug() << json_response;
} else if (response_code == ITEM_IS_STILL_IN_QUEUE) {
throw RequestStillInQueueException(verbose_msg);
} else if (response_code == ITEM_DOES_NOT_EXIST) {
throw ItemDoesNotExistException(verbose_msg);
} else {
throw UnknownResponseCodeException();
}
} else if (server_reply == API_REQUEST_LIMIT_EXCEEDED) {
throw PublicAPIRequestRateExceededException();
} else if (server_reply == FORBIDDEN) {
throw ForbiddenException();
} else {
throw UnknownHttpStatusCodeException();
}
} catch (std::exception& ex) {
QMessageBox message_box{QMessageBox::Warning, "Warning", QObject::tr(ex.what()),
QMessageBox::NoButton, 0, Qt::FramelessWindowHint};
message_box.exec();
}
}
So the question is where i have to put my QTimer, which will send retrieveXXXXRequest() function every 15 seconds till it gets response code what I need.
This is a link on github for more deep understanding.
https://github.com/lieroz/VirusTotalClient/tree/develop
So the answer was very easy. I will post a solution here.
just changed some lines in networkmanager.cpp in requestFinished function.
void NetworkManager::requestFinished(QNetworkReply* reply) {
try {
http_status_code_t server_reply{static_cast<http_status_code_t>(
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt())};
if (server_reply == OK) {
QJsonObject json_object = QJsonDocument::fromJson(reply->readAll()).object();
response_code_t response_code{static_cast<response_code_t>(json_object["response_code"].toInt())};
std::string verbose_msg{json_object["verbose_msg"].toString().toStdString()};
if (response_code == ITEM_IS_PRESENT) {
qDebug() << json_object;
if (verbose_msg == "Scan finished, information embedded") {
auto antiviruses = json_object["scans"].toObject().keys();
auto values = json_object["scans"].toObject();
for (auto antivirus : antiviruses) {
qDebug() << antivirus;
auto keys = values.value(antivirus).toObject().keys();
for (auto key : keys) {
qDebug() << key << " : " << values.value(antivirus).toObject().value(key);
}
}
return;
}
QTimer::singleShot(15000, this, [=]{
retrieveFileReportRequest(json_object["resource"].toString());
});
} else {
qDebug() << json_object;
QTimer::singleShot(15000, this, [=]{
retrieveFileReportRequest(json_object["resource"].toString());
});
}
} else if (server_reply == API_REQUEST_LIMIT_EXCEEDED) {
throw PublicAPIRequestRateExceededException();
} else if (server_reply == FORBIDDEN) {
throw ForbiddenException();
} else {
throw UnknownHttpStatusCodeException();
}
} catch (std::exception& ex) {
QMessageBox message_box{QMessageBox::Warning, "Warning", QObject::tr(ex.what()),
QMessageBox::NoButton, 0, Qt::FramelessWindowHint};
message_box.exec();
}
}

Generation of exe file in windows forms using c++

I have developed a console application which reads the values from csv file and updates it in .c file in a specific location. I need to extend it and create an exe file for better GUI. But the same code which works for console application is throwing errors in visual studio 2010 windows forms. Commands like getline, eof(), file.open are throwing errors. I am beginner in coding and any kind of help would be appreciated.
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include "stdafx.h"
namespace Application1
{
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
/// <summary>
/// Summary for Form1
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::OpenFileDialog^ openFileDialog1;
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::Button^ button3;
protected:
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog());
this->button2 = (gcnew System::Windows::Forms::Button());
this->button3 = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(197, 82);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 42);
this->button1->TabIndex = 0;
this->button1->Text = L"browse excel file";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// openFileDialog1
//
this->openFileDialog1->FileName = L"openFileDialog1";
//
// button2
//
this->button2->Location = System::Drawing::Point(197, 193);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(75, 23);
this->button2->TabIndex = 2;
this->button2->Text = L"Run";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
//
// button3
//
this->button3->Location = System::Drawing::Point(197, 150);
this->button3->Name = L"button3";
this->button3->Size = System::Drawing::Size(75, 23);
this->button3->TabIndex = 3;
this->button3->Text = L"browse c file";
this->button3->UseVisualStyleBackColor = true;
this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(284, 262);
this->Controls->Add(this->button3);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
openFileDialog1->Filter = "Csv Files|*.csv";
openFileDialog1->Title = "Select a Csv File";
if(openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
System::IO::StreamReader ^ sr = gcnew
System::IO::StreamReader(openFileDialog1->FileName);
MessageBox::Show(sr->ReadToEnd());
sr->Close();
}
}
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
openFileDialog1->Filter = "C Files|*.c";
openFileDialog1->Title = "Select a C File";
if(openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
System::IO::StreamReader ^ sr = gcnew
System::IO::StreamReader(openFileDialog1->FileName);
sr->Close();
}
}
private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
String ^ s1, ^ s2, ^ s3;
String ^ filename, ^ text, ^ line;
String ^ cfilename,^ funcname, ^ signal, ^ value;
String ^ line1, ^ line2;
StreamReader ^ file=gcnew StreamReader(filename);
{
while(getline(file, cfilename, ',') && getline(file, funcname, ',')
&& getline(file, signal, ',') && getline(file, value, '\n'))
{
s1=signal; s2=value;
s2 = s2 + "; //";
int offset, inset;
String ^ line;
StreamWriter ^ cfile=gcnew StreamWriter(cfilename);
//fstream ^ cfile(cfilename);
StreamWriter ^ fileOutput=gcnew StreamWriter("output.c");
//fstream ^ fileOutput;
fileOutput->open("output.c");
if(cfile->OpenFile() && fileOutput->OpenFile())
{
while(!cfile->eof())
{
if (getline(cfile, line))
{
if((offset = line->find(funcname, 0)) != string::npos)
{
MessageBox::Show("found: " << funcname);
fileOutput->WriteLine(line);
while(getline(cfile,line1))
{
if((inset=line1.find(s1, 0)) !=string::npos)
{
MessageBox::Show("found: " << s1);
string ^ s3 = s1+ "=" +s2;
MessageBox::Show(s3);
line1->replace( inset, inset+s1.size(), s3 );
}
fileOutput->Writeline(line1);
}
}
fileOutput->Writeline(line);
}
}
}
cfile->close();
fileOutput->close();
cfile->open(cfilename);
fileOutput->open("output.c");
if(cfile.is_open() && fileOutput.is_open())
while(getline(fileOutput,line2))
cfile->Writeline(line2);
cfile->close();
fileOutput->close();
}
}
file->close();
remove("output.c");
getchar();
return 0;
}
}
;}
}
My working C++ console application code is as below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string s1, s2, s3;
string filename, text, line;
string cfilename,funcname, signal, value;
string line1,line2;
cout << "Enter excel filename" << endl;
cin >> filename;
fstream file(filename);
if (!file) {
cerr << "No such file exists or the file is open." << endl;
exit(1);
}
if(file.is_open())
{
while(getline(file, cfilename, ',') && getline(file, funcname, ',')
&& getline(file, signal, ',') && getline(file, value, '\n'))
{
cout << cfilename << '\t' << funcname << '\t' << signal << '\t' << value << '\n';
string s1=signal,s2=value;
s2 = s2 + "; //";
int offset, inset;
string line;
fstream cfile(cfilename);
fstream fileOutput;
fileOutput.open("output.c");
if(cfile.is_open() && fileOutput.is_open())
{
while(!cfile.eof())
{
if (getline(cfile, line))
{
if((offset = line.find(funcname, 0)) != string::npos)
{
cout << "found: " << funcname << endl;
fileOutput << line << '\n';
while(getline(cfile,line1))
{
if((inset=line1.find(s1, 0)) !=string::npos )
{
cout<<"found: " << s1 << endl;
string s3 = s1+ "=" +s2;
cout<<s3<<'\n';
line1.replace( inset, inset+s1.size(), s3 );
}
fileOutput << line1 << '\n';
}
}
fileOutput << line << '\n';
}
}
}
cfile.close();
fileOutput.close();
cfile.open(cfilename);
fileOutput.open("output.c");
if(cfile.is_open() && fileOutput.is_open())
while(getline(fileOutput,line2))
cfile<<line2<<'\n';
cfile.close();
fileOutput.close();
}
}
file.close();
getchar();
return 0;
}
C++ CLI project what you are using is able to compile native c++ code and also managed c++ code. Your code doesn't compile just because you try to call e.g. std::getline(System::String^, ...), what is calling native c++ function with managed c++ parameter. It is possible to use std::getline, but you have to use std::string instead. I have changed your code, that way you will be able to compile it. I have removed StreamReader because then you won't need to mess with opening closing the files.
Form1.h
#pragma once
namespace Application1
{
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1();
protected:
~Form1();
private: System::Void Run(System::String^ FileName, System::String^ OutputFileName);
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e);
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e);
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e);
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::OpenFileDialog^ openFileDialog1;
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::Button^ button3;
private: System::ComponentModel::Container^ components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog());
this->button2 = (gcnew System::Windows::Forms::Button());
this->button3 = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(197, 82);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 42);
this->button1->TabIndex = 0;
this->button1->Text = L"browse excel file";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// openFileDialog1
//
this->openFileDialog1->FileName = L"openFileDialog1";
//
// button2
//
this->button2->Location = System::Drawing::Point(197, 193);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(75, 23);
this->button2->TabIndex = 2;
this->button2->Text = L"Run";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
//
// button3
//
this->button3->Location = System::Drawing::Point(197, 150);
this->button3->Name = L"button3";
this->button3->Size = System::Drawing::Size(75, 23);
this->button3->TabIndex = 3;
this->button3->Text = L"browse c file";
this->button3->UseVisualStyleBackColor = true;
this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(284, 262);
this->Controls->Add(this->button3);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Name = L"Form1";
this->Text = L"Form1";
this->ResumeLayout(false);
}
#pragma endregion
};
}
Form1.cpp
#include "stdafx.h"
#include "Form1.h"
namespace Application1
{
Form1::Form1()
{
InitializeComponent();
}
Form1::~Form1()
{
if (components)
delete components;
}
System::Void Form1::button1_Click(System::Object^ sender, System::EventArgs^ e)
{
openFileDialog1->Filter = "Csv Files|*.csv";
openFileDialog1->Title = "Select a Csv File";
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
System::String^ FileName = openFileDialog1->FileName;
System::String^ FileContent = System::IO::File::ReadAllText(FileName);
System::Windows::Forms::MessageBox::Show(FileContent);
}
}
System::Void Form1::button2_Click(System::Object^ sender, System::EventArgs^ e)
{
openFileDialog1->Filter = "Csv Files|*.csv";
openFileDialog1->Title = "Select a Csv File";
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
Run(openFileDialog1->FileName, "Output.txt");
}
}
System::Void Form1::button3_Click(System::Object^ sender, System::EventArgs^ e)
{
openFileDialog1->Filter = "C Files|*.c";
openFileDialog1->Title = "Select a C File";
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
// TODO
}
}
System::Void Form1::Run(System::String^ FileName, System::String^ OutputFileName)
{
if (!System::IO::File::Exists(FileName))
{
System::Windows::Forms::MessageBox::Show("File '" + FileName + "' doesn't exists");
return;
}
array<System::String^>^ InputLines = System::IO::File::ReadAllLines(FileName);
System::Collections::Generic::List<System::String^>^ OutputLines = gcnew System::Collections::Generic::List<System::String^>();
// do your procesing here
for (int i=0; i<InputLines->Length; i++)
{
System::String^ OutputLine = "";
// sample code
if (InputLines[i]->Contains("abc"))
OutputLine += InputLines[i] + "test";
OutputLines->Add(OutputLine);
}
// save output
System::IO::File::WriteAllLines(OutputFileName, OutputLines);
}
}
Btw, you definitely have to work on your coding style :)

Reconnect asio connection when the server is alive

I want to keep an asio connection responsive, that I mean to check the server every second till it become alive and then send and receive. Here is my code
---irunnable.h---
#ifndef IRUNNABLE_H
#define IRUNNABLE_H
#include <condition_variable>
#include <atomic>
#include <thread>
class IRunnable
{
public:
IRunnable(): mThread(nullptr) {
mRunning.store(false);
}
virtual ~IRunnable() {
if (mRunning.load())
Stop();
delete mThread;
}
virtual void Start() {
mRunning.store(true);
mThread = new std::thread(&IRunnable::Run, this);
}
virtual void Stop() {
mRunning.store(false);
if (mThread && mThread->joinable())
mThread->join();
}
virtual bool IsRunning() {return mRunning.load();}
protected:
virtual void Run() = 0;
std::atomic<bool> mRunning;
private:
std::thread *mThread;
};
#endif // IRUNNABLE_H
---mytcpconnection.h---
#ifndef MYTCPCONNECTION_H
#define MYTCPCONNECTION_H
#include <asio/io_service.hpp>
#include <asio/ip/tcp.hpp>
#include "irunnable.h"
class MyTCPConnection : public IRunnable
{
public:
MyTCPConnection(const std::string &ip, const std::string &port);
~MyTCPConnection();
void Stop();
void Write(const std::string &msg);
void Connect();
protected:
void Run();
private:
void readHeader();
private:
std::string mIP;
std::string mPort;
asio::io_service mIOService;
asio::ip::tcp::socket mSocket;
};
#endif // MYTCPCONNECTION_H
---mytcpconnection.cpp
#include "mytcpconnection.h"
#include <iostream>
#include <asio/connect.hpp>
#include <asio/write.hpp>
#include <asio/read.hpp>
MyTCPConnection::MyTCPConnection(const std::string &ip, const std::string &port):
mIP(ip),
mPort(port),
mSocket(mIOService)
{
Connect();
}
MyTCPConnection::~MyTCPConnection()
{
Stop();
}
void MyTCPConnection::Stop()
{
mIOService.stop();
mSocket.close();
IRunnable::Stop();
}
void MyTCPConnection::Write(const std::string &msg)
{
asio::async_write(mSocket,
asio::buffer(msg.c_str(),
msg.length()),
[this, msg](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
std::cout << msg << std::endl;
}
else
{
mSocket.close();
}
});
}
void MyTCPConnection::Run()
{
while (mRunning.load()) {
sleep(1);
// Connect();
std::cout << "before run\n";
mIOService.run();
std::cout << "after run\n";
}
}
void MyTCPConnection::Connect()
{
asio::ip::tcp::resolver resolver(mIOService);
asio::async_connect(mSocket, resolver.resolve({mIP, mPort}),
[this](std::error_code ec, asio::ip::tcp::resolver::iterator)
{
if (!ec)
{
std::cout << "readHeader called\n";
readHeader();
}
else {
std::cout << "can not connect\n";
mSocket.close();
mIOService.reset();
std::cout << "after stopping io_service\n";
}
});
}
void MyTCPConnection::readHeader()
{
const int header_length = 16;
std::shared_ptr<char> msg(new char[header_length]{0},
[](char *c) {
delete[] c;
});
asio::async_read(mSocket,
asio::buffer(msg.get(), header_length),
[this, msg](std::error_code ec, std::size_t s/*length*/)
{
if (!ec)
{
std::cout << "Message read " << s << std::endl;
readHeader();
}
else
{
std::cout << "closing socket\n";
mSocket.close();
mIOService.stop();
}
});
}
---main.cpp---
#include <iostream>
#include "mytcpconnection.h"
using namespace std;
int main()
{
MyTCPConnection conn("127.0.0.1", "12345");
conn.Start();
while (true)
{
conn.Write("Hello server");
sleep(1);
}
return 0;
}
---server.go---
package main
import (
"time"
"fmt"
"net"
)
func handle_conn(conn net.Conn) {
b := make([]byte, 1028)
for {
n, err:= conn.Read(b)
if err != nil {
fmt.Println(err.Error())
break
}
fmt.Println(string(b[:n]))
_, _ = conn.Write([]byte("hellohellohello1"))
time.Sleep(time.Second*1)
}
}
func main() {
ln, err := net.Listen("tcp", ":12345")
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("server started")
for {
conn, err := ln.Accept()
fmt.Println("connection from", conn.RemoteAddr())
if err != nil {
fmt.Println(err.Error())
continue
}
go handle_conn(conn)
}
}
In this form, the client connects to the server (when the server is running) and keeps reading and writing. If I move the Connect() method in the mytcpconnection constructor to the Run() function (where it is commented now), the connection is not able to connect to the server.
How can I fix this problem?

can't update (or write continuously) counter in ther form's textbox

I'm intermediate c++ programmer. But new to Visual Studio GUI programming. Please believe me that I really searched previous errors that other user's also get, but really cant go on further. Thank u very much for further help.
I just want to see a continuous counter in small screen. When I push the Start button the counter must start until the Stop button is pushed.
I debug the forms project the window is shown but when I press the Start button I get the error:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information: Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.
I tried also the choice of code part in /* */ but again I cant do what I want.
#include <windows.h>
using namespace System;
using namespace System::Threading;
int formcounter, xx;
#pragma once
namespace denemeform {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
formcounter=0;
}
protected:
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
protected:
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::TextBox^ textBox1;
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->SuspendLayout();
this->button1->Location = System::Drawing::Point(27, 24);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 0;
this->button1->Text = L"&Start";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
this->button2->Location = System::Drawing::Point(166, 24);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(75, 23);
this->button2->TabIndex = 1;
this->button2->Text = L"Sto&p";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
this->textBox1->Location = System::Drawing::Point(82, 71);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(100, 20);
this->textBox1->TabIndex = 2;
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(269, 139);
this->Controls->Add(this->textBox1);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Name = L"Form1";
this->Text = L"Form1";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
void Test() //test code:: when "Start" is pushed, this code is what executes
{
int formcounter=0; //test variable
while(xx)
{
formcounter++;
this->textBox1->Text = formcounter.ToString(); //sets first textbox to 'a'
Sleep(100); //pause for 1 second before continuing
}
/*formcounter++;
if (this->InvokeRequired)
this->Invoke(gcnew MethodInvoker(this, &Form1::Test));
else
this->textBox1->Text = formcounter.ToString();
Sleep(1000);*/
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
xx=1;
/*Thread^ oThread = gcnew Thread( gcnew ThreadStart( this, &Form1::Test ) );
oThread->Start();*/
Thread^ tThread = gcnew Thread(gcnew ThreadStart(this, &Form1::Test));
tThread->Start();
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
xx=0;
}
};
}
The code now executes correctly.
void SetTextBoxOnce()
{
this->textBox1->Text = formcounter.ToString();
}
void Test()
{
formcounter=0; //test variable
while(xx)
{
formcounter++;
this->Invoke(gcnew MethodInvoker(this, &Form1::SetTextBoxOnce));
Sleep(100);
}
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
xx=1;
Thread^ tThread = gcnew Thread(gcnew ThreadStart(this, &Form1::Test));
tThread->Start();
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
xx=0;
}
The code now executes correctly.
You didn't say what happens when you use the commented out code, but I believe I see what's going on.
You do need to use InvokeRequired & this->Invoke, but you're passing the wrong thing to this->Invoke. You're passing a method with a loop in it (Form1::Test), and it isn't returning. You should pass a delegate that just sets the text box once.
Try moving formcounter to be a class field instead of a local variable, and do something like this:
bool xx;
int formcounter;
void SetTextBoxOnce()
{
this->textBox1->Text = formcounter->ToString();
}
void TestThread()
{
this->formcounter = 0;
while(xx)
{
this->formcounter++;
// We're running on a newly created thread, we know that we ALWAYS need to Invoke.
this->Invoke(gcnew MethodInvoker(this, &Form1::SetTextBoxOnce));
Thread::Sleep(1000);
}
}