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(_mediaContext, 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             = _mediaContext.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");
        }
Пример #2
0
 private static void DeleteAsset(MediaClient mediaClient, IAsset asset)
 {
     using (DatabaseClient databaseClient = new DatabaseClient(true))
     {
         string collectionId = Constants.Database.DocumentCollection.Metadata;
         foreach (IAssetFile file in asset.AssetFiles)
         {
             if (file.Name.EndsWith(Constants.Media.FileExtension.Json))
             {
                 string[] fileNameInfo = file.Name.Split(Constants.NamedItemsSeparator);
                 string   documentId   = fileNameInfo[0];
                 databaseClient.DeleteDocument(collectionId, documentId);
             }
         }
     }
     foreach (ILocator locator in asset.Locators)
     {
         locator.Delete();
     }
     for (int i = asset.DeliveryPolicies.Count - 1; i > -1; i--)
     {
         asset.DeliveryPolicies.RemoveAt(i);
     }
     asset.Delete();
 }
Пример #3
0
        private void ConsolidateOutputs(List <IJobConfiguration> myJobs, int XConsolidateId)
        {
            IAsset ConsolidateOutPut;

            Directory.CreateDirectory(myRequest.ProcessInstanceId);
            foreach (var jobDef in myJobs)
            {
                for (int i = 0; i < jobDef.TaskDefinition.Count(); i++)
                {
                    if (jobDef.OutputAssetId[i] != "")
                    {
                        ConsolidateOutPut = (from m in _MediaServicesContext.Assets select m).Where(m => m.Id == jobDef.OutputAssetId[i]).FirstOrDefault();
                        ITask             xTask           = GetTask(jobDef, 0, 0);
                        IAsset            taskOutputAsset = xTask.OutputAssets.FirstOrDefault();
                        List <IAssetFile> filesToCopy;

                        if ((jobDef.CopyFilesFilter[i] != null) && (taskOutputAsset.Id != ConsolidateOutPut.Id))
                        {
                            filesToCopy = GetFiles(taskOutputAsset, jobDef.CopyFilesFilter[i]);
                            CopyAssetFiles(ConsolidateOutPut, filesToCopy);
                            taskOutputAsset.Delete();
                        }
                    }
                }
            }
            Directory.Delete(myRequest.ProcessInstanceId);
        }
Пример #4
0
        public override void HandleCompensation(Common.workflow.ChainRequest request)
        {
            myRequest = (ButlerProcessRequest)request;
            string txtTrace;

            if (currentJob != null)
            {
                foreach (IAsset item in currentJob.OutputMediaAssets)
                {
                    txtTrace = string.Format("[{0}] process Type {1} instance {2} deleted Asset id={3}", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId, item.Id);
                    item.Delete();
                    Trace.TraceWarning(txtTrace);
                }
            }
            if (myAssetOriginal != null)
            {
                txtTrace = string.Format("[{0}] process Type {1} instance {2} deleted Asset id={3}", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId, myAssetOriginal.Id);

                myAssetOriginal.Delete();
                Trace.TraceWarning(txtTrace);
            }

            if ((myWorkflow != null) && (string.IsNullOrEmpty(myConfig.AssetWorkflowID)))
            {
                txtTrace = string.Format("[{0}] process Type {1} instance {2} deleted Asset id={3}", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId, myWorkflow.Id);
                myWorkflow.Delete();
                Trace.TraceWarning(txtTrace);
            }
        }
