Skip to content

This repository is for active development of the Azure SDK for C++.

License

Notifications You must be signed in to change notification settings

Jinming-Hu/azure-sdk-for-cpp

 
 

Repository files navigation

Azure SDK for C++

Build Status

This repository is for active development of the Azure SDK for C++. For consumers of the SDK we recommend visiting our developer docs.

Getting started

The Azure SDK for C++ is compatible with a number of different development environments and tools. The following instructions will utilize Visual Studio or VSCode as the IDE, CMake for build automation, and vcpkg as our package manager.

Prerequisites

Development environment and tools set up

Install libraries

  • Open a terminal
    • Visual Studio: Open the Developer Command Prompt: Tools > Commandline > Developer Command Prompt
    • VSCode: Open a new Terminal in VSCode: Terminal > New Terminal
  • Add the azure-identity-cpp and azure-storage-blobs-cpp libraries with the following command:
vcpkg add port azure-identity-cpp azure-storage-blobs-cpp
  • Your vcpkg.json should now contain:
{
    "dependencies": [
        "azure-identity-cpp",
        "azure-storage-blobs-cpp"
    ]
}

Configure project files

  • Replace the contents of CMakeLists.txt with the following:
cmake_minimum_required(VERSION 3.10)

project(HelloWorld)

find_package(azure-identity-cpp CONFIG REQUIRED)
find_package(azure-storage-blobs-cpp CONFIG REQUIRED)

add_executable(HelloWorld helloworld.cpp)

target_link_libraries(HelloWorld PRIVATE Azure::azure-identity Azure::azure-storage-blobs)

Additional methods for installing and configuring

Using the SDK within your application

The entry point for most scenarios when using the SDK will be a top-level client type corresponding to the Azure service. For example, sending requests to blob storage can be done via the Azure::Storage::Blobs::BlobClient API. All APIs on the client type send HTTP requests to the cloud service and return back an HTTP Response<T>.

Azure C++ SDK headers needed are located within the <azure> folder, with sub-folders corresponding to each service. Similarly, all types and APIs can be found within the Azure:: namespace. For example, to use functionality from Azure::Core, include the following header at the beginning of your application #include <azure/core.hpp>.

Here's an example application to help you get started:

#include <iostream>

// Include the necessary SDK headers
#include <azure/core.hpp>
#include <azure/storage/blobs.hpp>

// Add appropriate using namespace directives
using namespace Azure::Storage;
using namespace Azure::Storage::Blobs;

// Secrets should be stored & retrieved from secure locations such as Azure::KeyVault. For
// convenience and brevity of samples, the secrets are retrieved from environment variables.
std::string GetEndpointUrl() { return std::getenv("AZURE_STORAGE_ACCOUNT_URL"); }
std::string GetAccountName() { return std::getenv("AZURE_STORAGE_ACCOUNT_NAME"); }
std::string GetAccountKey() { return std::getenv("AZURE_STORAGE_ACCOUNT_KEY"); }

int main()
{
  std::string endpointUrl = GetEndpointUrl();
  std::string accountName = GetAccountName();
  std::string accountKey = GetAccountKey();

  try
  {
    auto sharedKeyCredential = std::make_shared<StorageSharedKeyCredential>(accountName, accountKey);

    auto blockBlobClient = BlockBlobClient(endpointUrl, sharedKeyCredential);

    // Create some data to upload into the blob.
    std::vector<uint8_t> data = {1, 2, 3, 4};
    Azure::Core::IO::MemoryBodyStream stream(data);

    Azure::Response<Models::UploadBlockBlobResult> response = blockBlobClient.Upload(stream);

    Models::UploadBlockBlobResult model = response.Value;
    std::cout << "Last modified date of uploaded blob: " << model.LastModified.ToString()
              << std::endl;
  }
  catch (const Azure::Core::RequestFailedException& e)
  {
    std::cout << "Status Code: " << static_cast<int>(e.StatusCode)
              << ", Reason Phrase: " << e.ReasonPhrase << std::endl;
    std::cout << e.what() << std::endl;
    return 1;
  }
  return 0;
}

