CreateAsset() public static method

public static CreateAsset ( CloudMediaContext datacontext, string filePath, AssetCreationOptions options, bool isSetPrimary = true ) : IAsset
datacontext CloudMediaContext
filePath string
options AssetCreationOptions
isSetPrimary bool
return IAsset
        public void ShouldSubmitAndFinishChainedTasksUsingParentOverload()
        {
            IAsset asset = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.StorageEncrypted);

            IJob            job            = _mediaContext.Jobs.Create("Test");
            IMediaProcessor mediaProcessor = GetMediaProcessor(_mediaContext, WindowsAzureMediaServicesTestConfiguration.MpEncoderName);
            ITask           task           = job.Tasks.AddNew("Task1", mediaProcessor, GetWamePreset(mediaProcessor), TaskOptions.None);

            task.InputAssets.Add(asset);
            IAsset asset1 = task.OutputAssets.AddNew("output asset");

            string xmlPreset = File.ReadAllText(WindowsAzureMediaServicesTestConfiguration.ThumbnailXml);
            ITask  task2     = job.Tasks.AddNew("Task2", mediaProcessor, xmlPreset, TaskOptions.None, task);

            task2.OutputAssets.AddNew("JobOutput", options: AssetCreationOptions.None);
            job.Submit();
            WaitForJob(job.Id, JobState.Finished, VerifyAllTasksFinished);
        }
        public void ShouldThrowTryingUpdateJobPriorityWhenJobIsFinished()
        {
            const int newPriority = 3;

            IMediaProcessor processor = GetMediaProcessor(_mediaContext, WindowsAzureMediaServicesTestConfiguration.MpEncoderName);
            IAsset          asset     = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.StorageEncrypted);
            IJob            job       = CreateAndSubmitOneTaskJob(_mediaContext, GenerateName("ShouldSubmitJobAndUpdatePriorityWhenJobIsQueued"), processor, GetWamePreset(processor), asset, TaskOptions.None);

            try
            {
                WaitForJobStateAndUpdatePriority(job, JobState.Finished, newPriority);
            }
            catch (DataServiceRequestException ex)
            {
                Assert.IsTrue(ex.InnerException.Message.Contains("Job's priority can only be changed if the job is in Queued state"));
                throw ex;
            }
        }
        public void ShouldCreateAssetFileWithEncryption()
        {
            var    filePaths = new[] { WindowsAzureMediaServicesTestConfiguration.SmallWmv };
            IAsset asset     = AssetTests.CreateAsset(_dataContext, Path.GetFullPath(WindowsAzureMediaServicesTestConfiguration.SmallWmv), AssetCreationOptions.StorageEncrypted);

            // Associate an access policy with the asset so we can download the files associated with it
            IAccessPolicy policy = _dataContext.AccessPolicies.Create("Test", TimeSpan.FromMinutes(10), AccessPermissions.Read);

            _dataContext.Locators.CreateSasLocator(asset, policy);

            Assert.IsNotNull(asset, "Asset should be non null");
            Assert.AreNotEqual(Guid.Empty, asset.Id, "Asset ID shuold not be null");
            Assert.AreEqual(1, asset.AssetFiles.Count(), "Child files count wrong");
            Assert.IsTrue(asset.Options == AssetCreationOptions.StorageEncrypted, "AssetCreationOptions did not have the expected value");

            VerifyFileAndContentKeyMetadataForStorageEncryption(asset, _dataContext);
            VerifyStorageEncryptionOnFiles(asset, filePaths);
        }
        public void ShouldSubmitAndFinishEETaskWithStorageProtectedInputAndClearOutput()
        {
            //
            //  This test uses the same preset as the EE DRM tests but does not apply
            //  common encryption.  This preset gets split into multiple subtasks by EE.
            //

            IAsset asset = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.StorageEncrypted);

            // Load the EE preset to create a smooth streaming presentation with PlayReady protection
            string xmlPreset = File.ReadAllText(WindowsAzureMediaServicesTestConfiguration.EncodePlusEncryptWithEeXml);

            // Remove the DRM Section to produce clear content
            var doc = new XmlDocument();

            doc.LoadXml(xmlPreset);

            XmlNodeList drmNodes = doc.GetElementsByTagName("Drm");

            Assert.AreEqual(1, drmNodes.Count);

            XmlNode drmNode = drmNodes[0];

            drmNode.ParentNode.RemoveChild(drmNode);

            xmlPreset = doc.OuterXml;
            IMediaProcessor processor = GetMediaProcessor(_mediaContext, WindowsAzureMediaServicesTestConfiguration.MpEncoderName);
            IJob            job       = CreateAndSubmitOneTaskJob(_mediaContext, GenerateName("ShouldSubmitAndFinishEETaskWithStorageProtectedInputAndClearOutput"), processor, xmlPreset, asset, TaskOptions.None);

            Assert.AreEqual(1, job.Tasks.Count);
            Assert.AreEqual(TaskOptions.None, job.Tasks[0].Options);
            Assert.IsNull(job.Tasks[0].InitializationVector);
            Assert.IsTrue(String.IsNullOrEmpty(job.Tasks[0].EncryptionKeyId));
            Assert.IsNull(job.Tasks[0].EncryptionScheme);
            Assert.IsNull(job.Tasks[0].EncryptionVersion);

            WaitForJob(job.Id, JobState.Finished, VerifyAllTasksFinished);

            CloudMediaContext context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();
            IJob job2 = context2.Jobs.Where(c => c.Id == job.Id).Single();

            Assert.AreEqual(1, job2.Tasks.Count);
            Assert.AreEqual(1, job2.Tasks[0].OutputAssets.Count);
        }
        public void ShouldFinishJobWithErrorWithInvalidPreset()
        {
            IAsset          asset     = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.StorageEncrypted);
            IMediaProcessor processor = GetMediaProcessor(_mediaContext, WindowsAzureMediaServicesTestConfiguration.MpEncoderName);
            IJob            job       = CreateAndSubmitOneTaskJob(_mediaContext, GenerateName("ShouldFinishJobWithErrorWithInvalidPreset"), processor, "Some wrong Preset", asset, TaskOptions.None);
            Action <string> verify    = id =>
            {
                IJob job2 = _mediaContext.Jobs.Where(c => c.Id == id).SingleOrDefault();
                Assert.IsNotNull(job2);
                Assert.IsNotNull(job2.Tasks);
                Assert.AreEqual(1, job2.Tasks.Count);
                Assert.IsNotNull(job2.Tasks[0].ErrorDetails);
                Assert.AreEqual(1, job2.Tasks[0].ErrorDetails.Count);
                Assert.IsNotNull(job2.Tasks[0].ErrorDetails[0]);
                Assert.AreEqual("ErrorParsingConfiguration", job2.Tasks[0].ErrorDetails[0].Code);
            };

            WaitForJob(job.Id, JobState.Error, verify);
        }
 public void ShouldThrowSubmittingJobWhenNonexistingStorageSpecifiedForOutPut()
 {
     try
     {
         IAsset          asset          = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.StorageEncrypted);
         IMediaProcessor mediaProcessor = GetMediaProcessor(_mediaContext, WindowsAzureMediaServicesTestConfiguration.MpEncoderName);
         string          name           = GenerateName("Job 1");
         IJob            job            = _mediaContext.Jobs.Create(name);
         ITask           task           = job.Tasks.AddNew("Task1", mediaProcessor, GetWamePreset(mediaProcessor), TaskOptions.None);
         task.InputAssets.Add(asset);
         task.OutputAssets.AddNew("Output asset", Guid.NewGuid().ToString(), AssetCreationOptions.None);
         job.Submit();
     }
     catch (DataServiceRequestException ex)
     {
         Assert.IsTrue(ex.Response.First().Error.Message.Contains("Cannot find the storage account"));
         throw;
     }
 }
        public void ShouldReturnLocatorWhenCreateSasLocatorCalled()
        {
            // Arrange

            var accessPolicy = _mediaContext.AccessPolicies.Create("TestPolicy", TimeSpan.FromMinutes(10), AccessPermissions.List | AccessPermissions.Read);
            var asset        = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None);

            // Act
            var actual = _mediaContext.Locators.CreateSasLocator(asset, accessPolicy);

            // Assert
            Assert.IsNotNull(actual);
            Assert.IsNotNull(actual.Id);
            Assert.IsNotNull(actual.Path);
            Assert.IsTrue(actual.ExpirationDateTime < DateTime.UtcNow.AddMinutes(11));
            Assert.AreEqual(asset.Id, actual.Asset.Id);
            Assert.AreEqual(asset.Name, actual.Asset.Name);
            Assert.AreEqual(accessPolicy.Id, actual.AccessPolicy.Id);
        }
