### Install SDK on System Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Linux Installs the built C++ REST SDK on the system using Ninja. ```bash sudo ninja install ``` -------------------------------- ### Install cpprestsdk with dnf Source: https://github.com/microsoft/cpprestsdk/blob/master/README.md Install the cpprest-devel package on Fedora systems using dnf. ```bash $ sudo dnf install cpprest-devel ``` -------------------------------- ### Install Dependencies with Homebrew Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Mac-OS-X Use Homebrew to install CMake, Git, Boost, OpenSSL, and Ninja, which are required for building the SDK. ```shell brew install cmake git boost openssl ninja ``` -------------------------------- ### Install cpprestsdk with vcpkg Source: https://github.com/microsoft/cpprestsdk/blob/master/README.md Use vcpkg to install the cpprestsdk library on Windows. Specify the architecture if needed. ```powershell PS> vcpkg install cpprestsdk cpprestsdk:x64-windows ``` -------------------------------- ### Install cpprestsdk Dependencies with Vcpkg Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Windows Install necessary libraries for cpprestsdk on Windows using vcpkg. Ensure you have vcpkg installed and configured. ```bash vcpkg install --triplet x64-windows zlib openssl boost-system boost-date-time boost-regex boost-interprocess websocketpp brotli ``` -------------------------------- ### Install cpprestsdk with brew Source: https://github.com/microsoft/cpprestsdk/blob/master/README.md Install the cpprestsdk library on macOS using the Homebrew package manager. ```bash $ brew install cpprestsdk ``` -------------------------------- ### Install cpprestsdk with apt-get Source: https://github.com/microsoft/cpprestsdk/blob/master/README.md Install the cpprestsdk development package on Debian or Ubuntu systems using apt-get. ```bash $ sudo apt-get install libcpprest-dev ``` -------------------------------- ### Install Build Tools and Libraries on Linux Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Linux Installs essential packages for building the C++ REST SDK, including g++, git, Boost libraries, OpenSSL, and Ninja build system. ```bash sudo apt-get install g++ git libboost-atomic-dev libboost-thread-dev libboost-system-dev libboost-date-time-dev libboost-regex-dev libboost-filesystem-dev libboost-random-dev libboost-chrono-dev libboost-serialization-dev libwebsocketpp-dev openssl libssl-dev ninja-build ``` -------------------------------- ### Install C++ REST SDK with NuGet (Windows) Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial Install the C++ REST SDK on Windows using the NuGet Package Manager. This method is not recommended. ```powershell PM> Install-Package cpprestsdk ``` -------------------------------- ### Create HTTP Client and Make Request Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial Creates an http_client for a given URI and constructs an HTTP GET request with query parameters. The request is initiated within a task continuation. ```c++ // Open stream to output file. pplx::task requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile) { *fileStream = outFile; // Create http_client to send the request. http_client client(U("http://www.bing.com/")); // Build request URI and start the request. uri_builder builder(U("/search")); builder.append_query(U("q"), U("cpprestsdk github")); return client.request(methods::GET, builder.to_string()); }); ``` -------------------------------- ### Setup Environment and Build Android Tests Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Android-on-Linux-(2.3) Execute a PowerShell script to set up the Visual Studio environment for Android builds. Then, navigate to the Release directory and use msbuild to compile the x86 Debug configuration for the simulator. ```powershell .\setup_ps_env_VS2015.ps1 cd Release msbuild /p:Platform=x86 /p:Configuration=Debug ``` -------------------------------- ### Install cpprestsdk.android with NuGet Source: https://github.com/microsoft/cpprestsdk/blob/master/README.md Install the cpprestsdk.android package on Windows for Android development using NuGet Package Manager. ```powershell PM> Install-Package cpprestsdk.android ``` -------------------------------- ### Include Other Important Casablanca Headers Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial A list of other important header files available in Casablanca, not all of which are used in this example. ```cpp #include // HTTP server #include // JSON library #include // URI library #include // WebSocket client #include // Async streams backed by STL containers #include // Bridges for integrating Async streams with STL and WinRT streams #include // Async streams backed by raw pointer to memory #include // Async streams for producer consumer scenarios ``` -------------------------------- ### Make HTTP Request and Save Results with C++ Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial This C++ code snippet demonstrates how to use the Casablanca library to make an HTTP GET request to a specified URL, retrieve the response body, and save it to an HTML file. It includes error handling for exceptions during the process. ```cpp #include #include using namespace utility; // Common utilities like string conversions using namespace web; // Common features like URIs. using namespace web::http; // Common HTTP functionality using namespace web::http::client; // HTTP client features using namespace concurrency::streams; // Asynchronous streams int main(int argc, char* argv[]) { auto fileStream = std::make_shared(); // Open stream to output file. pplx::task requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile) { *fileStream = outFile; // Create http_client to send the request. http_client client(U("http://www.bing.com/")); // Build request URI and start the request. uri_builder builder(U("/search")); builder.append_query(U("q"), U("cpprestsdk github")); return client.request(methods::GET, builder.to_string()); }) // Handle response headers arriving. .then([=](http_response response) { printf("Received response status code:%u\n", response.status_code()); // Write response body into the file. return response.body().read_to_end(fileStream->streambuf()); }) // Close the file stream. .then([=](size_t) { return fileStream->close(); }); // Wait for all the outstanding I/O to complete and handle any exceptions try { requestTask.wait(); } catch (const std::exception &e) { printf("Error exception:%s\n", e.what()); } return 0; } ``` -------------------------------- ### Open Android Test Runner Project Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Android-on-Linux-(2.3) Locate and open the Android project file in Visual Studio to package the tests. Ensure the configuration is set to x86 Debug before starting the debugging process. ```bash Release\tests\common\TestRunner\vs14.android\TestRunner.android.Packaging\TestRunner.android.Packaging.androidproj ``` -------------------------------- ### Create HTTP Request Task Source: https://github.com/microsoft/cpprestsdk/wiki/Programming-with-Tasks Initiates an asynchronous HTTP GET request and returns a task representing the future response. Ensure the http_client is properly initialized. ```c++ web::http::client::http_client client(U("http://localhost:80")); pplx::task resp = client.request(web::http::methods::GET, U("/foo.html")); ``` -------------------------------- ### Link cpprestsdk with CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/README.md Configure your CMake project to find and link against the cpprestsdk library. Ensure cpprestsdk is installed and discoverable by CMake. ```cmake cmake_minimum_required(VERSION 3.9) project(main) find_package(cpprestsdk REQUIRED) add_executable(main main.cpp) target_link_libraries(main PRIVATE cpprestsdk::cpprest) ``` -------------------------------- ### Clone C++ REST SDK Repository Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Android-on-Linux-(2.3) Clone the C++ REST SDK repository and navigate to the Android build directory. This is the starting point for the Android build process. ```bash git clone https://github.com/Microsoft/cpprestsdk.git casablanca cd casablanca/Build_android ``` -------------------------------- ### Conditional Compiler Options for GCC Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/functional/utils/CMakeLists.txt Applies specific compiler options to the test target when using GCC. This example disables warnings for deprecated declarations. ```cmake if(CMAKE_COMPILER_IS_GNUCXX) target_compile_options(utils_test PRIVATE "-Wno-deprecated-declarations") endif() ``` -------------------------------- ### Retrieve JSON Number as int64_t Source: https://github.com/microsoft/cpprestsdk/wiki/JSON Access specific functionalities for JSON number types using `as_number()`. This example shows how to retrieve a JSON number as a C++ 64-bit integer. ```javascript json::value num = json::value(88); int64_t num64 = num.as_number().to_int64(); ``` -------------------------------- ### Handle Task Completion and Exceptions Source: https://github.com/microsoft/cpprestsdk/wiki/Programming-with-Tasks Attaches a handler to a task that retrieves the result and allows for exception handling. The handler receives the task itself, enabling calls to `get()` to observe exceptions. ```c++ resp.then([=](pplx::task task) { web::http::http_response response = task.get(); ... }); ``` -------------------------------- ### Clone and Initialize Project Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Mac-OS-X Clone the cpprestsdk repository and initialize its submodules. Ensure you are on the master branch for the latest release. ```shell git clone https://github.com/Microsoft/cpprestsdk.git casablanca cd casablanca git submodule update --init ``` -------------------------------- ### Run SDK Tests Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Linux Navigates to the 'Binaries' directory after building and executes the test runner to verify the SDK's functionality. ```bash cd Release/Binaries ./test_runner *_test.so ``` -------------------------------- ### Run Tests Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Mac-OS-X After building, navigate to the Binaries directory and execute the test runner to verify the build. ```shell cd Binaries ./test_runner *_test.dylib ``` -------------------------------- ### Configure and Build C++ REST SDK for Android Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Android-on-Linux-(2.3) Create a build directory and configure the SDK build process using the provided script, specifying the Android NDK path. This command compiles the SDK for Android, generating binaries in specified folders. ```bash mkdir build cd build ../configure.sh --ndk ~/android-ndk-r10 ``` -------------------------------- ### Connect to WebSocket Endpoint Source: https://github.com/microsoft/cpprestsdk/wiki/Web-Socket Create a websocket_client instance and connect to a specified URI. The connect function returns a task that can be awaited. ```c++ websocket_client client; client.connect(U("ws://localhost:1234")).then([](){ /* We've finished connecting. */ }); ``` -------------------------------- ### Run VS110COMNTOOLS vsvars32.bat Source: https://github.com/microsoft/cpprestsdk/wiki/Setting-up-Visual-Studio-command-line-prompt Execute this command to set up the Visual Studio 2012 command line prompt environment. ```cmd %VS110COMNTOOLS%\vsvars32.bat ``` -------------------------------- ### Check Task Completion Status Source: https://github.com/microsoft/cpprestsdk/wiki/Programming-with-Tasks Checks if an asynchronous operation represented by a task has completed. This can be used to determine if `get()` can be called without blocking. ```c++ bool done = resp.is_done(); ``` -------------------------------- ### Configure HTTP Client Implementation (CMake) Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/src/CMakeLists.txt Selects the HTTP client implementation based on the CPPREST_HTTP_CLIENT_IMPL variable. This snippet shows configurations for 'asio', 'winhttppal', and 'winhttp' implementations, including dependency finding and source file inclusion. ```cmake if(CPPREST_HTTP_CLIENT_IMPL STREQUAL "asio") cpprest_find_boost() cpprest_find_openssl() target_compile_definitions(cpprest PUBLIC -DCPPREST_FORCE_HTTP_CLIENT_ASIO) target_sources(cpprest PRIVATE http/client/http_client_asio.cpp http/client/x509_cert_utilities.cpp) target_link_libraries(cpprest PUBLIC cpprestsdk_boost_internal cpprestsdk_openssl_internal) elseif(CPPREST_HTTP_CLIENT_IMPL STREQUAL "winhttppal") cpprest_find_boost() cpprest_find_openssl() cpprest_find_winhttppal() target_compile_definitions(cpprest PUBLIC -DCPPREST_FORCE_HTTP_CLIENT_WINHTTPPAL) target_sources(cpprest PRIVATE http/client/http_client_winhttp.cpp http/client/x509_cert_utilities.cpp) target_link_libraries(cpprest PUBLIC cpprestsdk_boost_internal cpprestsdk_openssl_internal cpprestsdk_winhttppal_internal) elseif(CPPREST_HTTP_CLIENT_IMPL STREQUAL "winhttp") target_link_libraries(cpprest PRIVATE Winhttp.lib ) target_sources(cpprest PRIVATE http/client/http_client_winhttp.cpp) if(CPPREST_WEBSOCKETS_IMPL STREQUAL "wspp") target_sources(cpprest PRIVATE http/client/x509_cert_utilities.cpp) endif() elseif(CPPREST_HTTP_CLIENT_IMPL STREQUAL "winrt") target_sources(cpprest PRIVATE http/client/http_client_winrt.cpp) else() message(FATAL_ERROR "Invalid implementation") endif() ``` -------------------------------- ### Configure C++ REST SDK for 32/64-bit Architectures and Deployment Target Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-iOS Configure the build to include 32-bit architectures and set the minimum iOS deployment target to 10.0 using `configure.sh` arguments. ```bash ./configure.sh -deployment_target 10.0 -include_32bit ``` -------------------------------- ### Include HTTP Client and File Stream Headers Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial Include the necessary header files for using http_client and asynchronous file streams in Casablanca. ```cpp #include #include ``` -------------------------------- ### Compile and Run a C++ Program with SDK Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Linux Compiles a C++ file using g++ with C++11 standard, linking necessary libraries like boost_system, crypto, ssl, and cpprest. Then, it runs the compiled executable. ```bash g++ -std=c++11 my_file.cpp -o my_file -lboost_system -lcrypto -lssl -lcpprest ./my_file ``` -------------------------------- ### Run VS120COMNTOOLS vsvars32.bat Source: https://github.com/microsoft/cpprestsdk/wiki/Setting-up-Visual-Studio-command-line-prompt Execute this command to set up the Visual Studio 2013 command line prompt environment. ```cmd %VS120COMNTOOLS%\vsvars32.bat ``` -------------------------------- ### C++ REST SDK Build Configuration Arguments Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-iOS Lists the available arguments for the `configure.sh` script, which allow customization of the iOS build, such as build type, deployment target, and architecture inclusion. ```bash Usage: configure.sh [-build_type type] [-deployment_target version] [-config_only] [-include_32bit] [-no_bitcode] -build_type defines the CMAKE_BUILD_TYPE used. Defaults to Release. -deployment_target defines minimum iOS Deployment Target. The default is dependent on ios.toolchain.cmake and currently defaults to 8.0 -config_only only configures cmake (no make invoked). -include_32bit includes the 32-bit arm architectures. -no_bitcode disables bitcode ``` -------------------------------- ### Clone and Configure C++ REST SDK for iOS Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-iOS Clone the C++ REST SDK repository and run the configuration script to prepare for iOS builds. This script downloads and builds necessary dependencies like Boost and OpenSSL if they are not found. ```bash git clone https://github.com/Microsoft/cpprestsdk.git casablanca pushd casablanca/Build_iOS ./configure.sh ``` -------------------------------- ### Configure CMake Build with Vcpkg Toolchain Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Windows Configure the CMake build for cpprestsdk, specifying the architecture and the Vcpkg toolchain file. Replace the placeholder with your actual Vcpkg path. ```bash cpprestsdk> mkdir build.x64v141 cpprestsdk> cd build.x64v141 cpprestsdk/build.x64v141> cmake ../Release -A x64 -DCMAKE_TOOLCHAIN_FILE=/REPLACE_THIS_WITH_PATH_TO/vcpkg/scripts/buildsystems/vcpkg.cmake ``` -------------------------------- ### Build SearchFile Executable Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/SearchFile/CMakeLists.txt Adds the SearchFile executable and links it against the cpprest library. This is only done when not building for Windows Store or Windows Phone. ```cmake if (NOT WINDOWS_STORE AND NOT WINDOWS_PHONE) add_executable(SearchFile searchfile.cpp) target_link_libraries(SearchFile cpprest) endif() ``` -------------------------------- ### Build OAuth1 Client Executable Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/Oauth1Client/CMakeLists.txt This snippet shows how to add an executable for the OAuth1 client and link it with the cpprest library. It is conditional on not building for Windows Store or Windows Phone. ```cmake if (NOT WINDOWS_STORE AND NOT WINDOWS_PHONE) add_executable(oauth1client Oauth1Client.cpp ) target_link_libraries(oauth1client cpprest) endif() ``` -------------------------------- ### Build SDK in Debug Mode Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Mac-OS-X Configure the build using CMake with the Ninja generator and set the build type to Debug. Then, compile the project. ```shell mkdir build.debug cd build.debug cmake -G Ninja ../Release -DCMAKE_BUILD_TYPE=Debug ninja ``` -------------------------------- ### Set Message Handler for Callback Client Source: https://github.com/microsoft/cpprestsdk/wiki/Web-Socket Initialize a websocket_callback_client, connect to an endpoint, and set a message handler callback to process incoming messages from the server. ```c++ websocket_callback_client client; client.connect(U("ws://localhost:1234")).then([](){ /* We've finished connecting. */ }); // set receive handler client.set_message_handler([](websocket_incoming_message msg) { // handle message from server... }); ``` -------------------------------- ### Build SDK in Release Mode Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Mac-OS-X To build the Release version, replace 'Debug' with 'Release' in the CMake configuration command. ```shell mkdir build.release cd build.release cmake -G Ninja ../Release -DCMAKE_BUILD_TYPE=Release ninja ``` -------------------------------- ### Configure C++ REST SDK with Disabled Bitcode and Configuration Only Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-iOS Run `configure.sh` with `-no_bitcode` to disable bitcode generation and `-config_only` to only configure CMake without invoking the build process. ```bash ./configure.sh -no_bitcode -config_only ``` -------------------------------- ### Configure OAuth2 Client Executable Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/Oauth2Client/CMakeLists.txt Defines the OAuth2 client executable and links it with the cpprest library. This configuration is applied only when not building for Windows Store or Windows Phone. ```cmake if (NOT WINDOWS_STORE AND NOT WINDOWS_PHONE) add_executable(oauth2client Oauth2Client.cpp ) target_link_libraries(oauth2client cpprest) endif() ``` -------------------------------- ### Include WebSocket Client Headers Source: https://github.com/microsoft/cpprestsdk/wiki/Web-Socket Include the necessary header file for WebSocket client functionality and bring the relevant namespaces into scope. ```c++ #include using namespace web; using namespace web::websockets::client; ``` -------------------------------- ### Build C++ REST SDK in Debug Mode Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Linux Configures the build using CMake with Ninja as the generator and sets the build type to Debug. Then, it compiles the SDK. ```bash cd casablanca mkdir build.debug cd build.debug cmake -G Ninja .. -DCMAKE_BUILD_TYPE=Debug ninja ``` -------------------------------- ### Clone cpprestsdk Repository Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Windows Use this command to download the source code for cpprestsdk from GitHub. ```bash git clone https://github.com/Microsoft/cpprestsdk.git ``` -------------------------------- ### Initialize C++ REST SDK in Shared Libraries (JNI_OnLoad) Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Android-on-Windows Include this code in your main cpp file for shared library projects to initialize the C++ REST SDK via JNI_OnLoad, ensuring proper JVM access. ```cpp extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env; if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return -1; } cpprest_init(vm); return JNI_VERSION_1_6; } ``` -------------------------------- ### Create Test Runner Executable Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/common/TestRunner/CMakeLists.txt Creates the main test runner executable and links necessary libraries. Includes platform-specific manifest files for Windows. ```cmake add_executable(test_runner test_runner.cpp test_module_loader.cpp) target_link_libraries(test_runner PRIVATE unittestpp ${CMAKE_DL_LIBS}) if (WIN32) target_sources(test_runner PRIVATE test_runner.manifest) endif() ``` -------------------------------- ### Link Blackjack Client with cpprest Library Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BlackJack/BlackJack_Client/CMakeLists.txt Links the blackjackclient executable against the cpprest library, making its functionalities available. ```cmake target_link_libraries(blackjackclient cpprest) ``` -------------------------------- ### Configure Build for Unix Systems Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BlackJack/BlackJack_Client/CMakeLists.txt Adds a definition to disable switch warnings specifically for Unix-based systems during the build process. ```cmake if (UNIX) add_definitions(-Wno-switch) endif() ``` -------------------------------- ### Add Subdirectories for Build Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/CMakeLists.txt Includes subdirectories for building the 'src', 'tests', and 'samples' components of the project. The inclusion of 'tests' and 'samples' is conditional on the BUILD_TESTS and BUILD_SAMPLES variables, respectively. ```cmake add_subdirectory(src) if(BUILD_TESTS) add_subdirectory(tests) endif() if(BUILD_SAMPLES) add_subdirectory(samples) endif() ``` -------------------------------- ### Configure HTTP Listener Test Target Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/functional/http/listener/CMakeLists.txt Sets up the sources and test target for HTTP listener tests. This configuration is applied only when not building for Windows Store or Windows Phone. ```cmake if(NOT WINDOWS_STORE AND NOT WINDOWS_PHONE) set (SOURCES building_response_tests.cpp connections_and_errors.cpp header_tests.cpp listener_construction_tests.cpp reply_helper_tests.cpp request_extract_tests.cpp request_handler_tests.cpp request_relative_uri_tests.cpp request_stream_tests.cpp requests_tests.cpp response_stream_tests.cpp status_code_reason_phrase_tests.cpp to_string_tests.cpp ) add_casablanca_test(httplistener_test SOURCES) if(TEST_LIBRARY_TARGET_TYPE STREQUAL "OBJECT") target_include_directories(httplistener_test PRIVATE ../utilities/include) else() target_link_libraries(httplistener_test PRIVATE httptest_utilities) endif() configure_pch(httplistener_test stdafx.h stdafx.cpp) endif() ``` -------------------------------- ### Configure Precompiled Headers in CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/functional/utils/CMakeLists.txt Sets up precompiled headers for the test target. This can improve build times by pre-compiling common header files. ```cmake configure_pch(utils_test stdafx.h stdafx.cpp) ``` -------------------------------- ### Initialize C++ REST SDK in Native Activity Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Android-on-Windows Add this code at the top of the android_main function for NativeActivity projects to initialize the C++ REST SDK with the JVM pointer. ```cpp cpprest_init(state->activity->vm); ``` -------------------------------- ### Build BingRequest Executable with CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BingRequest/CMakeLists.txt This snippet defines how to add an executable target for the BingRequest sample and link it against the cpprest library. It is only included when not building for Windows Store or Windows Phone. ```cmake if (NOT WINDOWS_STORE AND NOT WINDOWS_PHONE) add_executable(BingRequest bingrequest.cpp) target_link_libraries(BingRequest cpprest) endif() ``` -------------------------------- ### Set Output Directories Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/CMakeLists.txt Configures the final output directories for runtime, library, and archive artifacts to a 'Binaries' subdirectory within the project's binary build directory. ```cmake set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries) ``` -------------------------------- ### Link cpprest Library Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BlackJack/BlackJack_Server/CMakeLists.txt Links the 'cpprest' library to the blackjackserver executable, making its functionalities available. ```cmake target_link_libraries(blackjackserver cpprest) ``` -------------------------------- ### Clone C++ REST SDK Repository Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-Linux Clones the C++ REST SDK project from GitHub into a local directory named 'casablanca'. ```bash git clone https://github.com/Microsoft/cpprestsdk.git casablanca ``` -------------------------------- ### Add Blackjack Server Executable Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BlackJack/BlackJack_Server/CMakeLists.txt Defines the main executable target for the Blackjack server and lists its source files. ```cmake add_executable(blackjackserver BlackJack_Server.cpp Dealer.cpp Table.cpp ) ``` -------------------------------- ### Configure HTTP Test Utilities Library Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/functional/http/utilities/CMakeLists.txt Defines the sources, library type, and dependencies for the httptest_utilities library. Includes conditional compilation for Windows exports and specific Windows Store app options. ```cmake set(SOURCES http_asserts.cpp test_http_client.cpp test_http_server.cpp test_server_utilities.cpp ) add_library(httptest_utilities ${SOURCES}) if(WIN32) target_compile_definitions(httptest_utilities PRIVATE -DHTTPTESTUTILITY_EXPORTS) endif() target_include_directories(httptest_utilities PUBLIC include) target_link_libraries(httptest_utilities PUBLIC cpprest unittestpp common_utilities ) if(WINDOWS_STORE) target_compile_options(httptest_utilities PRIVATE /DWINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP) endif() ``` -------------------------------- ### Add Websocket Test Utilities Library Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/functional/websockets/CMakeLists.txt Defines a library for websocket test utilities, including source files, include directories, and compile definitions. It also handles platform-specific API visibility. ```cmake if (NOT CPPREST_EXCLUDE_WEBSOCKETS) add_library(websockettest_utilities utilities/test_websocket_server.cpp) target_include_directories(websockettest_utilities PUBLIC utilities) target_compile_definitions(websockettest_utilities PRIVATE -DWEBSOCKETTESTUTILITY_EXPORTS) if(NOT WIN32) target_compile_definitions(websockettest_utilities PRIVATE "-DWEBSOCKET_UTILITY_API=__attribute__ ((visibility ("default")))") target_compile_definitions(websockettest_utilities INTERFACE "-DWEBSOCKET_UTILITY_API=") endif() cpprest_find_websocketpp() target_link_libraries(websockettest_utilities PRIVATE cpprest unittestpp common_utilities cpprestsdk_websocketpp_internal ) endif() ``` -------------------------------- ### Configure Common Utilities Library Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/common/utilities/CMakeLists.txt Defines the common_utilities library, sets include directories, and links necessary dependencies. This configuration is essential for building the utility library within the project. ```cmake include_directories(include) if(WIN32) add_definitions(-DCOMMONUTILITIES_EXPORTS) endif() add_library(common_utilities os_utilities.cpp ) if(NOT BUILD_SHARED_LIBS) target_compile_definitions(common_utilities INTERFACE -DTEST_UTILITY_API=) endif() target_link_libraries(common_utilities cpprest unittestpp ) ``` -------------------------------- ### Configure Precompiled Headers Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BlackJack/BlackJack_Server/CMakeLists.txt Configures precompiled headers for the blackjackserver target using specified header and source files, with a specific memory pool size. ```cmake configure_pch(blackjackserver stdafx.h stdafx.cpp /Zm120) ``` -------------------------------- ### Configure File I/O Streams Implementation (CMake) Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/src/CMakeLists.txt Selects the file I/O streams implementation based on the CPPREST_FILEIO_IMPL variable. This snippet shows configurations for 'win32', 'winrt', and 'posix' implementations. ```cmake if(CPPREST_FILEIO_IMPL STREQUAL "win32") target_sources(cpprest PRIVATE streams/fileio_win32.cpp) elseif(CPPREST_FILEIO_IMPL STREQUAL "winrt") target_sources(cpprest PRIVATE streams/fileio_winrt.cpp) elseif(CPPREST_FILEIO_IMPL STREQUAL "posix") target_sources(cpprest PRIVATE streams/fileio_posix.cpp) else() message(FATAL_ERROR "Invalid implementation") endif() ``` -------------------------------- ### Link Object Libraries for Windows (Non-Store/Phone) Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/common/TestRunner/CMakeLists.txt Links test object libraries directly to the test runner on Windows for non-Store/Phone builds. This approach is used to emulate --whole-archive behavior. ```cmake target_sources(test_runner PRIVATE $ $ $ $ $ $ ) if(NOT WINDOWS_STORE AND NOT WINDOWS_PHONE) target_sources(test_runner PRIVATE $) endif() target_link_libraries(test_runner PRIVATE common_utilities httptest_utilities cpprest ) if(TARGET websockettest_utilities) target_link_libraries(test_runner PRIVATE websockettest_utilities) endif() if(CPPREST_WEBSOCKETS_IMPL STREQUAL "wspp") cpprest_find_websocketpp() target_link_libraries(test_runner PRIVATE cpprestsdk_websocketpp_internal) endif() ``` -------------------------------- ### Define Casablanca Library Variables Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/CMakeLists.txt Sets variables for Casablanca library include directories and library names. It also attempts to include a parent directory's libraries if one exists. ```cmake set(Casablanca_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include) set(Casablanca_LIBRARY cpprest) set(Casablanca_LIBRARIES cpprest) get_directory_property(PARENT_DIR PARENT_DIRECTORY) if(NOT PARENT_DIR STREQUAL "") set(Casablanca_LIBRARIES ${Casablanca_LIBRARIES} PARENT_SCOPE) endif() ``` -------------------------------- ### Set Include Directories in CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/CMakeLists.txt Sets the include directories for UnitTest++ and Utilities. These paths are relative to the current source directory. ```cmake set(UnitTestpp_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/common/UnitTestpp) set(Utilities_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/common/utilities/include) ``` -------------------------------- ### Define Test Sources in CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/functional/utils/CMakeLists.txt Lists the source files to be compiled for the test executable. These files contain the actual test logic and utility functions. ```cmake set(SOURCES datetime.cpp base64.cpp strings.cpp macro_test.cpp nonce_generator_tests.cpp win32_encryption_tests.cpp ) ``` -------------------------------- ### Configure C++ REST SDK with Debug Build Type Source: https://github.com/microsoft/cpprestsdk/wiki/How-to-build-for-iOS Use the `-build_type Debug` argument with `configure.sh` to generate a debug version of the static library for iOS. ```bash ./configure.sh -build_type Debug ``` -------------------------------- ### Include Directories for Compilation in CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/CMakeLists.txt Adds the previously defined UnitTestpp_INCLUDE_DIR and Utilities_INCLUDE_DIR to the compiler's include path. ```cmake include_directories (${UnitTestpp_INCLUDE_DIR} ${Utilities_INCLUDE_DIR}) ``` -------------------------------- ### Open File Stream for Writing Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial Opens an asynchronous stream to a file for writing. This pattern is used for potentially blocking I/O operations. ```c++ auto fileStream = std::make_shared(); // Open stream to output file. pplx::task requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile) { *fileStream = outFile; }); ``` -------------------------------- ### Send Binary Message Source: https://github.com/microsoft/cpprestsdk/wiki/Web-Socket Prepare and send a binary message using a producer-consumer buffer. Includes error handling for the send operation. ```c++ websocket_outgoing_message msg; concurrency::streams::producer_consumer_buffer buf; std::vector body(6); memcpy(&body[0], "a\0b\0c\0", 6); auto send_task = buf.putn(&body[0], body.size()).then([&](size_t length) { msg.set_binary_message(buf.create_istream(), length); return client.send(msg); }).then([](pplx::task t) { try { t.get(); } catch(const websocket_exception& ex) { std::cout << ex.what(); } }); send_task.wait(); ``` -------------------------------- ### Add Test Executable Target in CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/functional/utils/CMakeLists.txt Creates a CMake target for the test executable, using the previously defined source files. This command is specific to the Casablanca library's build system. ```cmake add_casablanca_test(utils_test SOURCES) ``` -------------------------------- ### Define Other Important Casablanca Namespaces Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial Other important namespaces in Casablanca that are not used in this specific tutorial, including those for HTTP server, WebSockets client, and JSON library. ```cpp using namespace web::http::experimental::listener; // HTTP server using namespace web::experimental::web_sockets::client; // WebSockets client using namespace web::json; // JSON library ``` -------------------------------- ### Define Common Casablanca Namespaces Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial Use statements to avoid repeatedly typing common Casablanca namespaces for utilities, web features, HTTP client, and asynchronous streams. ```cpp using namespace utility; // Common utilities like string conversions using namespace web; // Common features like URIs. using namespace web::http; // Common HTTP functionality using namespace web::http::client; // HTTP client features using namespace concurrency::streams; // Asynchronous streams ``` -------------------------------- ### Define Blackjack Client Executable Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BlackJack/BlackJack_Client/CMakeLists.txt Defines the main executable target for the Blackjack client, specifying its source files. ```cmake add_executable(blackjackclient BlackJackClient.cpp ) ``` -------------------------------- ### Define Websockets Client Test Target Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/functional/websockets/CMakeLists.txt Configures the websockets client test executable, specifying its source files and linking it with necessary libraries and utilities. This is conditional on websockets being enabled. ```cmake # websocketsclient_test set(SOURCES client/authentication_tests.cpp client/client_construction.cpp client/close_tests.cpp client/error_tests.cpp client/receive_msg_tests.cpp client/send_msg_tests.cpp client/stdafx.cpp ) add_casablanca_test(websocketsclient_test SOURCES) if(NOT TEST_LIBRARY_TARGET_TYPE STREQUAL "OBJECT") target_link_libraries(websocketsclient_test PRIVATE websockettest_utilities) endif() target_include_directories(websocketsclient_test PRIVATE utilities) endif() ``` -------------------------------- ### Link Libraries for Unix Platforms Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/common/TestRunner/CMakeLists.txt Links test libraries to the test runner on Unix platforms using whole-archive linker option to ensure all symbols are included. ```cmake elseif(UNIX) target_link_libraries(test_runner PRIVATE -Wl,--whole-archive httpclient_test json_test uri_test pplx_test httplistener_test streams_test utils_test -Wl,--no-whole-archive ) ``` -------------------------------- ### Handle HTTP Response Headers Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial A task continuation that is signaled when HTTP response headers arrive. It prints the status code of the response. ```c++ // Handle response headers arriving. .then([=](http_response response) { printf("Received response status code:%u\n", response.status_code()); }); ``` -------------------------------- ### Link Debug Libraries for Windows Store Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/common/TestRunner/CMakeLists.txt Links specific debug libraries required for Windows Store builds. ```cmake if (WINDOWS_STORE) target_link_libraries(test_runner PRIVATE ucrtd.lib vcruntimed.lib vccorlibd.lib msvcrtd.lib msvcprtd.lib concrtd.lib RuntimeObject.lib) endif() ``` -------------------------------- ### Receive and Extract String Message Source: https://github.com/microsoft/cpprestsdk/wiki/Web-Socket Asynchronously receive a message, extract its content as a string, and process it. Note that only one receive() call is fulfilled per message. ```c++ client.receive().then([](websocket_incoming_message msg) { return msg.extract_string(); }).then([](std::string body) { std::cout << body << std::endl; }); ``` -------------------------------- ### Link Libraries for Apple Platforms Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/common/TestRunner/CMakeLists.txt Links test libraries to the test runner on Apple platforms using force_load linker option to ensure all symbols are included. ```cmake elseif(APPLE) target_link_libraries(test_runner PRIVATE -Wl,-force_load httpclient_test -Wl,-force_load json_test -Wl,-force_load uri_test -Wl,-force_load pplx_test -Wl,-force_load httplistener_test -Wl,-force_load streams_test -Wl,-force_load utils_test ) ``` -------------------------------- ### Define Build Flags for Unix Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BlackJack/BlackJack_Server/CMakeLists.txt Adds specific compiler flags for sign and enum comparisons when building on Unix-like systems. ```cmake if (UNIX) add_definitions(-Wno-sign-compare -Wno-enum-compare) endif() ``` -------------------------------- ### Add Casablanca Test Library Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/CMakeLists.txt A CMake function to add test libraries for Casablanca. It handles different test library target types (e.g., OBJECT) and links necessary dependencies. For non-OBJECT types, it also sets up test execution if shared libraries are being built. ```cmake function(add_casablanca_test NAME SOURCES_VAR) add_library(${NAME} ${TEST_LIBRARY_TARGET_TYPE} ${${SOURCES_VAR}}) message("-- Added test library ${NAME}") if(TEST_LIBRARY_TARGET_TYPE STREQUAL "OBJECT") foreach(_dep cpprest common_utilities unittestpp) target_include_directories(${NAME} PRIVATE $) target_compile_definitions(${NAME} PRIVATE $) endforeach() else() target_link_libraries(${NAME} PRIVATE cpprest common_utilities unittestpp ${ANDROID_LIBS} ) if (BUILD_SHARED_LIBS) add_test(NAME ${NAME} WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} COMMAND test_runner $ ) endif() endif() endfunction() ``` -------------------------------- ### Define Test Runner Symbols Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/common/TestRunner/CMakeLists.txt Defines preprocessor symbols for the test runner based on the Windows platform. Use WINRT_TEST_RUNNER for Windows Store/Phone and DESKTOP_TEST_RUNNER for other Windows environments. ```cmake if (WIN32) if (WINDOWS_STORE OR WINDOWS_PHONE) add_definitions(-DWINRT_TEST_RUNNER -D_CONSOLE) else() add_definitions(-DDESKTOP_TEST_RUNNER) endif() endif() ``` -------------------------------- ### Add Subdirectories in CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/tests/CMakeLists.txt Includes the 'common' and 'functional' subdirectories into the build. This allows for modular project structure. ```cmake add_subdirectory(common) add_subdirectory(functional) ``` -------------------------------- ### Convert JSON to C++ Types Source: https://github.com/microsoft/cpprestsdk/wiki/JSON Use `as_xxx()` methods to explicitly convert JSON values to C++ types. Attempting to convert to an incompatible type will throw a `json::json_exception`. ```javascript int i = v1.as_integer(); double d = v2.as_double(); bool b = v3.as_bool(); utility::string_t s = v4.as_string(); ``` -------------------------------- ### Write Response Body to File Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial Reads the entire response body from the HTTP response stream and writes it to the opened file stream. This operation is asynchronous. ```c++ // Handle response headers arriving. .then([=](http_response response) { printf("Received response status code:%u\n", response.status_code()); // Write response body into the file. return response.body().read_to_end(fileStream->streambuf()); }); ``` -------------------------------- ### Wait for Asynchronous Operations and Handle Exceptions Source: https://github.com/microsoft/cpprestsdk/wiki/Getting-Started-Tutorial Waits for all pending asynchronous I/O operations to complete and safely handles any exceptions that may occur during the process. ```c++ // Wait for all the outstanding I/O to complete and handle any exceptions try { requestTask.wait(); } catch (const std::exception &e) { ``` -------------------------------- ### Construct JSON Values Source: https://github.com/microsoft/cpprestsdk/wiki/JSON Create JSON values of different types (null, number, boolean, string, object, array) using factory functions. Objects and arrays can be mutated after creation. ```javascript using namespace web; ... json::value v0 = json::value::null(); json::value v1 = json::value::number(17); json::value v2 = json::value::number(3.1415); json::value v3 = json::value::boolean(true); json::value v4 = json::value::string(U("Hello Again!")); json::value v5 = json::value::object(); json::value v6 = json::value::array(); ``` -------------------------------- ### Retrieve Task Result Immediately Source: https://github.com/microsoft/cpprestsdk/wiki/Programming-with-Tasks Retrieves the result of a task. This is safe to call without blocking if `is_done()` has returned true. ```c++ web::http::http_response response = resp.get(); ``` -------------------------------- ### Conditional Subdirectory Addition in CMake Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/BlackJack/CMakeLists.txt This snippet conditionally adds subdirectories for Blackjack server and client builds. It is used when not building for Windows Store or Windows Phone targets. ```cmake if (NOT WINDOWS_STORE AND NOT WINDOWS_PHONE) add_subdirectory(BlackJack_Server) add_subdirectory(BlackJack_Client) else() # TODO: add BlackJack_UIClient endif() ``` -------------------------------- ### Send UTF-8 Message Source: https://github.com/microsoft/cpprestsdk/wiki/Web-Socket Send a UTF-8 encoded string message asynchronously over the WebSocket connection. A callback is executed upon successful sending. ```c++ websocket_outgoing_message msg; msg.set_utf8_message("I am a UTF-8 string! (Or close enough...)"); client.send(msg).then([](){ /* Successfully sent the message. */ }); ``` -------------------------------- ### Close WebSocket Connection Source: https://github.com/microsoft/cpprestsdk/wiki/Web-Socket Asynchronously close the WebSocket connection. A callback is executed upon successful closure. ```c++ client.close().then([](){ /* Successfully closed the connection. */ }); ``` -------------------------------- ### Configure Precompiled Headers (PCH) for MSVC Source: https://github.com/microsoft/cpprestsdk/blob/master/Release/CMakeLists.txt A CMake function to configure precompiled headers for MSVC targets. It handles differences between Visual Studio generators and others, setting appropriate compile flags for PCH creation (/Yc) and usage (/Yu). ```cmake function(configure_pch target precompile_header precomile_source) # optional additional compile arguments if(MSVC) get_target_property(_srcs ${target} SOURCES) set(pch_output_filepath_arg) if(NOT CMAKE_GENERATOR MATCHES "Visual Studio .*" ) set_property(SOURCE ${precomile_source} APPEND PROPERTY OBJECT_OUTPUTS "${CMAKE_CURRENT_BINARY_DIR}/${target}.pch") set_property(SOURCE ${_srcs} APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/${target}.pch") set(pch_output_filepath_arg "/Fp${CMAKE_CURRENT_BINARY_DIR}/${target}.pch") else() # Don't specify output file so that VS may choose a config spefic location. # Otherwise Debug/Release builds will interfere with one another. endif() set_source_files_properties(${precomile_source} PROPERTIES COMPILE_FLAGS "/Yc${precompile_header}") target_sources(${target} PRIVATE ${precomile_source}) # Note: as ${precomile_source} is also a SOURCE for ${target}, the below options will also be applied. # ${precomile_source} has /Yc option that will cause the shared /Yu to be ignored. target_compile_options(${target} PRIVATE /Yu${precompile_header} ${pch_output_filepath_arg} ${ARGN}) endif() endfunction() ```