ErrorCode ComProxyStatelessServiceFactory::CreateInstance(
    wstring const & serviceType, 
    wstring const & serviceName, 
    vector<byte> const & initializationData,
    Guid const & partitionId,
    const FABRIC_INSTANCE_ID instanceId, 
    __out IStatelessServiceInstancePtr & )
{
    HRESULT hr;
    ComPointer<IFabricStatelessServiceInstance> comService;

    hr = comImpl_->CreateInstance(
        serviceType.c_str(),
        serviceName.c_str(),
        (ULONG)initializationData.size(),
        initializationData.data(),
        partitionId.AsGUID(),
        instanceId,
        comService.InitializationAddress());

    if(SUCCEEDED(hr))
    {
        ASSERT_IFNOT(comService, "Instance create returned a null service.");
        // TODO: create proxy for the stateless service
        // service = make_unique<ComProxyStatelessService>(comService);
        //
    }
    
    return ErrorCode::FromHResult(hr);
}
HRESULT ComProxyStatefulService::ChangeRoleAsyncOperation::EndComAsyncOperation(IFabricAsyncOperationContext * context)
{
    HRESULT hr;
    ComPointer<IFabricStringResult> stringResult;

    hr = owner_.service_->EndChangeRole(context, stringResult.InitializationAddress());

    if(SUCCEEDED(hr))
    {
        if (stringResult.GetRawPointer() != nullptr)
        {
            hr = StringUtility::LpcwstrToWstring(stringResult->get_String(), true /*acceptNull*/, 0 /*minSize*/, ParameterValidator::MaxEndpointSize, serviceLocation_);
        }
        else
        {
            serviceLocation_ = L"";
        }
    }

    return hr;
}
HRESULT ComTestStoreService::BeginOpen( 
    /* [in] */ FABRIC_REPLICA_OPEN_MODE openMode,
    /* [in] */ IFabricStatefulServicePartition *statefulServicePartition,
    /* [in] */ IFabricAsyncOperationCallback *callback,
    /* [retval][out] */ IFabricAsyncOperationContext **context)
{
    UNREFERENCED_PARAMETER(openMode);

    if (statefulServicePartition == NULL || callback == NULL || context == NULL) { return E_POINTER; }

    TestSession::FailTestIfNot(openMode == FABRIC_REPLICA_OPEN_MODE::FABRIC_REPLICA_OPEN_MODE_NEW, "Wrong open mode is passed in for volatile service");

    ComPointer<IFabricStatefulServicePartition3> partition;
    // TODO: tempPartition below is used for replicator only, remove when everything is switched to IFabricStatefulServicePartition1 interface (RDBug 3114076)
    ComPointer<IFabricStatefulServicePartition> tempPartition;
    partition.SetAndAddRef((IFabricStatefulServicePartition3*)statefulServicePartition);
    tempPartition.SetAndAddRef(statefulServicePartition);

    CheckForReportFaultsAndDelays(tempPartition, ApiFaultHelper::Service, L"BeginOpen");


    if (testStoreService_.ShouldFailOn(ApiFaultHelper::Service, L"BeginOpen")) 
    {
        return E_FAIL;
    }

    ComPointer<ComCompletedAsyncOperationContext> operation = make_com<ComCompletedAsyncOperationContext>();
    HRESULT hr = E_FAIL;
    bool streamFaultsAndRequireServiceAckEnabled = false;

    if (testStoreService_.ShouldFailOn(ApiFaultHelper::Service, L"EndOpen")) 
    {
        hr = operation->Initialize(E_FAIL, ApiFaultHelper::Get().GetAsyncCompleteDelayTime(), root_, callback);
    }
    else
    {
        Common::ScopedHeap heap;
        ComPointer<IFabricStateReplicator> stateReplicator;
        ComPointer<IFabricReplicator> replicationEngine;
        FABRIC_REPLICATOR_SETTINGS replicatorSettings = { 0 };
        FABRIC_REPLICATOR_SETTINGS_EX1 replicatorSettingsEx1 = { 0 };
        FABRIC_REPLICATOR_SETTINGS_EX2 replicatorSettingsEx2 = { 0 };
        FABRIC_REPLICATOR_SETTINGS_EX3 replicatorSettingsEx3 = { 0 };
        FABRIC_REPLICATOR_SETTINGS_EX4 replicatorSettingsEx4 = { 0 };

        replicatorSettings.Flags = FABRIC_REPLICATOR_SETTINGS_NONE; // no memory limit, default number of items limit = 1024.
        replicatorSettings.Reserved = &replicatorSettingsEx1;
        replicatorSettingsEx1.Reserved = &replicatorSettingsEx2;
        replicatorSettingsEx2.Reserved = &replicatorSettingsEx3;
        replicatorSettingsEx3.Reserved = &replicatorSettingsEx4;
        replicatorSettingsEx4.Reserved = NULL;

		ReplicatorSettingServiceInitDataParser rsParser(testStoreService_.InitDataString);
        auto inputReplicatorSettings = rsParser.CreateReplicatorSettings(testStoreService_.InitDataString, testStoreService_.GetPartitionId());
        inputReplicatorSettings->ToPublicApi(heap, replicatorSettings);

        HRESULT result = partition->CreateReplicator(this, &replicatorSettings, replicationEngine.InitializationAddress(), stateReplicator.InitializationAddress());
        TestSession::FailTestIfNot(result == S_OK, "GetReplicator did not return success");
        TestSession::FailTestIfNot((bool) stateReplicator, "stateReplicator is null");
        TestSession::FailTestIfNot((bool) replicationEngine, "replicationEngine is null");

        ComPointer<ComTestReplicator> testReplicator = make_com<ComTestReplicator>(replicationEngine, tempPartition, false, testStoreService_.ServiceName, testStoreService_.NodeId);
        result = testReplicator->QueryInterface(IID_IFabricReplicator, reinterpret_cast<void**>(replicationEngine_.InitializationAddress()));
        TestSession::FailTestIfNot(result == S_OK, "testReplicator->QueryInterface did not return success");

        ErrorCode error = testStoreService_.OnOpen(partition, stateReplicator, streamFaultsAndRequireServiceAckEnabled);
        TestSession::FailTestIfNot(error.IsSuccess(), "testStoreService_.OnOpen failed with error {0}", error);

        hr = operation->Initialize(root_, callback);
    }

    TestSession::FailTestIf(FAILED(hr), "operation->Initialize should not fail");
    return ComAsyncOperationContext::StartAndDetach<ComCompletedAsyncOperationContext>(std::move(operation), context);
}
ErrorCode ComProxyXmlLiteWriter::Create(
    __in std::wstring const & outputName,
    __out ComProxyXmlLiteWriterUPtr & xmlLiteWriter, 
    bool writeByteOrderMark, 
    bool indent)
{
#if !defined(PLATFORM_UNIX)
    ComPointer<IStream> xmlFileStream;
    auto error = ComXmlFileStream::Open(outputName, true, xmlFileStream);
    if (!error.IsSuccess()) { return error; }

    ComPointer<IUnknown> comPointer;
    HRESULT hr = xmlFileStream->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(comPointer.InitializationAddress()));
    if (!SUCCEEDED(hr)) { return ErrorCode::FromHResult(hr); }

    error = ComProxyXmlLiteWriter::Create(comPointer, xmlLiteWriter, writeByteOrderMark, indent);
    if (!error.IsSuccess()) { return error; }

#else
    ComPointer<IXmlWriter> writer;
    auto hr = ::CreateXmlWriter(
        ::IID_IXmlWriter, 
        outputName.c_str(),
        writer.VoidInitializationAddress(),
        NULL);
    auto error = ToErrorCode(hr, L"CreateXmlWriter", L"", true, false);
    if (!error.IsSuccess()) { return error; }

    xmlLiteWriter = move(make_unique<ComProxyXmlLiteWriter>(writer));
#endif

    return ErrorCode(ErrorCodeValue::Success);
}