Пример #5
0
        public static void Run(
            [QueueTrigger(QueueNames.MediaToEncode)] MediaMetadata mediaMetadataFromQueue,
            [Queue(QueueNames.MediaToPublish)] out MediaMetadata mediaMetadataToPublish,
            TraceWriter log)
        {
            log.Info($"{nameof(EncodeMediaAsset)} triggered");

            IAsset asset = null;

            try
            {
                asset = AzureMediaServices.GetAsset(mediaMetadataFromQueue);
                var newAsset = AzureMediaServices.EncodeToAdaptiveBitrateMP4Set(asset, mediaMetadataFromQueue.Title);

                mediaMetadataToPublish = new MediaMetadata
                {
                    FileName             = newAsset.Name,
                    MediaServicesAssetId = newAsset.Id,
                    MediaAssetUri        = newAsset.Uri,
                    Title      = mediaMetadataFromQueue.Title,
                    UploadedAt = mediaMetadataFromQueue.UploadedAt,
                };
            }
            catch (Exception e)
            {
                log.Info($"Error {e.Message}");
                throw e;
            }
            finally
            {
                asset?.Delete(false);
                log.Info($"{nameof(EncodeMediaAsset)} completed");
            }
        }
        public async Task <IAsset> UploadAssetAsync(string localFilePath, UpdateProgressAction updateProgress, Guid assetProgressMoniker, CancellationToken cancellationToken)
        {
            Logger.Debug("UploadAssetAsync() invoked with localFilePath value '{0}'.", localFilePath);

            IAsset        asset = null;
            IAccessPolicy uploadAccessPolicy = null;

            try {
                var assetName = Guid.NewGuid().ToString();
                asset = await Context.Assets.CreateAsync(assetName, AssetCreationOptions.None, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

                var assetFile = await asset.AssetFiles.CreateAsync(Path.GetFileName(localFilePath), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

                assetFile.IsPrimary = true;

                uploadAccessPolicy = await Context.AccessPolicies.CreateAsync("Upload Policy", TimeSpan.FromDays(1), AccessPermissions.Write | AccessPermissions.List).ConfigureAwait(continueOnCapturedContext: false);

                var uploadLocator = await Context.Locators.CreateLocatorAsync(LocatorType.Sas, asset, uploadAccessPolicy).ConfigureAwait(continueOnCapturedContext: false);

                var uploadClient = new BlobTransferClient();

                uploadClient.TransferProgressChanged += (sender, e) => updateProgress(new WamsUploadProgressInfo(assetProgressMoniker, e));
                await assetFile.UploadAsync(localFilePath, uploadClient, uploadLocator, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

                await uploadLocator.DeleteAsync().ConfigureAwait(continueOnCapturedContext: false);

                await uploadAccessPolicy.DeleteAsync().ConfigureAwait(continueOnCapturedContext: false);

                Logger.Information("New asset with ID '{0}' was uploaded from temp file with name '{1}'.", asset.Id, localFilePath);

                return(asset);
            }
            catch (Exception ex) {
                if (ex is OperationCanceledException)
                {
                    Logger.Information("Upload of asset with ID '{0}' from temp file with name '{1}' was canceled.", asset.Id, localFilePath);
                }
                else
                {
                    Logger.Error(ex, "Error while uploading asset from temp file with name '{0}'. Cleaning up asset and any locators and access policy created for upload.", localFilePath);
                }

                try {
                    if (asset != null)
                    {
                        asset.Delete(); // Deletes any locators also.
                    }
                    if (uploadAccessPolicy != null)
                    {
                        uploadAccessPolicy.Delete();
                    }
                }
                catch (Exception iex) {
                    Logger.Warning(iex, "Error while cleaning up asset and any locators and access policy created for upload.");
                }

                throw;
            }
        }
        private void DeleteMediaService(Video video)
        {
            string assetId = video.EncodedAssetId;
            IAsset asset   = GetAssetFromDatabase(assetId);

            // Now delete the asset
            asset.Delete();
        }
Пример #8
0
        public static void DeleteAsset(IAsset asset)
        {
            // delete the asset
            asset.Delete();

            // Verify asset deletion
            if (GetAsset(asset.Id) == null)
                Console.WriteLine("Deleted the Asset");
        }
        public override void HandleExecute(ChainRequest request)
        {
            myRequest             = (ButlerProcessRequest)request;
            _MediaServicesContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey);

            IAsset theAsset = (from m in _MediaServicesContext.Assets select m).Where(m => m.Id == myRequest.AssetId).FirstOrDefault();

            theAsset.Delete();
        }
 public override void HandleCompensation(Common.workflow.ChainRequest request)
 {
     if (targetAsset != null)
     {
         string txtTrace = string.Format("[{0}] process Type {1} instance {2} Compensation deleted Asset id={3}", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId, targetAsset.Id);
         targetAsset.Delete();
         Trace.TraceWarning(txtTrace);
     }
 }
Пример #11
0
        private static void CleanupAsset(IAsset asset)
        {
            foreach (IAssetDeliveryPolicy policy in asset.DeliveryPolicies.ToList())
            {
                asset.DeliveryPolicies.Remove(policy);
                policy.Delete();
            }

            asset.Delete();
        }
Пример #12
0
        public bool execute(ICustomRequest request)
        {
            var    _MediaServicesContext = new CloudMediaContext(request.MediaAccountName, request.MediaAccountKey);
            IAsset asset = (from m in _MediaServicesContext.Assets select m).Where(m => m.Id == request.AssetId).FirstOrDefault();

            CopyCaptions(asset, asset.ParentAssets.FirstOrDefault());
            request.AssetId = asset.ParentAssets.FirstOrDefault().Id;
            asset.Delete();
            return(true);
        }
Пример #13
0
 private void DeleteAssest(IAsset asset)
 {
     // delete the asset
     asset.Delete();
     // Verify asset deletion
     if (GetAsset(asset.Id) == null)
     {
         Trace.TraceInformation("Deleted the Asset: " + asset.Name);
     }
 }
Пример #14
0
        /// <summary>
        /// Delete current asset on error
        /// </summary>
        private void deleteOtiginalAsset()
        {
            //Delete Original Asset becouse it is wrong
            if (myAssetOriginal != null)
            {
                string txtTrace = string.Format("[{0}] process Type {1} instance {2} deleted Asset id={3}", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId, myAssetOriginal.Id);

                myAssetOriginal.Delete();
                Trace.TraceWarning(txtTrace);
            }
        }
Пример #15
0
        private void DeleteMediaService(Video video)
        {
            // Delete from Media Services
            CloudMediaContext context = new CloudMediaContext(mediaAccountName, mediaAccountKey);

            string assetId = video.AssetId;
            IAsset asset   = GetAsset(context, assetId);

            // Now delete the asset
            asset.Delete();
        }
Пример #16
0
        static void DeleteAsset(IAsset asset)
        {
            Console.WriteLine("Deleting the Asset {0}", asset.Id);
            // delete the asset
            asset.Delete();

            // Verify asset deletion
            if (GetAsset(asset.Id) == null)
            {
                Console.WriteLine("Deleted the Asset");
            }
        }
        public void ShouldDeleteAssetsForFinishedJob()
        {
            IAsset asset;
            IJob   job;
            IAsset outasset = RunJobAndGetOutPutAsset("AssetTests_ShouldDeleteAssetsForFinishedJob", out asset, out job);

            foreach (ILocator locator in asset.Locators)
            {
                locator.Delete();
            }
            asset.Delete();
            outasset.Delete();
        }
Пример #18
0
 /// <summary>
 /// Step compensation on errror, delete asset
 /// </summary>
 /// <param name="request"></param>
 public override void HandleCompensation(ChainRequest request)
 {
     if (currentAsset != null)
     {
         string id = currentAsset.Id;
         currentAsset.Delete();
         Trace.TraceWarning("{0} HandleCompensation in process {2} processId {1}, with asset deletion assetid {3}", this.GetType().FullName, request.ProcessInstanceId, request.ProcessTypeId, id);
     }
     else
     {
         Trace.TraceWarning("{0} HandleCompensation in process {2} processId {1}, without asset deletion", this.GetType().FullName, request.ProcessInstanceId, request.ProcessTypeId);
     }
 }
 public HttpResponseMessage DeleteSoftware(int id)
 {
     try
     {
         _softwareService.Delete(id);
         HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
         return(response);
     }
     catch (Exception)
     {
         HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
         return(response);
     }
 }
 public HttpResponseMessage DeleteBook(int id)
 {
     try
     {
         _bookService.Delete(id);
         HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
         return(response);
     }
     catch (Exception)
     {
         HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotModified);
         return(response);
     }
 }
Пример #21
0
        public void AssetCRUDWithEmptyFile()
        {
            IAsset     asset = _mediaContext.Assets.Create("Test", AssetCreationOptions.None);
            IAssetFile file  = asset.AssetFiles.Create("test");

            Assert.IsNotNull(asset);
            Assert.IsNotNull(asset.AssetFiles);
            Assert.AreEqual(1, asset.AssetFiles.Count());
            file.ContentFileSize = 100;
            file.Update();
            file.Delete();
            Assert.IsNotNull(asset.AssetFiles);
            Assert.AreEqual(0, asset.AssetFiles.Count());
            asset.Delete();
            Assert.IsNull(_mediaContext.Assets.Where(c => c.Id == asset.Id).FirstOrDefault());
        }
        public void ShouldDeleteParentAssetAndGetParentCount()
        {
            IAsset asset;
            IJob   job;
            IAsset outasset = RunJobAndGetOutPutAsset("AssetTests_ShouldDeleteParentAssetAndGetParentCount", out asset, out job);

            Assert.AreEqual(1, outasset.ParentAssets.Count, "Unexpected number of parents assets");
            foreach (ILocator locator in asset.Locators)
            {
                locator.Delete();
            }
            asset.Delete();
            outasset = _mediaContext.Assets.Where(c => c.Id == outasset.Id).FirstOrDefault();
            Assert.AreEqual(1, outasset.ParentAssets.Count, "Unexpected number of parents assets");
            outasset.Delete();
        }
 private static void DeleteAsset(IAsset asset)
 {
     foreach (var locator in asset.Locators.ToArray())
     {
         locator.Delete();
     }
     foreach (var policy in asset.DeliveryPolicies.ToArray())
     {
         asset.DeliveryPolicies.Remove(policy);
         policy.Delete();
     }
     foreach (var key in asset.ContentKeys.ToArray())
     {
         CleanupKey(key);
         asset.ContentKeys.Remove(key);
     }
     asset.Delete();
 }
        public void ShouldDeleteEmptyAsset()
        {
            IAsset asset = _mediaContext.Assets.Create("ShouldDeleteEmptyAsset", AssetCreationOptions.None);


            Assert.AreEqual(AssetState.Initialized, asset.State);
            foreach (ILocator locator in asset.Locators)
            {
                locator.Delete();
            }

            asset.Delete();

            Assert.IsNull(_mediaContext.Assets.Where(a => a.Id == asset.Id).SingleOrDefault());

            CloudMediaContext newContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();

            Assert.IsNull(newContext.Assets.Where(a => a.Id == asset.Id).SingleOrDefault());
        }
        public void ShouldNotThrowTryingToDeleteAssetWithActiveLocators()
        {
            IAsset        asset         = CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None);
            IAccessPolicy accessPolicy  = _mediaContext.AccessPolicies.Create("ReadOnly", TimeSpan.FromMinutes(60), AccessPermissions.Read);
            ILocator      sasLocator    = _mediaContext.Locators.CreateSasLocator(asset, accessPolicy);
            ILocator      originLocator = _mediaContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, accessPolicy);

            Assert.IsNotNull(_mediaContext.Locators.Where(l => l.Id == sasLocator.Id).SingleOrDefault());
            Assert.IsNotNull(_mediaContext.Locators.Where(l => l.Id == originLocator.Id).SingleOrDefault());

            asset = _mediaContext.Assets.Where(a => a.Id == asset.Id).Single();
            Assert.AreEqual(3, asset.Locators.Count);
            Assert.IsTrue(asset.Locators.Any(l => l.Id == sasLocator.Id));
            Assert.IsTrue(asset.Locators.Any(l => l.Id == originLocator.Id));

            asset.Delete();
            Assert.IsNull(_mediaContext.Locators.Where(l => l.Id == sasLocator.Id).SingleOrDefault());
            Assert.IsNull(_mediaContext.Locators.Where(l => l.Id == originLocator.Id).SingleOrDefault());
        }
