I am trying to learn C++ by doing a small windows phone app. Currently I am just following a tutorial to get to grips with developing for the windows phone. However, I have encountered a ambiguous signal error when trying to build the code. I am used to the niceties associated with Java and am a bit lost as to what could be causing this error. The error dump I get is:
1>c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(740): error C2872: 'EventRegistrationToken' : ambiguous symbol
1> could be 'c:\program files (x86)\windows phone kits\8.0\include\eventtoken.h(51) : EventRegistrationToken'
1> or 'c:\program files (x86)\windows phone kits\8.0\windows metadata\windows.winmd : Windows::Foundation::EventRegistrationToken'
1> c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(1035) : see reference to class template instantiation 'Microsoft::WRL::EventSource<TDelegateInterface>' being compiled
1>c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(814): error C2872: 'EventRegistrationToken' : ambiguous symbol
1> could be 'c:\program files (x86)\windows phone kits\8.0\include\eventtoken.h(51) : EventRegistrationToken'
1> or 'c:\program files (x86)\windows phone kits\8.0\windows metadata\windows.winmd : Windows::Foundation::EventRegistrationToken'
The code is attached below - sorry for giving the whole file, but I literally dont know where to start. Any help would be greatly appreciated.
Thanks
#include "pch.h"
#include "WindowsPhoneGame.h"
#include "BasicTimer.h"
//#include <string.h>
#include <sstream>
//using namespace std;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace concurrency;
WindowsPhoneGame::WindowsPhoneGame() :
m_windowClosed(false),
m_windowVisible(true)
{
}
void WindowsPhoneGame::Initialize(CoreApplicationView^ applicationView)
{
applicationView->Activated +=
ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &WindowsPhoneGame::OnActivated);
CoreApplication::Suspending +=
ref new EventHandler<SuspendingEventArgs^>(this, &WindowsPhoneGame::OnSuspending);
CoreApplication::Resuming +=
ref new EventHandler<Platform::Object^>(this, &WindowsPhoneGame::OnResuming);
m_renderer = ref new Renderer();
}
void WindowsPhoneGame::SetWindow(CoreWindow^ window)
{
window->VisibilityChanged +=
ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &WindowsPhoneGame::OnVisibilityChanged);
window->Closed +=
ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &WindowsPhoneGame::OnWindowClosed);
window->PointerPressed +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerPressed);
window->PointerMoved +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerMoved);
window->PointerReleased +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerReleased);
m_renderer->Initialize(CoreWindow::GetForCurrentThread());
}
void WindowsPhoneGame::Load(Platform::String^ entryPoint)
{
}
void WindowsPhoneGame::Run()
{
BasicTimer^ timer = ref new BasicTimer();
while (!m_windowClosed)
{
if (m_windowVisible)
{
timer->Update();
CoreWindow::GetForCurrentThread()->Dispatcher- >ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
m_renderer->Update(timer->Total, timer->Delta);
m_renderer->Render();
m_renderer->Present(); // This call is synchronized to the display frame rate.
}
else
{
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
}
}
}
void WindowsPhoneGame::Uninitialize()
{
}
void WindowsPhoneGame::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
m_windowVisible = args->Visible;
}
void WindowsPhoneGame::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
m_windowClosed = true;
}
void WindowsPhoneGame::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
{
ostringstream sstream;
sstream << "Pressed at: " << "X: " << args->CurrentPoint->Position.X << " Y: " << args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}
void WindowsPhoneGame::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
{
ostringstream sstream;
sstream << "Moved at: " << "X: " << args->CurrentPoint->Position.X << " Y: " << args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}
void WindowsPhoneGame::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
{
ostringstream sstream;
sstream << "Released at: " << "X: " << args->CurrentPoint->Position.X << " Y: " << args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}
void WindowsPhoneGame::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
CoreWindow::GetForCurrentThread()->Activate();
}
void WindowsPhoneGame::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
// Save app state asynchronously after requesting a deferral. Holding a deferral
// indicates that the application is busy performing suspending operations. Be
// aware that a deferral may not be held indefinitely. After about five seconds,
// the app will be forced to exit.
SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
m_renderer->ReleaseResourcesForSuspending();
create_task([this, deferral]()
{
// Insert your code here.
deferral->Complete();
});
}
void WindowsPhoneGame::OnResuming(Platform::Object^ sender, Platform::Object^ args)
{
// Restore any data or state that was unloaded on suspend. By default, data
// and state are persisted when resuming from suspend. Note that this event
// does not occur if the app was previously terminated.
m_renderer->CreateWindowSizeDependentResources();
}
IFrameworkView^ Direct3DApplicationSource::CreateView()
{
return ref new WindowsPhoneGame();
}
[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
auto direct3DApplicationSource = ref new Direct3DApplicationSource();
CoreApplication::Run(direct3DApplicationSource);
return 0;
}
You're using a lot of namespaces. It would appear that
EventRegistrationToken
Is defined in
Windows::Foundation; //windows.winmd
And again in eventtoken.h. Not sure which namespace this would apply to, could be global. Ditch the
using namespace Windows::Foundation;
and then you can access the respective implementations like this:
//eventtoken.h impl
EventRegistrationToken();
//the one in Foundation namespace:
Windows::Foundation::EventRegistrationToken();
Although it looks like you don't need this function, so it may not matter, this is just for example, and for how... since you need to remove this namespace, how you can now access the other members of this namespace.
I imagine you coud safely do this as well, though I don't necessarily recommend it:
using namespace Windows;
Foundation::EventRegistrationToken();
I had this same issue with just WP8 SDK projects.
Fix: Remove using Windows::Foundation from the .h file and use the full namespace for calling your object types.
Windows::Foundation::IAsyncOperation<String^> ^Blah();
instead of
IAsyncOperation<String^> ^CreateSampleData();
Related
I am creating a simple UWP console server app with reference to the contents of this and this links.
However, if i create code based on the examples and run it, I will not be able to connect to the server. Also, the port is not open when checked with a command such as "netstat -na".
Does anyone know how to solve it?
The code is shown below. I would appreciate if you find any errors in the code below.
#include "pch.h"
#include <sstream>
#include <iostream>
using namespace Platform;
using namespace Concurrency;
using namespace Windows::Foundation;
using namespace Windows::Networking;
using namespace Windows::Networking::Sockets;
using namespace Windows::Networking::Connectivity;
using namespace Windows::Storage::Streams;
namespace SocketTest {
public ref class Server sealed {
public:
Server();
void Run();
protected:
void Server::onConnReceived(
Windows::Networking::Sockets::StreamSocketListener^ listener,
Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs^ object);
};
}
using namespace SocketTest;
Server::Server() {
}
void Server::onConnReceived(
StreamSocketListener^ listener,
StreamSocketListenerConnectionReceivedEventArgs^ object)
{
try {
DataReader^ reader = ref new DataReader(object->Socket->InputStream);
//ReceiveStringLoop(reader, object->Socket);
delete object->Socket;
}
catch (Exception^ exception) {
std::cout << "onconnection error" << std::endl;
}
}
void Server::Run() {
StreamSocketListener^ listener = ref new StreamSocketListener();
listener->ConnectionReceived += ref new TypedEventHandler<Windows::Networking::Sockets::StreamSocketListener^, Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs^>(this, &Server::onConnReceived);
listener->Control->KeepAlive = true;
create_task(listener->BindServiceNameAsync(L"12345")).then(
[=]
{
try
{
std::cout << "Listening ..." << std::endl;
}
catch (Exception^ exception)
{
std::cout << "Bind error" << exception->Message->Data() << std::endl;
}
});
}
int main(Platform::Array<Platform::String^>^ args)
{
Server^ s = ref new Server();
s->Run();
getchar();
}
Or, if you have a better code example, let me know.
I was trying to work on the below code but the program crashes:
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef void (*callBackMethod)(string);
class CTest
{
private:
map<string, callBackMethod> mapMethod;
void testMethod(string msg)
{
cout << msg << endl;
}
public:
CTest()
{
addFunction("AA", (callBackMethod) &CTest::testMethod);
}
void addFunction(string funName, callBackMethod methodName)
{
mapMethod[funName] = methodName;
}
callBackMethod getMethod(string funName)
{
auto fun = mapMethod.find(funName);
if(fun == mapMethod.end()) { return nullptr; }
return fun->second;
}
void runFunction(string funName)
{
getMethod(funName)("test");
}
};
int main()
{
CTest test;
test.runFunction("AA");
return 0;
}
I have a requirement where I need to pass private methods to a map. The program compiles with warning:
converting from 'void (CTest::*)(std::__cxx11::string) {aka void (CTest::*)(std::__cxx11::basic_string<char>)}' to 'callBackMethod {aka void (*)(std::__cxx11::basic_string<char>)}'
and when I execute this, it crashes.
When I move the callback method outside of the class it works. My requirement is to make the program flow this was (hide the methods from external call which needs to be added to a map).
Looking forward to your comments.
If you need to point to both CTest member functions and free functions, then you can use std::function<void(std::string)>.
#include <iostream>
#include <string>
#include <map>
#include <functional>
using namespace std;
using callBackFunction = std::function<void(string)>;
void testFunction(string msg)
{
cout << "[" << __PRETTY_FUNCTION__ << "] " << msg << endl;
}
class CTest
{
private:
map<string, callBackFunction> mapMethod;
void testMethod(string msg)
{
cout << "[" << __PRETTY_FUNCTION__ << "] " << msg << endl;
}
public:
CTest()
{
addFreeFunction("AA", testFunction);
addMemberFunction("BB", &CTest::testMethod);
}
void addMemberFunction(string funName, void(CTest::*methodName)(string))
{
using std::placeholders::_1;
mapMethod[funName] = std::bind(methodName, this, _1);
}
void addFreeFunction(string funName, void(*methodName)(string))
{
mapMethod[funName] = methodName;
}
callBackFunction getMethod(string funName)
{
auto fun = mapMethod.find(funName);
if(fun == mapMethod.end()) { return nullptr; }
return fun->second;
}
void runFunction(string funName)
{
getMethod(funName)("test");
}
};
int main()
{
CTest test;
test.runFunction("AA");
test.runFunction("BB");
return 0;
}
Notice that CTest must insert elements into the map in a different way depending on what type of function you are passing, since for member functions you must provide the object for which it is to be invoked, this in this example. This is achived by using std::bind.
Since you want to use member variables you need to specify the signature differently in your typedef:
In C++ Builder the following can be done:
typedef void(__closure *callBackMethod)(string);
If you do that, I do suggest that you keep a smart pointer to the object that the member belongs to so that you can check if the object is still valid before calling the function otherwise it will crash the application.
The __closure keyword is a C++ Builder extension to work around the requirement to use fully qualified member names source
To handle both global and member functions we have the following:
typedef void(__closure *callBackMethodMember)(string);
typedef void (*callBackMethodGlobal)(string);
/* And then on 2 overloaded functions */
void addFunction(string funName, callBackMethodMember methodName) {}
void addFunction(string funName, callBackMethodGlobal methodName) {}
I need some help to decrypt my text file and make it able to read in my program..
What I have programmed so far is to read the encrypted file, create a new file, decrypt it and read the newly created file..
I need to decrypt the encrypted file without having to create a new file that reads the decrypted text..
Well, Let me show you my code:
P.S Most of the include is not needed and I already know that
Visual studio 2010 Windows Form Application CLR
#pragma once
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <iomanip>
namespace EncryptandDecryptfiletest {
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;
using namespace std;
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
/*Decryption --- When program loads*/
char ch,mod;
char key = 97;
char name[100] = "Encrypted.txt";
char target[100] = "TTO.txt";
ifstream fin("Encrypted.txt", ios::binary); // Reading file
if(!fin) //open the encrypted file in a binary mode
{
MessageBox::Show("Encrypted.txt did not open"); //If file does not exist
} //or any kind of error
ofstream fout;
fout.open(target,ios::binary); //Opens outputfile
if(!fout)
{ //Show error if any error occurs in opening new file
MessageBox::Show("TTO.txt did not open");
}
while(fin.get(ch))
{ // opens the Encrypted file
if(ch==EOF)break;
mod = ch + key;
if (mod > 255 ) mod -= 255;
fout << mod; //Writes decrypted text to TTO.txt
}
fin.close(); //Close the encrypted file
fout.close(); // Close the decrypted file
}
private: System::Void comboBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
label1->Text = comboBox1->Text;
pictureBox1->Load("Images\\" + comboBox1->SelectedItem->ToString() + ".png");
//String^ openFileTest = "Encrypted.txt"; // Opens the encrypted .txt file
String^ openFileTest = "TTO.txt"; //Opens the newly created file that is decrypted
try //Reading the .txt file
{
StreamReader^ DataIn = File::OpenText(openFileTest);
String^ DataStr;
int count = 0;
array<String^>^ result;
array<Char>^ separ = gcnew array<Char>{'"'}; //After each Quote gets a new value of result[x]
while((DataStr = DataIn->ReadLine()) != nullptr)
{
count++;
result = DataStr->Split(separ);
if(comboBox1->Text == result[0]) // result[0] = Name
{
textBox1->Text = result[1]; //reads first word in txt file
textBox2->Text = result[2]; //second word in txt file
textBox3->Text = result[3]; //third word in txt file
}
} // ends while()
} // ends try
catch (Exception^ e)
{
if(dynamic_cast<FileNotFoundException^>(e))
MessageBox::Show("File " + openFileTest + " not found");
}
} // Ends comboBox1_SelectedIndexChanged void
};
}
You have my decryption code and the code I want to use..
I have uploaded the code for you to use on your computer because it is fairly hard for me to explain..
I want to be able to read the encrypted file in my program, without having to writing a new file to decrypt it..
I hope anyone is able to help me
Decrypted & Encrypted .txt file Included (And images)
--> Program .rar pack link <--
Build it with Visual Studio 2010
Just replace the output file stream with a MemoryStream.
The first thing to do is decompose into functions. Since you read your streams byte per byte, you won't need readers, which is good.
void Decrypt(Stream^ input, Stream^ output)
{
char key=97;
int byteRead;
while((byteRead=input->ReadByte()) >= 0)
{
char ch = (char)byteRead;
char mod = (char)(ch+key)
output->WriteByte(mod);
}
}
//When loading
MemoryStream^ ms = gcnew MemoryStream();
{
FileStream^ fs = File::OpenRead(L"encrypted.txt");
Decrypt(fr, ms);
delete fs;
}
ms.Seek(0, SeekOrigin::Begin);
//Later, read from the memory stream
I have created a logger mechanism based on Boost Log.
My code is based on the trivial logger as shown in this example.
I was wondering how to automatically call system exit
exit(1)
(or any other custom callback function) whenever a fatal error occurs.
Any help is welcomed!
UPDATE:
The solution is to extend the backend sink by overloading the consume() method.
Example of a sink examining the severity level of the trivial logger:
#include <boost/log/trivial.hpp>
#include <boost/log/sinks/basic_sink_backend.hpp>
#include <boost/log/attributes/value_extraction.hpp>
#include <boost/log/sinks/async_frontend.hpp>
namespace sinks = boost::log::sinks;
void initBoostLog() {
struct Sink: public sinks::basic_formatted_sink_backend<char, sinks::concurrent_feeding> {
void consume (const boost::log::record_view& rec, const string& str) {
using boost::log::trivial::severity_level;
auto severity = rec.attribute_values()[boost::log::aux::default_attribute_names::severity()].extract<severity_level>();
if (!severity || severity.get() <= severity_level::info) {
std::cout << str << std::endl;
} else {
std::cerr << str << std::endl;
}
}
};
typedef sinks::asynchronous_sink<Sink> sink_t; boost::shared_ptr<sink_t> sink (new sink_t());
boost::shared_ptr<boost::log::core> logc = boost::log::core::get();
logc->add_sink (sink);
}
I created a file chooser for windows it returns me a chosen file path. I want to read the given file but I do not know how to pass the file path to the right function.
File Form1.h I have a button action and inside of it I can get openFileDialog1->FileName but I do not know how to pass this variable to a readFile() function inside of main.cpp file.
I created a method to return the path:
System::String^ filePath;
....
private: System::String^ getPath() { return filePath; }
Here is the file-pickers code:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1->FilterIndex = 2;
openFileDialog1->RestoreDirectory = true;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK ){
if ( (myStream = openFileDialog1->OpenFile()) != nullptr ){
// Insert code to read the stream here.
textBox1->Text = openFileDialog1->FileName; //text box displays the chosen path
myStream->Close();
}
}
}
The variable is set on button click:
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
filePath = textBox1->Text;
}
How to call the return methods in my main.cpp:
#include "stdafx.h"
#include "Form1.h"
using namespace main;
using namespace std;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew Form1());
System::String^ p1 = /*Something missing her?*/getPath1(); //I am guessing it should look like this...
return 0;
}
Put the file name in a public property (public field, if it's what you prefer) in the Form1 class (or make your getPath() method public) then:
Form1^ form = gcnew Form1();
Application::Run(form);
String^ p1 = form->FileName;