Azure C++ SDK Documentation

Table of Contents

Getting Started

Welcome to the Azure C++ SDK! This guide will help you set up and start using the SDK to interact with Azure services from your C++ applications.

Prerequisites

Installation

The Azure C++ SDKs are distributed as libraries that you can integrate into your project using CMake.

Using vcpkg (Recommended)

vcpkg is a cross-platform C++ package manager. It's the easiest way to get and build libraries.

  1. Install vcpkg: https://github.com/microsoft/vcpkg
  2. Integrate vcpkg with your CMake toolchain file or use the CMake integration.
  3. Install a specific SDK, for example, Azure Core:
    vcpkg install azure-core

Manual Build

You can also clone the SDK repositories and build them manually.

  1. Clone the Azure SDK for C++ repository:
    git clone https://github.com/Azure/azure-sdk-for-cpp.git
  2. Navigate to the cloned directory and create a build directory:
    cd azure-sdk-for-cpp
    mkdir build
    cd build
  3. Configure the build with CMake, specifying the services you need:
    cmake .. -DBUILD_TESTING=OFF -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=./install
    (e.g., to build Azure Core and Storage)
  4. Build the SDK:
    cmake --build .
  5. Install the SDK (optional, but recommended for easier management):
    cmake --install .

Integrating with Your Project

In your CMakeLists.txt, find the installed SDKs using find_package. If you installed using vcpkg, CMake will automatically pick it up if it's integrated.

cmake_minimum_required(VERSION 3.8)
project(MyAzureApp)

# If using vcpkg
# set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_LIST_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file")

# Find Azure Core
find_package(Azure::core CONFIG REQUIRED)

# Find Azure Storage
find_package(Azure::storage::blobs CONFIG REQUIRED)

add_executable(my_app main.cpp)
target_link_libraries(my_app PRIVATE Azure::core Azure::storage::blobs)

Authentication

Azure SDKs support various authentication mechanisms to securely access Azure resources. The recommended approach is to use Managed Identity for Azure-hosted applications or Azure Identity libraries for local development and other scenarios.

DefaultAzureCredential

The Azure::Core::Credentials::DefaultAzureCredential is a convenient credential type that attempts to authenticate using a chain of strategies. This includes:

Example using DefaultAzureCredential

#include <azure/identity/default_azure_credential.hpp>
#include <azure/core/credentials.hpp>

// ...

Azure::Core::Credentials::TokenCredentialOptions options;
// options.TenantId = "YOUR_TENANT_ID"; // Optional: Specify tenant ID if needed
// options.ClientId = "YOUR_CLIENT_ID"; // Optional: Specify client ID for service principal
// options.ClientSecret = "YOUR_CLIENT_SECRET"; // Optional: Specify client secret for service principal

auto credential = std::make_unique<Azure::Identity::DefaultAzureCredential>(options);

// You can now pass this credential to service clients.
// For example, a blob client:
// auto blobClient = Azure::Storage::Blobs::BlobClient::CreateFromConnectionString("YOUR_CONNECTION_STRING");
// Or using the credential directly:
// auto blobServiceClient = Azure::Storage::Blobs::BlobServiceClient::CreateClient(endpoint, credential);

Note: For local development, ensure you are logged in via Azure CLI (az login) or have set the appropriate environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET) for DefaultAzureCredential to work.

Core Concepts

Understanding these core concepts will help you effectively use the Azure C++ SDK.

Clients

Each Azure service has one or more client classes (e.g., BlobClient, SecretClient). These clients are the primary interface for interacting with the service's API.

Models

Data structures used to represent requests and responses are defined in model classes (e.g., CreateBlobOptions, KeyVaultSecret).

Policies

Policies are reusable components that can be added to the SDK pipeline to perform actions such as retries, logging, or authentication.

Pipelines

A pipeline defines the sequence of policies that are applied to a request before it's sent to Azure and to the response after it's received.

Services

The Azure C++ SDK provides comprehensive support for various Azure services.

Azure Blob Storage

Interact with Azure Blob Storage to store and retrieve large amounts of unstructured data.

Key Classes

  • BlobServiceClient: Manages the blob service.
  • BlobContainerClient: Manages a blob container.
  • BlobClient: Manages a single blob.

Example: Upload a blob

#include <azure/storage/blobs/blob_client.hpp>
#include <azure/storage/blobs/blob_container_client.hpp>
#include <azure/storage/blobs/blob_service_client.hpp>
#include <azure/identity/default_azure_credential.hpp>
#include <fstream>
#include <vector>

// ...

auto credential = std::make_unique<Azure::Identity::DefaultAzureCredential>();
std::string blobStorageUrl = "YOUR_BLOB_STORAGE_ACCOUNT_URL"; // e.g., "https://myaccount.blob.core.windows.net"
std::string containerName = "my-container";
std::string blobName = "my-blob.txt";
std::string localFilePath = "path/to/local/file.txt";

