Примечание.
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
В двух примерах ниже показано, как создать объект profileSettings с помощью локального хранилища для хранилища состояний, а также только в памяти.
Загрузка профиля
Теперь, когда ProtectionProfileObserverImpl определён, мы будем использовать его для инстанцирования mip::ProtectionProfile.
mip::ProtectionProfile Для создания объекта требуетсяmip::ProtectionProfile::Settings.
Параметры ProtectionProfile::Settings
-
std::shared_ptr<MipContext>: объектmip::MipContext, инициализированный для хранения информации о приложении, пути состояния и т. д. -
mip::CacheStorageType: определяет, как хранить состояние: в памяти, на диске или на диске и зашифрованном. -
std::shared_ptr<mip::ConsentDelegate>: общий указатель классаmip::ConsentDelegate. -
std::shared_ptr<mip::ProtectionProfile::Observer> observer: общий указатель на реализацию профиляObserver(вPolicyProfile,ProtectionProfileиFileProfile).
В двух примерах ниже показано, как создать объект profileSettings с помощью локального хранилища для хранилища состояний, а также только в памяти.
Хранение состояния только в памяти
mip::ApplicationInfo appInfo {clientId, "APP NAME", "1.2.3" };
std::shared_ptr<mip::MipConfiguration> mipConfiguration = std::make_shared<mip::MipConfiguration>(mAppInfo,
"mip_data",
mip::LogLevel::Trace,
false);
std::shared_ptr<mip::MipContext> mMipContext = mip::MipContext::Create(mipConfiguration);
ProtectionProfile::Settings profileSettings(
mMipContext, // mipContext object
mip::CacheStorageType::InMemory, // use in memory storage
std::make_shared<ConsentDelegateImpl>(), // new consent delegate
std::make_shared<ProtectionProfileObserverImpl>()); // new protection profile observer
Параметры профиля чтения и записи из пути к хранилищу на диске
mip::ApplicationInfo appInfo {clientId, "APP NAME", "1.2.3" };
std::shared_ptr<mip::MipConfiguration> mipConfiguration = std::make_shared<mip::MipConfiguration>(mAppInfo,
"mip_data",
mip::LogLevel::Trace,
false);
std::shared_ptr<mip::MipContext> mMipContext = mip::MipContext::Create(mipConfiguration);
ProtectionProfile::Settings profileSettings(
mMipContext, // mipContext object
mip::CacheStorageType::OnDisk, // use on disk storage
std::make_shared<ConsentDelegateImpl>(), // new consent delegate
std::make_shared<ProtectionProfileObserverImpl>()); // new protection profile
Затем используйте шаблон Promise/Future для загрузки ProtectionProfile.
auto profilePromise = std::make_shared<std::promise<std::shared_ptr<ProtectionProfile>>>();
auto profileFuture = profilePromise->get_future();
ProtectionProfile::LoadAsync(profileSettings, profilePromise);
Если мы загрузили профиль, и эта операция была успешной, ProtectionProfileObserverImpl::OnLoadSuccess, активируется наша реализация mip::ProtectionProfile::Observer::OnLoadSuccess. Результирующий объект или указатель исключения, а также контекст передаются в качестве параметров функции. Контекст — это указатель на std::promise созданный для обработки асинхронной операции. Функция просто задает значение обещания объекту ProtectionProfile (контекст). При использовании Future.get()основной функции результат может храниться в новом объекте.
//get the future value and store in profile.
auto profile = profileFuture.get();
Объединение его вместе
После полной реализации делегата наблюдателей и проверки подлинности теперь можно полностью загрузить профиль. Приведенный ниже фрагмент кода предполагает, что все необходимые заголовки уже включены.
int main()
{
const string userName = "MyTestUser@contoso.com";
const string password = "P@ssw0rd!";
const string clientId = "MyClientId";
mip::ApplicationInfo appInfo {clientId, "APP NAME", "1.2.3" };
std::shared_ptr<mip::MipConfiguration> mipConfiguration = std::make_shared<mip::MipConfiguration>(mAppInfo,
"mip_data",
mip::LogLevel::Trace,
false);
std::shared_ptr<mip::MipContext> mMipContext = mip::MipContext::Create(mipConfiguration);
ProtectionProfile::Settings profileSettings(
mMipContext, // mipContext object
mip::CacheStorageType::OnDisk, // use on disk storage
std::make_shared<ConsentDelegateImpl>(), // new consent delegate
std::make_shared<ProfileObserver>()); // new protection profile observer
auto profilePromise = std::make_shared<promise<shared_ptr<ProtectionProfile>>>();
auto profileFuture = profilePromise->get_future();
ProtectionProfile::LoadAsync(profileSettings, profilePromise);
auto profile = profileFuture.get();
}
Конечным результатом является то, что мы успешно загрузили профиль и сохранили его в вызываемом profileобъекте.
Next Steps
Теперь, когда профиль был добавлен, следующим шагом является добавление двигателя в профиль.