static HRESULT End(__in IFabricAsyncOperationContext * context, __out IFabricInfrastructureTaskQueryResult ** result)
    {
        if ((context == NULL) || (result == NULL))
        {
            return E_POINTER;
        }

        ComPointer<ComQueryInfrastructureTaskAsyncOperation> thisCPtr(context, CLSID_ComQueryInfrastructureTaskAsyncOperation);
        
        auto hr = thisCPtr->Result;

        if (SUCCEEDED(hr))
        {
            vector<InfrastructureTaskQueryResult> resultList;
            auto error = thisCPtr->nativeResult_.MoveList(resultList);

            if (error.IsSuccess())
            {
                ComPointer<IFabricInfrastructureTaskQueryResult> cPtr = make_com<ComQueryResult, IFabricInfrastructureTaskQueryResult>(move(resultList));
                hr = cPtr->QueryInterface(IID_IFabricInfrastructureTaskQueryResult, reinterpret_cast<void**>(result));
            }
            else
            {
                hr = error.ToHResult();
            }
        }

        return hr;
    } 
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);
}
HRESULT ComWinFabStoreLayoutSpecification::FabricCreateWinFabStoreLayoutSpecification( 
    /* [in] */ REFIID riid,
    /* [retval][out] */ void **fabricLayoutSpecification)
{
    ComPointer<ComWinFabStoreLayoutSpecification> comWinFabStoreLayoutSpecificationCPtr = make_com<ComWinFabStoreLayoutSpecification>();
    return comWinFabStoreLayoutSpecificationCPtr->QueryInterface(riid, (LPVOID*)fabricLayoutSpecification);
}
HRESULT ComTestHostServiceFactory::CreateReplica(
    /* [in] */ LPCWSTR serviceType,
    /* [in] */ FABRIC_URI serviceName,
    /* [in] */ ULONG initializationDataLength,
    /* [size_is][in] */ const byte *initializationData,
    /* [in] */ FABRIC_PARTITION_ID partitionId,
    /* [in] */ FABRIC_REPLICA_ID replicaId,
    /* [retval][out] */ IFabricStatefulServiceReplica **service)
{
    // Deserialize initData to wstring
    wstring initDataStr = GetInitString(initializationData, initializationDataLength);

    wstring serviceTypeString(serviceType);

    ServiceTypeDescription serviceTypeDescription;
    TestSession::FailTestIfNot(TryGetServiceTypeDescription(serviceTypeString, serviceTypeDescription), "serviceType {0} not supported", serviceTypeString);
    TestSession::FailTestIfNot(serviceTypeDescription.IsStateful, "CreateStatefulService for invalid service type {0}", serviceTypeString);

    if(serviceTypeDescription.HasPersistedState)
    {
        TestPersistedStoreServiceSPtr testPersistedStoreServiceSPtr = factory_.CreatePersistedService(
            partitionId,
            replicaId,
            serviceName,
            serviceTypeString,
            initDataStr);
        ComPointer<ComTestPersistedStoreService> comPointer = make_com<ComTestPersistedStoreService>(*testPersistedStoreServiceSPtr);
        return comPointer->QueryInterface(IID_IFabricStatefulServiceReplica, reinterpret_cast<void**>(service));
    }
    else
    {
        TestStoreServiceSPtr testStoreServiceSPtr = factory_.CreateStatefulService(partitionId, serviceName, serviceTypeString, initDataStr);
        ComPointer<ComTestStoreService> comPointer = make_com<ComTestStoreService>(*testStoreServiceSPtr);
        return comPointer->QueryInterface(IID_IFabricStatefulServiceReplica, reinterpret_cast<void**>(service));
    }
}
HRESULT ComStatefulServiceFactory::CreateReplica( 
    /* [in] */ LPCWSTR serviceType,
    /* [in] */ FABRIC_URI serviceName,
    /* [in] */ ULONG initializationDataLength,
    /* [size_is][in] */ const byte *initializationData,
    /* [in] */ FABRIC_PARTITION_ID partitionId,
    /* [in] */ FABRIC_REPLICA_ID replicaId,
    /* [retval][out] */ IFabricStatefulServiceReplica **serviceReplica)
{
    if (serviceType == NULL || serviceName == NULL || serviceReplica == NULL) 
    {
        return ComUtility::OnPublicApiReturn(E_POINTER);
    }

    wstring parsedServiceType;
    auto hr = StringUtility::LpcwstrToWstring(serviceType, false, parsedServiceType);
    if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); }

    NamingUri parsedServiceName;
    hr = NamingUri::TryParse(serviceName, "serviceName", parsedServiceName).ToHResult();
    if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); }

    std::vector<byte> initializationDataBytes;
    if (initializationDataLength > 0)
    {
        initializationDataBytes.insert(
            initializationDataBytes.end(), 
            initializationData,
            initializationData + initializationDataLength);
    }

    IStatefulServiceReplicaPtr serviceReplicaImpl;

    auto error = impl_->CreateReplica(
        parsedServiceType,
        parsedServiceName,
        initializationDataBytes,
        Guid(partitionId),
        replicaId,
        serviceReplicaImpl);
    if (!error.IsSuccess()) { return ComUtility::OnPublicApiReturn(error.ToHResult()); }

    ComPointer<ComStatefulServiceReplica> result = make_com<ComStatefulServiceReplica>(serviceReplicaImpl);
    return result->QueryInterface(IID_IFabricStatefulServiceReplica,  reinterpret_cast<void**>(serviceReplica));
}
HRESULT ComTestHostServiceFactory::CreateInstance( 
    /* [in] */ LPCWSTR serviceType,
    /* [in] */ FABRIC_URI serviceName,
    /* [in] */ ULONG initializationDataLength,
    /* [size_is][in] */ const byte *initializationData,
    /* [in] */ FABRIC_PARTITION_ID partitionId,
    /* [in] */ FABRIC_INSTANCE_ID instanceId,
    /* [retval][out] */ IFabricStatelessServiceInstance **service)
{
    UNREFERENCED_PARAMETER(instanceId);

    // Deserialize initData to wstring
    wstring initDataStr = GetInitString(initializationData, initializationDataLength);
    
    wstring serviceTypeString(serviceType);

    ServiceTypeDescription serviceTypeDescription;
    TestSession::FailTestIfNot(TryGetServiceTypeDescription(serviceTypeString, serviceTypeDescription), "serviceType {0} not supported", serviceTypeString);
    TestSession::FailTestIf(serviceTypeDescription.IsStateful, "CreateStatefulService for invalid service type {0}", serviceTypeString);

    CalculatorServiceSPtr testGenericStatelessServiceSPtr = factory_.CreateStatelessService(partitionId, serviceName, serviceTypeString, initDataStr);
    ComPointer<ComCalculatorService> comPointer = make_com<ComCalculatorService>(*testGenericStatelessServiceSPtr);
    return comPointer->QueryInterface(IID_IFabricStatelessServiceInstance, reinterpret_cast<void**>(service));
}
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);
}