Build and run the project

  • Visual Studio: Press Ctrl+Shift+B to build the project in Visual Studio. Then click the run play button.
  • VSCode: Open the Command Palette with Ctrl+Shift+P and run the CMake: Build command. Select the default CMake preset. Then launch the project.

Key Core concepts

Understanding the key concepts from the Azure Core library, which is leveraged by all client libraries is helpful in getting started, regardless of which Azure service you want to use.

The main shared concepts of Azure Core include:

  • Accessing HTTP response details for the returned model of any SDK client operation, via Response<T>.
  • Exceptions for reporting errors from service requests in a consistent fashion via the base exception type RequestFailedException.
  • Abstractions for Azure SDK credentials (TokenCredential).
  • Handling streaming data and input/output (I/O) via BodyStream along with its derived types.
  • Polling long-running operations (LROs), via Operation<T>.
  • Collections are returned via PagedResponse<T>.
  • HTTP pipeline and HTTP policies such as retry and logging, which are configurable via service client specific options.
  • Replaceable HTTP transport layer to send requests and receive responses over the network.

Response <T> Model Types

Many client library operations return the templated Azure::Core::Response<T> type from the API calls. This type let's you get the raw HTTP response from the service request call the Azure service APIs make, along with the result of the operation to get more API specific details. This is the templated T operation result which can be extracted from the response, using the Value field.

  // Azure service operations return a Response<T> templated type.
  Azure::Response<Models::BlobProperties> propertiesResponse = blockBlobClient.GetProperties();

  // You can get the T, from the returned Response<T>,
  // which is typically named with a Result suffix in the type name.
  Models::BlobProperties propertiesModel = propertiesResponse.Value;

  // Now you can look at API specific members on the result object that is returned.
  std::cout << "The size of the blob is: " << propertiesModel.BlobSize << std::endl;

Long Running Operations

Some operations take a long time to complete and require polling for their status. Methods starting long-running operations return Operation<T> types.

You can intermittently poll whether the operation has finished by using the Poll() method inside a loop on the returned Operation<T> and track progress of the operation using Value(), while the operation is not done (using IsDone()). Your per-polling custom logic can go in that loop, such as logging progress. Alternatively, if you just want to wait until the operation completes, you can use PollUntilDone().

  std::string sourceUri = "<a uri to the source blob to copy>";

  // Typically, long running operation APIs have names that begin with Start.
  StartBlobCopyOperation operation = blockBlobClient.StartCopyFromUri(sourceUri);

  // Waits for the operation to finish, checking for status every 1 second.
  auto copyResponse = operation.PollUntilDone(std::chrono::milliseconds(1000));
  auto propertiesModel = copyResponse.Value;

  // Now you can look at API specific members on the result object that is returned.
  if (propertiesModel.CopySource.HasValue())
  {
    std::cout << "The source of the copied blob is: " << propertiesModel.CopySource.Value()
              << std::endl;
  }

Interacting with Azure SDK for C++

Static SDK members should not be accessed and SDK functions should not be called before the static initialization phase is finished.

Visual Studio - CMakeSettings.json

When building your application via Visual Studio, you can create and update a CMakeSettings.json file and include the following properties to let Visual Studio know where the packages are installed and which triplet needs to be used:

{
  "configurations": [
    {
        "cmakeToolchain": "<path to vcpkg repo>/vcpkg/scripts/buildsystems/vcpkg.cmake",
        "variables": [
        {
          "name": "VCPKG_TARGET_TRIPLET",
          "value": "x64-windows",
          "type": "STRING"
        }
      ]
    }
  ]
}

Azure Requirements

To call Azure services, you must first have an Azure subscription. Sign up for a free trial or use your MSDN subscriber benefits.

Packages available

Each service might have a number of libraries available. These libraries follow the Azure SDK Design Guidelines for C++ and share a number of core features such as HTTP retries, logging, transport protocols, authentication protocols, etc., so that once you learn how to use these features in one client library, you will know how to use them in other client libraries. You can learn about these shared features at Azure::Core.

The client libraries can be identified by the naming used for their folder, package, and namespace. Each will start with azure, followed by the service category, and then the name of the service. For example azure-storage-blobs.

For a complete list of available packages, please see the latest available packages page.

