How to enumerate folder contents in Oct 2018 - c++-winrt

Trying to translate to cppwinrt the StorageFolder method GetFilesAsync I'm unable to get past compiler link errors. Here is a very simple routine to test the concept:
#include "winrt/Windows.Storage.h"
#include "winrt/Windows.Foundation.Collections.h"
IAsyncAction TestClass::LoadFiles()
{
StorageFolder appFolder = Windows::ApplicationModel::Package::Current().InstalledLocation();
StorageFolder assetsFolder = co_await appFolder.GetFolderAsync(hstring(L"Assets"));
auto files = co_await assetsFolder.GetFilesAsync(CommonFileQuery::DefaultQuery);
}
The problem seems to lie in the return type for GetFilesAsync. I've tried various types for that, e.g. IVectorView, but nothing seems to work. Does anyone know of a code example showing how this enumeration might be accomplished in C++/winrt?
[UPDATE] Returning to this project with SDK 10.0.17666 and VS 15.9.0 Preview 3 I find that the solution adopted earlier from these answers no longer works. This time I will be sure to include the full error to see if anyone has ideas. For simplicity I'll use just the simple code provided by IInspectable, altered only to make it a class member in my ResourceManager class:
#include "winrt/Windows.ApplicationModel.h"
#include "winrt/Windows.Storage.h"
#include "winrt/Windows.Storage.Streams.h"
#include "winrt/Windows.Foundation.Collections.h"
#include "winrt/Windows.Storage.Search.h"
#include "winrt/Windows.UI.Core.h"
#include "pch.h"
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Storage;
using namespace Windows::Storage::Search;
IAsyncAction ResourceManager::LoadActivities()
{
StorageFolder appFolder = Windows::ApplicationModel::Package::Current().InstalledLocation();
StorageFolder assetsFolder = co_await appFolder.GetFolderAsync(L"Activities");
auto files = co_await assetsFolder.GetFilesAsync(CommonFileQuery::DefaultQuery);
}
The call to GetFilesAsync now produces the following link error:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "public: struct winrt::Windows::Foundation::IAsyncOperation > __thiscall winrt::impl::consume_Windows_Storage_Search_IStorageFolderQueryOperations::GetFilesAsync(enum winrt::Windows::Storage::Search::CommonFileQuery const &)const " (?GetFilesAsync#?$consume_Windows_Storage_Search_IStorageFolderQueryOperations#UStorageFolder#Storage#Windows#winrt###impl#winrt##QBE?AU?$IAsyncOperation#U?$IVectorView#UStorageFile#Storage#Windows#winrt###Collections#Foundation#Windows#winrt###Foundation#Windows#3#ABW4CommonFileQuery#Search#Storage#63##Z) referenced in function "public: struct winrt::Windows::Foundation::IAsyncAction __thiscall AppEngine::ResourceManager::LoadActivities$_ResumeCoro$2(void)" (?LoadActivities$_ResumeCoro$2#ResourceManager#AppEngine##QAE?AUIAsyncAction#Foundation#Windows#winrt##XZ)
(followed by the path to the object file)
I have to admit I find that error message hard to decipher. Perhaps someone else here will have an idea? Must be something that changed in recent system updates.

For what it's worth, the following standalone code builds just fine. So you're probably either missing a #include or a link library, but it's impossible to tell when you don't share important information like what actual error(s) you're seeing.
#pragma comment(lib, "WindowsApp")
#include <winrt/Windows.ApplicationModel.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Storage.Search.h>
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Storage;
using namespace Windows::Storage::Search;
IAsyncAction LoadFiles()
{
StorageFolder appFolder = Windows::ApplicationModel::Package::Current().InstalledLocation();
StorageFolder assetsFolder = co_await appFolder.GetFolderAsync(L"Assets");
auto files = co_await assetsFolder.GetFilesAsync(CommonFileQuery::DefaultQuery);
}
int main()
{
LoadFiles().get();
}

Related

AWSSDKCPP S3Client.GetObject

Having issues with GetObject. Intellisense in Visual Studio keeps evaluating the method as GetObjectW
...
unresolved external symbol "__declspec(dllimport) public: virtual class Aws::Utils::Outcome<class Aws::S3::Model::GetObjectResult,class Aws::Client::AWSError > __cdecl Aws::S3::S3Client::GetObjectW(class Aws::S3::Model::GetObjectRequest const &)const " (_imp?GetObjectW#S3Client#S3#Aws##UEBA?AV?$Outcome#VGetObjectResult#Model#S3#Aws##V?$AWSError#W4S3Errors#S3#Aws###Client#4##Utils#3#AEBVGetObjectRequest#Model#23##Z)
Here are my includes
#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentialsProvider.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/DeleteObjectRequest.h>
#include <aws/s3/model/GetBucketLocationRequest.h>
#include <aws/s3/model/ListObjectsRequest.h>
All other methods work. Put works, Delete Works, Lists work. it all works. the projects are set to VS 2017. I am ONLY having problems with GetObject and as I said intellisense sees every other method except GetObject which it evaluates to GetObjectW
Client::ClientConfiguration config;
config.region = Region::US_EAST_2;
config.scheme = Http::Scheme::HTTPS;
config.connectTimeoutMs = 30000;
config.requestTimeoutMs = 30000;
S3Client s3Client(Auth::AWSCredentials(ACCESS_KEY, SECRET_KEY), config);
GetObjectRequest getObjectRequest;
getObjectRequest.WithBucket(bucket)
.WithKey(fileKey);
// //GetObject is Having issues here where it is not being found in referenced assembly it keeps being called GetObjectW...
// //It is perhaps the case there is a missing required reference for the method?
GetObjectOutcome getObjectOutcome = s3Client.GetObject(getObjectRequest);
resolved on https://github.com/aws/aws-sdk-cpp/issues/625
answer is:
must #undef GetObject before aws includes as follows:
#undef GetObject
#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentialsProvider.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/GetObjectRequest.h>
This is a conflict with Windows.h

TFLite: Micro mutable Op Resolver does not name a type

I am trying to compile a TFLite micro-based Arduino sketch using MicroMutableOpsResolver class (to only include required operations for reducing the memory usage).
Though see similar usage in TF lite example here - https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/micro/examples/micro_speech/micro_speech_test.cc
But keep hitting the below compilation error.
IMU_Classifier_TinyML:22:1: error: 'micro_op_resolver' does not name a type
micro_op_resolver.AddFullyConnected();
^~~~~~~~~~~~~~~~~
IMU_Classifier_TinyML:23:1: error: 'micro_op_resolver' does not name a type
micro_op_resolver.AddSoftmax();
^~~~~~~~~~~~~~~~~
IMU_Classifier_TinyML:24:1: error: 'micro_op_resolver' does not name a type
micro_op_resolver.AddRelu();
^~~~~~~~~~~~~~~~~
Using library Arduino_LSM9DS1 at version 1.1.0 in folder: /home/balaji/Arduino/libraries/Arduino_LSM9DS1
Using library Wire in folder: /home/balaji/.arduino15/packages/arduino/hardware/mbed/1.3.2/libraries/Wire (legacy)
Using library Arduino_TensorFlowLite at version 2.4.0-ALPHA in folder: /home/balaji/Arduino/libraries/Arduino_TensorFlowLite
exit status 1
'micro_op_resolver' does not name a type
The code snippet looks as below:
#include <Arduino_LSM9DS1.h>
#include <TensorFlowLite.h>
#include <tensorflow/lite/micro/micro_mutable_op_resolver.h>
#include <tensorflow/lite/micro/kernels/micro_ops.h>
#include <tensorflow/lite/micro/micro_error_reporter.h>
#include <tensorflow/lite/micro/micro_interpreter.h>
#include <tensorflow/lite/schema/schema_generated.h>
#include <tensorflow/lite/version.h>
// Include the TFlite converted model header file
#include "model.h"
const float accelThreshold = 2.5;
const int numOfSamples = 119; // acceleration sample-rate
int samplesRead = numOfSamples;
tflite::MicroErrorReporter tfLiteErrorReporter;
/*Import only the required ops to reduce the memory usage*/
static tflite::MicroMutableOpResolver<3> micro_op_resolver;
micro_op_resolver.AddFullyConnected();
micro_op_resolver.AddSoftmax();
micro_op_resolver.AddRelu();
Am I missing any dependency or could this be due to TF lite version mismatch?
At least the function calls like micro_op_resolver.AddFullyConnected(); must be placed into a function body. Something like this should compile:
#include <Arduino_LSM9DS1.h>
#include <TensorFlowLite.h>
#include <tensorflow/lite/micro/micro_mutable_op_resolver.h>
#include <tensorflow/lite/micro/kernels/micro_ops.h>
#include <tensorflow/lite/micro/micro_error_reporter.h>
#include <tensorflow/lite/micro/micro_interpreter.h>
#include <tensorflow/lite/schema/schema_generated.h>
#include <tensorflow/lite/version.h>
// Include the TFlite converted model header file
#include "model.h"
const float accelThreshold = 2.5;
const int numOfSamples = 119; // acceleration sample-rate
int samplesRead = numOfSamples;
tflite::MicroErrorReporter tfLiteErrorReporter;
/*Import only the required ops to reduce the memory usage*/
static tflite::MicroMutableOpResolver<3> micro_op_resolver;
void setup() {
micro_op_resolver.AddFullyConnected();
micro_op_resolver.AddSoftmax();
micro_op_resolver.AddRelu();
}
void loop() {
// put your main code here, to run repeatedly:
}

How do we add an event in C++/WinRt project?

I am currently work on a C++/WinRt which connects(Sender) to one of the available devices(Client) around a specific region using WifiDirect. When the device wants to connect, it sends a connection request to the sender. The sender needs to detect the connection request sent by the client and connect to the client. For this I need to add an event - (On Connection requested). As soon as I add it should execute the code of OnConnectionRequested.
#include "pch.h"
#include <winrt/Windows.Foundation.Collections.h>
#include "winrt/Windows.Devices.WiFiDirect.h"
#pragma once
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Devices::WiFiDirect;
using namespace Windows::Storage::Streams;
using namespace winrt::Windows::Devices::WiFiDirect;
using namespace winrt::Windows::Devices::Enumeration;
enum class NotifyType
{
StatusMessage,
ErrorMessage
};
enum class CallbackContext
{
Any,
Same
};
class st
{
public:
void OnConnectionRequested(WiFiDirectConnectionListener sender,
WiFiDirectConnectionRequestedEventArgsconnection EventArgs)
{
WiFiDirectConnectionRequest connectionRequest = connectionEventArgs.GetConnectionRequest();
printf("Connection request received from ", connectionRequest.DeviceInformation().Name(), "Connection Request");
printf("Connecting to ", connectionRequest.DeviceInformation().Name(), NotifyType::StatusMessage);
}
void start()
{
Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher _publisher;
Windows::Devices::WiFiDirect::WiFiDirectConnectionListener _listener;
winrt::event_token _connectionRequestedToken;
try
{
_connectionRequestedToken = _listener.ConnectionRequested({this, &st::OnConnectionRequested});
_publisher.Start();
printf("Advertisement started, waiting for StatusChangedcallback...", NotifyType::StatusMessage);
}
catch (...)
{
printf("Error starting Advertisement: ", NotifyType::ErrorMessage);
}
getchar();
}
};
int main()
{
st s;
s.start();
}
Is this the right way to add an event in C++/WinRt :
_connectionRequestedToken = _listener.ConnectionRequested({this, &st::OnConnectionRequested});
The errors are :
LNK1120 1 unresolved externals - error in Winrt.exe file
LNK2019
unresolved external symbol "public: struct winrt::hstring __thiscall
winrt::impl::consume_Windows_Devices_Enumeration_IDeviceInformation::Name(void)const
"
(?Name#?$consume_Windows_Devices_Enumeration_IDeviceInformation#UIDeviceInformation#Enumeration#Devices#Windows#winrt###impl#winrt##QBE?AUhstring#3#XZ)
referenced in function "public: void __thiscall
st::OnConnectionRequested(struct
winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionListener,struct
winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionRequestedEventArgs)"
(?OnConnectionRequested#st##QAEXUWiFiDirectConnectionListener#WiFiDirect#Devices#Windows#winrt##UWiFiDirectConnectionRequestedEventArgs#3456##Z) - error in Program.obj 1
What changes should I make at this line to clear the error? What does the error actually mean ? Or is there any other way to add an event in C++/WinRt project?
You are missing an #include directive:
#include <winrt/Windows.Devices.Enumeration.h>
See Why is the linker giving me a "LNK2019: Unresolved external symbol" error?:
If the unresolved symbol is an API from the Windows namespace headers for the C++/WinRT projection (in the winrt namespace), then the API is forward-declared in a header that you've included, but its definition is in a header that you haven't yet included. Include the header named for the API's namespace, and rebuild. For more info, see C++/WinRT projection headers.
For general instructions on how to handle events see Handle events by using delegates in C++/WinRT.
Capturing this (raw pointer) into the delegate might be dangerous, too. This breaks the link between object lifetime and visibility, and puts the burden of lifetime management on you. See Safely accessing the this pointer with an event-handling delegate for safer, more manageable alternatives.

HPDF_SetCompressionMode() not working in Libharu

I am generating Pdf files using LibHaru libraries. My code is following
#include <iostream>
#include "hpdf.h"
using namespace std;
void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void *user_data)
{
}
int main()
{
cout<<"Compression"<<endl;
HPDF_Doc pdf = HPDF_New(error_handler, NULL);
if (!pdf)
return 0;
HPDF_STATUS Status = HPDF_SetCompressionMode(pdf, HPDF_COMP_ALL);
return 0;
}
PROBLEM: I debugged the code and found that HPDF_SetCompressionMode() returns 4129, which is the error code for Invalid value set when invoking HPDF_SetCommpressionMode(). .
If you step into the code, you will see you are getting the error because the ZLIB compression library was not compiled into your copy of HaruPDF.
First: comment out this line in ..\win32\include\hpdf_config.h:
/* zlib is not available */
//#define LIBHPDF_HAVE_NOZLIB
Second: find, download and unzip the ZLIB code. You can obtain the source from the following Website:
http://www.zlib.net/
Third: tell HaruPDF where it can find the ZLIB code, and recompile HaruPDF.
You should now be able to use compression.
Ain't Open Source grand?

DLL import failure in using WinDivert

I am going to design a program using WinDivert to manipulate the network traffic.
The language I use is C++ and the program is designed under Visual Studio 2008.
Firstly I create a project in visual C++ CLR (Windows Forms Application) so I can implement the UI simply.
For importing the WinDirvert Library, I have done the following setting in project properties:
Configuaration Properties: General
Common Language Runtime support: Common Language Runtime Support(/ctr)
Configuaration Properties: Linker
Additional Dependencies: link of WinDivert.lib
Module Definition File: link of windivert.def
Within the project I have created, I also added the windivert.h in the header files.
Also, windivert.h is included in the main entry point of my project (ProjectG.cpp):
#include "stdafx.h"
#include "Form1.h"
#pragma managed(push, off)
#include "windivert.h"
#pragma managed(pop)
using namespace ProjectG;
[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());
HANDLE handle;
unsigned char packet[8192];
UINT packet_len;
WINDIVERT_ADDRESS addr;
handle = WinDivertOpen("udp", WINDIVERT_LAYER_NETWORK, 0,
WINDIVERT_FLAG_DROP);
if (handle == INVALID_HANDLE_VALUE)
{
Application::Exit();
}
while (TRUE)
{
// Read a matching packet.
if (!WinDivertRecv(handle, packet, sizeof(packet), &addr, &packet_len))
{
MessageBox::Show("Fail");
continue;
}
}
return 0;
}
Finally, I put the {WinDivert.dll, windivert.h, WinDivert.lib, WinDivert32.sys} under the project directory.
However, the following error is shown:
fatal error LNK1306: DLL entry point "int __clrcall main(cli::array<class
System::String ^ >^)" (?main##$$HYMHP$01AP$AAVString#System###Z) cannot be managed;
compile to native ProjectG.obj ProjectG
Additional: (a warning)
warning LNK4070: /OUT:WinDivert.dll directive in .EXP differs from output filename
'C:\Users\David\Desktop\css\ProjectG\Debug\ProjectG.exe'; ignoring directive
ProjectG.exp ProjectG
Question:
How can I resolve this situation?
a) your main source is .cpp, so you can delete [STAThreadAttribute] and change
int main(array<System::String ^> ^args) to int _tmain(int argc, _TCHAR* argv[])
b) exclude windivert.def from linker Module Definition File, this only when you are creating a DLL
c) the DLL/SYS files would need to be copied to the Debug and Release folders