C++ (22.06.X)

Follow

This document will guide you through the process of SDK installation and it applies to version 22.06.X.

To access the documentation for version 22.02 and older, click here.

It is an open-source SDK, you can take a look at our SDK code in the Github repo

Supported Platforms: Windows, GNU/Linux, and Mac OS X.

Adding the SDK to the Project

Countly C++ SDK has been designed to work with very few dependencies in order to run on most platforms. In order to build this SDK, you need:

  • C++ compiler with C++14 support
  • libcurl (with openssl) and its headers if you are on *nix
  • cmake >= 3.13

First, clone the repository with its submodules:

git clone --recursive https://github.com/Countly/countly-sdk-cpp

If you want to use SQLite to store session data persistently, build sqlite:

# assuming we are on project root
cd vendor/sqlite
cmake -D BUILD_SHARED_LIBS=1 -B build . # out of source build, we don't like clutter :)
# we define `BUILD_SHARED_LIBS` because sqlite's cmake file compiles statically by default for some reason
cd build
make # you might want to add something like -j8 to parallelize the build process

The cmake build flow is pretty straightforward:

# assuming we are on project root again
ccmake -B build . # this will launch a TUI, configure the build as you see fit
cd build
make

Build with the option COUNTLY_BUILD_TESTS and COUNTLY_BUILD_SAMPLEON to build executables to run the tests and the sample app.

cmake -DCOUNTLY_BUILD_SAMPLE=1 -DCOUNTLY_BUILD_TESTS=1 -B build . # or do it interactively with cmake
cd build
make ./countly-tests   # run unit test
make ./countly-sample # run sample app

SDK Integration

Minimal Setup

Before you can use any functionality, you have to initiate the SDK. 

The shortest way to initiate the SDK is with this code snippet:

cly::Countly& countly = cly::Countly::getInstance();
countly.setDeviceID("test-device-id");
countly.start("YOUR_APP_KEY", "https://try.count.ly", 443, true);

Here you have to provide your appKey, and your Countly server URL. For more information on how to acquire you application key (appKey) and server URL, check here.

The third parameter with typeint is a virtual port number and it is an optional parameter with a default value of -1.
The last bool parameter is also optional with the default value of false. When you set this value to true SDK automatically extends the session every 60 seconds. 

If you are in doubt about the correctness of your Countly SDK integration you can learn more about methods to verify it from here.

SDK Logging

The first thing you should do while integrating our SDK is to enable logging. If logging is enabled, then our SDK will print out debug messages about its internal state and about encountered problems. 

Set setLogger(logger_function) on the Counlty object to enable logging:

void printLog(cly::Countly::LogLevel level, const string& msg) {...}
...

void (*logger_function)(cly::Countly::LogLevel level, const std::string& message);
logger_function = printLog;
cly::Countly::getInstance().setLogger(logger_function);

Device ID

All tracked information is tied to a "device ID", which is used as a unique identifier of your users.

You have to specify the device ID by yourself (it has to be unique for each of your users). It may be an email or some other internal ID used in your system's internal logic.

cly::Countly::getInstance().setDeviceID("UNIQUE_DEVICE_ID");

SDK Notes

To access the Countly Global Instance use the following code snippet:

cly::Countly::getInstance().

Crash Reporting

This feature requires the minimum SDK version of 22.06.1

The Countly SDK for C++ can collect Crash Reports, which you may examine and resolve later on the server.

In the SDK all crash-related functionalities can be browsed from the returned interface on:

countly.crash().

Handled Exceptions

This feature requires the minimum SDK version of 22.06.1

You might catch an exception or similar error during your app’s runtime. You may also log these handled exceptions to monitor how and when they are happening. To log handled exceptions use the following code snippet:

/* any additional info can be provided as a segmentation */
std::map<std::string, std::string> segmentation = {
{"platform", "ubuntu"},
{"time", "60"},
};

/* should create the crashMetrics map */
std::map<std::string, std::any> crashMetrics;

/* mandatory values */
crashMetrics["_os"] = "Android"; # your OS info
crashMetrics["_app_version"] = "1.22";

/* any optional info */
crashMetrics["_cpu"] = "armv7";

countly.crash().recordException("title", "stackTrace", true, crashMetrics, segmentation);

recordException expects the parameters below:

  • title - a string that describes the exception.
  • stackTrace - a string that describes the contents of the call stack.
  • fatal - set true if the error is fatal.
  • crashMetrics - key/values contain device information e.g app version, OS
  • segments - custom key/values to be reported.

