static int Main(string[] args) { if (args.Length != 1) { Console.Error.WriteLine("DecryptAsset <asset-id>"); return -1; } string accountName = Environment.GetEnvironmentVariable("ACCOUNT_NAME"); string accountKey = Environment.GetEnvironmentVariable("ACCOUNT_KEY"); CloudMediaContext cloudMediaContext = new CloudMediaContext(accountName, accountKey); string assetId = args[0]; IAsset asset = cloudMediaContext.FindAssetById(assetId); IJob job = cloudMediaContext.Jobs.Create(string.Format("Decrypt {0}", asset.Name)); IMediaProcessor decryptProcessor = cloudMediaContext.GetMediaProcessor("Storage Decryption"); ITask decryptTask = job.Tasks.AddNew(string.Format("Decrypt {0}", asset.Name), decryptProcessor,string.Empty, Microsoft.WindowsAzure.MediaServices.Client.TaskOptions.None); decryptTask.InputAssets.Add(asset); decryptTask.OutputAssets.AddNew(string.Format("{0} decrypted", asset.Name), AssetCreationOptions.None); job.Submit(); Console.WriteLine(job.Id); return 0; }
public AzureVideoRepository(IConfigurationManager configurationManager, IMediaFacade mediaFacade, IAssetFilter assetFilter) { this.configurationManager = configurationManager; this.mediaFacade = mediaFacade; this.assetFilter = assetFilter; this.mediaContext = new CloudMediaContext(configurationManager.AccountName, configurationManager.AccountKey); }
public BulkUpload(CloudMediaContext context) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; dataGridAssetFiles.DataSource = assetFiles; _context = context; }
/// <summary> /// Gets the storage account mapping from config /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public static Dictionary<CloudStorageAccount, IStorageAccount> GetStorageAccountMappingFromConfig(CloudMediaContext context) { if (context == null) { throw new ArgumentNullException("context"); } var storageAccounts = new Dictionary<CloudStorageAccount, IStorageAccount>(); var registeredAccounts = context.StorageAccounts.ToList(); foreach (var registeredAccount in registeredAccounts) { var connectionString =ConfigurationManager.AppSettings["Storage_" + registeredAccount.Name]; //If user don't provide all connection strings to storage accounts we are skipping this storage account. //We also skipping if connection string is not correct if (!String.IsNullOrEmpty(connectionString)) { CloudStorageAccount storageAccount = null; CloudStorageAccount.TryParse(connectionString, out storageAccount); if (storageAccount != null) { storageAccounts.Add(storageAccount, registeredAccount); } { Debug.WriteLine("Unable to parse connection string for storage account {0}", registeredAccount.Name); } } else { Debug.WriteLine("Storage account {0} has missing setting with connection string in App.config", registeredAccount.Name); } } return storageAccounts; }
static int Main(string[] args) { if (args.Length != 1) { Console.Error.WriteLine("MP4ToSmoothStream <asset-id>"); return -1; } string accountName = Environment.GetEnvironmentVariable("ACCOUNT_NAME"); string accountKey = Environment.GetEnvironmentVariable("ACCOUNT_KEY"); CloudMediaContext cloudMediaContext = new CloudMediaContext(accountName, accountKey); string assetId = args[0]; IAsset asset = cloudMediaContext.FindAssetById(assetId); IJob job = cloudMediaContext.Jobs.Create(string.Format("Convert {0} to Smooth Stream", asset.Name)); IMediaProcessor processor = cloudMediaContext.GetMediaProcessor("Windows Azure Media Encoder"); ITask task = job.Tasks.AddNew("MP4 to Smooth Stream Conversion", processor, "H264 Smooth Streaming 720p", // Task Preset. Amend as required. Microsoft.WindowsAzure.MediaServices.Client.TaskOptions.ProtectedConfiguration); task.InputAssets.Add(asset); task.OutputAssets.AddNew(string.Format("Smooth Stream for {0}", asset.Name), AssetCreationOptions.None); job.Submit(); Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", job.Id, job.Name, job.State, job.RunningDuration, job.LastModified); return 0; }
public Subclipping(CloudMediaContext context, MediaServiceContextForDynManifest contextdynmanifest, List<IAsset> assetlist, Mainform mainform) { InitializeComponent(); buttonJobOptions.Initialize(context); this.Icon = Bitmaps.Azure_Explorer_ico; _context = context; _contextdynmanifest = contextdynmanifest; _parentassetmanifestdata = new ManifestTimingData(); _selectedAssets = assetlist; _mainform = mainform; if (_selectedAssets.Count == 1 && _selectedAssets.FirstOrDefault() != null) // one asset only { var myAsset = assetlist.FirstOrDefault(); textBoxAssetName.Text = myAsset.Name; // let's try to read asset timing _parentassetmanifestdata = AssetInfo.GetManifestTimingData(myAsset); if (!_parentassetmanifestdata.Error) // we were able to read asset timings and not live { _timescale = timeControlStart.TimeScale = timeControlEnd.TimeScale = _parentassetmanifestdata.TimeScale; timeControlStart.ScaledFirstTimestampOffset = timeControlEnd.ScaledFirstTimestampOffset = _parentassetmanifestdata.TimestampOffset; textBoxOffset.Text = _parentassetmanifestdata.TimestampOffset.ToString(); labelOffset.Visible = textBoxOffset.Visible = true; textBoxFilterTimeScale.Text = _timescale.ToString(); textBoxFilterTimeScale.Visible = labelAssetTimescale.Visible = true; timeControlStart.Max = timeControlEnd.Max = new TimeSpan(AssetInfo.ReturnTimestampInTicks(_parentassetmanifestdata.AssetDuration, _parentassetmanifestdata.TimeScale)); labelassetduration.Visible = textBoxAssetDuration.Visible = true; textBoxAssetDuration.Text = timeControlStart.Max.ToString(@"d\.hh\:mm\:ss") + (_parentassetmanifestdata.IsLive ? " (LIVE)" : ""); // let set duration and active track bat timeControlStart.ScaledTotalDuration = timeControlEnd.ScaledTotalDuration = _parentassetmanifestdata.AssetDuration; timeControlStart.DisplayTrackBar = true; timeControlEnd.DisplayTrackBar = true; timeControlEnd.SetTimeStamp(timeControlEnd.Max); } else // one asset but not able to read asset timings { timeControlStart.DisplayTrackBar = timeControlEnd.DisplayTrackBar = false; timeControlStart.TimeScale = timeControlEnd.TimeScale = _timescale; timeControlStart.Max = timeControlEnd.Max = TimeSpan.MaxValue; //timeControlEnd.SetTimeStamp(timeControlEnd.Max); } } else // several assets { groupBoxTrimming.Enabled = panelAssetInfo.Visible = false; // no trimming and no asset info radioButtonAssetFilter.Enabled = false; // no asset filter option timeControlStart.DisplayTrackBar = timeControlEnd.DisplayTrackBar = false; timeControlStart.TimeScale = timeControlEnd.TimeScale = _timescale; timeControlStart.Max = timeControlEnd.Max = TimeSpan.MaxValue; //timeControlEnd.SetTimeStamp(timeControlEnd.Max); } }
static int Main(string[] args) { if (args.Length != 1) { Console.Error.WriteLine("DownloadAsset <asset-id> - downloads all asset files."); return -1; } string accountName = Environment.GetEnvironmentVariable("ACCOUNT_NAME"); string accountKey = Environment.GetEnvironmentVariable("ACCOUNT_KEY"); CloudMediaContext cloudMediaContext = new CloudMediaContext(accountName, accountKey); string assetId = args[0]; IAsset asset = cloudMediaContext.FindAssetById(assetId); string folder = asset.Id.ToString().Replace(":", ""); Directory.CreateDirectory(folder); foreach (var file in asset.AssetFiles) { file.Download(string.Format(@"{0}\{1}" ,folder ,file.Name)); } return 0; }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); bool tokenRestriction = false; string tokenTemplateString = null; IContentKey key = CreateCommonTypeContentKey(); // Print out the key ID and Key in base64 string format Console.WriteLine("Created key {0} with key value {1} ", key.Id, System.Convert.ToBase64String(key.GetClearKeyValue())); Console.WriteLine("PlayReady License Key delivery URL: {0}", key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense)); if (tokenRestriction) tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); else AddOpenAuthorizationPolicy(key); Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId); Console.WriteLine(); Console.ReadLine(); }
public Thumbnails(CloudMediaContext context) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; _context = context; buttonJobOptions.Initialize(_context); }
public ChannelRunOnPremisesEncoder(CloudMediaContext context, IList<IChannel> channels) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; _context = context; _channels = channels; }
public AssetInformation(Mainform mainform, CloudMediaContext context) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; myMainForm = mainform; myContext = context; }
public EncodingAMEPreset(CloudMediaContext context) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; _context = context; buttonJobOptions.Initialize(_context); }
public MultipleProcessor(CloudMediaContext context, IJob myJob = null) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; _context = context; _myJob = myJob; buttonTaskOptions1.Initialize(_context, true); buttonTaskOptions2.Initialize(_context, true); buttonTaskOptions3.Initialize(_context, true); buttonTaskOptions4.Initialize(_context, true); buttonTaskOptions5.Initialize(_context, true); buttonTaskOptions1.Click += ButtonTaskOptions_Click; buttonTaskOptions2.Click += ButtonTaskOptions_Click; buttonTaskOptions3.Click += ButtonTaskOptions_Click; buttonTaskOptions4.Click += ButtonTaskOptions_Click; buttonTaskOptions5.Click += ButtonTaskOptions_Click; if (_myJob != null) // we are in resubmit mode { textBoxConfiguration1.Text = _myJob.Tasks.FirstOrDefault().GetClearConfiguration(); radioButtonSingleJobForAllInputAssets.Checked = true; panelJobMode.Enabled = false; numericUpDownTasks.Enabled = false; SelectedAssets = myJob.InputMediaAssets.ToList(); } labelWarningJSON1.Text = labelWarningJSON2.Text = labelWarningJSON3.Text = labelWarningJSON4.Text = labelWarningJSON5.Text = string.Empty; init = false; }
static int Main(string[] args) { if (args.Length != 1) { Console.Error.WriteLine("MP4ToHLS <asset-id>"); return -1; } string accountName = Environment.GetEnvironmentVariable("ACCOUNT_NAME"); string accountKey = Environment.GetEnvironmentVariable("ACCOUNT_KEY"); CloudMediaContext cloudMediaContext = new CloudMediaContext(accountName, accountKey); string assetId = args[0]; IAsset asset = cloudMediaContext.FindAssetById(assetId); IJob job = cloudMediaContext.Jobs.Create(string.Format("Convert {0} to HLS Asset", asset.Name)); IMediaProcessor processor = cloudMediaContext.GetMediaProcessor("Windows Azure Media Encoder"); ITask task = job.Tasks.AddNew("MP4 to HLS", processor, "H264 Adaptive Bitrate MP4 Set SD 16x9", Microsoft.WindowsAzure.MediaServices.Client.TaskOptions.ProtectedConfiguration); task.InputAssets.Add(asset); task.OutputAssets.AddNew(string.Format("HLS for {0}", asset.Name), AssetCreationOptions.None); job.Submit(); Console.WriteLine(job.Id); Console.WriteLine("Once job is complete, retrieve StreamingURL and append (format=m3u8-aapl)"); return 0; }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); // Use the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); // Encoding and encrypting assets ////////////////////// // Load a single MP4 file. IAsset asset = IngestSingleMP4File(_singleMP4File, AssetCreationOptions.None); // Encode an MP4 file to a set of multibitrate MP4s. // Then, package a set of MP4s to clear Smooth Streaming. IAsset clearSmoothStreamAsset = ConvertMP4ToMultibitrateMP4sToSmoothStreaming(asset); // Encrypt your clear Smooth Streaming to Smooth Streaming with PlayReady. IAsset outputAsset = CreateSmoothStreamEncryptedWithPlayReady(clearSmoothStreamAsset); // You can use the http://smf.cloudapp.net/healthmonitor player // to test the smoothStreamURL URL. string smoothStreamURL = outputAsset.GetSmoothStreamingUri().ToString(); Console.WriteLine("Smooth Streaming URL:"); Console.WriteLine(smoothStreamURL); // You can use the http://dashif.org/reference/players/javascript/ player // to test the dashURL URL. string dashURL = outputAsset.GetMpegDashUri().ToString(); Console.WriteLine("MPEG DASH URL:"); Console.WriteLine(dashURL); }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); bool tokenRestriction = false; string tokenTemplateString = null; IAsset asset = UploadFileAndCreateAsset(_singleMP4File); Console.WriteLine("Uploaded asset: {0}", asset.Id); IAsset encodedAsset = EncodeToAdaptiveBitrateMP4Set(asset); Console.WriteLine("Encoded asset: {0}", encodedAsset.Id); IContentKey key = CreateCommonTypeContentKey(encodedAsset); Console.WriteLine("Created key {0} for the asset {1} ", key.Id, encodedAsset.Id); Console.WriteLine("PlayReady License Key delivery URL: {0}", key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense)); Console.WriteLine(); if (tokenRestriction) tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); else AddOpenAuthorizationPolicy(key); Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId); Console.WriteLine(); CreateAssetDeliveryPolicy(encodedAsset, key); Console.WriteLine("Created asset delivery policy. \n"); Console.WriteLine(); if (tokenRestriction && !String.IsNullOrEmpty(tokenTemplateString)) { // Deserializes a string containing an Xml representation of a TokenRestrictionTemplate // back into a TokenRestrictionTemplate class instance. TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); // Generate a test token based on the the data in the given TokenRestrictionTemplate. // Note, you need to pass the key id Guid because we specified // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(365)); Console.WriteLine("The authorization token is:\nBearer {0}", testToken); Console.WriteLine(); } // You can use the http://smf.cloudapp.net/healthmonitor player // to test the smoothStreamURL URL. // string url = GetStreamingOriginLocator(encodedAsset); Console.WriteLine("Encrypted Smooth Streaming URL: {0}/manifest", url); Console.ReadLine(); }
public ExportAssetToAzureStorage(CloudMediaContext contextUploadArg, string MediaServicesStorageAccountKeyArg, IAsset sourceAsset, string StorageSuffix) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; MediaServicesStorageAccountKey = MediaServicesStorageAccountKeyArg; contextUpload = contextUploadArg; // list asset files /////////////////////// bool bfileinasset = (sourceAsset.AssetFiles.Count() == 0) ? false : true; listViewAssetFiles.Items.Clear(); if (bfileinasset) { listViewAssetFiles.BeginUpdate(); foreach (IAssetFile file in sourceAsset.AssetFiles) { ListViewItem item = new ListViewItem(file.Name, 0); if (file.IsPrimary) item.ForeColor = Color.Blue; item.SubItems.Add(file.LastModified.ToLocalTime().ToString("G")); item.SubItems.Add(AssetInfo.FormatByteSize(file.ContentFileSize)); (listViewAssetFiles.Items.Add(item)).Selected = true; listassetfiles.Add(file); } listViewAssetFiles.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); listViewAssetFiles.EndUpdate(); } myStorageSuffix = StorageSuffix; }
public async Task<Video> CreateVideoAsync(string title, string description, string name, string type, Stream dataStream) { // Create an instance of the CloudMediaContext var mediaContext = new CloudMediaContext( CloudConfigurationManager.GetSetting("MediaServicesAccountName"), CloudConfigurationManager.GetSetting("MediaServicesAccountKey")); // Create the Media Services asset from the uploaded video var asset = mediaContext.CreateAssetFromStream(name, title, type, dataStream); // Get the Media Services asset URL var videoUrl = mediaContext.GetAssetVideoUrl(asset); // Launch the smooth streaming encoding job and store its ID var jobId = mediaContext.ConvertAssetToSmoothStreaming(asset, true); var video = new Video { Title = title, Description = description, SourceVideoUrl = videoUrl, JobId = jobId }; this.context.Videos.Add(video); await this.context.SaveChangesAsync(); return video; }
private void SendMail() { Setup(); var credentials = new NetworkCredential(mySenGridData.UserName, mySenGridData.Pswd); // Create the email object first, then add the properties. SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(mySenGridData.To); myMessage.From = new MailAddress(mySenGridData.FromMail, mySenGridData.FromName); myMessage.Subject = string.Format("Butler Media Process {0} inctance {1}",myRequest.ProcessTypeId,myRequest.ProcessInstanceId); _MediaServiceContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey); IAsset x = _MediaServiceContext.Assets.Where(xx => xx.Id == myRequest.AssetId).FirstOrDefault(); AssetInfo ai = new AssetInfo(x); StringBuilder AssetInfoResume = ai.GetStatsTxt(); AssetInfoResume.AppendLine(""); AssetInfoResume.AppendLine("Media Butler Process LOG " + DateTime.Now.ToString()); foreach (string txt in myRequest.Log) { AssetInfoResume.AppendLine(txt); } AssetInfoResume.AppendLine("-----------------------------"); myMessage.Html = AssetInfoResume.Replace(" ", " ").Replace(Environment.NewLine, "<br />").ToString(); var transportWeb = new Web(credentials); transportWeb.Deliver(myMessage); }
private static async Task<IJob> CreateMediaEncodeJob(CloudMediaContext context, IAsset assetToEncode) { //string encodingPreset = "H264 Broadband 720p"; string encodingPreset = "H264 Smooth Streaming 720p"; IJob job = context.Jobs.Create("Encoding " + assetToEncode.Name + " to " + encodingPreset); string[] y = context.MediaProcessors.Where(mp => mp.Name.Equals("Azure Media Encoder")) .ToArray() .Select(mp => mp.Version) .ToArray(); IMediaProcessor latestWameMediaProcessor = context.MediaProcessors.Where(mp => mp.Name.Equals("Azure Media Encoder")) .ToArray() .OrderByDescending( mp => new Version(int.Parse(mp.Version.Split('.', ',')[0]), int.Parse(mp.Version.Split('.', ',')[1]))) .First(); ITask encodeTask = job.Tasks.AddNew("Encoding", latestWameMediaProcessor, encodingPreset, TaskOptions.None); encodeTask.InputAssets.Add(assetToEncode); encodeTask.OutputAssets.AddNew(assetToEncode.Name + " as " + encodingPreset, AssetCreationOptions.None); job.StateChanged += new EventHandler<JobStateChangedEventArgs>((sender, jsc) => Console.WriteLine( $"{((IJob) sender).Name}\n State: {jsc.CurrentState}\n Time: {DateTime.UtcNow.ToString(@"yyyy_M_d_hhmmss")}\n\n")); return await job.SubmitAsync(); }
public Encoder(CloudMediaContext context, StorageCredentialsAccountAndKey storageCredentials, MediaEncoding mediaEncoding, TextWriter textWriter) { this.context = context; this.storageCredentials = storageCredentials; this.MediaEncoding = mediaEncoding; this.textWriter = textWriter; }
public IEnumerable<Video> GetActiveJobs() { var activeJobs = this.context.Videos.Where(v => !string.IsNullOrEmpty(v.JobId)); if (activeJobs.Any()) { var mediaContext = new CloudMediaContext( CloudConfigurationManager.GetSetting("MediaServicesAccountName"), CloudConfigurationManager.GetSetting("MediaServicesAccountKey")); foreach (var video in activeJobs) { var job = mediaContext.GetJob(video.JobId); if (job != null) { // The video status will be Encoding unless the encoding job is finished or error video.JobStatus = (job.State == JobState.Finished || job.State == JobState.Error) ? JobStatus.Completed : JobStatus.Encoding; yield return video; } } } yield break; }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); IChannel channel = CreateAndStartChannel(); //IChannel channel = _context.Channels.Where(c => c.Name == "playreadylive").Single(); // Set the Live Encoder to point to the channel's input endpoint: string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString(); // Use the previewEndpoint to preview and verify // that the input from the encoder is actually reaching the Channel. string previewEndpoint = channel.Preview.Endpoints.FirstOrDefault().Url.ToString(); // Once you previewed your stream and verified that it is flowing into your Channel, // you can create an event by creating an Asset, Program, and Streaming Locator. IProgram program = CreateAndStartProgram(channel); ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength); // IStreamingEndpoint streamingEndpoint = CreateAndStartStreamingEndpoint(); GetLocatorsInAllStreamingEndpoints(program.Asset); Console.ReadLine(); // Once you are done streaming, clean up your resources. //Cleanup(streamingEndpoint, channel); }
private static async Task<ILocator> CreateSasLocatorAsync(CloudMediaContext context, IAsset asset) { var accessPolicy = await context.AccessPolicies.CreateAsync( asset.Name, TimeSpan.FromDays(2), AccessPermissions.Write | AccessPermissions.List); return await context.Locators.CreateSasLocatorAsync(asset, accessPolicy); }
public override void HandleExecute(Common.workflow.ChainRequest request) { myRequest = (ButlerProcessRequest)request; Setup(); _MediaServiceContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey); IAsset encodedAsset = (from m in _MediaServiceContext.Assets select m).Where(m => m.Id == myRequest.AssetId).FirstOrDefault(); //Create key IContentKey key = CreateEnvelopeTypeContentKey(encodedAsset); //Create Token Template string tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); Trace.TraceInformation("Added authorization policy: {0}", key.AuthorizationPolicyId); //create Delivery Policy CreateAssetDeliveryPolicy(encodedAsset, key); if (!String.IsNullOrEmpty(tokenTemplateString)) { // Deserializes a string containing an Xml representation of a TokenRestrictionTemplate // back into a TokenRestrictionTemplate class instance. TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); // Generate a test token based on the data in the given TokenRestrictionTemplate. // Note, you need to pass the key id Guid because we specified // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey); Trace.TraceInformation("The authorization token is:\n{0}", testToken); myRequest.Log.Add("The authorization token"); myRequest.Log.Add(testToken); myRequest.Log.Add(""); } }
static int Main(string[] args) { if (args.Length != 2) { Console.Error.WriteLine("AddFile <AssetId> <filename>, Adds a file to an existing asset"); return -1; } string accountName = Environment.GetEnvironmentVariable("ACCOUNT_NAME"); string accountKey = Environment.GetEnvironmentVariable("ACCOUNT_KEY"); CloudMediaContext cloudMediaContext = new CloudMediaContext(accountName, accountKey); string assetId = args[0]; IAsset asset = cloudMediaContext.FindAssetById(assetId); string fileName = args[1]; // create the AssetFile with the name as the file being uploaded. // This is required by the service var assetFile = asset.AssetFiles.Create(System.IO.Path.GetFileName(fileName)); assetFile.Upload(fileName); return 0; }
public void ShouldDownloadAssetFilesToFolder() { var originalFolderPath = "Media"; this.asset = this.context.Assets.CreateFromFolder(originalFolderPath, AssetCreationOptions.None); var assetId = this.asset.Id; string downloadFolderPath = CreateEmptyDirectory(); try { this.asset.DownloadToFolder(downloadFolderPath); Assert.AreEqual(3, Directory.GetFiles(downloadFolderPath).Length); AssertDownloadedFile(originalFolderPath, downloadFolderPath, "smallwmv1.wmv"); AssertDownloadedFile(originalFolderPath, downloadFolderPath, "smallwmv2.wmv"); AssertDownloadedFile(originalFolderPath, downloadFolderPath, "dummy.ism"); this.context = TestHelper.CreateContext(); Assert.AreEqual(0, this.context.Locators.Where(l => l.AssetId == assetId).Count()); } finally { DeleteDirectoryIfExists(downloadFolderPath); } }
public AssetHelper(CloudMediaContext context, Encoder encoder, RestServices restServices, TextWriter textWriter) { this.context = context; this.encoder = encoder; this.restServices = restServices; this.textWriter = textWriter; }
public static void DeleteAllAssets(CloudMediaContext cloudMediaContext) { foreach (var asset in cloudMediaContext.Assets) { try { foreach (var key in asset.ContentKeys) { asset.ContentKeys.Remove(key); } asset.Update(); } catch (Exception e) { Console.Error.WriteLine("Cant remove content keys for asset {0}, {1}", asset.Id, e); } } foreach (var asset in cloudMediaContext.Assets) { try { asset.Delete(); } catch (Exception e) { Console.Error.WriteLine("Cant delete asset {0}, {1}", asset.Id, e); } } }
public ImportFromAzureStorage(CloudMediaContext contextUploadArg, string MediaServicesStorageAccountKeyArg, string StorageSuffix = null) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; MediaServicesStorageAccountKey = MediaServicesStorageAccountKeyArg; contextUpload = contextUploadArg; mystoragesuffix = StorageSuffix; }
//string legacyAccountKey = "2n0gfPJzqlOY5MWFW38oVyQQer6vfnrQMmeFY8g2Jps="; //string legacyAccountName = "neamsaccount"; //string azureregion = "northeurope"; //string azureActiveDirectoryTenantDomain = "microsoft.onmicrosoft.com"; //string applicationID = "1e5b04c6-391b-41f8-ace5-7a5e67fe232a"; //string applicationKey = "07oVRNVe+i9HGXfGY/Kvt/tDGKgeHIfyUtjvJUl0904="; //string clegacyAccountNameKey = "WXa5wXm86Gp2dr+QyWZMB3y+kA1mEEC8JN7ZSllOric="; //string clegacyAccountName = "weamsaccount"; //string cazureRegion = "westeurope"; //string cazureActiveDirectoryTenantDomain = "flecoquihotmail.onmicrosoft.com"; //string capplicationID = "c1a69f3e-be7a-414f-ab12-5b51d47a8177"; //string capplicationKey = "gkVUkurVEwEp5LUt1es/9hFHlFd8HyyWmVw8sqhSlVs="; private void LegacyAuthentication_Click(object sender, RoutedEventArgs e) { LogMessage("Legacy Authentication: Account Name: " + legacyAccountName.Text + " Account Name Key: " + legacyAccountNameKey.Text); CloudMediaContext context = new Microsoft.WindowsAzure.MediaServices.Client.CloudMediaContext(legacyAccountName.Text, legacyAccountNameKey.Text); int count = -1; string msg = string.Empty; if (context != null) { try { var assets = context.Assets; if (assets != null) { LogMessage("Legacy Authentication successful"); count = assets.Count(); LogMessage("Getting Media Objects"); foreach (var a in assets) { Console.WriteLine(a.Name); } LogMessage(count.ToString() + " Media Object(s) found..."); SaveSettings(); } } catch (Exception ex) { msg = ex.Message; LogMessage("Getting Media Objects - Exception: " + msg); } if (count >= 0) { MessageBox.Show("LegacyAuthentication successful: " + count.ToString() + " asset(s) found"); } else { MessageBox.Show("LegacyAuthentication failed" + (string.IsNullOrEmpty(msg) ? "" : ": Exception - " + msg)); } } else { MessageBox.Show("LegacyAuthentication failed"); } }
/// <summary> /// Initializes the cloud media context. /// </summary> /// <param name="context">The context.</param> public void InitCloudMediaContext(CloudMediaContext context) { this._cloudMediaContext = context; }
/// <summary> /// Initializes a new instance of the <see cref="TaskCollection"/> class. /// </summary> /// <param name="job">The job.</param> /// <param name="tasks">The tasks.</param> /// <param name="cloudMediaContext">The <seealso cref="CloudMediaContext"/> instance.</param> internal TaskCollection(IJob job, IEnumerable <ITask> tasks, CloudMediaContext cloudMediaContext) { this._tasks = new List <ITask>(tasks); this._job = job; this._cloudMediaContext = cloudMediaContext; }
/// <summary> /// Initializes a new instance of the <see cref="AssetFileCollection"/> class. /// </summary> /// <param name="cloudMediaContext">The cloud media context.</param> internal AssetFileCollection(CloudMediaContext cloudMediaContext) { _cloudMediaContext = cloudMediaContext; this._dataContext = cloudMediaContext.DataContextFactory.CreateDataServiceContext(); this._assetFileQuery = new Lazy <IQueryable <IAssetFile> >(() => this._dataContext.CreateQuery <AssetFileData>(FileSet)); }
/// <summary> /// Initializes a new instance of the <see cref="ContentKeyCollection"/> class. /// </summary> /// <param name="cloudMediaContext">The <seealso cref="CloudMediaContext"/> instance.</param> internal ContentKeyCollection(CloudMediaContext cloudMediaContext) { this._cloudMediaContext = cloudMediaContext; this.ContentKeyQueryable = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext().CreateQuery <ContentKeyData>(ContentKeySet); }
/// <summary> /// Initializes a new instance of the <see cref="AssetFileCollection"/> class. /// </summary> /// <param name="cloudMediaContext">The cloud media context.</param> /// <param name="parentAsset">The parent <see cref="IAsset"/>.</param> internal AssetFileCollection(CloudMediaContext cloudMediaContext, IAsset parentAsset) : this(cloudMediaContext) { _parentAsset = parentAsset; }
/// <summary> /// Initializes a new instance of the <see cref="AzureMediaServicesDataServiceContextFactory"/> class. /// </summary> /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param> /// <param name="dataServiceAdapter">The data service adapter.</param> /// <param name="serviceVersionAdapter">The service version adapter.</param> /// <param name="cloudMediaContext">The <seealso cref="CloudMediaContext"/> instance.</param> public AzureMediaServicesDataServiceContextFactory(Uri azureMediaServicesEndpoint, OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter serviceVersionAdapter, CloudMediaContext cloudMediaContext) { this._dataServiceAdapter = dataServiceAdapter; this._serviceVersionAdapter = serviceVersionAdapter; this._cloudMediaContext = cloudMediaContext; this._azureMediaServicesEndpoint = GetAccountApiEndpoint(this._dataServiceAdapter, this._serviceVersionAdapter, azureMediaServicesEndpoint); }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] // todo: remove internal OperationBaseCollection(CloudMediaContext cloudMediaContext) { this._cloudMediaContext = cloudMediaContext; }
/// <summary> /// Returns a <see cref="System.Threading.Tasks.Task"/> instance to download all the asset files in the <paramref name="asset"/> to the <paramref name="folderPath"/>. /// </summary> /// <param name="context">The <see cref="CloudMediaContext"/> instance.</param> /// <param name="asset">The <see cref="IAsset"/> instance where to download the asset files.</param> /// <param name="folderPath">The path to the folder where to download the asset files in the <paramref name="asset"/>.</param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> instance to download all the asset files in the <paramref name="asset"/>.</returns> public static Task DownloadAssetFilesToFolderAsync(this CloudMediaContext context, IAsset asset, string folderPath, CancellationToken cancellationToken) { return(context.DownloadAssetFilesToFolderAsync(asset, folderPath, null, cancellationToken)); }
/// <summary> /// Downloads all the asset files in the <paramref name="asset"/> to the <paramref name="folderPath"/>. /// </summary> /// <param name="context">The <see cref="CloudMediaContext"/> instance.</param> /// <param name="asset">The <see cref="IAsset"/> instance where to download the asset files.</param> /// <param name="folderPath">The path to the folder where to download the asset files in the <paramref name="asset"/>.</param> public static void DownloadAssetFilesToFolder(this CloudMediaContext context, IAsset asset, string folderPath) { context.DownloadAssetFilesToFolder(asset, folderPath, null); }
/// <summary> /// Returns a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>. /// </summary> /// <param name="context">The <see cref="CloudMediaContext"/> instance.</param> /// <param name="folderPath">The path to the folder with the files to upload to the new <see cref="IAsset"/>.</param> /// <param name="options">The <see cref="AssetCreationOptions"/>.</param> /// <param name="uploadProgressChangedCallback">A callback to report upload progress of the files.</param> /// <returns>A new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>.</returns> public static IAsset CreateAssetFromFolder(this CloudMediaContext context, string folderPath, AssetCreationOptions options, Action <IAssetFile, UploadProgressChangedEventArgs> uploadProgressChangedCallback) { return(context.CreateAssetFromFolder(folderPath, null, options, uploadProgressChangedCallback)); }
/// <summary> /// Returns a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>. /// </summary> /// <param name="context">The <see cref="CloudMediaContext"/> instance.</param> /// <param name="folderPath">The path to the folder with the files to upload to the new <see cref="IAsset"/>.</param> /// <param name="options">The <see cref="AssetCreationOptions"/>.</param> /// <returns>A new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>.</returns> public static IAsset CreateAssetFromFolder(this CloudMediaContext context, string folderPath, AssetCreationOptions options) { return(context.CreateAssetFromFolder(folderPath, options, null)); }
/// <summary> /// Returns a <see cref="System.Threading.Tasks.Task<IAsset>"/> instance for a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>. /// </summary> /// <param name="context">The <see cref="CloudMediaContext"/> instance.</param> /// <param name="folderPath">The path to the folder with the files to upload to the new <see cref="IAsset"/>.</param> /// <param name="options">The <see cref="AssetCreationOptions"/>.</param> /// <param name="uploadProgressChangedCallback">A callback to report upload progress of the files.</param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task<IAsset>"/> instance for a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>.</returns> public static Task <IAsset> CreateAssetFromFolderAsync(this CloudMediaContext context, string folderPath, AssetCreationOptions options, Action <IAssetFile, UploadProgressChangedEventArgs> uploadProgressChangedCallback, CancellationToken cancellationToken) { return(context.CreateAssetFromFolderAsync(folderPath, null, options, uploadProgressChangedCallback, cancellationToken)); }
/// <summary> /// Returns a <see cref="System.Threading.Tasks.Task<IAsset>"/> instance for the new <see cref="IAsset"/>. /// </summary> /// <param name="context">The <see cref="CloudMediaContext"/> instance.</param> /// <param name="folderPath">The path to the folder with the files to upload to the new <see cref="IAsset"/>.</param> /// <param name="options">The <see cref="AssetCreationOptions"/>.</param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task<IAsset>"/> instance for new <see cref="IAsset"/>.</returns> public static Task <IAsset> CreateAssetFromFolderAsync(this CloudMediaContext context, string folderPath, AssetCreationOptions options, CancellationToken cancellationToken) { return(context.CreateAssetFromFolderAsync(folderPath, options, null, cancellationToken)); }
/// <summary> /// Returns a <see cref="System.Threading.Tasks.Task<IAsset>"/> instance for a new <see cref="IAsset"/> with the file in <paramref name="filePath"/>. /// </summary> /// <param name="context">The <see cref="CloudMediaContext"/> instance.</param> /// <param name="filePath">The path to the file to upload to the new <see cref="IAsset"/>.</param> /// <param name="storageAccountName">The name of the Storage Account where to store the new <see cref="IAsset"/>.</param> /// <param name="options">The <see cref="AssetCreationOptions"/>.</param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task<IAsset>"/> instance for a new <see cref="IAsset"/> with the file in <paramref name="filePath"/>.</returns> public static Task <IAsset> CreateAssetFromFileAsync(this CloudMediaContext context, string filePath, string storageAccountName, AssetCreationOptions options, CancellationToken cancellationToken) { return(context.CreateAssetFromFileAsync(filePath, storageAccountName, options, null, cancellationToken)); }
/// <summary> /// Returns a new <see cref="IAsset"/> with the file in <paramref name="filePath"/>. /// </summary> /// <param name="context">The <see cref="CloudMediaContext"/> instance.</param> /// <param name="filePath">The path to the file to upload to the new <see cref="IAsset"/>.</param> /// <param name="storageAccountName">The name of the Storage Account where to store the new <see cref="IAsset"/>.</param> /// <param name="options">The <see cref="AssetCreationOptions"/>.</param> /// <returns>A new <see cref="IAsset"/> with the file in <paramref name="filePath"/>.</returns> public static IAsset CreateAssetFromFile(this CloudMediaContext context, string filePath, string storageAccountName, AssetCreationOptions options) { return(context.CreateAssetFromFile(filePath, storageAccountName, options, null)); }
internal NotificationEndPointCollection(CloudMediaContext cloudMediaContext) { _cloudMediaContext = cloudMediaContext; DataContextFactory = _cloudMediaContext.DataContextFactory; Queryable = DataContextFactory.CreateDataServiceContext().CreateQuery <NotificationEndPoint>(NotificationEndPoints); }
/// <summary> /// Inits the cloud media context. /// </summary> /// <param name="context">The context.</param> public void InitCloudMediaContext(CloudMediaContext context) { InvalidateCollections(); this._cloudMediaContext = context; this._jobNotificationSubscriptions.InitCloudMediaContext(context); }