Ejemplo n.º 8
0
        public void ValidateEffectiveEncryptionStatusOfStorageEncryptedWmv()
        {
            IAsset asset = AssetTests.CreateAsset(_mediaContext, WindowsAzureMediaServicesTestConfiguration.SmallWmv, AssetCreationOptions.StorageEncrypted);

            Assert.AreEqual(false, asset.IsStreamable);
            Assert.AreEqual(AssetType.Unknown, asset.AssetType);
            Assert.AreEqual(AssetCreationOptions.StorageEncrypted, asset.Options);

            AssetDeliveryProtocol protocolsToTest = AssetDeliveryProtocol.SmoothStreaming |
                                                    AssetDeliveryProtocol.Dash |
                                                    AssetDeliveryProtocol.HLS |
                                                    AssetDeliveryProtocol.Hds;

            List <TestCase> testCases = GetTestsCasesForProtocolCombination(protocolsToTest, AssetEncryptionState.Unsupported);

            ValidateAssetEncryptionState(asset, testCases);

            CleanupAsset(asset);
        }
        public void ShouldUpdateExpiryTimeWhenUpdateLocatorCalledWithExpiryTime()
        {
            // Arrange
            var accessPolicyDuration = TimeSpan.FromHours(2);
            var expectedExpiryTime   = DateTime.UtcNow.Date.AddDays(2);

            var accessPolicy = _mediaContext.AccessPolicies.Create("TestPolicy", accessPolicyDuration, AccessPermissions.Read);
            var asset        = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None);
            var locator      = _mediaContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, accessPolicy);

            // Act
            locator.Update(expectedExpiryTime);

            var context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();
            var actual   = context2.Locators.Where(x => x.Id == locator.Id).FirstOrDefault();

            // Assert
            Assert.AreEqual(expectedExpiryTime, locator.ExpirationDateTime);
            Assert.AreEqual(expectedExpiryTime, actual.ExpirationDateTime);
        }
        public void ShouldDeleteLocatorWhenDeleteLocatorAsyncCalled()
        {
            // Arrange


            var accessPolicy = _mediaContext.AccessPolicies.Create("TestPolicy", TimeSpan.FromMinutes(10), AccessPermissions.List | AccessPermissions.Read);
            var asset        = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None);
            var locator      = _mediaContext.Locators.CreateSasLocator(asset, accessPolicy);

            // Act
            var task = locator.DeleteAsync();

            task.Wait();

            var context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();
            var actual   = context2.Locators.Where(x => x.Id == locator.Id).FirstOrDefault();

            // Assert
            Assert.IsNull(actual);
        }
        public void ShouldCreateTaskUsingStorageEncryptedAsset()
        {
            var             filePaths = new[] { WindowsAzureMediaServicesTestConfiguration.SmallWmv };
            IAsset          asset     = AssetTests.CreateAsset(_mediaContext, Path.GetFullPath(WindowsAzureMediaServicesTestConfiguration.SmallWmv), AssetCreationOptions.StorageEncrypted);
            IMediaProcessor processor = JobTests.GetEncoderMediaProcessor(_mediaContext);
            IJob            job       = _mediaContext.Jobs.Create("Encode Job with encrypted asset");
            ITask           task      = job.Tasks.AddNew("Task 1", processor, JobTests.GetWamePreset(processor), TaskOptions.None);

            task.InputAssets.Add(asset);
            task.OutputAssets.AddNew("Encrypted Output", AssetCreationOptions.StorageEncrypted);
            job.Submit();
            JobTests.WaitForJob(job.Id, JobState.Finished, JobTests.VerifyAllTasksFinished);

            CloudMediaContext context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();
            IJob job2 = context2.Jobs.Where(c => c.Id == job.Id).Single();

            foreach (IAsset outputAsset in job2.Tasks[0].OutputAssets)
            {
                VerifyFileAndContentKeyMetadataForStorageEncryption(outputAsset, _mediaContext);
            }
        }
        public void ShouldCreateAssetFileWithPlayReadyEncryption()
        {
            // Note that this file is not really PlayReady encrypted.  For the purposes of this test that is okay.
            IAsset asset = AssetTests.CreateAsset(_mediaContext, Path.GetFullPath(WindowsAzureMediaServicesTestConfiguration.SmallWmv), AssetCreationOptions.CommonEncryptionProtected);

            Guid keyId = Guid.NewGuid();

            byte[] contentKey = GetRandomBuffer(16);

            IContentKey key = _mediaContext.ContentKeys.Create(keyId, contentKey);

            asset.ContentKeys.Add(key);

            Assert.IsNotNull(asset, "Asset should be non null");
            Assert.AreNotEqual(Guid.Empty, asset.Id, "Asset ID should not be null");
            Assert.AreEqual(1, asset.AssetFiles.Count(), "Child files count wrong");
            Assert.IsTrue(asset.Options == AssetCreationOptions.CommonEncryptionProtected, "AssetCreationOptions did not have the expected value");

            VerifyFileAndContentKeyMetadataForCommonEncryption(asset);
            VerifyContentKeyVersusExpectedValue2(asset, contentKey, keyId);
        }
        public void ShouldCreateLocatorWhenCreateSasLocatorCalled()
        {
            // Arrange

            var accessPolicy = _mediaContext.AccessPolicies.Create("TestPolicy", TimeSpan.FromMinutes(10), AccessPermissions.List | AccessPermissions.Read);
            var asset        = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None);

            // Act
            var locator = _mediaContext.Locators.CreateSasLocator(asset, accessPolicy);

            var context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();
            var actual   = context2.Locators.Where(x => x.Id == locator.Id).FirstOrDefault();

            // Assert
            Assert.IsNotNull(actual);
            Assert.AreEqual(locator.Id, actual.Id);
            Assert.IsNotNull(actual.Path);
            Assert.IsTrue(actual.ExpirationDateTime < DateTime.UtcNow.AddMinutes(11));
            Assert.AreEqual(asset.Id, actual.Asset.Id);
            Assert.AreEqual(asset.Name, actual.Asset.Name);
            Assert.AreEqual(accessPolicy.Id, actual.AccessPolicy.Id);
        }
        public void ShouldDeleteAssetWithStorageEncryptionContentKey()
        {
            // Use two contexts to cover the case where the content key needs to be internally attached to
            // the data context.  This simulates deleting a content key that we haven't just created.
            var dataContext2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();

            IAsset asset = AssetTests.CreateAsset(_mediaContext, Path.GetFullPath(WindowsAzureMediaServicesTestConfiguration.SmallWmv), AssetCreationOptions.StorageEncrypted);

            Assert.AreEqual(1, asset.ContentKeys.Count, "Expected 1 content key associated with the asset for storage encryption");
            Assert.AreEqual(ContentKeyType.StorageEncryption, asset.ContentKeys[0].ContentKeyType);

            // Get the ids to make sure they are no longer in the system after deleting the asset
            string assetId = asset.Id;
            string fileId  = asset.AssetFiles.ToList()[0].Id;
            string keyId   = asset.ContentKeys[0].Id;

            foreach (ILocator locator in asset.Locators)
            {
                locator.Delete();
            }

            // Now delete the asset and ensure that the content key and file are also deleted
            asset.Delete();

            foreach (IAsset assetFromRest in dataContext2.Assets)
            {
                Assert.IsFalse(assetFromRest.Id == assetId, "Asset was deleted we should not be able to query it by identifier.");
            }

            foreach (IAssetFile fileFromRest in dataContext2.Files)
            {
                Assert.IsFalse(fileFromRest.Id == fileId, "Asset was deleted we should not be able to query its associated File by identifier.");
            }

            foreach (IContentKey keyFromRest in dataContext2.ContentKeys)
            {
                Assert.IsFalse(keyFromRest.Id == keyId, "Asset was deleted we should not be able to query its associated storage encryption key by identifier.");
            }
        }