crashMetrics is a map that contains the core information about the crash you want to capture and report. If it is not properly formed, your Countly server would not be able to recognize and interpret your crash report and you would not be able to observe the error from your server. There are two mandatory key-value pairs that you need to fill when forming the crashMetrics object. These are _os and _app_version keys. Any other keys are optional so you can add more key-value pairs to form a detailed crash report from among the available options shown below:

std::map<std::string, std::any> crashMetrics;

/* mandatory values */
crashMetrics["_os"] = "Android"; /* your OS info */
crashMetrics["_app_version"] = "22.06.1"; /* SDK version */

/* optional values */
crashMetrics["_os_version"] = "4.1";
crashMetrics["_manufacture"] = "Samsung"; /* may not be provided for ios or be constant, like Apple */
crashMetrics["_device"] = "Galaxy S4"; /* model for Android, iPhone1,1 etc for iOS */
crashMetrics["_resolution"] = "1900x1080"; /* SDK version */
crashMetrics["_cpu"] = "armv7"; /* type of cpu used on device (for ios will be based on device)*/
crashMetrics["_opengl"] = "2.1"; /* version of open gl supported */
crashMetrics["_ram_current"] = 1024; /* in megabytes */
crashMetrics["_ram_total"] = 4096; /* in megabytes */
crashMetrics["_disk_current"] = 3000; /* in megabytes */
crashMetrics["_disk_total"] = 10240; /* in megabytes */
crashMetrics["_bat"] = 99; /* battery level from 0 to 100 */
crashMetrics["_orientation"] = "portrait"; /* in which device was held, landscape, portrait, etc */
crashMetrics["_root"] = false; /* true if device is rooted/jailbroken, false or not provided if not */
crashMetrics["_online"] = false; /* true if device is connected to the internet (WiFi or 3G), false or not provided if not connected */
crashMetrics["_muted"] = false; /* true if volume is off, device is in muted state */
crashMetrics["_background"] = false; /* true if app was in background when it crashed */
crashMetrics["_run"] = 2000; /* running time since app start in seconds */

Crash Breadcrumbs

This feature requires the minimum SDK version of 22.06.1

Throughout your app, you can leave crash breadcrumbs. They are short string logs that would ideally describe the previous steps that were taken in your app before the crash. After a crash happens, they will be sent together with the crash report.

The following command adds a crash breadcrumb:

countly.crash().addBreadcrumb("breadcrumb");

Events

An event is any type of action that you can send to a Countly instance, e.g. purchases, changed settings, view enabled, and so on, letting you get valuable information about your application.

There are a couple of values that can be set when recording an event. The main one is the key property which would be the identifier/name for that event.  For example, in case a user buys an item in your game, you can create an event with the key 'purchase' to inform this action to your Countly server.

Optionally there are also other properties that you might want to set:

  • count -  a whole numerical value that marks how many times this event has happened. The default value for this is 1.
  • sum - This value would be summed across all events in the dashboard. For example, for in-app purchase events, it can be the sum of purchased items. Its default value is 0.
  • duration - For recording and tracking the duration of events. The default value is 0.
  • segments - A value where you can provide custom segmentation for your events to track additional information. It is a key and value map. The accepted data type for the value is std::string.

Recording Events

Here are some examples below, showing how to record an event for a purchase with varying levels of complexity:

  • Usage 1: Times the purchase event occurred.
  • Usage 2: Times the purchase event occurred + the total amount of those purchases.
  • Usage 3: Times the purchase event occurred + origin of the purchase.
  • Usage 4: Times the purchase event occurred + the total amount + origin of the purchase.
  • Usage 5: Times the purchase event occurred + the total amount + origin of the purchase + the total duration of those events.

1. Event key and count

cly::Countly::getInstance().RecordEvent("purchase", 1);

2. Event key, count, and sum

cly::Countly::getInstance().RecordEvent("purchase", 1, 0.99);

3. Event key and count with segmentation(s)

std::map<std::string, std::string> segmentation;
segmentation["country"] = "Germany";

cly::Countly::getInstance().RecordEvent("purchase", segmentation, 1);

4. Event key, count, and sum with segmentation(s)

std::map<std::string, std::string> segmentation;
segmentation["country"] = "Germany";