// Create a blob service client
auto blobServiceClient = Azure::Storage::Blobs::BlobServiceClient::CreateClient(blobStorageUrl, std::move(credential));

// Create a container client
auto containerClient = blobServiceClient.GetBlobContainerClient(containerName);

// Optionally create the container if it doesn't exist
try {
    containerClient.CreateIfNotExists();
} catch (const Azure::Core::RequestFailedException& e) {
    std::cerr << "Error creating container: " << e.Message << std::endl;
    // Handle error
}

// Get a blob client
auto blobClient = containerClient.GetBlobClient(blobName);

// Upload the blob
std::ifstream fileStream(localFilePath, std::ios::binary);
if (fileStream.is_open()) {
    std::vector<uint8_t> buffer(std::istreambuf_iterator<char>(fileStream), {});
    Azure::Storage::Blobs::UploadBlobOptions options;
    options.ContentType = "text/plain"; // Set content type if known

    try {
        auto response = blobClient.Upload(buffer.data(), buffer.size(), options);
        std::cout << "Blob '" << blobName << "' uploaded successfully. ETag: " << response.Value.ETag << std::endl;
    } catch (const Azure::Core::RequestFailedException& e) {
        std::cerr << "Error uploading blob: " << e.Message << std::endl;
        // Handle error
    }
} else {
    std::cerr << "Error opening file: " << localFilePath << std::endl;
}

Azure Key Vault

Securely manage secrets, cryptographic keys, and certificates.

Key Classes

  • SecretClient: Manages secrets.
  • KeyClient: Manages cryptographic keys.
  • CertificateClient: Manages certificates.

Example: Get a secret

#include <azure/keyvault/secrets/secret_client.hpp>
#include <azure/identity/default_azure_credential.hpp>

// ...

auto credential = std::make_unique<Azure::Identity::DefaultAzureCredential>();
std::string keyVaultUrl = "YOUR_KEY_VAULT_URL"; // e.g., "https://myvault.vault.azure.net"
std::string secretName = "my-secret";

auto secretClient = Azure::KeyVault::Secrets::SecretClient::CreateClient(keyVaultUrl, std::move(credential));

try {
    auto response = secretClient.GetSecret(secretName);
    std::cout << "Secret '" << secretName << "' retrieved successfully." << std::endl;
    std::cout << "Value: " << response.Value.Value << std::endl;
} catch (const Azure::Core::RequestFailedException& e) {
    std::cerr << "Error retrieving secret: " << e.Message << std::endl;
    // Handle error
}

Azure Cosmos DB

A globally distributed, multi-model database service.

(Documentation for Cosmos DB C++ SDK is under development. Please refer to the official GitHub repository for the latest status and examples.)

Azure IoT Hub

A scalable, bi-directional communication service for IoT devices.

(Documentation for IoT Hub C++ SDK is under development. Please refer to the official GitHub repository for the latest status and examples.)

API Reference

For detailed information on classes, methods, and their parameters, please refer to the generated API documentation available on the Azure SDK for C++ GitHub repository.

Example: Azure Storage Blobs API

Class Method Description Parameters
BlobClient Upload Uploads a block blob. const uint8_t* data, size_t dataSize, const UploadBlobOptions& options = {}
BlobClient Download Downloads a block blob. const DownloadBlobOptions& options = {}
BlobContainerClient CreateIfNotExists Creates a blob container if it does not already exist. const CreateContainerOptions& options = {}
BlobContainerClient ListBlobs Lists blobs within a container. const ListBlobsOptions& options = {}
BlobServiceClient GetBlobContainerClient Gets a client for the specified blob container. const std::string& containerName

Examples

Find more practical examples and use cases in the samples directory on the Azure SDK for C++ GitHub repository.

Troubleshooting

Common Issues

Warning: If you encounter persistent issues, please check the Azure SDK for C++ GitHub repository's Issues section or open a new issue with detailed information about your problem.

Logging

The Azure SDK for C++ supports diagnostic logging, which can be invaluable for debugging. You can enable logging by configuring the Azure::Core::Diagnostics::Logger.

#include <azure/core/diagnostics/logger.hpp>
#include <iostream>

// ...

// Set the log level and output stream
Azure::Core::Diagnostics::Logger::SetTraceLevel(Azure::Core::Diagnostics::Logger::Level::Verbose);
Azure::Core::Diagnostics::Logger::SetListener([](const Azure::Core::Diagnostics::LogMessage& msg) {
    std::cerr << msg.Level << ": " << msg.Message << std::endl;
});

// Now any SDK operations will log verbose output to stderr.
// Remember to disable or reduce the log level in production environments.