Ejemplo n.º 15
0
        public void ShouldThrowFileIOExceptionWhenAccessToLocalFolderisNotThere()
        {
            string fileUploaded = _smallWmv;
            IAsset asset        = AssetTests.CreateAsset(_mediaContext, Path.GetFullPath(fileUploaded),
                                                         AssetCreationOptions.StorageEncrypted);
            IAssetFile assetFile = asset.AssetFiles.First();

            Assert.AreEqual(assetFile.Asset.Id, asset.Id);
            if (Directory.Exists(_outputDirectory))
            {
                Directory.Delete(_outputDirectory, true);
            }
            try
            {
                VerifyAndDownloadAssetFileNTimes(assetFile, asset, 1, 0, false, true);
            }
            catch (AggregateException exception)
            {
                Assert.IsTrue(exception.InnerException.Message.Contains("Could not find a part of the path"));
                throw exception.InnerException;
            }
            Assert.Fail();
        }
        public void ShouldReturnLocatorWhenCreateOriginLocatorWithStartDateCalled()
        {
            // Arrange


            var accessPolicyDuration = TimeSpan.FromMinutes(10);
            var accessPolicy         = _mediaContext.AccessPolicies.Create("TestPolicy", accessPolicyDuration, AccessPermissions.Read);
            var asset              = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None);
            var startDateTime      = DateTime.UtcNow.AddDays(1);
            var expirationDateTime = startDateTime.Add(accessPolicyDuration);

            // Act
            var actual = _mediaContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, accessPolicy, startDateTime);

            // Assert
            Assert.IsNotNull(actual);
            Assert.IsNotNull(actual.Id);
            Assert.IsNotNull(actual.Path);
            Assert.AreEqual(startDateTime, actual.StartTime);
            Assert.IsTrue(actual.ExpirationDateTime < expirationDateTime.AddMinutes(1));
            Assert.AreEqual(asset.Id, actual.Asset.Id);
            Assert.AreEqual(asset.Name, actual.Asset.Name);
            Assert.AreEqual(accessPolicy.Id, actual.AccessPolicy.Id);
        }