cly::Countly::getInstance().RecordEvent("purchase", segmentation, 1, 0.99);

5. Event key, count, sum, and duration with segmentation(s)

std::map<std::string, std::string> segmentation;
segmentation["country"] = "Germany";

cly::Countly::getInstance().RecordEvent("purchase", segmentation, 1, 0.99, 60.0);

These are only a few examples of what you can do with Events. You may go beyond those examples and use country, app_version, game_level, time_of_day, or any other segmentation of your choice that will provide you with valuable insights.

Timed Events

It's possible to create timed events by defining a start and a stop moment.

cly::Event event("Some event", 1);

//start some event

event.startTimer();
//wait some time

//end the timer and record event
event.stopTimer();
cly::Countly.getInstance().addEvent(event);

You may also provide additional information e.g segmentation, count, and sum.

//event with count and sum
cly::Event event("Some event", 1, 0.99);
//add segmentation to event
event.addSegmentation("country", "Germany");
...

cly::Countly.getInstance().addEvent(event);

Sessions

Automatic Session Tracking

The SDK handles the sessions automatically. After calling the start(...) method, the SDK starts the session tracking automatically and extends sessions after every 60 seconds. This value is configurable during and after initialization. 
Example:

cly::Countly::getInstance().setAutomaticSessionUpdateInterval(10);

The SDK ends the current session whenever the user exits from the app.

View Tracking

Manual View Recording

The Countly C++ SDK supports manual view (screen) tracking, with which, you can report which views a user has visited with the duration of that visit. To report a screen from your app to the Countly server, you can use the following method:

std::string& viewID = cly::Countly::getInstance().views()("Home Scene");

While tracking views manually, you may add your custom segmentation to those views like this:

std::map<std::string, std::string> segmentation = {
{"cats", "123"},
{"moons", "9.98"},
{"Moose", "deer"},
};

std::string& viewID = cly::Countly::getInstance().views().openView("Home Scene", segmentation);

When the screen closes you can report it to the server by using one of the following methods:

1. Ending a view with a view ID:

When you start recording a view by calling the openView method, it returns a view ID of type std::string. You can use this ID to close a view.

For example:

std::string& viewID = cly::Countly::getInstance().views().openView("Home Scene");
...
cly::Countly::getInstance().views().closeViewWithID(viewId);

2. Ending a view with a view name:
You may close a view by its name using the following method:

cly::Countly::getInstance().views().closeViewWithName("Home Scene");

To review the resulting view data, go to the Analytics > Views section in your Countly server. For more information on how to utilize view tracking data to its fullest potential, click here.

Device ID management

A device ID is a unique identifier of your users. You have to specify the device ID yourself. When providing one you should keep in mind that it has to be unique for all users. Some potential sources for such an ID may be the user's username, email, or some other internal ID used within your other systems.

In the C++ SDK the device ID is not persistent and has to be provided every time you start the SDK.

Changing Device ID

In case your application authenticates users, you might want to change the initial device ID of the user to another one in your backend after the user logs in. This helps you identify a specific user with a specific ID on a device the user logs in, and the same scenario can also be used in cases where same user logs in using a different device (e.g another tablet, another mobile phone, or web). If you employ this logic, any data stored in your Countly server database associated with the current device ID will be transferred (merged) into the user profile with the device ID you specified in the following method call:

cly::Countly::getInstance().setDeviceID("new-device-id", true);

If you integrate this method, there might be times where you might want to track information about another user that starts using your app from the same device (an account change), or your app enters a state where you no longer can verify the identity of the current user (user logs out). In those cases, you can change the current device ID to a new one without merging their data. You would call:

cly::Countly::getInstance().setDeviceID("new-device-id", false);

Doing it this , will prevent the previous user's data to merge with the new id.

If the second parameter same_user is set to true, the old device ID on the server will be replaced with the new one, and data associated with the old device ID will be merged automatically.

Otherwise, if same_user is set to false, the device will be counted as a new device on the server.

User Location

While integrating this SDK into your application, you might want to track your user's location. You could use this information to learn more about your app’s user base. There are 4 fields that can be provided:

  • Country code (two-letter ISO standard).
  • City name (must be set together with the country code).
  • Latitude and longitude values, separated by a comma e.g. "56.42345,123.45325".
  • Your user’s IP address.

Setting Location

During init, you may set location, and after the SDK initialization, this location info will be sent to the server at the start of the user session.

Example:

string countryCode = "us";
string city =
"Houston";
string latitude =
"29.634933";
string longitude =
"-95.220255";
string ipAddress = "192.168.0.1"
; 

cly::Countly::getInstance().setLocation(countryCode, city, latitude + "," + longitude, ipAddress);

Note that the IP address would only be updated if it's set during the init process.

When these values are set after the SDK initialization, a separate request will be created to send them to the server. Except for the IP address, because Countly server can process an IP address only when starting a new session.

If you don't want to set specific fields, you should set them to empty.

Remote Config

Available in the Enterprise Edition, Remote Config allows you to modify how your app functions or looks by requesting key-value pairs from your Countly server. The returned values may be modified based on the user profile. For more details, please see the Remote Config documentation.

Manual Remote Config

To download Remote Config, call updateRemoteConfig()

cly::Countly.getInstance().updateRemoteConfig();

Accessing Remote Config Values

To access the stored config,  call cly::Countly.getInstance().getRemoteConfigValue(const std::string& key). It will return null if there isn't any config stored.

cly::Countly.getInstance().getRemoteConfigValue("Key");

It returns a value of the type json

User profiles

For information about User Profiles, review this documentation.

Setting Predefined Values

The Countly C++ SDK allows you to upload user specific data to your Countly server. You may set the data against predefined keys for a particular user.

The keys for predefined user data fields are as follows:

Key Type Description
name string User's full name
username string User's nickname
email string User's email address
organization string User's organization name
phone string User's phone number
picture string URL to avatar or profile picture of the user
gender string User's gender as M for male and F for female
byear string User's year of birth as integer

The SDK allows you to upload user details using the methods listed below.

Example:

std::map<std::string, std::string> userdetail = { 
{"name", "Full name"},
{"username", "username123"},
{"email", "useremail@email.com"},
{"phone", "222-222-222"},
{"picture", "http://webresizer.com/images2/bird1_after.jpg"},
{"gender", "M"},
{"byear", "1991"},
{"organization", "Organization"},
};
cly::Countly.getInstance().setUserDetails(userdetail);

Setting Custom Values

The SDK gives you the flexibility to send only the custom data to Countly servers, even when you don’t want to send other user-related data.

Example:

std::map<std::string, std::string> userdetail = { 
{"Height", "5.8"},
{"Mole", "Lower Left Cheek"}
};

cly::Countly.getInstance().setCustomUserDetails(userdetail);

Setting User Picture

The SDK allows you to set the user's picture URL along with other details using the methods listed below.

Example:

std::map<std::string, std::string> userdetail = { 
{"name", "Full name"},
{"picture", "http://webresizer.com/images2/bird1_after.jpg"},
};

cly::Counlty.getInstance().setUserDetails(userdetail);

Security and Privacy

Parameter Tamper Protection

You may set an optional salt to be used for calculating the checksum of requested data which will be sent with each request, using the &checksum field. You will need to set the exact same salt on the Countly server. If the salt on the Countly server is set, all requests would be checked for the validity of the &checksum the field before being processed.

cly::Countly.getInstance().setSalt("salt");

Other Features and Notes

Setting Event Queue Threshold

After SDK init, you may limit the number of events that can be recorded internally by the system before sent together in a single request. 
Example:

cly::Counlty.getInstance().SetMaxEventsPerMessage(10);

Once the threshold limit is reached, the system groups all recorded events and sends them to the server.

Setting Custom SHA-256

C++ SDK allows users to set a custom SHA-256 method for calculating the checksum of request data.

To use the custom SHA-256 feature follow the following steps:

1. Build the Countly C++ SDK executable with the COUNTLY_USE_CUSTOM_SHA256 option.

cmake -DCOUNTLY_USE_SQLITE=1 -DCOUNTLY_USE_CUSTOM_SHA256=1 -B build

2. Set custom SHA-256 method setSha256

For example:

std::string customChecksumCalculator(const std::string& data) {
...
return result;
}


cly::Countly& countly = cly::Countly.getInstance();
countly.setSalt("salt");
countly.setSha256(customChecksumCalculator);

FAQ

What Information is Collected by the SDK

There are some data that is collected by SDK to perform their functions and implement the required features. Before any of it is sent to the server, it is stored locally.

* When sending any network requests to the server, the following things are sent in addition to the main data:
- Timestamp of when the request is created
- SDK version
- SDK name

Comments

0 comments

Please sign in to leave a comment.