static private void GetLocator(IAsset asset) { var manifest = from f in asset.AssetFiles where f.Name.EndsWith(".ism") select f; IAssetFile manifestFile = manifest.First(); IAccessPolicy policy = mediaContext.AccessPolicies.Create("Streaming policy", TimeSpan.FromDays(90), AccessPermissions.Read); ILocator locator = mediaContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, policy, DateTime.UtcNow.AddMinutes(-5)); // Compensate for clock drift Console.WriteLine($"Base origin: {locator.Path}"); // Create a full URL to the manifest file. Use this for playback // in streaming media clients. string streamurl = locator.Path + Uri.EscapeUriString(manifestFile.Name) + "/manifest"; // HLS string hsl = String.Format("{0}{1}", streamurl, "(format=m3u8-aapl)"); Console.WriteLine("HLS manifest for streaming: "); Console.WriteLine(hsl); }
public void ShouldCreateAssetFileArrayWithEncryption() { var filePaths = new[] { WindowsAzureMediaServicesTestConfiguration.SmallWmv, WindowsAzureMediaServicesTestConfiguration.SmallWmv2 }; IAsset asset = _dataContext.Assets.Create(Guid.NewGuid().ToString(), AssetCreationOptions.StorageEncrypted); IAccessPolicy policy = _dataContext.AccessPolicies.Create("Write", TimeSpan.FromMinutes(5), AccessPermissions.Write); ILocator locator = _dataContext.Locators.CreateSasLocator(asset, policy); var blobclient = new BlobTransferClient { NumberOfConcurrentTransfers = 5, ParallelTransferThreadCount = 5 }; foreach (string filePath in filePaths) { var info = new FileInfo(filePath); IAssetFile file = asset.AssetFiles.Create(info.Name); file.UploadAsync(filePath, blobclient, locator, CancellationToken.None).Wait(); } // Associate an access policy with the asset so we can download the files associated with it 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.IsTrue(asset.Options == AssetCreationOptions.StorageEncrypted, "AssetCreationOptions did not have the expected value"); VerifyFileAndContentKeyMetadataForStorageEncryption(asset, _dataContext); VerifyStorageEncryptionOnFiles(asset, filePaths); }
public static string GetOrignUrl(IAsset objIAsset, CloudMediaContext objCloudMediaContext) { ILocator objILocator = null; string url = string.Empty; var assetLocators = objIAsset.Locators.ToList(); foreach (var assetLocator in assetLocators) { //It must be origin if (assetLocator.Type == LocatorType.OnDemandOrigin) { //It must not expire for the next 5 minutes: if (assetLocator.ExpirationDateTime > DateTime.UtcNow.AddMinutes(5)) { //Use it: objILocator = assetLocator; break; } } } if (objILocator != null) { var theManifest = from f in objILocator.Asset.AssetFiles where f.Name.EndsWith(".ism") select f; // Cast the reference to a true IAssetFile type. IAssetFile objIAssetFile = theManifest.First(); url = string.Format("{0}{1}/manifest", objILocator.Path, objIAssetFile.Name); } return(url); }
private static void VerifyEncryptionSettingsMatch(IAssetFile file, IAsset assetFromServer, ContentKeyType expectedKeyType) { bool fileFound = false; foreach (IAssetFile fileFromServer in assetFromServer.AssetFiles) { if (fileFromServer.Id == file.Id) { fileFound = true; Assert.IsTrue(file.IsEncrypted == fileFromServer.IsEncrypted, "IsEncrypted doesn't match"); Assert.IsTrue(file.InitializationVector == fileFromServer.InitializationVector, "InitializationVector doesn't match"); Assert.IsTrue(file.EncryptionKeyId == fileFromServer.EncryptionKeyId, "EncryptionKeyId doesn't match"); Assert.IsTrue(file.EncryptionScheme == fileFromServer.EncryptionScheme, "EncryptionScheme doesn't match"); Assert.IsTrue(file.EncryptionVersion == fileFromServer.EncryptionVersion, "EncryptionVersion doesn't match"); if (!string.IsNullOrEmpty(fileFromServer.EncryptionKeyId)) { VerifyContentKeyExists(file, assetFromServer, expectedKeyType); } break; } } Assert.IsTrue(fileFound, "The expected file identifier was not found in the IAsset.Files collection queried from the server."); }
public void ShouldCreateAssetFile() { IAsset asset = _mediaContext.Assets.Create("Empty", AssetCreationOptions.StorageEncrypted); IAssetFile file = asset.AssetFiles.CreateAsync(Path.GetFileName(_smallWmv), CancellationToken.None).Result; IAccessPolicy policy = _mediaContext.AccessPolicies.Create("temp", TimeSpan.FromMinutes(10), AccessPermissions.Write); ILocator locator = _mediaContext.Locators.CreateSasLocator(asset, policy); BlobTransferClient blobTransferClient = _mediaContext.MediaServicesClassFactory.GetBlobTransferClient(); bool transferCompletedFired = false; blobTransferClient.TransferCompleted += (sender, args) => { transferCompletedFired = true; Assert.AreEqual(BlobTransferType.Upload, args.TransferType, "file.UploadAsync Transfer completed expected BlobTransferType is Upload"); }; file.UploadAsync(_smallWmv, blobTransferClient, locator, CancellationToken.None).Wait(); Assert.IsNotNull(asset, "Asset should be non null"); Assert.IsTrue(transferCompletedFired, "TransferCompleted event has not been fired"); Assert.AreNotEqual(Guid.Empty, asset.Id, "Asset ID shuold not be null"); Assert.AreEqual(AssetState.Initialized, asset.State, "Asset state wrong"); foreach (IAssetFile ifile in asset.AssetFiles) { if (ifile.IsPrimary) { Assert.IsTrue(string.Compare(Path.GetFileName(_smallWmv), ifile.Name, StringComparison.InvariantCultureIgnoreCase) == 0, "Main file is wrong"); break; } } }
public void ShouldCreateAssetFileArrayWithPlayReadyEncryption() { // Note that these files are not really PlayReady encrypted. For the purposes of this test that is okay. IAsset asset = _dataContext.Assets.Create(Guid.NewGuid().ToString(), AssetCreationOptions.CommonEncryptionProtected); IAccessPolicy policy = _dataContext.AccessPolicies.Create("Write", TimeSpan.FromMinutes(5), AccessPermissions.Write); ILocator locator = _dataContext.Locators.CreateSasLocator(asset, policy); var blobclient = new BlobTransferClient { NumberOfConcurrentTransfers = 5, ParallelTransferThreadCount = 5 }; foreach (string filePath in new[] { WindowsAzureMediaServicesTestConfiguration.SmallWmv, WindowsAzureMediaServicesTestConfiguration.SmallWmv2 }) { var info = new FileInfo(filePath); IAssetFile file = asset.AssetFiles.Create(info.Name); file.UploadAsync(filePath, blobclient, locator, CancellationToken.None).Wait(); } Guid keyId = Guid.NewGuid(); byte[] contentKey = GetRandomBuffer(16); IContentKey key = _dataContext.ContentKeys.Create(keyId, contentKey); asset.ContentKeys.Add(key); Assert.IsNotNull(asset, "Asset should be non null"); Assert.AreNotEqual(Guid.Empty, asset.Id, "Asset ID shuold not be null"); Assert.IsTrue(asset.Options == AssetCreationOptions.CommonEncryptionProtected, "AssetCreationOptions did not have the expected value"); VerifyFileAndContentKeyMetadataForCommonEncryption(asset); VerifyContentKeyVersusExpectedValue2(asset, contentKey, keyId); }
public static void CreateAssetAndUploadNFilesSync(int expected, CloudMediaContext mediaContext, string sourceFileName) { IAsset asset = mediaContext.Assets.Create("TestWithMultipleFiles", AssetCreationOptions.None); VerifyAsset(asset); DirectoryInfo info = null; try { info = Directory.CreateDirectory(Guid.NewGuid().ToString()); for (int i = 0; i < expected; i++) { string fullFilePath = null; string fileName; fullFilePath = CreateNewFileFromOriginal(info, sourceFileName, out fileName); IAssetFile file = asset.AssetFiles.Create(fileName); file.Upload(fullFilePath); } Assert.AreEqual(expected, mediaContext.Files.Where(c => c.ParentAssetId == asset.Id).Count()); } finally { if (info != null) { info.Delete(recursive: true); } } }
public void ShouldCreateOutputAssetWithAccountSelectionStrategy() { CapacityBasedAccountSelectionStrategy strategy = CapacityBasedAccountSelectionStrategy.FromAccounts(context, true); string inputAssetFilePath = Path.Combine(TestContext.TestDeploymentDir, smallWmv); string inputAssetFileName = Path.GetFileName(inputAssetFilePath); this.inputAsset = context.Assets.Create("InputAsset", strategy, AssetCreationOptions.StorageEncrypted); IAssetFile file = this.inputAsset.AssetFiles.Create(inputAssetFileName); file.Upload(inputAssetFilePath); IJob job = context.Jobs.Create("Job to test using an account selection strategy for an output asset"); ITask task = job.Tasks.AddNew( "Task to test using an account selection strategy for an output asset", context.MediaProcessors.GetLatestMediaProcessorByName(MediaProcessorNames.MediaEncoderStandard), MediaEncoderStandardTaskPresetStrings.H264SingleBitrate4x3SD, TaskOptions.None); task.InputAssets.Add(this.inputAsset); task.OutputAssets.AddNew("OutputAsset", strategy, AssetCreationOptions.None); job.Submit(); job.GetExecutionProgressTask(CancellationToken.None).Wait(); Assert.IsNotNull(job); Assert.AreEqual(1, job.Tasks.Count, "Unexpected number of tasks in job"); Assert.AreEqual(1, job.OutputMediaAssets.Count, "Unexpected number of output assets in the job"); this.outputAsset = job.OutputMediaAssets[0]; Assert.IsNotNull(outputAsset.StorageAccountName, "Storage account name in output assset is null"); }
public void ShouldCreateEmptyAssetUploadTwoFilesSetPrimaryAndDownloadFile() { IAsset asset = _mediaContext.Assets.Create("Test", AssetCreationOptions.None); VerifyAsset(asset); IAccessPolicy policy = _mediaContext.AccessPolicies.Create("temp", TimeSpan.FromMinutes(10), AccessPermissions.Write); ILocator locator = _mediaContext.Locators.CreateSasLocator(asset, policy); UploadFile(locator, asset, _smallWmv, _mediaContext); //asset = _dataContext.Assets.Where(c => c.Id == asset.Id).FirstOrDefault(); UploadFile(locator, asset, WindowsAzureMediaServicesTestConfiguration.SmallWmv2, _mediaContext); Assert.AreEqual(2, asset.AssetFiles.Count()); IAssetFile assetFile = asset.AssetFiles.ToList()[1]; assetFile.IsPrimary = true; assetFile.Update(); locator.Delete(); policy.Delete(); IAsset refreshedAsset = RefreshedAsset(asset); Assert.AreEqual(2, refreshedAsset.AssetFiles.Count(), "file count wrong"); VerifyAndDownloadAsset(refreshedAsset, 2, _smallWmv, false); }
public void ShouldDownloadSameAssetFile2TimesIdenticallyAsStorageSDK() { IAsset asset = _mediaContext.Assets.Create("Test", AssetCreationOptions.None); VerifyAsset(asset); IAccessPolicy policy = _mediaContext.AccessPolicies.Create("temp", TimeSpan.FromMinutes(10), AccessPermissions.Write); ILocator locator = _mediaContext.Locators.CreateSasLocator(asset, policy); UploadFile(locator, asset, _smallWmv, _mediaContext); UploadFile(locator, asset, WindowsAzureMediaServicesTestConfiguration.SmallWmv2, _mediaContext); IAssetFile assetFile = asset.AssetFiles.FirstOrDefault(); Assert.IsNotNull(assetFile); assetFile.IsPrimary = true; assetFile.Update(); locator.Delete(); policy.Delete(); IAsset refreshedAsset = RefreshedAsset(asset); Assert.AreEqual(2, refreshedAsset.AssetFiles.Count(), "file count wrong"); for (int i = 0; i < 2; i++) { VerifyAndDownloadAsset(refreshedAsset, 2, _smallWmv, false); } }
private void CopyAssetFiles(IAsset myAssetTo, List <IAssetFile> files) { foreach (var assetFile in files) { string magicName = string.Format(@".\{0}\{1}", myRequest.ProcessInstanceId, assetFile.Name); assetFile.Download(magicName); try { Trace.TraceInformation("Copying {0}", magicName); IAssetFile newFile = myAssetTo.AssetFiles.Create(assetFile.Name); newFile.Upload(magicName); newFile.Update(); } catch (Exception X) { Trace.TraceError("Error CopyAssetFiles " + X.Message); if (File.Exists(magicName)) { System.IO.File.Delete(magicName); } throw X; } System.IO.File.Delete(magicName); } myAssetTo.Update(); }
public static void FillAMSEvent(this IProgram program, AMSChannel channel, IProgramRelativeEntity eventData) { if (program != null) { eventData.AMSProgramID = program.Id; eventData.State = program.State.ToAMSEventState(); IAsset asset = program.Asset; if (asset != null) { IAssetFile file = asset.AssetFiles.AsEnumerable().FirstOrDefault(a => a.Name.EndsWith(".ism")); if (file != null) { ILocator locator = asset.Locators.FirstOrDefault(); if (locator != null) { eventData.DefaultPlaybackUrl = locator.Path + file.Name + "/manifest"; eventData.CDNPlaybackUrl = GetCDNPlaybackUrl(locator.Path, eventData.DefaultPlaybackUrl, file.Name, channel.CDNPrefixMode, channel.CDNPrefix); } } } } }
public void ShouldCreateAssetFromFileWithUploadProgressChangedCallback() { var uploadResults = new ConcurrentDictionary <string, UploadProgressChangedEventArgs>(); Action <IAssetFile, UploadProgressChangedEventArgs> uploadProgressChangedCallback = (af, e) => { IAssetFile assetFile = af; UploadProgressChangedEventArgs eventArgs = e; Assert.IsNotNull(assetFile); Assert.IsNotNull(eventArgs); uploadResults.AddOrUpdate(assetFile.Name, eventArgs, (k, e2) => eventArgs); }; var fileName = "smallwmv1.wmv"; this.asset = this.context.Assets.CreateFromFile(fileName, AssetCreationOptions.None, uploadProgressChangedCallback); var assetId = this.asset.Id; Assert.IsNotNull(this.asset); Assert.AreEqual(fileName, this.asset.Name); Assert.AreEqual(1, uploadResults.Count); AssertUploadedFile(".\\", fileName, uploadResults[fileName]); var assetFiles = this.asset.AssetFiles.ToList().OrderBy(a => a.Name); Assert.AreEqual(1, assetFiles.Count()); Assert.AreEqual("smallwmv1.wmv", assetFiles.ElementAt(0).Name); this.context = TestHelper.CreateContext(); Assert.AreEqual(0, this.context.Locators.Where(l => l.AssetId == assetId).Count()); }
public static string ReturnContent(IAssetFile assetFile) { string datastring = null; try { string tempPath = System.IO.Path.GetTempPath(); string filePath = Path.Combine(tempPath, assetFile.Name); if (File.Exists(filePath)) { File.Delete(filePath); } assetFile.Download(filePath); StreamReader streamReader = new StreamReader(filePath); Encoding fileEncoding = streamReader.CurrentEncoding; datastring = streamReader.ReadToEnd(); streamReader.Close(); File.Delete(filePath); } catch { } return(datastring); }
/// <summary> /// Returns the SAS URL of the <paramref name="assetFile"/> for progressive download; otherwise, null. /// </summary> /// <param name="assetFile">The <see cref="IAssetFile"/> instance.</param> /// <returns>A <see cref="System.Uri"/> representing the SAS URL of the <paramref name="assetFile"/> for progressive download; otherwise, null.</returns> public static Uri GetSasUri(this IAssetFile assetFile) { if (assetFile == null) { throw new ArgumentNullException("assetFile", "The asset file cannot be null."); } Uri sasUri = null; IAsset asset = assetFile.Asset; if (asset != null) { ILocator sasLocator = asset .Locators .ToList() .Where(l => l.Type == LocatorType.Sas) .OrderBy(l => l.ExpirationDateTime) .LastOrDefault(); if (sasLocator != null) { UriBuilder builder = new UriBuilder(new Uri(sasLocator.Path, UriKind.Absolute)); builder.Path = Path.Combine(builder.Path, assetFile.Name); sasUri = builder.Uri; } } return(sasUri); }
private IAsset CreateSmoothAsset(string[] filePaths) { IAsset asset = _mediaContext.Assets.Create(Guid.NewGuid().ToString(), AssetCreationOptions.StorageEncrypted); IAccessPolicy policy = _mediaContext.AccessPolicies.Create("Write", TimeSpan.FromMinutes(5), AccessPermissions.Write); ILocator locator = _mediaContext.Locators.CreateSasLocator(asset, policy); var blobclient = new BlobTransferClient { NumberOfConcurrentTransfers = 5, ParallelTransferThreadCount = 5 }; foreach (string filePath in filePaths) { var info = new FileInfo(filePath); IAssetFile file = asset.AssetFiles.Create(info.Name); file.UploadAsync(filePath, blobclient, locator, CancellationToken.None).Wait(); if (WindowsAzureMediaServicesTestConfiguration.SmallIsm == filePath) { file.IsPrimary = true; file.Update(); } } return(asset); }
public static CloudBlockBlob WriteContentToBlob(IAsset asset, CloudBlobContainer dstContainer, string dstBlobName, string blobContent) { string uri = null; CloudBlockBlob blob = null; try { //dstContainer.CreateIfNotExists(); blob = dstContainer.GetBlockBlobReference(dstBlobName); blob.DeleteIfExists(); var options = new BlobRequestOptions() { ServerTimeout = TimeSpan.FromMinutes(10) }; using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(blobContent), false)) { blob.UploadFromStream(stream, null, options); } IAssetFile assetFile = asset.AssetFiles.Create(dstBlobName); blob.FetchAttributes(); assetFile.ContentFileSize = blob.Properties.Length; //assetFile.IsPrimary = false; assetFile.Update(); } catch (Exception e) { throw e; } return(blob); }
public void ShouldThrowArgumentExceptionWhenUploadAsyncFileNameNotEqualToAssetFileName() { IAsset asset = _mediaContext.Assets.Create("test", AssetCreationOptions.None); string fileUploaded = _smallWmv; IAssetFile fileInfo = asset.AssetFiles.Create("test.txt"); IAccessPolicy policy = _mediaContext.AccessPolicies.Create("Write", TimeSpan.FromMinutes(1), AccessPermissions.Write); ILocator locator = _mediaContext.Locators.CreateLocator(LocatorType.Sas, asset, policy); try { fileInfo.UploadAsync(fileUploaded, new BlobTransferClient { NumberOfConcurrentTransfers = 5, ParallelTransferThreadCount = 5 }, locator, CancellationToken.None); } catch (ArgumentException ex) { AssertFileMismatchException(fileUploaded, ex); throw; } }
/// <summary> /// Returns the SAS URL of the <paramref name="assetFile"/> for progressive download using the SAS locator with the longest expiration time; otherwise, null. /// </summary> /// <param name="assetFile">The <see cref="IAssetFile"/> instance.</param> /// <returns>A <see cref="System.Uri"/> representing the SAS URL of the <paramref name="assetFile"/> for progressive download; otherwise, null.</returns> public static Uri GetSasUri(this IAssetFile assetFile) { if (assetFile == null) { throw new ArgumentNullException("assetFile", "The asset file cannot be null."); } Uri sasUri = null; IAsset asset = assetFile.Asset; if (asset != null) { ILocator sasLocator = asset .Locators .ToList() .Where(l => l.Type == LocatorType.Sas) .OrderBy(l => l.ExpirationDateTime) .LastOrDefault(); if (sasLocator != null) { sasUri = BuildSasUri(assetFile, sasLocator); } } return(sasUri); }
/// <summary> /// Returns a <see cref="AssetFileMetadata"/> instance with the <paramref name="assetFile"/> metadata. /// </summary> /// <param name="assetFile">The <see cref="IAssetFile"/> instance from where to get the metadata.</param> /// <param name="sasLocator">The <see cref="ILocator"/> instance.</param> /// <returns>A <see cref="AssetFileMetadata"/> instance with the <paramref name="assetFile"/> metadata.</returns> public static AssetFileMetadata GetMetadata(this IAssetFile assetFile, ILocator sasLocator) { using (Task <AssetFileMetadata> task = assetFile.GetMetadataAsync(sasLocator, CancellationToken.None)) { return(task.Result); } }
/// <summary> /// Returns the SAS URL of the <paramref name="assetFile"/> for progressive download using the <paramref name="sasLocator"/>. /// </summary> /// <param name="assetFile">The <see cref="IAssetFile"/> instance.</param> /// <param name="sasLocator">The <see cref="ILocator"/> instance.</param> /// <returns>A <see cref="System.Uri"/> representing the SAS URL of the <paramref name="assetFile"/> for progressive download; otherwise, null.</returns> public static Uri GetSasUri(this IAssetFile assetFile, ILocator sasLocator) { if (assetFile == null) { throw new ArgumentNullException("assetFile", "The asset file cannot be null."); } if (sasLocator == null) { throw new ArgumentNullException("sasLocator", "The SAS locator cannot be null."); } if (sasLocator.Type != LocatorType.Sas) { throw new ArgumentException("The locator type must be SAS.", "sasLocator"); } if (assetFile.ParentAssetId != sasLocator.AssetId) { throw new ArgumentException("sasLocator", "The SAS locator does not belong to the parent asset."); } Uri sasUri = BuildSasUri(assetFile, sasLocator); return(sasUri); }
public void ShouldCreateAssetAsyncWithMultipleFiles() { string[] files = Directory.GetFiles("TestFiles"); IAsset asset = _mediaContext.Assets.Create(Guid.NewGuid().ToString(), AssetCreationOptions.None); IAccessPolicy policy = _mediaContext.AccessPolicies.Create("Write", TimeSpan.FromMinutes(5), AccessPermissions.Write); ILocator locator = _mediaContext.Locators.CreateSasLocator(asset, policy); var blobclient = _mediaContext.MediaServicesClassFactory.GetBlobTransferClient(); var tasks = new List <Task>(); foreach (string filePath in files) { var info = new FileInfo(filePath); IAssetFile file = asset.AssetFiles.Create(info.Name); tasks.Add(file.UploadAsync(filePath, blobclient, locator, CancellationToken.None)); } Task.WaitAll(tasks.ToArray()); Assert.AreEqual(AssetState.Initialized, asset.State); Assert.AreEqual(files.Length, asset.AssetFiles.Count()); Assert.AreEqual(1, asset.Locators.Count); foreach (IAssetFile assetFile in asset.AssetFiles) { Assert.IsTrue(files.Any(f => Path.GetFileName(f).Equals(assetFile.Name, StringComparison.OrdinalIgnoreCase))); } }
private static async Task <IAssetFile> CreateAssetFileFromLocalFileAsync(this CloudMediaContext context, IAsset asset, string filePath, ILocator sasLocator, EventHandler <UploadProgressChangedEventArgs> uploadProgressChangedEventArgs, CancellationToken cancellationToken) { string assetFileName = Path.GetFileName(filePath); IAssetFile assetFile = await asset.AssetFiles.CreateAsync(assetFileName, cancellationToken); assetFile.UploadProgressChanged += uploadProgressChangedEventArgs; BlobTransferClient blobTransferClient = new BlobTransferClient { NumberOfConcurrentTransfers = context.NumberOfConcurrentTransfers, ParallelTransferThreadCount = context.ParallelTransferThreadCount }; await assetFile.UploadAsync(filePath, blobTransferClient, sasLocator, cancellationToken); assetFile.UploadProgressChanged -= uploadProgressChangedEventArgs; if (assetFileName.EndsWith(ManifestFileExtension, StringComparison.OrdinalIgnoreCase)) { assetFile.IsPrimary = true; await assetFile.UpdateAsync(); } return(assetFile); }
public void ShouldDeleteAssetWithCommonEncryptionContentKey() { var dataContext2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); // Note that this file is not really PlayReady encrypted. For the purposes of this test that is okay. IAsset asset = AssetTests.CreateAsset(_dataContext, Path.GetFullPath(WindowsAzureMediaServicesTestConfiguration.SmallWmv), AssetCreationOptions.CommonEncryptionProtected); string assetId = asset.Id; string fileId = asset.AssetFiles.ToList()[0].Id; Guid keyId = Guid.NewGuid(); byte[] contentKeyBytes = GetRandomBuffer(16); IContentKey key = _dataContext.ContentKeys.Create(keyId, contentKeyBytes); asset.ContentKeys.Add(key); string keyIdentifier = key.Id; asset.Delete(); IAsset resultAsset = dataContext2.Assets.Where(a => a.Id == assetId).FirstOrDefault(); Assert.IsNull(resultAsset, "Asset was deleted we should not be able to query it by identifier."); IAssetFile resultFile = dataContext2.Files.Where(f => f.Id == fileId).FirstOrDefault(); Assert.IsNull(resultFile, "Asset was deleted we should not be able to query its associated File by identifier."); // The content key should not exists IContentKey resultContentKey = dataContext2.ContentKeys.Where(c => c.Id == keyIdentifier).FirstOrDefault(); Assert.IsNull(resultContentKey, "Common Encryption Content Key should be deleted by deleting the asset"); }
private static Uri GetStreamingUri(this IAsset asset, string streamingParameter) { if (asset == null) { throw new ArgumentNullException("asset", "The asset cannot be null."); } Uri smoothStreamingUri = null; IAssetFile manifestAssetFile = asset.GetManifestAssetFile(); if (manifestAssetFile != null) { ILocator originLocator = asset .Locators .ToList() .Where(l => l.Type == LocatorType.OnDemandOrigin) .OrderBy(l => l.ExpirationDateTime) .FirstOrDefault(); if (originLocator != null) { smoothStreamingUri = new Uri( string.Format( CultureInfo.InvariantCulture, BaseProgramUrlTemplate, originLocator.Path.TrimEnd('/'), manifestAssetFile.Name, streamingParameter), UriKind.Absolute); } } return(smoothStreamingUri); }
private static Uri GetStreamingUri(this ILocator originLocator, string streamingParameter) { if (originLocator == null) { throw new ArgumentNullException("locator", "The locator cannot be null."); } if (originLocator.Type != LocatorType.OnDemandOrigin) { throw new ArgumentException("The locator type must be on-demand origin.", "originLocator"); } Uri smoothStreamingUri = null; IAsset asset = originLocator.Asset; IAssetFile manifestAssetFile = asset.GetManifestAssetFile(); if (manifestAssetFile != null) { smoothStreamingUri = new Uri( string.Format( CultureInfo.InvariantCulture, BaseStreamingUrlTemplate, originLocator.Path.TrimEnd('/'), manifestAssetFile.Name, streamingParameter), UriKind.Absolute); } return(smoothStreamingUri); }
private void SetPrimaryAssetFile() { IEncoderSupport myEncodigSupport = new EncoderSupport(_MediaServicesContext); IAssetFile mp4 = myAssetOriginal.AssetFiles.Where(f => f.Name.ToLower().EndsWith(".mp4")).FirstOrDefault(); myEncodigSupport.SetPrimaryFile(myAssetOriginal, mp4); }
private static Uri BuildSasUri(IAssetFile assetFile, ILocator sasLocator) { UriBuilder builder = new UriBuilder(new Uri(sasLocator.Path, UriKind.Absolute)); builder.Path = Path.Combine(builder.Path, assetFile.Name); return(builder.Uri); }
public void ShouldCreateEncryptedInitilizedAsset() { IAsset asset = _mediaContext.Assets.Create("Test", AssetCreationOptions.StorageEncrypted); Assert.IsNotNull(asset, "Asset should be non null"); Assert.AreNotEqual(Guid.Empty, asset.Id, "Asset ID shuold not be null"); Assert.AreEqual(0, asset.AssetFiles.Count(), "Asset has files"); Assert.AreEqual(AssetState.Initialized, asset.State, "Expecting initilized state"); IAccessPolicy policy = _mediaContext.AccessPolicies.Create("temp", TimeSpan.FromMinutes(10), AccessPermissions.Write); ILocator locator = _mediaContext.Locators.CreateSasLocator(asset, policy); IAssetFile file = asset.AssetFiles.Create(Path.GetFileName(_smallWmv)); Task task = file.UploadAsync(_smallWmv, _mediaContext.MediaServicesClassFactory.GetBlobTransferClient(), locator, CancellationToken.None); task.Wait(); Assert.IsTrue(task.IsCompleted); Assert.IsTrue(!task.IsFaulted); locator.Delete(); policy.Delete(); IAsset refreshedAsset = _mediaContext.Assets.Where(c => c.Id == asset.Id).FirstOrDefault(); Assert.AreEqual(asset.Name, refreshedAsset.Name); Assert.AreEqual(AssetState.Initialized, refreshedAsset.State); Assert.AreEqual(1, refreshedAsset.AssetFiles.Count(), "file count wrong"); VerifyAndDownloadAsset(refreshedAsset, 1, _smallWmv, true, false); ContentKeyTests.VerifyFileAndContentKeyMetadataForStorageEncryption(refreshedAsset, _mediaContext); }
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); BlobTransferClient blobTransferClient = _mediaContext.MediaServicesClassFactory.GetBlobTransferClient(); Exception canceledException = null; Task downloadToFileTask = null; try { downloadToFileTask = assetFile.DownloadAsync(fileDownloaded, blobTransferClient, 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); }
//ロケータの割り当てたURLを取得する static string BuildFileSasUrl(IAssetFile file, ILocator locator) { // ロケータのパスを得るため、SAS URL にファイル名を結合する if (locator.Type == LocatorType.OnDemandOrigin) { return new Uri(locator.Path + file.Name + "/Manifest").ToString(); } else if (locator.Type == LocatorType.None || locator.Type == LocatorType.Sas) { var uriBuilder = new UriBuilder(locator.Path); uriBuilder.Path = uriBuilder.Path + "/" + file.Name; //SAS URL を返す return uriBuilder.Uri.AbsoluteUri; } return string.Empty; }
public static AssetOutputFile Create(IAssetFile from, byte[] content, AssetHeader meta = null, string extension = null) { var name = extension == null ? new FileInfo(from.FullName) : new FileInfo(Path.ChangeExtension(from.FullName, extension)); var head = meta == null ? from.Meta : meta; return new AssetOutputFile( from.Project, name, head, content ); }
// Create and return a SAS URL to a single file in an asset. static string BuildFileSasUrl(IAssetFile file, ILocator locator) { // Take the locator path, add the file name, and build // a full SAS URL to access this file. This is the only // code required to build the full URL. var uriBuilder = new UriBuilder(locator.Path); uriBuilder.Path += "/" + file.Name; // Optional: print the locator.Path to the asset, and // the full SAS URL to the file Console.WriteLine("Locator path: "); Console.WriteLine(locator.Path); Console.WriteLine(); Console.WriteLine("Full URL to file: "); Console.WriteLine(uriBuilder.Uri.AbsoluteUri); Console.WriteLine(); //Return the SAS URL. return uriBuilder.Uri.AbsoluteUri; }
/// <summary> /// Renders a single page using the input asset and a layout. /// </summary> /// <param name="input">The input file to render.</param> /// <param name="layout">The layout to use for the render.</param> /// <returns>The content generated.</returns> public AssetContent RenderPage(IAssetFile input, string layout) { // Create the template with the specified layout var headers = input.Meta; var content = this.GetUsings() + Environment.NewLine + "@{Layout=\"" + layout + "\";}" + Environment.NewLine + input.Content.AsString(); // Using a new scope, avoiding state sharing problems that way using (var service = new TemplateService()) { // Process the content this.ProcessContent(content, service, headers); // Parse without caching return AssetContent.FromString( service.Parse(content, headers, null, null) ); } }
private static void VerifyEncryptionSettingsMatch(IAssetFile file, IAsset assetFromServer, ContentKeyType expectedKeyType) { bool fileFound = false; foreach (IAssetFile fileFromServer in assetFromServer.AssetFiles) { if (fileFromServer.Id == file.Id) { fileFound = true; Assert.IsTrue(file.IsEncrypted == fileFromServer.IsEncrypted, "IsEncrypted doesn't match"); Assert.IsTrue(file.InitializationVector == fileFromServer.InitializationVector, "InitializationVector doesn't match"); Assert.IsTrue(file.EncryptionKeyId == fileFromServer.EncryptionKeyId, "EncryptionKeyId doesn't match"); Assert.IsTrue(file.EncryptionScheme == fileFromServer.EncryptionScheme, "EncryptionScheme doesn't match"); Assert.IsTrue(file.EncryptionVersion == fileFromServer.EncryptionVersion, "EncryptionVersion doesn't match"); if (!string.IsNullOrEmpty(fileFromServer.EncryptionKeyId)) { VerifyContentKeyExists(file, assetFromServer, expectedKeyType); } break; } } Assert.IsTrue(fileFound, "The expected file identifier was not found in the IAsset.Files collection queried from the server."); }
public void DoDownloadFileFromAsset(IAsset asset, IAssetFile File, object folder, int index) { // If download is in the queue, let's wait our turn DoGridTransferWaitIfNeeded(index); string labeldb = string.Format("Starting download of '{0}' of asset '{1}' to {2}", File.Name, asset.Name, folder as string); ILocator sasLocator = null; var locatorTask = Task.Factory.StartNew(() => { sasLocator = _context.Locators.Create(LocatorType.Sas, asset, AccessPermissions.Read, TimeSpan.FromHours(24)); }); locatorTask.Wait(); TextBoxLogWriteLine(labeldb); BlobTransferClient blobTransferClient = new BlobTransferClient { NumberOfConcurrentTransfers = _context.NumberOfConcurrentTransfers, ParallelTransferThreadCount = _context.ParallelTransferThreadCount }; Task.Factory.StartNew(async () => { bool Error = false; try { await File.DownloadAsync(Path.Combine(folder as string, File.Name), blobTransferClient, sasLocator, CancellationToken.None); sasLocator.Delete(); } catch (Exception e) { Error = true; TextBoxLogWriteLine(string.Format("Download of file '{0}' failed !", File.Name), true); TextBoxLogWriteLine(e); DoGridTransferDeclareError(index, e); } if (!Error) { DoGridTransferDeclareCompleted(index, folder.ToString()); } }); }
private static void VerifyContentKeyExists(IAssetFile file, IAsset assetFromServer, ContentKeyType expectedKeyType) { bool keyFound = false; foreach (IContentKey contentKeyFromServer in assetFromServer.ContentKeys) { if (file.EncryptionKeyId == contentKeyFromServer.Id) { keyFound = true; Assert.IsNotNull(contentKeyFromServer.ProtectionKeyType, "ProtectionKeyType should not be null."); Assert.IsNotNull(contentKeyFromServer.ProtectionKeyId, "ProtectionKeyId should not be null."); Assert.IsNotNull(contentKeyFromServer.EncryptedContentKey, "EncryptedContentKey should not be null."); Assert.IsTrue(contentKeyFromServer.ContentKeyType == expectedKeyType, "ContentKeyType does not match expected value"); break; } } Assert.IsTrue(keyFound, "The expected key identifier was not found in the IAsset.ContentKeys collection queried from the server."); }
/// <summary> /// Verifies the and download asset. /// </summary> /// <param name="asset">The asset.</param> /// <param name="expectedFileCount">The expected file count.</param> private void VerifyAndDownloadAssetFile(IAssetFile assetFile, IAsset asset, string uploadedFile) { string downloadPathForWamsSdk = Guid.NewGuid().ToString(); try { _downloadProgress = 0; //Downloading using WAMS SDK assetFile.DownloadProgressChanged += AssetTests_OnDownloadProgress; assetFile.Download(downloadPathForWamsSdk); assetFile.DownloadProgressChanged -= AssetTests_OnDownloadProgress; Assert.AreEqual(100, _downloadProgress); var fileUploadedInfo = new FileInfo(uploadedFile); var fileDownloadedInfo = new FileInfo(downloadPathForWamsSdk); Assert.AreEqual(fileUploadedInfo.Length, fileDownloadedInfo.Length); } finally { if (File.Exists(downloadPathForWamsSdk)) { File.Delete(downloadPathForWamsSdk); } } }
/// <summary> /// Verifies the and download asset. /// </summary> /// <param name="asset">The asset.</param> /// <param name="expectedFileCount">The expected file count.</param> private void VerifyAndDownloadAssetFileNTimes(IAssetFile assetFile, IAsset asset,int count,int expirationTime, bool cleanOutputDirectory,bool expectFailure = false) { var source = new CancellationTokenSource(); if (expirationTime == 0) { expirationTime = 1000; } IAccessPolicy accessPolicy = _mediaContext.AccessPolicies.Create("SdkDownload", TimeSpan.FromSeconds(expirationTime), AccessPermissions.Read); ILocator locator = _mediaContext.Locators.CreateSasLocator(asset, accessPolicy); var blobTransfer = new BlobTransferClient { NumberOfConcurrentTransfers = _mediaContext.NumberOfConcurrentTransfers, ParallelTransferThreadCount = _mediaContext.ParallelTransferThreadCount }; var downloads = new List<Task>(); var paths = new List<string>(); if (cleanOutputDirectory) { CleanDirectory(_outputDirectory); } try { for (int i = 0; i < count; i++) { foreach (IAssetFile file in _mediaContext.Files.Where(c => c.ParentAssetId == asset.Id)) { string path = Path.Combine(_outputDirectory, Guid.NewGuid().ToString()); paths.Add(path); downloads.Add(assetFile.DownloadAsync(path, blobTransfer, locator, source.Token)); } } Task.WaitAll(downloads.ToArray()); } finally { foreach (var fileDownloaded in paths) { if (File.Exists(fileDownloaded)) { File.Delete(fileDownloaded); } else { if (!expectFailure) { Assert.Fail(); } } } } }
private static string GetFileUrl(this ILocator locator, IAssetFile file) { return locator.GetFileUrl(file.Name); }
private string GetFilePathFromArray(string[] originalFilePaths, IAssetFile file) { string returnValue = null; for (int i = 0; i < originalFilePaths.Length; i++) { if (file.Name == Path.GetFileName(originalFilePaths[i])) { returnValue = originalFilePaths[i]; break; } } return returnValue; }
private static void CallUpdateUploadDownloadAndDelete(IAssetFile file, string name) { file.Update(); file.UpdateAsync(); var uploadFile = Path.Combine(Path.GetTempPath(), name); try { File.CreateText(uploadFile).Close(); file.Upload(uploadFile); } finally { File.Delete(uploadFile); } file.Download(Path.GetTempFileName()); file.Delete(); }
public static AssetOutputFile Create(IAssetFile from, string content, AssetHeader meta = null, string extension = null) { return Create(from, Encoding.UTF8.GetBytes(content), meta, extension); }
public static AssetOutputFile Create(IAssetFile from, MemoryStream content, AssetHeader meta = null, string extension = null) { return Create(from, content.ToArray(), meta, extension); }
private void ProcessDownloadFileToAsset(IAssetFile assetFile, string destfolderpath) { try { assetFile.DownloadProgressChanged += MyDownloadProgressChanged; assetFile.Download(destfolderpath); } catch (Exception ex) { throw; } }
/// <summary> /// Gets or adds a view from the cache. /// </summary> /// <param name="input">The input asset.</param> /// <param name="valueFactory">A function that produces the value that should be added to the cache in case it does not already exist.</param> /// <returns></returns> public IViewTemplate Update(IAssetFile input) { // Prepare the cache key var cacheName = input .RelativeName .Replace(input.Extension, String.Empty) .Replace(@"\", @"/"); // Attach usings too var content = this.GetUsings() + Environment.NewLine + input.Content.AsString(); Tracing.Info("Template", cacheName); // Update the map Cache.AddOrUpdate(cacheName, content, (k, v) => content ); return new ViewTemplate(cacheName); }
private static Uri BuildSasUri(IAssetFile assetFile, ILocator sasLocator) { UriBuilder builder = new UriBuilder(new Uri(sasLocator.Path, UriKind.Absolute)); builder.Path = Path.Combine(builder.Path, assetFile.Name); return builder.Uri; }
// Create and return a SAS URL to a single file in an asset. static VideoAsset BuildFileSasUrl(IAssetFile file, ILocator locator) { // Take the locator path, add the file name, and build // a full SAS URL to access this file. This is the only // code required to build the full URL. var uriBuilder = new UriBuilder(locator.Path); uriBuilder.Path += "/" + file.Name; //Return the SAS URL. return new VideoAsset() { ContentUrl = uriBuilder.Uri.AbsoluteUri, Type = (file.Name.StartsWith("flicker") || file.Name.StartsWith("stock_vhs")) ? "flicker" : file.Name.StartsWith("v") ? "wallpaper" : "content"}; }