Ejemplo n.º 17
0
        public void ApplyDynamicManifestFilter()
        {
            const string typeAudio = "Type=\"audio\"";
            const string typeVideo = "Type=\"video\"";

            string          configuration  = File.ReadAllText(WindowsAzureMediaServicesTestConfiguration.DefaultMp4ToSmoothConfig);
            IAsset          inputAsset     = AssetTests.CreateAsset(_mediaContext, WindowsAzureMediaServicesTestConfiguration.SmallMp41, AssetCreationOptions.None);
            IMediaProcessor mediaProcessor = JobTests.GetMediaProcessor(_mediaContext, WindowsAzureMediaServicesTestConfiguration.MpPackagerName);
            IJob            job            = JobTests.CreateAndSubmitOneTaskJob(_mediaContext, "ApplyDynamicManifestFilter" + Guid.NewGuid().ToString().Substring(0, 5), mediaProcessor, configuration, inputAsset, TaskOptions.None);

            JobTests.WaitForJob(job.Id, JobState.Finished, JobTests.VerifyAllTasksFinished);


            var outputAsset = job.OutputMediaAssets.FirstOrDefault();

            outputAsset = _mediaContext.Assets.Where(c => c.Id == outputAsset.Id).FirstOrDefault();
            var assetFile = outputAsset.AssetFiles.Where(c => c.Name.EndsWith(".ism")).First();

            IAccessPolicy policy        = _mediaContext.AccessPolicies.Create("ApplyDynamicManifestFilter" + Guid.NewGuid().ToString().Substring(0, 5), TimeSpan.FromDays(30), AccessPermissions.Read);
            ILocator      originLocator = _mediaContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, outputAsset, policy, DateTime.UtcNow.AddMinutes(-5));

            string     urlForClientStreaming = originLocator.Path + assetFile.Name + "/manifest";
            HttpClient client  = new HttpClient();
            var        message = client.GetAsync(urlForClientStreaming).Result;
            var        content = message.Content;
            var        result  = content.ReadAsStringAsync().Result;

            Assert.AreEqual(message.StatusCode, HttpStatusCode.OK);
            Assert.IsTrue(result.Length > 0);

            Assert.IsTrue(result.Contains(typeAudio));

            Assert.IsTrue(result.Contains(typeVideo));

            var manifestLength = result.Length;

            // string filterName = "ApplyDynamicManifestFilter_" + DateTime.Now;
            string filterName = "ApplyDynamicManifestFilter_" + Guid.NewGuid().ToString().Substring(0, 5);
            List <FilterTrackSelectStatement> filterTrackSelectStatements = new List <FilterTrackSelectStatement>();
            FilterTrackSelectStatement        filterTrackSelectStatement  = new FilterTrackSelectStatement();

            filterTrackSelectStatement.PropertyConditions = new List <IFilterTrackPropertyCondition>();
            filterTrackSelectStatement.PropertyConditions.Add(new FilterTrackTypeCondition(FilterTrackType.Video, FilterTrackCompareOperator.NotEqual));
            filterTrackSelectStatements.Add(filterTrackSelectStatement);
            IStreamingFilter filter = _mediaContext.Filters.Create(filterName, new PresentationTimeRange(), filterTrackSelectStatements);

            Assert.IsNotNull(filter);


            var        filterUrlForClientStreaming = originLocator.Path + assetFile.Name + String.Format("/manifest(filter={0})", filterName);
            HttpClient filterclient  = new HttpClient();
            var        filtermessage = filterclient.GetAsync(filterUrlForClientStreaming).Result;

            Assert.AreEqual(filtermessage.StatusCode, HttpStatusCode.OK);
            var filtercontent = filtermessage.Content;
            var filterresult  = filtercontent.ReadAsStringAsync().Result;

            Assert.IsTrue(filterresult.Length > 0);
            Assert.AreNotEqual(manifestLength, filterresult);
            Assert.IsTrue(filterresult.Contains(typeAudio));
            Assert.IsFalse(filterresult.Contains(typeVideo));

            outputAsset.DeleteAsync();
            inputAsset.DeleteAsync();
            job.DeleteAsync();
            filter.DeleteAsync();
        }
 private void CreateOriginLocatorWithSpecificPermission(AccessPermissions accessPermissions)
 {
     var accessPolicy = _mediaContext.AccessPolicies.Create("TestPolicy", TimeSpan.FromMinutes(10), accessPermissions);
     var asset        = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None);
     var locator      = _mediaContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, accessPolicy);
 }
