When creating new class instance I get "A first chance exception of type 'System.Deployment.Application.InvalidDeploymentException' occurred in System.Deployment.dll".
It happens at:
PrinterSettings^ MyPS = gcnew PrinterSettings();
Everything works fine and I get a value I want.
Form1.cpp:
#include "stdafx.h"
#include "Form1.h"
#include "Print.h"
#include <iostream>
System::Void DPrint::Form1::Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
PrinterSettings^ MyPS = gcnew PrinterSettings();
System::Windows::Forms::MessageBox::Show("From Class PrinterSettings: " + MyPS->IniFilePath());
}
Print.h:
#ifndef PRINT_H
#define PRINT_H
public ref class PrinterSettings
{
private:
System::String^ m_strPath;
public:
PrinterSettings()
{
m_strPath = System::Windows::Forms::Application::UserAppDataPath;
}
System::String^ IniFilePath() { return m_strPath; };
};
#endif
Any ideas what is going on? Thank you.
This is a "first chance" exception, meaning the debugger observes an exception is thrown that may be handled. In this case, it is likely the application is trying to determine how the app is installed, such as via ClickOnce, to determine what your User app path is.
See What causes an InvalidDeploymentException in a WPF application? for a good explanation.
Related
I'm trying to create a program that, on execution, zips a given directory. Most of my errors have been resolved and I am hopefully getting to the end of this, but I still have the issue of an exception being thrown and a question regarding the program. I code in C++20 and on Visual Studio 2019.
I've come across this exact error when debugging the program:
Exception thrown at 0x76820B42 in aixLogger.exe: Microsoft C++ exception: bit7z::BitException at memory location 0x001AF440.
I already checked with a breakpoint what code is giving me this error:
catch (const BitException& ex) {
ex.what(); //<-
}
The code runs otherwise and isn't giving me any error messages, the breakpoint activates on the line I marked with an arrow (not actually part of my code).
To eliminate further possible edits I will add the rest of my code as well:
main.cpp
#include <QCoreApplication>
#include <string>
#include <iostream>
#include <filesystem>
#include <bit7z.hpp>
#include "main.h"
#include <bitcompressor.hpp>
namespace fs = std::filesystem;
using namespace bit7z;
using namespace std;
int main(int argc, char* argv[])
{
QCoreApplication a(argc, argv);
try {
Bit7zLibrary lib{ L"7z.dll" };
BitCompressor compressor{ lib, BitFormat::Zip };
//vector< wstring > files = { L"aretz/Downloads/test" };
wstring dir = { L"D: / local / aretz / Programmierung / git - workplace / aixLogger / test /" } ;
wstring zip = { L"zippedtest.zip" };
compressor.compressDirectory(dir, zip);
}
catch (const BitException& ex) {
ex.what();
}
return a.exec();
}
void AIXLogger::CompressDir() {
/*try {
Bit7zLibrary lib{ L"7z.dll" };
BitCompressor compressor{ lib, BitFormat::Zip };
vector< wstring > files = { L"C:/Users/aretz/Downloads/test" };
wstring zip = { L"zippedtest.zip" };
compressor.compressFiles(files, zip);
}
catch (const BitException& ex) {
ex;
}*/
}
main.h
#pragma once
#include <qwidget.h>
#include <qobject.h>
#include <bit7z.hpp>
class AIXLogger : public QWidget
{
Q_OBJECT
public slots:
public:
void CompressDir();
};
I've currently commented out the function CompressDir() as I can't call it in my main since it gives me either a syntax error or tells me the identifier is undefined.
Syntax Error:
AIXLogger.CompressDir(); the dot is marked as the error
identifier is undefined:
CompressDir();
I don't know what exactly is causing the catch to thrown an exception. From other posts I suspected that my paths for the files and directories are at fault, but changing them or moving my test directory didn't help at all. Removing the try and catch lines from my codeblock only adds the same error message where Exception Thrown is being replaced by Unhandled Exception. Thanks to anyone who can help.
I already checked with a breakpoint what code is giving me this error:
catch (const BitException& ex) {
ex.what(); //<-
}
The code runs otherwise and isn't giving me any error messages
The code isn't giving you any error message since you're not doing anything with the information provided by the thrown exception.
You're simply calling ex.what() without, for example, printing the error message string it returns, e.g., via std::cout.
the breakpoint activates on the line I marked with an arrow (not actually
part of my code).
I don't know what exactly is causing the catch to thrown an exception. From other posts I suspected that my paths for the files and directories are at fault, but changing them or moving my test directory didn't help at all.
The ex.what() error message should give you more details about the actual issue you're having.
By the way, I'm the author of the bit7z library, and from my experience and looking at the code you posted, I can think of some possible causes (the most common ones):
The program could not find the 7z.dll library.
Please ensure that the DLL is in the same directory as the executable or in one of the default DLL search paths of Windows.
The program could not find the directory path to be compressed.
As before, make sure that the path exists.
So I've got this interface class that I include, both in the dll and the client project
// InterfaceClass.h
#pragma once
class InterfaceClass
{
public:
virtual void Update() = 0;
};
This is the dll class that calls one of its own methods inside update
// DLLClassThatDoesSomething.cpp
#include "InterfaceClass.h"
#include <iostream>
#include <string>
class __declspec(dllexport) DLLClass : public InterfaceClass
{
public:
void Update()
{
std::cout << this->GetString();
}
std::string& GetString()
{
std::string thestring = "bruhmoment";
return thestring;
}
};
extern "C"
{
__declspec(dllexport) InterfaceClass* CreateInstance()
{
return new DLLClass();
}
}
And this is the "Client" project
// main.cpp
#include "InterfaceClass.h"
#include <Windows.h>
typedef InterfaceClass* (__cdecl *Class) ();
int main()
{
HINSTANCE dll = LoadLibrary(L"DLLClass.dll");
Class klass = (Class)GetProcAddress(dll, "CreateInstance");
InterfaceClass* IKlass = klass();
IKlass->Update();
FreeLibrary(dll);
return 0;
}
The moment I call IKlass->Update() I get an exception for Access Memory Violation because of the DLLClass calling its own method.
I haven't tried anything since I barely know how to load a DLL on runtime and I've used this nifty tutorial
How can I let it call the method and not get thrown an exception? I'm trying to let ppl that will create mods for my game create their own mods with their custom classes for bosses, mobs and etc. in DLLs.
EDIT:
Turns out it was a syntax mistake on my end. Instead of return new DLLClass;, it had to be return new DLLClass();. After fixing it, it works as intended.
You return a reference to a local variable thestring, and by the time you try to access it in
std::cout << this->GetString(), referenced data is already destroyed. In fact, it is destroyed right after the end of enclosing scope of compound statement where the variable was declared.
It may "appear" to work sometimes due to the stack not being overwritten yet, but eventually it will fail miserably like it did in your case. This triggers UB (undefined behavior).
I am new c++ so forgive me to be asking this question. I created a project and run it the first time, it is successful. But when i start another project and i added 4 classes to it (you can see from the tabs) and the main.cpp is unable to run. I am confused as the codes are exactly the same in both projects.
Run Successful:
Success
Build Successful but run failed:
Run Failed
What are the solutions to solve this problem?
Do i have to post codes of all my classes? (there are 8 files)
student.h:
#ifndef CLSSTUDENT_H
#define CLSSTUDENT_H
#include <string>
#include <iostream>
using namespace std;
class clsStudent {
protected:
string name;
string student_no;
string program;
public:
clsStudent(string n, string sn,string prog );
virtual void displayStudentDetails();
};
student.cpp
#include "TutorialClass.h"
void TutorialClass::addStudent(clsStudent std)
{
_students.push_back(std);
}
int TutorialClass::getStudentCount()
{
return _students.size();
}
void TutorialClass::display()
{
}
#endif /* CLSSTUDENT_H */
I open up a new project and added only this class. It is unable to run as well. What is the problem in the codes?
It seems that your program only fails to run when it's compiled with other files. My bet is that in these files you've got buggy code that is running before main() gets to run.
This can happen in cases like this:
int f() {
throw; // bam! Uncaught exception;
}
int x = f(); // this runs before main()
Or this:
class C {
C() {
cout << "This runs before main() too!" << endl;
}
};
C my_c; // calls constructor
In both cases: code was executed before main(). You want this because you want your global variables to be initialized before running main(). If this initialization code manages to crash the program via a segfault or an exit() call or throwing some exception which isn't caught? You've got a crashed program before it ever even gets the chance to run.
I'm working on an CLR C++ project, it works properly when running single instace.
However when i debug run the program from visual studio and then run the compiled executable from the project debug folder i get Socket and IO exceptions, the application doesn't crash and it keeps running normally.
I'm using the following class to enable single instance:
initializer.h
#pragma once
namespace Project2
{
public ref class SingleApplication: public Microsoft::VisualBasic::ApplicationServices::WindowsFormsApplicationBase
{
protected:
virtual void OnCreateMainForm() override;
protected:
~SingleApplication ()
{
}
public:
SingleApplication (void);
System::Void StartNextInstance (System::Object ^sender, Microsoft::VisualBasic::ApplicationServices::StartupNextInstanceEventArgs ^e);
};
}
initializer.cpp
#include "initializer.h"
#include "MyForm.h"
using namespace Project2;
using namespace System;
using namespace System::Windows::Forms;
using namespace Microsoft::VisualBasic::ApplicationServices;
SingleApplication::SingleApplication (void)
{
this->IsSingleInstance = true;
this->EnableVisualStyles = true;
this->StartupNextInstance += gcnew
StartupNextInstanceEventHandler (this, &SingleApplication::StartNextInstance);
}
Void SingleApplication::StartNextInstance (Object ^sender, StartupNextInstanceEventArgs ^e)
{
MyForm ^form = safe_cast<MyForm ^> (this->MainForm);
if (form->IsMinimizedToSystemTray()) form->MakeVisible();
else if (form->WindowState == FormWindowState::Minimized)
{
form->Show();
form->WindowState = FormWindowState::Normal;
}
else form->BringToFront();
form->Focus();
}
void SingleApplication::OnCreateMainForm()
{
this->MainForm = gcnew MyForm();
}
Entry Point:
[STAThread]
int main (array<String ^> ^argv)
{
SingleApplication ^MyApplication = gcnew SingleApplication();
MyApplication->Run (argv);
return 0;
}
Debug log:
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.IO.IOException' occurred in System.dll
After enabling break on exceptions i got these details:
1.SocketException:
Additional information: An existing connection was forcibly closed by the remote host
If there is a handler for this exception, the program may be safely continued.
2.IOException:
Additional information: The read operation failed, see inner exception.
If there is a handler for this exception, the program may be safely continued.
What's causing these exceptions and how can handle them?
I think your visual studio debugger is still running basically not terminating properly, it could be that you may still have a thread running in the background that is holding the socket open.
Updated-2
I have interesting combination of warnings & errors.
Firstly, when debugging, i get warnings:
can't find linker symbol for virtual table for `QFile' value
found `WebCore::JSDocument::JSDocument(JSC::Structure*, WebCore::JSDOMGlobalObject*, WTF::PassRefPtr<WebCore::Document>)' instead
RTTI symbol not found for class 'WebCore::JSHTMLDocument'
RTTI symbol not found for class 'WebCore::JSHTMLDocument'
RTTI symbol not found for class 'WebCore::JSHTMLDocument'
secondly, i have runtime error:
QIODevice::open: File access not specified
and momently
*** glibc detected *** <path>: double free or corruption (out): 0x081f9d00 ***
Here's the minimal code that causes that errors (i've minimized it):
Files
In result folder created folder "resources" and in it file "vk.cookie" (everything without quotes).
Bug.pro
QT += core gui webkit network xml
TARGET = Bug
TEMPLATE = app
SOURCES += main.cpp \
api_vk.cpp \
printer.cpp
HEADERS += \
api_vk.h \
printer.h
main.cpp
#include <QtGui/QApplication>
#include "api_vk.h"
#include "printer.h"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
API_VK *apivk = new API_VK;
apivk->authorise();
Printer *printer = new Printer;
QObject::connect(apivk, SIGNAL(authorisationSucceed()), printer, SLOT(printOK()));
QObject::connect(apivk, SIGNAL(authorisationFailed(QString,QString)), printer, SLOT(printFail()));
return a.exec(); }
api_vk.h
#ifndef API_VK_H
#define API_VK_H
#include <QObject>
#include <QTimer>
#include <QUrl>
#include <QtNetwork/QNetworkCookieJar>
class QWebView;
class QString;
class QNetworkReply;
class QXmlInputSource;
class QTimer;
class QNetworkCookie;
class API_VK : public QObject
{
Q_OBJECT
public:
explicit API_VK(QObject *parent = 0);
signals:
void authorisationFailed(QString error, QString error_description);
void authorisationSucceed();
public slots:
void authorise();
protected:
void readCookies();
void writeCookies();
protected slots:
void newAuthoriseRequest();
void processUrl(QUrl url);
private:
static const QString app_id;
static QString access_token;
static qint32 expires_in;
QWebView *messagesPage;
QList<QNetworkCookie> cookies;
QNetworkCookieJar jar;
static bool authorised;
};
#endif
api_vk.cpp
#include "api_vk.h"
#include <QtGui>
#include <QWebView>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkCookie>
#include <QtNetwork/QNetworkCookieJar>
#include <QString>
#include <QStringList>
#include <QFile>
#include <QTextStream>
#include <QTimer>
#include <QUrl>
#include <QtXml>
#include <QVariant>
#include <QDateTime>
#include <QDebug>
bool API_VK::authorised = false;
const QString API_VK::app_id = "2783286";
QString API_VK::access_token = "";
int API_VK::expires_in = 0;
// defining class methods
API_VK::API_VK(QObject *parent) :
QObject(parent)
{
}
void API_VK::authorise() {
newAuthoriseRequest(); // 1. going here
}
void API_VK::newAuthoriseRequest() {
// gets new access_token
// 2. going here
messagesPage = new QWebView;
readCookies();
jar.setCookiesFromUrl(cookies, QUrl("http://vk.com"));
messagesPage->page()->networkAccessManager()->setCookieJar(&jar);
QUrl url("http://oauth.vk.com/authorize");
url.addQueryItem("client_id", app_id);
url.addQueryItem("scope", "messages");
url.addQueryItem("redirect_uri","http://api.vk.com/blank.html");
url.addQueryItem("display","page");
url.addQueryItem("response_type","token");
messagesPage->load(QNetworkRequest(url));
connect(messagesPage, SIGNAL(urlChanged(QUrl)), this, SLOT(processUrl(QUrl)));
messagesPage->show();
}
void API_VK::processUrl(QUrl url) { // 3. going here
/* firstly we're here when oath.vk.com redirects us to api.vk.com/login...
* in this case we're exiting at 4.
* secondly, user logs in, and api.vk.com/login redirects us back to oath.vk.com,
* where we get access_token, etc
* and when debugging, we start receiving warnings about "can't find linker symbol" secondly, not firstly
*/
// if (!url.hasQueryItem("access_token"))
// return;
/* I commented previous part because most of you doesn't have VK accounts so you can't go
* to the next part of code */
access_token = url.queryItemValue("access_token");
expires_in = url.queryItemValue("expires_in").toInt();
emit authorisationSucceed();
authorised = true;
cookies = messagesPage->page()->networkAccessManager()->cookieJar()->cookiesForUrl(QUrl("http://vk.com"));
messagesPage->deleteLater();
writeCookies();
}
void API_VK::readCookies() {
QFile file("./resouces/vk.cookie");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QTextStream in(&file);
QByteArray name, value;
while (!in.atEnd()) {
in >> name >> value;
cookies.append(QNetworkCookie(name, value));
}
}
void API_VK::writeCookies() {
QFile file("./resouces/vk.cookie"); // note: this file exists
if (!file.open(QIODevice::Truncate | QIODevice::Text)) { // 5. at this line i receive runtime errors
return;
}
QTextStream out(&file);
for (QList<QNetworkCookie>::const_iterator i = cookies.begin(); i != cookies.end(); ++i) {
out << (*i).name() << ' ' << (*i).value() << '\n';
}
}
printer.h
#ifndef PRINTER_H
#define PRINTER_H
#include <QObject>
#include <QDebug>
struct Printer: public QObject {
Q_OBJECT
public slots:
void printOK() { qDebug() << "OK"; }
void printFail() { qDebug() << "Fail"; }
};
#endif // PRINTER_H
printer.cpp
#include "printer.h"
Here's the full output with memory dump: http://pastebin.com/btVNe4nd
At 5 QtCreator says that app received signal from OS (signal: SIGABRT) and decompiles
Disassembler (__kernel_vsyscall)
0x132414 <+0x0000> int $0x80
0x132416 <+0x0002> ret
And valgrind says:
Analysis of memory <path>
QMetaObject::connectSlotsByName: No matching signal for on_cancelButton_clicked()
"sni-qt/23102" WARN 20:28:53.697 void StatusNotifierItemFactory::connectToSnw() Invalid interface to SNW_SERVICE
** Analysis finished **
** Unknown error **
And one more thing. When I added qDebug() output after each line of code in writeCookies() and launched the program in Run (not debug) mode, it have printed all this output. So, the problem is in some Qt class destructor. (code with qDebug output)
So, why I receive that errors?
Your problem is in the line
messagesPage->page()->networkAccessManager()->setCookieJar(&jar);
The documentation for setCookieJar() states:
Note: QNetworkAccessManager takes ownership of the cookieJar object.
That means that when the QNetworkAccessManager gets destroyed, it will execute the following code:
delete cookieJar;
Note that when this happens:
The stack-allocated jar you passed to setCookieJar is long gone. The network manager was likely corrupting things by accessing a destroyed cookie jar -- it got destroyed as soon as newAuthoriseRequest() had exited. Remember that network manager can run some of its functionality in a separate thread.
A deletion is attempted on an object that was not allocated directly on the heap via new.
Simply change the declaration to
QPointer<QNetworkCookieJar> jar;
and allocate a new cookie jar whenever you create a new QWebView.
The use of QPointer will protect you from trying to use a dangling pointer to a cookie jar that got deleted by QWebView's network access manager. If, by mistake, you try to use it, the pointer will be already reset to zero, and you'll get an instant segfault at the line where you try to dereference the pointer. That's easy to debug.
Your major mistake was stopping to further minimize your self-contained example. If you kept at it, you'd have found the problem in the next 10-15 minutes tops.
This is a minimal example that reproduces your problem:
#include <QtGui/QApplication>
#include <QtWebKit/QWebView>
#include <QtNetwork/QNetworkCookieJar>
#include <QtCore/QList>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QWebView * view = new QWebView();
QNetworkCookieJar jar;
QList<QNetworkCookie> cookies;
jar.setCookiesFromUrl(cookies, QUrl("http://google.com"));
view->page()->networkAccessManager()->setCookieJar(&jar);
view->load(QUrl("http://www.google.com"));
view->show();
view->connect(view, SIGNAL(loadFinished(bool)), SLOT(deleteLater()));
a.exec();
}
Homework: read up on QPointer, QScopedPointer, QSharedPointer and QWeakPointer. They are very useful, and in most cases you'll find that use of naked pointers as class members in your code is a bug waiting to happen, with exception of child QObjects (such as QWidgets) whose lifetime matches the lifetime of their parent (i.e. they die only when the parent dies).