Пример #26
0
        public static void Run(
            [QueueTrigger(QueueNames.MediaToPublish)] MediaMetadata mediaMetadataFromQueue,
            [Queue(QueueNames.MediaToAddToCosmosDb)] out MediaMetadata mediaMetadataToAddToCosmosDb,
            TraceWriter log)
        {
            log.Info($"{nameof(PublishMediaAsset)} triggered");

            IAsset asset = null;

            try
            {
                mediaMetadataToAddToCosmosDb = mediaMetadataFromQueue;

                asset = AzureMediaServices.GetAsset(mediaMetadataFromQueue);

                log.Info($"Publishing Media");
                var locator = AzureMediaServices.PublishMedia(asset, TimeSpan.FromDays(999));

                log.Info($"Generating Streaming Endpoint");
                AzureMediaServices.CreateStreamingEndpoint();

                log.Info($"Generating Urls");
                var(manifestUri, hlsUri, mpegDashUri) = AzureMediaServices.BuildStreamingURLs(asset, locator);

                mediaMetadataToAddToCosmosDb.BlobStorageMediaUrl = $"{mediaMetadataToAddToCosmosDb.MediaAssetUri}/{AzureMediaServices.GetMP4FileName(asset)}";
                mediaMetadataToAddToCosmosDb.ManifestUrl         = manifestUri;
                mediaMetadataToAddToCosmosDb.HLSUrl      = hlsUri;
                mediaMetadataToAddToCosmosDb.MPEGDashUrl = mpegDashUri;
            }
            catch (Exception e)
            {
                log.Info($"Error: {e.Message}");
                asset?.Delete();

                throw e;
            }
            finally
            {
                log.Info($"{nameof(PublishMediaAsset)} completed");
            }
        }
        public void ShouldDeleteAssetWithStorageEncryptionContentKey()
        {
            // Use two contexts to cover the case where the content key needs to be internally attached to
            // the data context.  This simulates deleting a content key that we haven't just created.
            var dataContext2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();

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

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

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

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

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

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

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

            foreach (IContentKey keyFromRest in dataContext2.ContentKeys)
            {
                Assert.IsFalse(keyFromRest.Id == keyId, "Asset was deleted we should not be able to query its associated storage encryption key by identifier.");
            }
        }