Ejemplo n.º 19
0
        public void ShouldCancelDownloadToFileAsyncTaskAfter50Milliseconds()
        {
            string fileUploaded    = _smallWmv;
            string outputDirectory = "Download" + Guid.NewGuid();
            string fileDownloaded  = Path.Combine(outputDirectory, Path.GetFileName(fileUploaded));

            IAsset     asset     = AssetTests.CreateAsset(_mediaContext, Path.GetFullPath(fileUploaded), AssetCreationOptions.StorageEncrypted);
            IAssetFile assetFile = asset.AssetFiles.First();

            Assert.AreEqual(assetFile.Asset.Id, asset.Id);
            Assert.AreEqual(1, asset.Locators.Count);

            CleanDirectory(outputDirectory);

            var           source       = new CancellationTokenSource();
            IAccessPolicy accessPolicy = _mediaContext.AccessPolicies.Create("SdkDownload", TimeSpan.FromHours(12), AccessPermissions.Read);
            ILocator      locator      = _mediaContext.Locators.CreateSasLocator(asset, accessPolicy);
            var           blobTransfer = new BlobTransferClient
            {
                NumberOfConcurrentTransfers = _mediaContext.NumberOfConcurrentTransfers,
                ParallelTransferThreadCount = _mediaContext.ParallelTransferThreadCount
            };

            Exception canceledException  = null;
            Task      downloadToFileTask = null;

            try
            {
                downloadToFileTask = assetFile.DownloadAsync(fileDownloaded, blobTransfer, locator, source.Token);

                // Send a cancellation signal after 2 seconds.
                Thread.Sleep(50);
                source.Cancel();

                // Block the thread waiting for the job to finish.
                downloadToFileTask.Wait();
            }
            catch (AggregateException exception)
            {
                Assert.AreEqual(1, exception.InnerExceptions.Count);
                canceledException = exception.InnerException;
            }
            finally
            {
                if (File.Exists(fileDownloaded))
                {
                    File.Delete(fileDownloaded);
                }
            }

            Assert.IsNotNull(canceledException);
            Assert.IsInstanceOfType(canceledException, typeof(OperationCanceledException));

            // The async task ends in a Canceled state.
            Assert.AreEqual(TaskStatus.Canceled, downloadToFileTask.Status);

            CloudMediaContext newContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();

            IAsset retreivedAsset = newContext.Assets.Where(a => a.Id == asset.Id).Single();

            Assert.AreEqual(2, retreivedAsset.Locators.Count);
        }