NOTE: If you need to ensure your code is ready for production we strongly recommend using one of the stable, non-beta libraries.

Vcpkg

The following SDK library releases are available on vcpkg:

  • azure-core-cpp
  • azure-identity-cpp
  • azure-security-attestation-cpp
  • azure-security-keyvault-certificates-cpp
  • azure-security-keyvault-keys-cpp
  • azure-security-keyvault-secrets-cpp
  • azure-storage-blobs-cpp
  • azure-storage-files-datalake-cpp
  • azure-storage-files-shares-cpp
  • azure-storage-queues-cpp

NOTE: In case of getting linker errors when consuming the SDK on Windows, make sure that vcpkg triplet being consumed matches the CRT link flags being set for your app or library build. See also MSVC_USE_STATIC_CRT build flag.

OpenSSL Version

Several packages within the Azure SDK for C++ use the OpenSSL library. By default, the Azure SDK will use whatever the most recent version of OpenSSL is within the VCPKG repository.

Using a specific version of OpenSSL

If you need to use a specific version of OpenSSL, you can use the vcpkg custom ports feature to specify the version of OpenSSL to use. For example, if you want to use OpenSSL 1.1.1, you should create a folder named vcpkg-custom-ports next to to your vcpkg.json file.

Navigate to your clone of the vcpkg vcpkg repo and execute "git checkout 3b3bd424827a1f7f4813216f6b32b6c61e386b2e" - this will reset your repo to the last version of OpenSSL 1.1.1 in vcpkg. Then, copy the contents of the ports/openssl folder from the vcpkg repo to the vcpkg-custom-ports folder you created earlier:

cd <your vcpkg repo>
git checkout 3b3bd424827a1f7f4813216f6b32b6c61e386b2e
cd ports
cp -r openssl <the location of the vcpkg-custom-ports directory listed above>

This will copy the port information for OpenSSL 1.1.1n to your vcpkg-custom-ports directory.

Once that is done, you can install the custom port of OpenSSL 1.1.1n using the vcpkg tool:

vcpkg install --overlay-ports=<path to the vcpkg-custom-ports above>

If you are building using CMAKE, you can instruct CMAKE to apply the overlay ports using the following command line switches:

cmake -DVCPKG_MANIFEST_MODE=ON -DVCPKG_OVERLAY_PORTS=<path to the vcpkg-custom-ports above> -DVCPKG_MANIFEST_DIR=<path to the directory containing the vcpkg.json file>

In addition, if you need to consume OpenSSL from a dynamic linked library/shared object, you can set the VCPKG triplet to reflect that you want to build the library with dynamic entries. Set the VCPKG_you can set the environment variable to x64-windows-static or x64-windows-dynamic depending on whether you want to use the static or dynamic version of OpenSSL. Similarly you can use the x64-linux-dynamic and x64-linux-static triplet to specify consumption of libraries as a shared object or dynamic.

Using the system package manager to install OpenSSL

If you are using a Linux distribution that uses the system package manager to install libraries, you can use the system package manager to install OpenSSL.

The vcpkg team has a feature which allows you to use the system package manager to install dependencies.

Need help

Navigating the repository

Main branch

The main branch has the most recent code with new features and bug fixes. It does not represent latest released beta or GA SDK.

Release branches (Release tagging)

For each package we release there will be a unique Git tag created that contains the name and the version of the package to mark the commit of the code that produced the package. This tag will be used for servicing via hotfix branches as well as debugging the code for a particular beta or stable release version. Format of the release tags are <package-name>_<package-version>. For more information please see our branching strategy.

Contributing

For details on contributing to this repository, see the contributing guide.

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, view Microsoft's CLA.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Additional Helpful Links for Contributors

Many people all over the world have helped make this project better. You'll want to check out:

Reporting security issues and security bugs

Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter.

License

Azure SDK for C++ is licensed under the MIT license.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

Impressions

About

This repository is for active development of the Azure SDK for C++.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C++ 90.3%
  • PowerShell 6.1%
  • CMake 2.8%
  • CSS 0.5%
  • HTML 0.1%
  • Dockerfile 0.1%
  • Other 0.1%