Пример #28
0
        private static void DeleteAsset(string authToken, string accountId, MediaClient mediaClient, IAsset asset)
        {
            string documentId = DocumentClient.GetDocumentId(asset, out bool videoIndexer);

            if (!string.IsNullOrEmpty(documentId))
            {
                DocumentClient documentClient = new DocumentClient();
                string         collectionId   = Constant.Database.Collection.ContentInsight;
                documentClient.DeleteDocument(collectionId, documentId);
                if (videoIndexer)
                {
                    IndexerClient indexerClient = new IndexerClient(authToken);
                    if (indexerClient.IndexerEnabled)
                    {
                        indexerClient.DeleteVideo(documentId, true);
                    }

                    TableClient  tableClient    = new TableClient();
                    string       tableName      = Constant.Storage.Table.InsightPublish;
                    MediaPublish insightPublish = tableClient.GetEntity <MediaPublish>(tableName, accountId, documentId);
                    if (insightPublish != null)
                    {
                        tableClient.DeleteEntity(tableName, insightPublish);
                    }
                }
            }
            foreach (ILocator locator in asset.Locators)
            {
                locator.Delete();
            }
            for (int i = asset.DeliveryPolicies.Count - 1; i >= 0; i--)
            {
                asset.DeliveryPolicies.RemoveAt(i);
            }
            asset.Delete();
        }
