public void TestADTokenProvider() { var provider = new AzureADTokenProvider(); var uri = new Uri(ConfigurationManager.AppSettings["MediaServicesUri"]); var context = new CloudMediaContext(uri, provider); var asset = context.Assets.FirstOrDefault(); }
public static IContentKey CreateTestKey(CloudMediaContext mediaContext, ContentKeyType contentKeyType, out byte[] key, string name = "") { key = ContentKeyTests.GetRandomBuffer(16); IContentKey contentKey = mediaContext.ContentKeys.Create(Guid.NewGuid(), key, name, contentKeyType); return contentKey; }
public static void ClassInit(TestContext context) { //CreateCounters(); _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); IContentKeyAuthorizationPolicyOption policyOption = null; for (int i = 0; i < 10; i++) { byte[] expectedKey = null; IContentKey contentKey = GetKeyDeliveryUrlTests.CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey); policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty, ContentKeyDeliveryType.BaselineHttp, null, null, ContentKeyRestrictionType.Open); List<IContentKeyAuthorizationPolicyOption> options = new List<IContentKeyAuthorizationPolicyOption> { policyOption }; GetKeyDeliveryUrlTests.CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey); Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp); Assert.IsNotNull(keyDeliveryServiceUri); string rawkey = EncryptionUtils.GetKeyIdAsGuid(contentKey.Id).ToString(); _testData.Add(new Tuple<Uri, string, string>(keyDeliveryServiceUri, TokenServiceClient.GetAuthTokenForKey(rawkey), GetKeyDeliveryUrlTests.GetString(expectedKey))); } }
public void AddingAdditionalFilesToAssetInManifest() { IIngestManifest ingestManifestCreated = CreateManifestWithAssetsAndVerifyIt(_context); _context = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); var ingestManifestRefreshed = _context.IngestManifests.Where(c => c.Id == ingestManifestCreated.Id).FirstOrDefault(); Assert.IsNotNull(ingestManifestRefreshed.Statistics); Assert.IsNotNull(ingestManifestCreated.Statistics); Assert.AreEqual(2, ingestManifestRefreshed.Statistics.PendingFilesCount); AddFileToExistingManifestAssetInfo(_context, ingestManifestCreated.Id); _context = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); ingestManifestRefreshed = _context.IngestManifests.Where(c => c.Id == ingestManifestCreated.Id).FirstOrDefault(); Assert.AreEqual(3, ingestManifestRefreshed.Statistics.PendingFilesCount); }
public static IContentKeyAuthorizationPolicy CreateTestPolicy(CloudMediaContext mediaContext, string name, List<IContentKeyAuthorizationPolicyOption> policyOptions, ref IContentKey contentKey) { IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(name).Result; foreach (IContentKeyAuthorizationPolicyOption option in policyOptions) { contentKeyAuthorizationPolicy.Options.Add(option); } // Associate the content key authorization policy with the content key contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id; contentKey = contentKey.UpdateAsync().Result; return contentKeyAuthorizationPolicy; }
public static IContentKey CreateTestKeyWithSpecified(string keyIdentifier, CloudMediaContext mediaContext, ContentKeyType contentKeyType, string name = "") { var keyId = EncryptionUtils.GetKeyIdAsGuid(keyIdentifier); SymmetricAlgorithm symmetricAlgorithm = new AesCryptoServiceProvider(); if ((contentKeyType == ContentKeyType.CommonEncryption) || (contentKeyType == ContentKeyType.EnvelopeEncryption)) { symmetricAlgorithm.KeySize = EncryptionUtils.KeySizeInBitsForAes128; } else { symmetricAlgorithm.KeySize = EncryptionUtils.KeySizeInBitsForAes256; } IContentKey contentKey = mediaContext.ContentKeys.Create(keyId, symmetricAlgorithm.Key, name, contentKeyType); return contentKey; }
public static IContentKeyAuthorizationPolicyOption CreateOption(CloudMediaContext dataContext, string optionName, ContentKeyDeliveryType deliveryType, string requirements, string configuration, ContentKeyRestrictionType restrictionType) { var restrictions = new List<ContentKeyAuthorizationPolicyRestriction> { new ContentKeyAuthorizationPolicyRestriction { Requirements = requirements, Name = "somename" } }; restrictions[0].SetKeyRestrictionTypeValue(restrictionType); IContentKeyAuthorizationPolicyOption option = dataContext.ContentKeyAuthorizationPolicyOptions.Create( optionName, deliveryType, restrictions, configuration); return option; }
public static IJob CreateAndSubmitOneTaskJob(CloudMediaContext context, string name, IMediaProcessor mediaProcessor, string preset, IAsset asset, TaskOptions options) { IJob job = context.Jobs.Create(name); job.Priority = InitialJobPriority; ITask task = job.Tasks.AddNew("Task1", mediaProcessor, preset, options); task.InputAssets.Add(asset); task.OutputAssets.AddNew("Output asset", AssetCreationOptions.None); DateTime timebeforeSubmit = DateTime.UtcNow; job.Submit(); Assert.AreEqual(1, job.Tasks.Count, "Job contains unexpected amount of tasks"); Assert.AreEqual(1, job.InputMediaAssets.Count, "Job contains unexpected total amount of input assets"); Assert.AreEqual(1, job.OutputMediaAssets.Count, "Job contains unexpected total amount of output assets"); Assert.AreEqual(1, job.Tasks[0].InputAssets.Count, "job.Task[0] contains unexpected amount of input assets"); Assert.AreEqual(1, job.Tasks[0].OutputAssets.Count, "job.Task[0] contains unexpected amount of output assets"); Assert.IsFalse(String.IsNullOrEmpty(job.Tasks[0].InputAssets[0].Id), "Asset Id is Null or empty"); Assert.IsFalse(String.IsNullOrEmpty(job.Tasks[0].OutputAssets[0].Id), "Asset Id is Null or empty"); return job; }
public static IAsset CreateAsset(CloudMediaContext datacontext, string filePath, AssetCreationOptions options) { IAsset asset = datacontext.Assets.Create(Guid.NewGuid().ToString(), options); IAccessPolicy policy = datacontext.AccessPolicies.Create("Write", TimeSpan.FromMinutes(5), AccessPermissions.Write); ILocator locator = datacontext.Locators.CreateSasLocator(asset, policy); var info = new FileInfo(filePath); IAssetFile file = asset.AssetFiles.Create(info.Name); BlobTransferClient blobTransferClient = datacontext.MediaServicesClassFactory.GetBlobTransferClient(); blobTransferClient.NumberOfConcurrentTransfers = 5; blobTransferClient.ParallelTransferThreadCount = 5; file.UploadAsync(filePath, blobTransferClient, locator, CancellationToken.None).Wait(); file.IsPrimary = true; file.Update(); return asset; }
public static void VerifyFileAndContentKeyMetadataForStorageEncryption(IAsset asset, CloudMediaContext dataContext) { IAsset assetFromServer = Enumerable.First(dataContext.Assets.Where(c => c.Id == asset.Id)); Assert.IsTrue(assetFromServer.Options == AssetCreationOptions.StorageEncrypted); foreach (IAssetFile file in asset.AssetFiles) { // ensure that the file is marked as encrypted and has data for // the encryption fields string fileInfo = string.Format("File {0}, Asset {1}", file.Id, file.Asset.Id); Assert.IsTrue(file.IsEncrypted, "IsEncrypted is not set." + fileInfo); Assert.IsNotNull(file.InitializationVector, "InitializationVector is not set" + fileInfo); Assert.IsNotNull(file.EncryptionKeyId, "EncryptionKeyId is not set" + fileInfo); Assert.IsTrue(file.EncryptionScheme == FileEncryption.SchemeName, "EncryptionScheme does not match expected value" + fileInfo); Assert.IsTrue(file.EncryptionVersion == FileEncryption.SchemeVersion, "EncryptionVersion does not match expected" + fileInfo); // ensure that the local settings match those stored on the server VerifyEncryptionSettingsMatch(file, assetFromServer, ContentKeyType.StorageEncryption); } }
public static void ClassInit(TestContext context) { CreateCounters(); InitilizeChallenges(); _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); IContentKeyAuthorizationPolicyOption policyOption = null; PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate(); responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate()); string licenseTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate); IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _mediaContext.ContentKeyAuthorizationPolicies.CreateAsync("PerfTest"+Guid.NewGuid().ToString()).Result; policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty, ContentKeyDeliveryType.PlayReadyLicense, null, licenseTemplate, ContentKeyRestrictionType.Open); contentKeyAuthorizationPolicy.Options.Add(policyOption); foreach (var tuple in _keys) { IContentKey contentKey = _mediaContext.ContentKeys.Where(c => c.Id == tuple.Item1) .FirstOrDefault(); if (contentKey != null) { contentKey.Delete(); } contentKey = GetKeyDeliveryUrlTests.CreateTestKeyWithSpecified(tuple.Item1, _mediaContext, ContentKeyType.CommonEncryption); // Associate the content key authorization policy with the content key contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id; contentKey = contentKey.UpdateAsync().Result; Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense); Assert.IsNotNull(keyDeliveryServiceUri); _testData.Add(new Tuple<Uri, string>(keyDeliveryServiceUri, contentKey.Id)); } }
public void RefreshPrograms(CloudMediaContext context, int pagetodisplay) // all assets are refreshed { if (!_initialized) { return; } this.BeginInvoke(new Action(() => this.FindForm().Cursor = Cursors.WaitCursor)); _context = context; IEnumerable <ProgramEntry> programquery; int days = FilterTime.ReturnNumberOfDays(_timefilter); programs = (days == -1) ? context.Programs : context.Programs.Where(a => (a.LastModified > (DateTime.UtcNow.Add(-TimeSpan.FromDays(days))))); // search if (_searchinname != null && !string.IsNullOrEmpty(_searchinname.Text)) { switch (_searchinname.SearchType) { case SearchIn.ProgramName: programs = programs.Where(a => (a.Name.IndexOf(_searchinname.Text, StringComparison.OrdinalIgnoreCase) != -1) // for no case sensitive ); break; case SearchIn.ProgramId: programs = programs.Where(a => (a.Id.IndexOf(_searchinname.Text, StringComparison.OrdinalIgnoreCase) != -1) ); break; default: break; } } if (FilterState != "All") { programs = programs.Where(p => p.State == (ProgramState)Enum.Parse(typeof(ProgramState), _statefilter)); } switch (_orderitems) { case OrderPrograms.LastModified: programquery = programs.AsEnumerable().Where(p => idsList.Contains(p.ChannelId)).OrderByDescending(p => p.LastModified) .Join(_context.Channels.AsEnumerable(), p => p.ChannelId, c => c.Id, (p, c) => new ProgramEntry { Name = p.Name, Id = p.Id, Description = p.Description, ArchiveWindowLength = p.ArchiveWindowLength, State = p.State, LastModified = p.LastModified.ToLocalTime(), ChannelName = c.Name, ChannelId = c.Id, Published = p.Asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).Count() > 0 ? Streaminglocatorimage : null, }).ToArray(); break; case OrderPrograms.Name: programquery = programs.AsEnumerable().Where(p => idsList.Contains(p.ChannelId)).OrderBy(p => p.Name) .Join(_context.Channels.AsEnumerable(), p => p.ChannelId, c => c.Id, (p, c) => new ProgramEntry { Name = p.Name, Id = p.Id, Description = p.Description, ArchiveWindowLength = p.ArchiveWindowLength, State = p.State, LastModified = p.LastModified.ToLocalTime(), ChannelName = c.Name, ChannelId = c.Id, Published = p.Asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).Count() > 0 ? Streaminglocatorimage : null, }).ToArray(); break; case OrderPrograms.State: programquery = programs.AsEnumerable().Where(p => idsList.Contains(p.ChannelId)).OrderBy(p => p.State) .Join(_context.Channels.AsEnumerable(), p => p.ChannelId, c => c.Id, (p, c) => new ProgramEntry { Name = p.Name, Id = p.Id, Description = p.Description, ArchiveWindowLength = p.ArchiveWindowLength, State = p.State, LastModified = p.LastModified.ToLocalTime(), ChannelName = c.Name, ChannelId = c.Id, Published = p.Asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).Count() > 0 ? Streaminglocatorimage : null, }).ToArray(); break; default: programquery = programs.AsEnumerable().Where(p => idsList.Contains(p.ChannelId)) .Join(_context.Channels.AsEnumerable(), p => p.ChannelId, c => c.Id, (p, c) => new ProgramEntry { Name = p.Name, Id = p.Id, Description = p.Description, ArchiveWindowLength = p.ArchiveWindowLength, State = p.State, LastModified = p.LastModified.ToLocalTime(), ChannelName = c.Name, ChannelId = c.Id, Published = p.Asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).Count() > 0 ? Streaminglocatorimage : null, }).ToArray(); break; } if ((!string.IsNullOrEmpty(_timefilter)) && _timefilter == FilterTime.First50Items) { programquery = programquery.Take(50); } _MyObservPrograms = new BindingList <ProgramEntry>(programquery.ToList()); _MyObservProgramsthisPage = new BindingList <ProgramEntry>(_MyObservPrograms.Skip(_itemssperpage * (_currentpage - 1)).Take(_itemssperpage).ToList()); this.BeginInvoke(new Action(() => this.DataSource = _MyObservProgramsthisPage)); _refreshedatleastonetime = true; this.BeginInvoke(new Action(() => this.FindForm().Cursor = Cursors.Default)); }
public static IContentKey CreateTestKey(CloudMediaContext mediaContext, ContentKeyType contentKeyType, string name = "") { byte[] key; return CreateTestKey(mediaContext, contentKeyType, out key); }
public void SetupTest() { _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); _smallWmv = WindowsAzureMediaServicesTestConfiguration.GetVideoSampleFilePath(TestContext, WindowsAzureMediaServicesTestConfiguration.SmallWmv); _largeFile = WindowsAzureMediaServicesTestConfiguration.GetVideoSampleFilePath(TestContext, "largeFile"); _emptyFile = WindowsAzureMediaServicesTestConfiguration.GetVideoSampleFilePath(TestContext, "emptyFile"); _outputDirectory = "MediaDownloads"; }
public static async Task <IOperation> ChannelExecuteOperationAsync(Func <TimeSpan, string, Task <IOperation> > fCall, TimeSpan ts, string s, IChannel channel, string strStatusSuccess, CloudMediaContext _context, Mainform mainform, DataGridViewLiveChannel dataGridViewChannelsV = null) //used for all except creation { IOperation operation = null; try { var state = channel.State; var STask = fCall(ts, s); operation = await STask; while (operation.State == OperationState.InProgress) { //refresh the operation operation = _context.Operations.GetOperation(operation.Id); // refresh the channel IChannel channelR = _context.Channels.Where(c => c.Id == channel.Id).FirstOrDefault(); if (channelR != null && state != channelR.State) { state = channelR.State; if (dataGridViewChannelsV != null) { dataGridViewChannelsV.BeginInvoke(new Action(() => dataGridViewChannelsV.RefreshChannel(channelR)), null); } } System.Threading.Thread.Sleep(1000); } if (operation.State == OperationState.Succeeded) { mainform.TextBoxLogWriteLine("Channel '{0}' : {1}.", channel.Name, strStatusSuccess); } else { mainform.TextBoxLogWriteLine("Channel '{0}' NOT {1}. (Error {2})", channel.Name, strStatusSuccess, operation.ErrorCode, true); mainform.TextBoxLogWriteLine("Error message : {0}", operation.ErrorMessage, true); } if (dataGridViewChannelsV != null) { dataGridViewChannelsV.BeginInvoke(new Action(() => dataGridViewChannelsV.RefreshChannel(channel)), null); } } catch (Exception ex) { mainform.TextBoxLogWriteLine("Channel '{0}' : Error! {1}", channel.Name, Program.GetErrorMessage(ex), true); } return(operation); }
private static void AddFileToExistingManifestAssetInfo(CloudMediaContext context, string id) { IIngestManifest ingestManifest = context.IngestManifests.Where(c => c.Id == id).FirstOrDefault(); Assert.IsNotNull(ingestManifest); Assert.IsNotNull(ingestManifest.IngestManifestAssets); int expectedFilesCount = context.IngestManifestFiles.Where(c => c.ParentIngestManifestId == ingestManifest.Id).Count(); foreach (IIngestManifestAsset assetInfo in ingestManifest.IngestManifestAssets) { Assert.IsNotNull(assetInfo.IngestManifestFiles); //Enumerating through all files foreach (IIngestManifestFile file in assetInfo.IngestManifestFiles) { VerifyManifestFile(file); } //Adding new file to collection } var firstOrDefault = ingestManifest.IngestManifestAssets.FirstOrDefault(); Assert.IsNotNull(firstOrDefault); IIngestManifestFile addedFile = firstOrDefault.IngestManifestFiles.Create(InterviewWmv); VerifyManifestFile(addedFile); expectedFilesCount++; int filesCountFinal = context.IngestManifestFiles.Where(c => c.ParentIngestManifestId == ingestManifest.Id).Count(); Assert.AreEqual(expectedFilesCount, filesCountFinal); }
private void VerifyAssetIsNotExist(IIngestManifestAsset asset, CloudMediaContext context) { Assert.AreEqual(0, context.IngestManifestAssets.Where(c => c.Id == asset.Id).Count(), "Manifest Asset exists.Expected result that asset is not returned by REST API"); }
public static int Main(string[] args = null) { // Test if there are arguments if (args.Length == 0) { System.Console.WriteLine("Usage: Voice2Text <filename>\n filename = Path to file."); return(1); } // Test if the argument is a file string sFilename = Path.GetFullPath(args[0]); if (!File.Exists(sFilename)) { Console.WriteLine("File {0} does not exist.", sFilename); return(1); } // Setup File and config file string sDirectory = Path.GetDirectoryName(sFilename); string sConfigFile = sDirectory + @"\config.json"; // Get Configuration from appsettings.json var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); string sTenant = Configuration["AMSTenantDomain"]; string sAPIep = Configuration["AMSRestAPIEndpoint"]; string sClientId = Configuration["AMSAClientId"]; string sClientSecret = Configuration["AMSClientSecret"]; // Disable console logging in Threds LoggerCallbackHandler.UseDefaultLogging = false; AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(sTenant, new AzureAdClientSymmetricKey(sClientId, sClientSecret), AzureEnvironments.AzureCloudEnvironment); // Create Cloud Media context var tokenProvider = new AzureAdTokenProvider(tokenCredentials); _context = new CloudMediaContext(new Uri(sAPIep), tokenProvider); // Run indexing job. var outputAsset = RunIndexingJob(sFilename, sConfigFile); if (outputAsset != null) { Console.WriteLine("Downloading output..."); DownloadAssetToLocal(outputAsset, sDirectory); // Cleaning up Output Asset outputAsset.Delete(); // Convert the VTT file to text file ProcessVTTfile(sFilename); Console.WriteLine("Done."); } return(0); }
public void SetupTest() { _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate(); responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate()); TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT); tokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(); // the default constructor automatically generates a random key tokenRestrictionTemplate.Audience = "http://sampleIssuerUrl"; tokenRestrictionTemplate.Issuer = "http://sampleAudience"; string optionName = "integrationtest-crud-749"; string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate); string configuration = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate); ContentKeyRestrictionType restrictionType = ContentKeyRestrictionType.TokenRestricted; _testOption = CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.PlayReadyLicense, requirements, configuration, restrictionType); }
public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log) { log.Info($"Webhook was triggered!"); string jsonContent = await req.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(jsonContent); log.Info("Request : " + jsonContent); MediaServicesCredentials amsCredentials = new MediaServicesCredentials(); log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}"); // Validate input objects if (data.assetId == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetId in the input object" })); } string assetId = data.assetId; var attachedstoragecred = KeyHelper.ReturnStorageCredentials(); string mp4FileName = ""; IAsset asset = null; try { AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain, new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret), AzureEnvironments.AzureCloudEnvironment); AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials); _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider); // Find the Asset asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault(); if (asset == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" })); } var files = asset.AssetFiles.ToList().Where(f => !f.Name.EndsWith(".mp4")); string storname = amsCredentials.StorageAccountName; string storkey = amsCredentials.StorageAccountKey; if (asset.StorageAccountName != amsCredentials.StorageAccountName) { if (attachedstoragecred.ContainsKey(asset.StorageAccountName)) // asset is using another storage than default but we have the key { storname = asset.StorageAccountName; storkey = attachedstoragecred[storname]; } else // we don't have the key for that storage { log.Info($"Face redaction Asset is in {asset.StorageAccountName} and key is not provided in MediaServicesAttachedStorageCredentials application settings"); return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Storage key is missing" })); } } // Setup blob container CloudBlobContainer sourceBlobContainer = CopyBlobHelpers.GetCloudBlobContainer(storname, storkey, asset.Uri.Segments[1]); foreach (var file in asset.AssetFiles.ToList()) { if (file.Name.EndsWith(".mp4")) { file.IsPrimary = true; file.Update(); mp4FileName = file.Name; } else { file.Delete(); CloudBlob sourceBlob = sourceBlobContainer.GetBlockBlobReference(file.Name); sourceBlob.DeleteIfExists(); log.Info($"Start copy of file : {file.Name}"); } } asset.Update(); MediaServicesHelper.SetAFileAsPrimary(asset); } catch (Exception ex) { string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : ""); log.Info($"ERROR: Exception {message}"); return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message })); } return(req.CreateResponse(HttpStatusCode.OK, new { mp4FileName })); }
public void Initialize(CloudMediaContext mycontext) { myjoboptions = new JobOptions(mycontext); }
public static IMediaProcessor GetEncoderMediaProcessor(CloudMediaContext context) { return(GetMediaProcessor(context, WindowsAzureMediaServicesTestConfiguration.MpEncoderName)); }
public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log) { log.Info($"Webhook was triggered!"); string jsonContent = await req.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(jsonContent); log.Info("Request : " + jsonContent); MediaServicesCredentials amsCredentials = new MediaServicesCredentials(); log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}"); // Validate input objects if (data.assetId == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetId in the input object" })); } string startsWith = data.startsWith; string endsWith = data.endsWith; string assetId = data.assetId; IAsset asset = null; try { AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain, new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret), AzureEnvironments.AzureCloudEnvironment); AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials); _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider); // Find the Asset asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault(); if (asset == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" })); } var files = asset.AssetFiles.ToList().Where(f => ((string.IsNullOrEmpty(endsWith) || f.Name.EndsWith(endsWith)) && (string.IsNullOrEmpty(startsWith) || f.Name.StartsWith(startsWith)))); foreach (var file in files) { file.Delete(); log.Info($"Deleted file: {file.Name}"); } } catch (Exception ex) { string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : ""); log.Info($"ERROR: Exception {message}"); return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message })); } return(req.CreateResponse(HttpStatusCode.OK)); }
public GenerateUploadDestinationHandler(ISession session, TaskCache <string, PreparedStatement> statementCache, IBus bus, CloudMediaContext cloudMediaContext) { if (session == null) { throw new ArgumentNullException("session"); } if (statementCache == null) { throw new ArgumentNullException("statementCache"); } if (bus == null) { throw new ArgumentNullException("bus"); } if (cloudMediaContext == null) { throw new ArgumentNullException("cloudMediaContext"); } _session = session; _statementCache = statementCache; _bus = bus; _cloudMediaContext = cloudMediaContext; }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable <ChannelEntry> channelquery; _credentials = credentials; _context = context; channelquery = from c in _context.Channels orderby c.LastModified descending select new ChannelEntry { Name = c.Name, Id = c.Id, Description = c.Description, InputProtocol = string.Format("{0} ({1})", Program.ReturnNameForProtocol(c.Input.StreamingProtocol), c.Input.Endpoints.Count), Encoding = ReturnChannelBitmap(c), InputUrl = c.Input.Endpoints.FirstOrDefault().Url, PreviewUrl = c.Preview.Endpoints.FirstOrDefault().Url, State = c.State, LastModified = c.LastModified.ToLocalTime() }; DataGridViewCellStyle cellstyle = new DataGridViewCellStyle() { NullValue = null, Alignment = DataGridViewContentAlignment.MiddleCenter }; DataGridViewImageColumn imageCol = new DataGridViewImageColumn() { DefaultCellStyle = cellstyle, Name = _encoded, DataPropertyName = _encoded, }; this.Columns.Add(imageCol); BindingList <ChannelEntry> MyObservJobInPage = new BindingList <ChannelEntry>(channelquery.Take(0).ToList()); this.DataSource = MyObservJobInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayLiveChannelIDinGrid; this.Columns["InputUrl"].HeaderText = "Primary Input Url"; this.Columns["InputUrl"].Width = 140; this.Columns["InputProtocol"].HeaderText = "Input Protocol (input nb)"; this.Columns["InputProtocol"].Width = 180; this.Columns["PreviewUrl"].Width = 120; this.Columns[_encoded].DisplayIndex = this.ColumnCount - 3; this.Columns[_encoded].DefaultCellStyle.NullValue = null; this.Columns[_encoded].HeaderText = "Cloud Encoding"; this.Columns[_encoded].Width = 100; this.Columns["LastModified"].Width = 140; this.Columns["State"].Width = 75; this.Columns["Description"].Width = 110; WorkerRefreshChannels = new BackgroundWorker(); WorkerRefreshChannels.WorkerSupportsCancellation = true; WorkerRefreshChannels.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshChannels_DoWork); _initialized = true; }
private void Setup() { _MediaServicesContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey); theAsset = _MediaServicesContext.Assets.Where(xx => xx.Id == myRequest.AssetId).FirstOrDefault(); }
private static void MakeRestCallAndVerifyToken(CloudMediaContext context) { context.Assets.FirstOrDefault(); Assert.IsNotNull(context.Credentials.AccessToken); }
public BatchUploadFrame2(string BatchFolderPath, bool BatchProcessFiles, bool BatchProcessSubFolders, CloudMediaContext context) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; _context = context; folders = Directory.GetDirectories(BatchFolderPath).ToList(); files = Directory.GetFiles(BatchFolderPath).ToList(); try { if (BatchProcessFiles) { foreach (var file in files) { var it = checkedListBoxFiles.Items.Add(Path.GetFileName(file)); it.Checked = true; if (!AssetInfo.AssetFileNameIsOk(Path.GetFileName(file))) { it.ForeColor = Color.Red; } } } if (BatchProcessSubFolders) { folders.RemoveAll(f => Directory.GetFiles(f).Count() == 0); // we remove all folder with 0 file in it at the root string s; int filecount; foreach (var folder in folders) { filecount = Directory.GetFiles(folder).Count(); s = filecount > 1 ? "{0} ({1} files)" : "{0} ({1} file)"; var it = checkedListBoxFolders.Items.Add(string.Format(s, Path.GetFileName(folder), filecount)); it.Checked = true; if (AssetInfo.ReturnFilenamesWithProblem(Directory.GetFiles(folder).ToList()).Count > 0) { it.ForeColor = Color.Red; } } } } catch (Exception e) { ErrorConnect = true; this.DialogResult = DialogResult.None; MessageBox.Show("Error when reading files or folders." + Constants.endline + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void ListAssetsAndFilesForNewlyCreatedManifests() { IIngestManifest ingestManifest = CreateEmptyManifestAndVerifyIt(); IAsset asset = _context.Assets.Create("name", AssetCreationOptions.None); Assert.IsNotNull(asset); IIngestManifestAsset ingestManifestAsset = ingestManifest.IngestManifestAssets.Create(asset, new[] { TestFile1 }); VerifyManifestAsset(ingestManifestAsset); IIngestManifestAsset firstAsset = ingestManifest.IngestManifestAssets.FirstOrDefault(); VerifyManifestAsset(firstAsset); Assert.AreEqual(ingestManifestAsset.Id, firstAsset.Id); _context = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); IIngestManifest sameIngestManifest = _context.IngestManifests.Where(c => c.Id == ingestManifest.Id).FirstOrDefault(); Assert.IsNotNull(sameIngestManifest); Assert.AreEqual(1, sameIngestManifest.IngestManifestAssets.Count(), "Manifest asset count is not matching expecting value 1"); firstAsset = sameIngestManifest.IngestManifestAssets.FirstOrDefault(); VerifyManifestAsset(firstAsset); Assert.AreEqual(1, firstAsset.IngestManifestFiles.Count(), "Manifest file count is not matching expecting value 1"); IIngestManifestFile firstFile = firstAsset.IngestManifestFiles.FirstOrDefault(); Assert.AreEqual("text/plain", firstFile.MimeType, "IngestManifestFile's MimeType is wrong"); VerifyManifestFile(firstFile); }
static void Main(string[] args) { try { MediaServicesCredentials credentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); CloudMediaContext context = new CloudMediaContext(credentials); Console.WriteLine("Creating new asset from local file..."); // 1. Create a new asset by uploading a mezzanine file from a local path. IAsset inputAsset = context.Assets.CreateFromFile(_singleInputMp4Path, AssetCreationOptions.None, (af, p) => { Console.WriteLine("Uploading '{0}' - Progress: {1:0.##}%", af.Name, p.Progress); }); Console.WriteLine("Asset created."); // 2. Prepare a job with a single task to transcode the previous mezzanine asset // into a multi-bitrate asset. IJob job = context.Jobs.CreateWithSingleTask(MediaProcessorNames.WindowsAzureMediaEncoder, MediaEncoderTaskPresetStrings.H264AdaptiveBitrateMP4Set720p, inputAsset, "Sample Adaptive Bitrate MP4", AssetCreationOptions.None); Console.WriteLine("Submitting transcoding job..."); // 3. Submit the job and wait until it is completed. job.Submit(); job = job.StartExecutionProgressTask(j => { Console.WriteLine("Job state: {0}", j.State); Console.WriteLine("Job progress: {0:0.##}%", j.GetOverallProgress()); }, CancellationToken.None).Result; Console.WriteLine("Transcoding job finished."); IAsset outputAsset = job.OutputMediaAssets[0]; Console.WriteLine("Publishing output asset..."); // 4. Publish the output asset by creating an Origin locator for adaptive streaming, // and a SAS locator for progressive download. context.Locators.Create(LocatorType.OnDemandOrigin, outputAsset, AccessPermissions.Read, TimeSpan.FromDays(30)); context.Locators.Create(LocatorType.Sas, outputAsset, AccessPermissions.Read, TimeSpan.FromDays(30)); IEnumerable <IAssetFile> mp4AssetFiles = outputAsset.AssetFiles.ToList() .Where(af => af.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase)); // 5. Generate the Smooth Streaming, HLS and MPEG-DASH URLs for adaptive streaming, // and the Progressive Download URL. Uri smoothStreamingUri = outputAsset.GetSmoothStreamingUri(); Uri hlsUri = outputAsset.GetHlsUri(); Uri mpegDashUri = outputAsset.GetMpegDashUri(); List <Uri> mp4ProgressiveDownloadUris = mp4AssetFiles.Select(af => af.GetSasUri()).ToList(); // 6. Get the asset URLs. Console.WriteLine(smoothStreamingUri); Console.WriteLine(hlsUri); Console.WriteLine(mpegDashUri); mp4ProgressiveDownloadUris.ForEach(uri => Console.WriteLine(uri)); Console.WriteLine("Output asset available for adaptive streaming and progressive download."); Console.WriteLine("VOD workflow finished."); } catch (Exception exception) { // Parse the XML error message in the Media Services response and create a new // exception with its content. exception = MediaServicesExceptionParser.Parse(exception); Console.Error.WriteLine(exception.Message); } finally { Console.ReadLine(); } }
private static string DecryptedFile(IIngestManifestFile ingestManifestFile, string encryptedPath, CloudMediaContext context) { IIngestManifestAsset ingestManifestAsset = context.IngestManifestAssets.Where(a => a.Id == ingestManifestFile.ParentIngestManifestAssetId).FirstOrDefault(); Assert.IsNotNull(ingestManifestAsset); IList<IContentKey> keys = ingestManifestAsset.Asset.ContentKeys.Where(c => c.ContentKeyType == ContentKeyType.StorageEncryption).ToList(); Assert.AreEqual(1, keys.Count, "Expecting only one storage key per asset"); IContentKey key = keys.FirstOrDefault(); Assert.IsNotNull(ingestManifestAsset); Guid keyId = EncryptionUtils.GetKeyIdAsGuid(key.Id); FileEncryption fileEncryption = new FileEncryption(key.GetClearKeyValue(), keyId); ulong iv = Convert.ToUInt64(ingestManifestFile.InitializationVector, CultureInfo.InvariantCulture); var decryptedPath = @".\Resources\TestFiles\Decrypted" + Guid.NewGuid(); if (!Directory.Exists(decryptedPath)) { Directory.CreateDirectory(decryptedPath); } decryptedPath = Path.Combine(decryptedPath, ingestManifestFile.Name); FileInfo fileInfo = new FileInfo(encryptedPath); var maxblocksize = GetBlockSize(fileInfo.Length); List<string> blockList = new List<string>(); int numberOfthreads = 1; var queue = PreapreDownloadQueue(maxblocksize, fileInfo.Length, ref numberOfthreads, out blockList); using (var fs = new FileStream(decryptedPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) { KeyValuePair<int, int> block; while (queue.TryDequeue(out block)) { fs.Seek(block.Key * maxblocksize, SeekOrigin.Begin); using (FileStream stream = File.OpenRead(encryptedPath)) { byte[] buffer = new byte[block.Value]; stream.Seek(block.Key * maxblocksize, SeekOrigin.Begin); int read = stream.Read(buffer, 0, (int)block.Value); if (fileEncryption != null) { lock (fileEncryption) { using (FileEncryptionTransform encryptor = fileEncryption.GetTransform(iv, block.Key * maxblocksize)) { encryptor.TransformBlock(inputBuffer: buffer, inputOffset: 0, inputCount: buffer.Length, outputBuffer: buffer, outputOffset: 0); } } } fs.Write(buffer, 0, buffer.Length); } } } return decryptedPath; }
public bool execute(ICustomRequest request) { bool response = true; MediaServicesCredentials xIdentity = new MediaServicesCredentials(request.MediaAccountName, request.MediaAccountKey); _MediaServicesContext = new CloudMediaContext(xIdentity); IJob job = _MediaServicesContext.Jobs.Create("Video Thumbnail Job"); string MediaProcessorName = "Azure Media Video Thumbnails"; var processor = GetLatestMediaProcessorByName(MediaProcessorName); IAsset curretAsset = _MediaServicesContext.Assets.Where(a => a.Id == request.AssetId).FirstOrDefault(); IAsset video360 = _MediaServicesContext.Assets.Create(curretAsset.Name.ToString() + " 360", AssetCreationOptions.None); List <IAssetFile> filesToCopy; filesToCopy = GetFiles(curretAsset, "360_500.mp4"); CopyAssetFiles(video360, filesToCopy); String configuration = "{\"version\":\"1.0\",\"options\":{\"outputAudio\" : \"false\", \"maxMotionThumbnailDurationInSecs\": \"10\", \"fadeInFadeOut\" : \"false\" }}"; // Create a task with the encoding details, using a string preset. ITask task = job.Tasks.AddNew("My Video Thumbnail Task " + curretAsset.Id.ToString(), processor, configuration, TaskOptions.None); // Specify the input asset. task.InputAssets.Add(video360); // Specify the output asset. task.OutputAssets.AddNew(curretAsset.Id.ToString() + " Summarized", AssetCreationOptions.None); // Use the following event handler to check job progress. job.StateChanged += new EventHandler <JobStateChangedEventArgs>(StateChanged); // Launch the job. job.Submit(); // Check job execution and wait for job to finish. Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None); progressJobTask.Wait(); // If job state is Error, the event handling // method for job progress should log errors. Here we check // for error state and exit if needed. if (job.State == JobState.Error) { ErrorDetail error = job.Tasks.First().ErrorDetails.First(); Console.WriteLine(string.Format("Error: {0}. {1}", error.Code, error.Message)); response = false; } IAsset summarizedAsset = _MediaServicesContext.Assets.Where(a => a.Name == curretAsset.Id.ToString() + " Summarized").FirstOrDefault(); List <IAssetFile> filesToCopy2; filesToCopy2 = GetFiles(summarizedAsset, ".mp4"); CopyAssetFiles(curretAsset, filesToCopy2); video360.Delete(); summarizedAsset.Delete(); return(response); }
public CreateTestToken(IAsset _asset, CloudMediaContext _context, ContentKeyType?keytype = null, string optionid = null) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; MyAsset = _asset; mycontext = _context; var query = from key in MyAsset.ContentKeys join autpol in _context.ContentKeyAuthorizationPolicies on key.AuthorizationPolicyId equals autpol.Id select new { keyname = key.Name, keytype = key.ContentKeyType, keyid = key.Id, aupolid = autpol.Id }; listViewAutOptions.BeginUpdate(); listViewAutOptions.Items.Clear(); foreach (var key in query) { var queryoptions = _context.ContentKeyAuthorizationPolicies.Where(a => a.Id == key.aupolid).FirstOrDefault().Options; foreach (var option in queryoptions) { if (option.Restrictions.FirstOrDefault().KeyRestrictionType == (int)ContentKeyRestrictionType.TokenRestricted) { ListViewItem item = new ListViewItem(key.keytype.ToString()); IContentKey keyj = MyAsset.ContentKeys.Where(k => k.Id == key.keyid).FirstOrDefault(); ContentKeyDisplayed.Add(keyj); item.SubItems.Add(option.Name); item.SubItems.Add(option.Id); string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements; if (!string.IsNullOrEmpty(tokenTemplateString)) { TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); item.SubItems.Add(tokenTemplate.TokenType == TokenType.JWT ? "JWT" : "SWT"); if (tokenTemplate.PrimaryVerificationKey != null) { item.SubItems.Add(tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey) ? "Symmetric" : "Asymmetric X509"); } else if (tokenTemplate.OpenIdConnectDiscoveryDocument != null) { item.SubItems.Add("OpenID"); } } listViewAutOptions.Items.Add(item); if (optionid == option.Id) { listViewAutOptions.Items[listViewAutOptions.Items.IndexOf(item)].Selected = true; } } } } if (listViewAutOptions.Items.Count > 0 && listViewAutOptions.SelectedItems.Count == 0) // no selection, in that case, first line selected { listViewAutOptions.Items[0].Selected = true; } listViewAutOptions.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); listViewAutOptions.EndUpdate(); }
public EncoderSupport(CloudMediaContext MediaServicesContext) { _MediaServicesContext = MediaServicesContext; }
internal static IAsset CreateSmoothAsset(CloudMediaContext mediaContext, string[] filePaths, AssetCreationOptions options) { IAsset asset = mediaContext.Assets.Create(Guid.NewGuid().ToString(), options); 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 void SetupTest() { _dataContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); _smallWmv = WindowsAzureMediaServicesTestConfiguration.GetVideoSampleFilePath(TestContext, WindowsAzureMediaServicesTestConfiguration.SmallWmv); _downloadProgress = 0; }
public void ShouldSetContentFileSizeOnAssetFileWithoutUpload() { IAsset asset = _mediaContext.Assets.Create("test", AssetCreationOptions.None); IAssetFile fileInfo = asset.AssetFiles.Create("test.txt"); int expected = 0; Assert.AreEqual(expected, fileInfo.ContentFileSize, "Unexpected ContentFileSize value"); expected = 100; fileInfo.ContentFileSize = expected; fileInfo.Update(); IAssetFile refreshedFile = _mediaContext.Files.Where(c => c.Id == fileInfo.Id).FirstOrDefault(); Assert.IsNotNull(refreshedFile); Assert.AreEqual(expected, refreshedFile.ContentFileSize, "ContentFileSize Mismatch after Update"); //Double check with new context _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); refreshedFile = _mediaContext.Files.Where(c => c.Id == fileInfo.Id).FirstOrDefault(); Assert.IsNotNull(refreshedFile); Assert.AreEqual(expected, refreshedFile.ContentFileSize, "ContentFileSize Mismatch after Update"); }
/// <summary> /// Creates a new asset and copies blobs from the specifed storage account. /// </summary> /// <param name="blob">The specified blob.</param> /// <returns>The new asset.</returns> public static async Task <IAsset> CreateAssetFromBlobAsync(CloudMediaContext context, CloudBlockBlob blob, string assetName, TraceWriter log) { //Get a reference to the storage account that is associated with the Media Services account. StorageCredentials mediaServicesStorageCredentials = new StorageCredentials(_storageAccountName, _storageAccountKey); _destinationStorageAccount = new CloudStorageAccount(mediaServicesStorageCredentials, false); // Create a new asset. var asset = context.Assets.Create(blob.Name, AssetCreationOptions.None); log.Info($"Created new asset {asset.Name}"); IAccessPolicy writePolicy = context.AccessPolicies.Create("writePolicy", TimeSpan.FromHours(4), AccessPermissions.Write); ILocator destinationLocator = context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy); CloudBlobClient destBlobStorage = _destinationStorageAccount.CreateCloudBlobClient(); // Get the destination asset container reference string destinationContainerName = (new Uri(destinationLocator.Path)).Segments[1]; CloudBlobContainer assetContainer = destBlobStorage.GetContainerReference(destinationContainerName); try { await assetContainer.CreateIfNotExistsAsync(); } catch (Exception ex) { log.Error("ERROR:" + ex.Message); } log.Info("Created asset."); // Get hold of the destination blob CloudBlockBlob destinationBlob = assetContainer.GetBlockBlobReference(blob.Name); // Copy Blob try { using (var stream = await blob.OpenReadAsync()) { await destinationBlob.UploadFromStreamAsync(stream); } log.Info("Copy Complete."); var assetFile = asset.AssetFiles.Create(blob.Name); assetFile.ContentFileSize = blob.Properties.Length; //assetFile.MimeType = "video/mp4"; assetFile.IsPrimary = true; assetFile.Update(); asset.Update(); } catch (Exception ex) { log.Error(ex.Message); log.Info(ex.StackTrace); log.Info("Copy Failed."); throw; } destinationLocator.Delete(); writePolicy.Delete(); return(asset); }
private static void UploadFile(ILocator locator, IAsset asset, string filePath, CloudMediaContext mediaContext) { var info = new FileInfo(filePath); IAssetFile file = asset.AssetFiles.Create(info.Name); BlobTransferClient blobTransferClient = mediaContext.MediaServicesClassFactory.GetBlobTransferClient(); Task task = file.UploadAsync(filePath, blobTransferClient, locator, CancellationToken.None); task.Wait(); Assert.IsTrue(task.IsCompleted); Assert.IsTrue(!task.IsFaulted); }
public static async Task <IAsset> CreateAssetFromBlobMultipleFilesAsync(CloudMediaContext context, CloudBlockBlob blob, string assetName, TraceWriter log, List <assetfileinJson> assetfilesAsset) { //Get a reference to the storage account that is associated with the Media Services account. StorageCredentials mediaServicesStorageCredentials = new StorageCredentials(_storageAccountName, _storageAccountKey); _destinationStorageAccount = new CloudStorageAccount(mediaServicesStorageCredentials, false); // Create a new asset. var asset = context.Assets.Create(Path.GetFileNameWithoutExtension(blob.Name), AssetCreationOptions.None); log.Info($"Created new asset {asset.Name}"); IAccessPolicy writePolicy = context.AccessPolicies.Create("writePolicy", TimeSpan.FromHours(4), AccessPermissions.Write); ILocator destinationLocator = context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy); CloudBlobClient destBlobStorage = _destinationStorageAccount.CreateCloudBlobClient(); // Get the destination asset container reference string destinationContainerName = (new Uri(destinationLocator.Path)).Segments[1]; CloudBlobContainer assetContainer = destBlobStorage.GetContainerReference(destinationContainerName); try { await assetContainer.CreateIfNotExistsAsync(); } catch (Exception ex) { log.Error("ERROR:" + ex.Message); } log.Info("Created asset."); var sourceBlobContainer = blob.Container; foreach (var file in assetfilesAsset) { int nbtry = 0; var sourceBlob = sourceBlobContainer.GetBlobReference(file.fileName); while (!await sourceBlob.ExistsAsync() && nbtry < 86400) // let's wait 24 hours max { log.Info("File " + file.fileName + " does not exist... waiting..."); Thread.Sleep(1000); // let's wait for the blob to be there nbtry++; } if (nbtry == 86440) { log.Info("File " + file.fileName + " does not exist... File asset transfer canceled."); break; } log.Info("File " + file.fileName + " found."); // Copy Blob try { // Get hold of the destination blob CloudBlockBlob destinationBlob = assetContainer.GetBlockBlobReference(file.fileName); using (var stream = await sourceBlob.OpenReadAsync()) { await destinationBlob.UploadFromStreamAsync(stream); } log.Info("Copy Complete."); var assetFile = asset.AssetFiles.Create(sourceBlob.Name); assetFile.ContentFileSize = sourceBlob.Properties.Length; //assetFile.MimeType = "video/mp4"; if (file.isPrimary) { assetFile.IsPrimary = true; } assetFile.Update(); asset.Update(); } catch (Exception ex) { log.Error(ex.Message); log.Info(ex.StackTrace); log.Info("Copy Failed."); throw; } } destinationLocator.Delete(); writePolicy.Delete(); return(asset); }
public void RefreshChannels(CloudMediaContext context, int pagetodisplay) // all assets are refreshed { if (!_initialized) { return; } this.BeginInvoke(new Action(() => this.FindForm().Cursor = Cursors.WaitCursor)); _context = context; IEnumerable <ChannelEntry> channelquery; int days = FilterTime.ReturnNumberOfDays(_timefilter); channels = (days == -1) ? context.Channels : context.Channels.Where(a => (a.LastModified > (DateTime.UtcNow.Add(-TimeSpan.FromDays(days))))); // search if (_searchinname != null && !string.IsNullOrEmpty(_searchinname.Text)) { switch (_searchinname.SearchType) { case SearchIn.ChannelName: channels = channels.Where(a => (a.Name.IndexOf(_searchinname.Text, StringComparison.OrdinalIgnoreCase) != -1) // for no case sensitive ); break; case SearchIn.ChannelId: channels = channels.Where(a => (a.Id.IndexOf(_searchinname.Text, StringComparison.OrdinalIgnoreCase) != -1) ); break; default: break; } } if (FilterState != "All") { channels = channels.Where(c => c.State == (ChannelState)Enum.Parse(typeof(ChannelState), _statefilter)); } switch (_orderitems) { case OrderChannels.LastModified: channelquery = from c in channels orderby c.LastModified descending select new ChannelEntry { Name = c.Name, Id = c.Id, Description = c.Description, InputProtocol = string.Format("{0} ({1})", Program.ReturnNameForProtocol(c.Input.StreamingProtocol), c.Input.Endpoints.Count), Encoding = ReturnChannelBitmap(c), InputUrl = c.Input.Endpoints.FirstOrDefault().Url, PreviewUrl = c.Preview.Endpoints.FirstOrDefault().Url, State = c.State, LastModified = c.LastModified.ToLocalTime() }; break; case OrderChannels.Name: channelquery = from c in channels orderby c.Name select new ChannelEntry { Name = c.Name, Id = c.Id, Description = c.Description, InputProtocol = string.Format("{0} ({1})", Program.ReturnNameForProtocol(c.Input.StreamingProtocol), c.Input.Endpoints.Count), Encoding = ReturnChannelBitmap(c), InputUrl = c.Input.Endpoints.FirstOrDefault().Url, PreviewUrl = c.Preview.Endpoints.FirstOrDefault().Url, State = c.State, LastModified = c.LastModified.ToLocalTime() }; break; case OrderChannels.State: channelquery = from c in channels orderby c.State select new ChannelEntry { Name = c.Name, Id = c.Id, Description = c.Description, InputProtocol = string.Format("{0} ({1})", Program.ReturnNameForProtocol(c.Input.StreamingProtocol), c.Input.Endpoints.Count), Encoding = ReturnChannelBitmap(c), InputUrl = c.Input.Endpoints.FirstOrDefault().Url, PreviewUrl = c.Preview.Endpoints.FirstOrDefault().Url, State = c.State, LastModified = c.LastModified.ToLocalTime() }; break; default: channelquery = from c in channels select new ChannelEntry { Name = c.Name, Id = c.Id, Description = c.Description, InputProtocol = string.Format("{0} ({1})", Program.ReturnNameForProtocol(c.Input.StreamingProtocol), c.Input.Endpoints.Count), Encoding = ReturnChannelBitmap(c), InputUrl = c.Input.Endpoints.FirstOrDefault().Url, PreviewUrl = c.Preview.Endpoints.FirstOrDefault().Url, State = c.State, LastModified = c.LastModified.ToLocalTime() }; break; } if ((!string.IsNullOrEmpty(_timefilter)) && _timefilter == FilterTime.First50Items) { channelquery = channelquery.Take(50); } _MyObservChannels = new BindingList <ChannelEntry>(channelquery.ToList()); _MyObservChannelthisPage = new BindingList <ChannelEntry>(_MyObservChannels.Skip(_channelsperpage * (_currentpage - 1)).Take(_channelsperpage).ToList()); this.BeginInvoke(new Action(() => this.DataSource = _MyObservChannelthisPage)); _refreshedatleastonetime = true; this.BeginInvoke(new Action(() => this.FindForm().Cursor = Cursors.Default)); }
public CreateProgram(CloudMediaContext context) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; _context = context; }
public ProgramInfo(List <IProgram> MySelectedPrograms, CloudMediaContext context) { SelectedPrograms = MySelectedPrograms; _context = context; }
public static IMediaProcessor GetMediaProcessor(CloudMediaContext context, string mpName) { IMediaProcessor mp = context.MediaProcessors.Where(c => c.Name == mpName).ToList().OrderByDescending(c => new Version(c.Version)).FirstOrDefault(); if (mp == null) { throw new ArgumentException(string.Format("Media Processor {0} is not found", mpName), "mpName"); } Trace.WriteLine(string.Format("Using media processor {0} Version {1}, ID {2}", mp.Name, mp.Version, mp.Id)); return mp; }
public void SetupTest() { _mediaContext = Helper.GetMediaDataServiceContextForUnitTests(); }
public void SetupTest() { _dataContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); }
public ProgramInfo(IProgram program, CloudMediaContext context) { SelectedPrograms = new List <IProgram>(); SelectedPrograms.Add(program); _context = context; }
public static int AddTask(Microsoft.Azure.WebJobs.ExecutionContext execContext, CloudMediaContext context, IJob job, IAsset sourceAsset, string value, string processor, string presetfilename, string stringtoreplace, ref int taskindex, int priority = 10, string specifiedStorageAccountName = null) { if (value != null) { // Get a media processor reference, and pass to it the name of the // processor to use for the specific task. IMediaProcessor mediaProcessor = MediaServicesHelper.GetLatestMediaProcessorByName(context, processor); string presetPath = Path.Combine(System.IO.Directory.GetParent(execContext.FunctionDirectory).FullName, "presets", presetfilename); string Configuration = File.ReadAllText(presetPath).Replace(stringtoreplace, value); // Create a task with the encoding details, using a string preset. var task = job.Tasks.AddNew(processor + " task", mediaProcessor, Configuration, TaskOptions.None); task.Priority = priority; // Specify the input asset to be indexed. task.InputAssets.Add(sourceAsset); // Add an output asset to contain the results of the job. // Use a non default storage account in case this was provided in 'AddTask' task.OutputAssets.AddNew(sourceAsset.Name + " " + processor + " Output", specifiedStorageAccountName, AssetCreationOptions.None); return(taskindex++); } else { return(-1); } }
public void SetupTest() { _context = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); }
private static IIngestManifest CreateManifestWithAssetsAndVerifyIt(CloudMediaContext context) { //Creating empty manifest const string manifestName = "Manifest 1"; IIngestManifest ingestManifest = context.IngestManifests.Create(manifestName); Assert.AreEqual(IngestManifestState.Inactive, ingestManifest.State, "Expecting empty manifest to be inactive"); //Adding manifest asset info with multiple file IAsset asset2 = context.Assets.Create(Guid.NewGuid().ToString(), AssetCreationOptions.StorageEncrypted); var files2 = new string[2] { TestFile1, TestFile2 }; IIngestManifestAsset ingestManifestAssetInfo2 = ingestManifest.IngestManifestAssets.Create(asset2, files2); Assert.AreEqual(1, asset2.ContentKeys.Count, "No keys associated with asset"); VerifyManifestAsset(ingestManifestAssetInfo2); Assert.AreEqual(2, ingestManifestAssetInfo2.IngestManifestFiles.Count(), "Files collection size is not matching expectations"); return ingestManifest; }
private void buttonLogin_Click(object sender, EventArgs e) { LoginCredentials = GenerateLoginCredentials; if (string.IsNullOrEmpty(LoginCredentials.ReturnAccountName())) { MessageBox.Show(string.Format("The {0} cannot be empty.", labelE1.Text), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } var accName = LoginCredentials.ReturnAccountName(); var entryWithSameName = CredentialList.MediaServicesAccounts.Where(c => c.ReturnAccountName().ToLower().Trim() == accName.ToLower().Trim()).FirstOrDefault(); // if found the same name if (entryWithSameName == null) // not found { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToSaveTheCredentialsFor0, accName), AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_SaveCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to save { CredentialList.MediaServicesAccounts.Add(LoginCredentials); Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); AddItemToListviewAccounts(LoginCredentials); //listViewAccounts.Items.Add(ReturnAccountName(LoginCredentials)); } else if (result == DialogResult.Cancel) { return; } } else // found { if (!LoginCredentials.Equals(entryWithSameName)) // changed ? { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToUpdateTheCredentialsFor0, accName), AMSExplorer.Properties.Resources.AMSLogin_listBoxAccounts_SelectedIndexChanged_UpdateCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to update the credentials { CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = LoginCredentials; Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); } else if (result == DialogResult.Cancel) { return; } } } if (LoginCredentials.UseAADServicePrincipal) // service principal mode { var spcrendentialsform = new AMSLoginServicePrincipal(); if (spcrendentialsform.ShowDialog() == DialogResult.OK) { LoginCredentials.ADSPClientId = spcrendentialsform.ClientId; LoginCredentials.ADSPClientSecret = spcrendentialsform.ClientSecret; } else { return; } } // OLD ACS Mode - let's warm the user if (!LoginCredentials.UseAADServicePrincipal && !LoginCredentials.UseAADInteract) { var f = new DisplayBox("Warning", "ACS authentication keys will no longer be supported by Azure Media Services as of June 1st, 2018.\n\nYou should move to Azure AD authentication as soon as possible.", 10); f.ShowDialog(); } // Context creation this.Cursor = Cursors.WaitCursor; context = Program.ConnectAndGetNewContext(LoginCredentials, false, true); accName = LoginCredentials.ReturnAccountName(); try { var a = context.Assets.FirstOrDefault(); this.Cursor = Cursors.Default; } catch (Exception ex) { MessageBox.Show(Program.GetErrorMessage(ex), "Login error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Cursor = Cursors.Default; return; } accountName = accName; this.DialogResult = DialogResult.OK; // form will close with OK result // else --> form won't close... }
private static void VerifyExistenceofAssetsAndFilesForManifest(IIngestManifest ingestManifest, CloudMediaContext context) { int assetsCount = context.IngestManifestAssets.Where(c => c.ParentIngestManifestId == ingestManifest.Id).Count(); int filescount = context.IngestManifestFiles.Where(c => c.ParentIngestManifestId == ingestManifest.Id).Count(); Assert.IsTrue(assetsCount > 0, "When manifest is empty we are expecting to have associated assets"); Assert.IsTrue(filescount > 0, "When manifest is empty we are expecting to have associated files"); }
public void SetupTest() { _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); testRun = "integrationtest_" + Guid.NewGuid(); }
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); }
internal JobTemplateBaseCollection(CloudMediaContext cloudMediaContext) { this.DataContextFactory = cloudMediaContext.DataContextFactory; this.Queryable = this.DataContextFactory.CreateDataServiceContext().CreateQuery <JobTemplateData>(JobTemplateSet); }
public void SetupTest() { _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); _smallWmv = WindowsAzureMediaServicesTestConfiguration.GetVideoSampleFilePath(TestContext, WindowsAzureMediaServicesTestConfiguration.SmallWmv); }
public static string GetAssetVideoUrl(this CloudMediaContext context, IAsset asset) { var locator = context.CreateSasLocator(asset, AccessPermissions.Read, TimeSpan.FromDays(30)); return(locator.GetFileUrl(asset.AlternateId)); }
public static IMediaProcessor GetEncoderMediaProcessor(CloudMediaContext context) { return GetMediaProcessor(context, WindowsAzureMediaServicesTestConfiguration.MpEncoderName); }
public static IJob GetJob(this CloudMediaContext context, string jobId) { return(context.Jobs.Where(j => j.Id == jobId).FirstOrDefault()); }