Uploading

How to Unit Test uploading fo files

Minimum Version: 2.6.0 / 3.6.0

Before uploading a file against a file column for an entity record, the record must exist. This means the record must have been initalised beforehand.

Once the record exists in the In-Memory database, you can upload a file against it using the InitializeFileBlocksUploadRequest, UploadBlockRequest, and CommitFileBlocksUploadRequest messages.

You can see a full example by checking the CommitFileBlocksUploadRequestTests sample code.

Initialize a record

First, create an entity record where you’d like to upload the file. You can do so with .Initialize();

_entity = new Entity("dv_test") { Id = Guid.NewGuid() };
_context.Initialize(_entity);

InitializeFileBlocksUploadRequest

Then, construct an InitializeFileBlocksUploadRequest and execute it. The target of that request will be the record you just have initialized. The request will return a FileContinuationToken you need to use to upload the different file bocks and commit the file.

_initFileUploadRequest = new InitializeFileBlocksUploadRequest()
{
    FileName = "Test.pdf",
    Target = _entity.ToEntityReference(),
    FileAttributeName = "dv_file"
};

var initFileUploadResponse = _service.Execute(_initFileUploadRequest) as InitializeFileBlocksUploadResponse;

UploadBlockRequest

With the FileContinuationToken response, upload as many blocks as needed (in this example we’ll upload just one for simplicity).

_uploadBlockRequest = new UploadBlockRequest()
{
    BlockData = new byte[] { 1, 2, 3, 4 },
    BlockId = new Guid().ToString(),
};

_uploadBlockRequest.FileContinuationToken = initFileUploadResponse.FileContinuationToken;
_service.Execute(_uploadBlockRequest);

CommitFileBlocksUploadRequest

Finally, once you have uploaded all the necessary blocks, call CommitFileBlocksUploadRequest to combine all the blocks into one file that will be stored In-Memory.

Pay special attention to the order of the blocks.

In the CommitFileBlocksUploadResponse you’ll get useful information in you want to do something with the file that was uploaded, like the total file size, or the FileId.

_commitFileBlocksUploadRequest = new CommitFileBlocksUploadRequest()
{
    FileName = "Test.pdf",
    BlockList = new[] { _uploadBlockRequest.BlockId },
    MimeType = "application/pdf"
};

_commitFileBlocksUploadRequest.FileContinuationToken = initFileUploadResponse.FileContinuationToken;
var response = _service.Execute(_commitFileBlocksUploadRequest);
Assert.NotNull(response);
Assert.IsType<CommitFileBlocksUploadResponse>(response);

var commitResponse = response as CommitFileBlocksUploadResponse;
Assert.Equal(4L, commitResponse.FileSizeInBytes);
Assert.NotEqual(Guid.Empty, commitResponse.FileId);

That’s it! Congrats! You just have uploaded your first file into FakeXrmEasy’s In-Memory File Storage!