Пример #29
0
 private void DeleteAssest(IAsset asset)
 {
     // delete the asset
     asset.Delete();
     // Verify asset deletion
     if (GetAsset(asset.Id) == null)
     {
         Trace.TraceInformation("Deleted the Asset: " + asset.Name);
     }
 }
Пример #30
0
        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);
        }
        static IAsset CreateAssetAndProtectedStreamingLocatorInV2(CloudMediaContext v2Client, ConfigWrapper config, string assetNameOrDescription)
        {
            // Create the input Asset
            IAsset     originalAsset = v2Client.Assets.Create("input asset", AssetCreationOptions.None);
            string     filename      = Path.GetFileName(config.FilePathToUpload);
            IAssetFile assetFile     = originalAsset.AssetFiles.Create(filename);

            assetFile.Upload(config.FilePathToUpload);

            // Submit a job to encode the single input file into an adaptive streaming set
            IJob            job       = v2Client.Jobs.Create("Media Encoder Standard Job");
            IMediaProcessor processor = GetMediaEncoderStandardProcessor(v2Client);

            ITask task = job.Tasks.AddNew("Adaptive Streaming encode", processor, "Adaptive Streaming", TaskOptions.None);

            task.InputAssets.Add(originalAsset);
            task.OutputAssets.AddNew(assetNameOrDescription, AssetCreationOptions.None);

            job.Submit();
            job.GetExecutionProgressTask(CancellationToken.None).Wait();

            // Get the output asset to publish
            job.Refresh();
            IAsset assetToPublish = v2Client.Assets.Where(a => a.Id == job.Tasks[0].OutputAssets[0].Id).First();

            // Create the content key
            Guid keyId = Guid.NewGuid();

            byte[] contentKey = GetRandomBuffer(16);

            IContentKey key = v2Client.ContentKeys.Create(keyId, contentKey, "ContentKey", ContentKeyType.EnvelopeEncryption);

            // Create ContentKeyAuthorizationPolicy with Open restriction and create authorization policy
            IContentKeyAuthorizationPolicy policy = v2Client.ContentKeyAuthorizationPolicies.CreateAsync("Open Authorization Policy").Result;

            ContentKeyAuthorizationPolicyRestriction restriction =
                new ContentKeyAuthorizationPolicyRestriction
            {
                Name = "Open Authorization Policy",
                KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                Requirements       = null
            };

            List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>();

            restrictions.Add(restriction);

            var policyOption = v2Client.ContentKeyAuthorizationPolicyOptions.Create("policy", ContentKeyDeliveryType.BaselineHttp, restrictions, "");

            policy.Options.Add(policyOption);

            // Add ContentKeyAuthorizationPolicy to ContentKey
            key.AuthorizationPolicyId = policy.Id;
            key.Update();

            assetToPublish.ContentKeys.Add(key);

            Uri        keyAcquisitionUri = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);
            UriBuilder uriBuilder        = new UriBuilder(keyAcquisitionUri);

            uriBuilder.Query  = String.Empty;
            keyAcquisitionUri = uriBuilder.Uri;

            // The following policy configuration specifies:
            //   key url that will have KID=<Guid> appended to the envelope and
            //   the Initialization Vector (IV) to use for the envelope encryption.
            var assetDeliveryPolicyConfiguration = new Dictionary <AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.EnvelopeBaseKeyAcquisitionUrl, keyAcquisitionUri.ToString() },
            };

            var assetDeliveryPolicy = v2Client.AssetDeliveryPolicies.Create("AssetDeliveryPolicy",
                                                                            AssetDeliveryPolicyType.DynamicEnvelopeEncryption,
                                                                            AssetDeliveryProtocol.SmoothStreaming | AssetDeliveryProtocol.HLS | AssetDeliveryProtocol.Dash,
                                                                            assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            assetToPublish.DeliveryPolicies.Add(assetDeliveryPolicy);

            // Create a 30-day readonly access policy.
            // You cannot create a streaming locator using an AccessPolicy that includes write or delete permissions.
            IAccessPolicy accessPolicy = v2Client.AccessPolicies.Create("Streaming Access Policy", TimeSpan.FromDays(365 * 100), AccessPermissions.Read);

            // Create a locator to the streaming content on an origin.
            ILocator originLocator = v2Client.Locators.CreateLocator(LocatorType.OnDemandOrigin, assetToPublish, accessPolicy, DateTime.UtcNow.AddMinutes(-5));

            // remove the original input asset as we don't need it for demonstration purposes
            originalAsset.Delete();

            return(assetToPublish);
        }
        private static void CleanupAsset(IAsset asset)
        {
            foreach (IAssetDeliveryPolicy policy in asset.DeliveryPolicies.ToList())
            {
                asset.DeliveryPolicies.Remove(policy);
                policy.Delete();
            }

            asset.Delete();
        }
Пример #33
0
        public void DeleteAsset(string AssetId)
        {
            IAsset X = _mediaContext.Assets.Where(a => a.Id == AssetId).FirstOrDefault();

            X.Delete();
        }
 static void DeleteAsset(IAsset asset)
 {
     // delete the asset
     asset.Delete();
 }
        //////////////////////////////////////////////////
        // Delete tasks
        //////////////////////////////////////////////////

        public static void DeleteAsset(IAsset asset)
        {
            // Delete Asset's locators before
            // deleting the asset.
            foreach (var l in asset.Locators)
            {
                Console.WriteLine("Deleting the Locator {0}", l.Id);
                l.Delete();
            }

            Console.WriteLine("Deleting the Asset {0}", asset.Id);
            // delete the asset
            asset.Delete();
        }
Пример #36
0
        private void DeleteAsset(IAsset asset, CloudMediaContext context = null)
        {
            if (asset == null)
            {
                return;
            }

            if (context == null) {
                context = CloudServiceContext;
            }
            // delete the asset
            asset.Delete();
            // Verify asset deletion
            if (GetAsset(asset.Id, context) == null)
                Debug.WriteLine("asset deleted");
        }