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();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudMediaContext"/> class.
 /// </summary>
 /// <param name="apiServer">A <see cref="Uri"/> representing the API endpoint.</param>
 /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param>
 public CloudMediaContext(Uri apiServer, MediaServicesCredentials credentials)
 {
     this.apiServer = apiServer;
     this.ParallelTransferThreadCount = 10;
     this.NumberOfConcurrentTransfers = 2;
     this.Credentials = credentials;
 }
        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);

            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);
        }
        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();
        }
Example #6
0
 public static CloudMediaContext GetCloudMediaContext()
 {
     var amsAccessToken = ClaimsPrincipal.Current.FindFirst(Configuration.ClaimsAmsAcessToken).Value;
     var amsCredentials = new MediaServicesCredentials(Configuration.MediaAccount, Configuration.MediaKey);
     amsCredentials.AccessToken = amsAccessToken;
     CloudMediaContext cntx = new CloudMediaContext(amsCredentials);
     return cntx;
 }
        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);

            // Create a common encryption content key that is used 
            // a) to set the key values in the MediaEncryptor_PlayReadyProtection.xml file
            //    that is used for encryption.
            // b) to configure the license delivery service and 
            //
            Guid keyId;
            byte[] contentKey;

            IContentKey key = CreateCommonEncryptionKey(out keyId, out contentKey); 
            // Add the common encryption key to asset's keys. 
           // asset.ContentKeys.Add(key);
            
            // The content key authorization policy must be configured by you 
            // and met by the client in order for the PlayReady license
            // to be delivered to the client. 
            ConfigureLicenseDeliveryService(key);

            Uri acquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);

            // Update the MediaEncryptor_PlayReadyProtection.xml file with the key and URL info.
            UpdatePlayReadyConfigurationXMLFile(keyId, contentKey, acquisitionUrl);


            // 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);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudMediaContext"/> class.
 /// </summary>
 /// <param name="apiServer">A <see cref="Uri"/> representing the API endpoint.</param>
 /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param>
 public CloudMediaContext(Uri apiServer, MediaServicesCredentials credentials)
 {
     this.apiServer = apiServer;
     this.ParallelTransferThreadCount = 10;
     this.NumberOfConcurrentTransfers = 2;
     this.Credentials   = credentials;
     dataServiceAdapter = new OAuthDataServiceAdapter(credentials, NimbusRestApiCertificateThumbprint, NimbusRestApiCertificateSubject);
     versionAdapter     = new ServiceVersionAdapter(KnownApiVersions.Current);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudMediaContext"/> class.
 /// </summary>
 /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param>
 public CloudMediaContext(MediaServicesCredentials credentials)
     : this(_mediaServicesUri, credentials)
 {
 }
        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();

            // The channel's input endpoint:
            string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString();

            Console.WriteLine("Intest URL: {0}", ingestUrl);

            // 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();

            Console.WriteLine("Preview URL: {0}", previewEndpoint);

            // When Live Encoding is enabled, you can now get a preview of the live feed as it reaches the Channel.
            // This can be a valuable tool to check whether your live feed is actually reaching the Channel.
            // The thumbnail is exposed via the same end-point as the Channel Preview URL.
            string thumbnailUri = new UriBuilder
            {
                Scheme = Uri.UriSchemeHttps,
                Host = channel.Preview.Endpoints.FirstOrDefault().Url.Host,
                Path = "thumbnails/input.jpg"
            }.Uri.ToString();

            Console.WriteLine("Thumbain URL: {0}", thumbnailUri);

            // 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.
            IAsset asset = CreateAndConfigureAsset();

            IProgram program = CreateAndStartProgram(channel, asset);

            ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength);

            // You can use slates and ads only if the channel type is Standard.
            StartStopAdsSlates(channel);

            // Once you are done streaming, clean up your resources.
            Cleanup(channel);
        }
Example #11
0
        static int doListAllAssets(string outputFile)
        {
            MediaServicesCredentials credentials = new MediaServicesCredentials(
                                        _accountName, _accountKey);
            CloudMediaContext _context = new CloudMediaContext(credentials);

            try
            {
                int selectlimit = 1000;
                int offset = 0;
                int selectposition = 0;

                int assetcount = _context.Assets.Count();
                Console.WriteLine("Assets Total Count:" + assetcount.ToString());

                StreamWriter writer = new StreamWriter(outputFile);

                string FieldDefines = "\"AssetName=\",\"AssetID\",\"LastModified\",\"StroageAccountName\",ContentKeyId\",\"ContentKeyType\"";
                writer.WriteLine(FieldDefines);

                while (true)
                {
                    foreach (IAsset asset in _context.Assets.Skip(offset).Take(selectlimit))
                    {
                        selectposition++;
                        string line = "";
                        var contentkeys = asset.ContentKeys;
                        if (contentkeys.Count() > 0)
                        {
                            foreach (IContentKey contentkey in contentkeys)
                            {
                                line = string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\"",
                                        asset.Name,
                                        asset.Id,
                                        asset.StorageAccountName,
                                        contentkey.Id,
                                        contentkey.ContentKeyType
                                        );
                                break;
                            }
                        }
                        else
                        {
                            line = string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\"",
                                    asset.Name,
                                    asset.Id,
                                    asset.StorageAccountName,
                                    "", ""
                                    );
                        }
                        writer.WriteLine(line);
                    }
                    if (selectposition == selectlimit)
                    {
                        offset += selectlimit;
                        selectposition = 0;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return -1;
            }
            return 0;
        }
Example #12
0
        static void Main(string[] args)
        {
            //var resultsURLs = AzureMediaLib.MediaService.GetProgressiveDownloadURLs("nb:jid:UUID:3880ae6a-e5a4-6642-a786-40437555c8c8");

            AzureMediaLib.MediaService.uploadFolderAndTranscode(_mediaFiles, 30);

            //string configuration2 = File.ReadAllText(Path.GetFullPath(@"../..\configs\Thumbnails.xml"));
            _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey);
            _context = new CloudMediaContext(_cachedCredentials);

            //DownloadAssetForTest();
            Console.WriteLine("finish download test.");
            Console.ReadLine();

            Console.WriteLine("Creating new asset from local file...");

            // Create a new asset and upload a mezzanine file from a local path.
            IAsset inputAsset = _context.Assets.CreateFromFile(
                _singleMP4File,
                AssetCreationOptions.None,
                (af, p) =>
                {
                    Console.WriteLine("Uploading '{0}' - Progress: {1:0.##}%", af.Name, p.Progress);
                });

            Console.WriteLine("Asset created.");

            // 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);

            //create thumbnail
            string configuration = File.ReadAllText(Path.GetFullPath(@"../..\configs\Thumbnails.xml"));

            var job = _context.Jobs.CreateWithSingleTask(
                MediaProcessorNames.WindowsAzureMediaEncoder,
                MediaEncoderTaskPresetStrings.Thumbnails,
                inputAsset,
                "Sample thumbnail 1",
                AssetCreationOptions.None);

            Console.WriteLine("Submitting transcoding job...");

            // 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.");

            // The OutputMediaAssets[0] contains the first
            // (and in this case the only) output asset
            // produced by the encoding job.
            IAsset outputAsset = job.OutputMediaAssets[0];

            Console.WriteLine("Publishing output asset...");

            // Publish the output asset by creating an Origin locator.
            // Define the Read only access policy and
            // specify that the asset can be accessed for 30 days.
            _context.Locators.Create(
                LocatorType.OnDemandOrigin,
                outputAsset,
                AccessPermissions.Read,
                TimeSpan.FromDays(30));

            // Generate the Smooth Streaming, HLS and MPEG-DASH URLs for adaptive streaming.
            Uri smoothStreamingUri = outputAsset.GetSmoothStreamingUri();
            Uri hlsUri = outputAsset.GetHlsUri();
            Uri mpegDashUri = outputAsset.GetMpegDashUri();

            // To stream your content based on the set of
            // adaptive bitrate MP4 files, you must first get
            // at least one On-demand Streaming reserved unit.
            // For more information, see http://msdn.microsoft.com/en-us/library/jj889436.aspx.
            Console.WriteLine("Output is now available for adaptive streaming:");

            // Show the streaming URLs.
            Console.WriteLine(smoothStreamingUri);
            Console.WriteLine(hlsUri);
            Console.WriteLine(mpegDashUri);

            //
            // Create a SAS locator that is used for progressive download
            // or to download files to a local directory.
            // The content that you want to progressively download cannot be encrypted.
            _context.Locators.Create(
                LocatorType.Sas,
                outputAsset,
                AccessPermissions.Read,
                TimeSpan.FromDays(30));

            // Get all the MP4 files in the output asset.
            IEnumerable<IAssetFile> mp4AssetFiles = outputAsset
                    .AssetFiles
                    .ToList()
                    .Where(af => af.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase));

            // Generate the Progressive Download URLs for each MP4.
            List<Uri> mp4ProgressiveDownloadUris =
                mp4AssetFiles.Select(af => af.GetSasUri()).ToList();

            Console.WriteLine("You can progressively download the following MP4 files:");
            mp4ProgressiveDownloadUris.ForEach(uri => Console.WriteLine(uri));

            string outputFolder = Path.Combine(_mediaFiles, @"job-output");

            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }

            Console.WriteLine("Downloading output asset files to local folder...");

            // Download the output asset to a local folder.
            outputAsset.DownloadToFolder(
                outputFolder,
                (af, p) =>
                {
                    Console.WriteLine("Downloading '{0}' - Progress: {1:0.##}%", af.Name, p.Progress);
                });

            Console.WriteLine("Downloaded files are located in '{0}'.", Path.GetFullPath(outputFolder));
        }
Example #13
0
        public static void Main(string[] args)
        {
            try
            {
                string accountName = ConfigurationManager.AppSettings["MediaServicesAccountName"];
                string accountKey = ConfigurationManager.AppSettings["MediaServicesAccountKey"];
                MediaServicesCredentials credentials = new MediaServicesCredentials(accountName, accountKey);
                MediaContextBase 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(
                    "video.mp4",
                    AssetCreationOptions.None,
                    (af, p) =>
                    {
                        Console.WriteLine("Uploading '{0}' - Progress: {1:0.##}%", af.Name, p.Progress);
                    });

                Console.WriteLine("Asset created.");

                // 2. Prepare a job with two tasks:
                //    - One to transcode the previous mezzanine asset into a multi-bitrate asset
                //    - One to generate a closed captioning TTML file from the audio
                IJob job = context.Jobs.Create("Demo Job");

                IMediaProcessor azureMediaEncoder = context.MediaProcessors.GetLatestMediaProcessorByName("Azure Media Encoder");
                ITask encodingTask = job.Tasks.AddNew("Encoding Task", azureMediaEncoder, MediaEncoderTaskPresetStrings.H264AdaptiveBitrateMP4Set720p, TaskOptions.None);
                encodingTask.InputAssets.Add(inputAsset);
                encodingTask.OutputAssets.AddNew("Multibitrate Asset", AssetCreationOptions.None);

                IMediaProcessor azureMediaIndexer = context.MediaProcessors.GetLatestMediaProcessorByName("Azure Media Indexer");
                ITask indexingTask = job.Tasks.AddNew("Indexing Task", azureMediaIndexer, Resources.IndexerPreset, TaskOptions.None);
                indexingTask.InputAssets.Add(inputAsset);
                indexingTask.OutputAssets.AddNew("Indexer Result Asset", 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 multibitrateOutputAsset = job.OutputMediaAssets[0];
                IAsset indexerResultOutputAsset = job.OutputMediaAssets[1];

                Console.WriteLine("Creating key authorization policy and delivery policy...");

                // 4. [Dynamic Encryption] Configure Key Authorization Policy and Asset Delivery Policy
                IContentKey key = CreateEnvelopeTypeContentKey(context, multibitrateOutputAsset);
                AddOpenRestrictedAuthorizationPolicy(context, key);
                CreateAssetDeliveryPolicy(context, multibitrateOutputAsset, key);

                Console.WriteLine("Publishing output asset...");

                // 5. Publish the output asset by creating an Origin locator for adaptive streaming, and a SAS locator for progressive download.
                context.Locators.Create(LocatorType.OnDemandOrigin, multibitrateOutputAsset, AccessPermissions.Read, TimeSpan.FromDays(30));
                context.Locators.Create(LocatorType.Sas, multibitrateOutputAsset, AccessPermissions.Read, TimeSpan.FromDays(30));

                IEnumerable<IAssetFile> mp4AssetFiles = multibitrateOutputAsset
                        .AssetFiles
                        .ToList()
                        .Where(af => af.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase));

                // 6. [Dynamic Packaging] Generate the Smooth Streaming, HLS and MPEG-DASH URLs for adaptive streaming
                Uri smoothStreamingUri = multibitrateOutputAsset.GetSmoothStreamingUri();
                Uri hlsv4Uri = multibitrateOutputAsset.GetHlsUri();
                Uri hlsv3Uri = multibitrateOutputAsset.GetHlsv3Uri();
                Uri mpegDashUri = multibitrateOutputAsset.GetMpegDashUri();

                // 7. Generate SAS URL for progressive download.
                List<Uri> mp4ProgressiveDownloadUris = mp4AssetFiles.Select(af => af.GetSasUri()).ToList();

                // 8. Get the asset URLs.
                Console.WriteLine(smoothStreamingUri);
                Console.WriteLine(hlsv4Uri);
                Console.WriteLine(hlsv3Uri);
                Console.WriteLine(mpegDashUri);
                mp4ProgressiveDownloadUris.ForEach(uri => Console.WriteLine(uri));

                Console.WriteLine("Output asset available for adaptive streaming and progressive download.");

                string outputFolder = "indexer-job-output";
                if (!Directory.Exists(outputFolder))
                {
                    Directory.CreateDirectory(outputFolder);
                }

                Console.WriteLine("Downloading output asset files to local folder...");

                // 9. Download the indexer result output asset to a local folder.
                indexerResultOutputAsset.DownloadToFolder(
                    outputFolder,
                    (af, p) =>
                    {
                        Console.WriteLine("Downloading '{0}' - Progress: {1:0.##}%", af.Name, p.Progress);
                    });

                Console.WriteLine("Indexer output files available at '{0}'.", Path.GetFullPath(outputFolder));

                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();
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            try
            {
                // Create and cache the Media Services credentials in a static class variable.
                _cachedCredentials = new MediaServicesCredentials(
                                _mediaServicesAccountName,
                                _mediaServicesAccountKey);
                // Used the chached credentials to create CloudMediaContext.
                _context = new CloudMediaContext(_cachedCredentials);

                // Add calls to methods defined in this section.

                IAsset inputAsset =
                    UploadFile(@"D:\MediaServices\dotnetsdk\dotnetsdk\videos\Wildlife.wmv", AssetCreationOptions.None);

                IAsset encodedAsset =
                    EncodeToAdaptiveBitrateMP4s(inputAsset, AssetCreationOptions.None);

                PublishAssetGetURLs(encodedAsset);
            }
            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();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudMediaContext"/> class.
 /// </summary>
 /// <param name="apiServer">A <see cref="Uri"/> representing the API endpoint.</param>
 /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param>
 public CloudMediaContext(Uri apiServer, MediaServicesCredentials credentials)
 {
     this.apiServer = apiServer;
     this.ParallelTransferThreadCount = 10;
     this.NumberOfConcurrentTransfers = 2;
     this.Credentials = credentials;
     dataServiceAdapter = new OAuthDataServiceAdapter(credentials, NimbusRestApiCertificateThumbprint, NimbusRestApiCertificateSubject);
     versionAdapter = new ServiceVersionAdapter(KnownApiVersions.Current);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudMediaContext"/> class.
 /// </summary>
 /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param>
 public CloudMediaContext(MediaServicesCredentials credentials)
     : this(_mediaServicesUri, credentials)
 {
 }
        static void Main(string[] args)
        {
            //
            //  Get all of the values we need from the App.Config
            //
            string mediaServicesAccountName = ConfigurationManager.AppSettings["MediaServiceAccountName"];
            string mediaServicesAccountKey = ConfigurationManager.AppSettings["MediaServiceAccountKey"];
            string clientId = ConfigurationManager.AppSettings["AcsAccountName"];
            string clientSecret = ConfigurationManager.AppSettings["AcsAccountKey"];
            string issuerString = ConfigurationManager.AppSettings["AcsEndpoint"];
            string scopeString = ConfigurationManager.AppSettings["AcsScope"];
            string signingKeyString = ConfigurationManager.AppSettings["AcsSigningKey"];
            byte[] signingKey = Convert.FromBase64String(signingKeyString);

            //
            //  Create the context to talk to Azure Media Services
            //
            MediaServicesCredentials creds = new MediaServicesCredentials(mediaServicesAccountName, mediaServicesAccountKey);
            CloudMediaContext context = new CloudMediaContext(creds);

            //
            //  Setup Media Services for Key Delivery of an Envelope Content Key with a Token Restriction.
            //  The GetTokenRestriction method has all of the details on how the ACS parameters from the App.Config
            //  are used to configure the token validation logic associated with delivering the content key.
            //
            List<ContentKeyAuthorizationPolicyRestriction> restrictions = GetTokenRestriction("Token Restriction using token from ACS", issuerString, scopeString, signingKey);

            IContentKey contentKey = SetupContentKey(context, restrictions);

            //
            //  Now simulate a client downloading the content key to use for playback by
            //  using ACS to get an authentication token and using the token to download
            //  the Envelope key from the Key Delivery service.
            //
            string authToken = GetToken(clientId, clientSecret, scopeString, issuerString);

            Uri keyUrl = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

            using (WebClient client = new WebClient())
            {
                Console.WriteLine("Token=Bearer " + authToken);
                client.Headers["Authorization"] = "Bearer " + authToken;
                byte[] downloadedKeyValue;
                try
                {
                    downloadedKeyValue = client.DownloadData(keyUrl);
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("\nContent Key acquired successfully!");
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("\nKey acquisition failed.\n{0}", ex.Message);
                }
            }
            Console.ResetColor();
            Console.ReadLine();
        }
 private static void SetMediaServicesCredentials()
 {
     // 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);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudMediaContext"/> class.
        /// </summary>
        /// <param name="apiServer">A <see cref="Uri"/> representing the API endpoint.</param>
        /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param>
        public CloudMediaContext(Uri apiServer, MediaServicesCredentials credentials)
        {
            this.ParallelTransferThreadCount = 10;
            this.NumberOfConcurrentTransfers = 2;

            this.Credentials = credentials;

            OAuthDataServiceAdapter dataServiceAdapter =
                new OAuthDataServiceAdapter(credentials, NimbusRestApiCertificateThumbprint, NimbusRestApiCertificateSubject);
            ServiceVersionAdapter versionAdapter = new ServiceVersionAdapter(KnownApiVersions.Current);

            this.MediaServicesClassFactory = new AzureMediaServicesClassFactory(apiServer, dataServiceAdapter, versionAdapter, this);

            this._jobs = new JobBaseCollection(this);
            this._jobTemplates = new JobTemplateBaseCollection(this);
            this._assets = new AssetCollection(this);
            this._files = new AssetFileCollection(this);
            this._accessPolicies = new AccessPolicyBaseCollection(this);
            this._contentKeys = new ContentKeyCollection(this);
            this._notificationEndPoints = new NotificationEndPointCollection(this);
            this._mediaProcessors = new MediaProcessorBaseCollection(this);
            this._locators = new LocatorBaseCollection(this);
            this._ingestManifests = new IngestManifestCollection(this);
            this._ingestManifestAssets = new IngestManifestAssetCollection(this,null);
            this._ingestManifestFiles = new IngestManifestFileCollection(this, null);
            this._storageAccounts = new StorageAccountBaseCollection(this);
        }
Example #20
0
 static MediaService()
 {
     //init contexts.
     _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey);
     _context = new CloudMediaContext(_cachedCredentials);
 }
        static void Main(string[] args)
        {
            // Create and cache the Media Services credentials in a static class variable.
            _cachedCredentials = new MediaServicesCredentials(
                            _mediaServicesAccountName,
                            _mediaServicesAccountKey);
            // Used the chached credentials to create CloudMediaContext.
            _context = new CloudMediaContext(_cachedCredentials);

            bool tokenRestriction = true;
            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 = CreateEnvelopeTypeContentKey(encodedAsset);
            Console.WriteLine("Created key {0} for the asset {1} ", key.Id, encodedAsset.Id);
            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 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);

                //The GenerateTestToken method returns the token without the word “Bearer” in front
                //so you have to add it in front of the token string.
                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 bit.ly/aesplayer Flash player to test the URL
            // (with open authorization policy).
            // Paste the URL and click the Update button to play the video.
            //
            string URL = GetStreamingOriginLocator(encodedAsset);
            Console.WriteLine("Smooth Streaming Url: {0}/manifest", URL);
            Console.WriteLine();
            Console.WriteLine("HLS Url: {0}/manifest(format=m3u8-aapl)", URL);
            Console.WriteLine();

            Console.ReadLine();
        }
        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();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudMediaContext"/> class.
 /// </summary>
 /// <param name="apiServer">A <see cref="Uri"/> representing the API endpoint.</param>
 /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param>
 public CloudMediaContext(Uri apiServer, MediaServicesCredentials credentials)
 {
     this.apiServer = apiServer;
     this.ParallelTransferThreadCount = 10;
     this.NumberOfConcurrentTransfers = 2;
     this.Credentials = credentials;
 }
        // added by [email protected] to the original template


        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                       AuthorizationCodeReceived = (context) => 
                       {
                           var code = context.Code;
                           ClientCredential credential = new ClientCredential(clientId, appKey);
                           string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                           AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                           AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                               code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                           // added by [email protected] to the original template
                           // Getting KeyDelivery Access Token
                           AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(
                               code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, kdResourceId);
                           string kdAccessToken = kdAPiresult.AccessToken;
                           System.IdentityModel.Tokens.JwtSecurityToken kdAccessJwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(kdAccessToken);

                           try {
                               // Initializing MediaServicesCredentials in order to obtain access token to be used to connect 
                               var amsCredentials = new MediaServicesCredentials(mediaServicesAccount, mediaServicesKey);
                               // Forces to get access token
                               amsCredentials.RefreshToken();
                               //Adding media services access token as claim so it can be accessible within controller
                               context.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(VideoPortalDemo.Configurations.ClaimsAmsAcessToken, amsCredentials.AccessToken));
                           }
                           catch { }

                           //context.AuthenticationTicket.Identity.AddClaim(
                           //    new System.Security.Claims.Claim("KdAccessJwtSecurityTokenClaim", kdAccessJwtToken.RawData));
                           // added by [email protected] to the original template

                           return Task.FromResult(0);
                       }
                    }
                });
        }
Example #25
0
        //
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        // The App Key is a credential used to authenticate the application to Azure AD.  Azure AD supports password and certificate credentials.
        // The Metadata Address is used by the application to retrieve the signing keys used by Azure AD.
        // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
        // The Authority is the sign-in URL of the tenant.
        // The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
        //
        // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = MediaLibraryWebApp.Configuration.ClientId,
                    Authority = MediaLibraryWebApp.Configuration.Authority,
                    PostLogoutRedirectUri = MediaLibraryWebApp.Configuration.PostLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        //
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        //
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;
                            System.IdentityModel.Tokens.JwtSecurityToken jwtToken = context.JwtSecurityToken;

                            string userObjectID = context.AuthenticationTicket.Identity.FindFirst(MediaLibraryWebApp.Configuration.ClaimsObjectidentifier).Value;

                            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(MediaLibraryWebApp.Configuration.ClientId, MediaLibraryWebApp.Configuration.AppKey);

                            NaiveSessionCache cache = new NaiveSessionCache(userObjectID);
                            AuthenticationContext authContext = new AuthenticationContext(MediaLibraryWebApp.Configuration.Authority, cache);

                            //Getting a token to connect with GraphApi later on userProfile page
                            AuthenticationResult graphAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.GraphResourceId);

                            //Getting a access token which can be used to configure auth restrictions for multiple tentants since audience will be same for each web app requesting this token
                            //AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.KdResourceId);

                            //string kdAccessToken = kdAPiresult.AccessToken;

                            //Initializing  MediaServicesCredentials in order to obtain access token to be used to connect
                            var amsCredentials = new MediaServicesCredentials(MediaLibraryWebApp.Configuration.MediaAccount, MediaLibraryWebApp.Configuration.MediaKey);
                            //Forces to get access token
                            amsCredentials.RefreshToken();

                            //Adding token to a claim so it can be accessible within controller
                            context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsSignInJwtToken, jwtToken.RawData));

                            //Adding media services access token as claim so it can be accessible within controller
                            context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsAmsAcessToken, amsCredentials.AccessToken));

                            return Task.FromResult(0);
                        }

                    }

                });
        }
        static void Main(string[] args)
        {
            try
            {
                // Create and cache the Media Services credentials in a static class variable.
                _cachedCredentials = new MediaServicesCredentials(
                                _mediaServicesAccountName,
                                _mediaServicesAccountKey);
                // Used the chached credentials to create CloudMediaContext.
                _context = new CloudMediaContext(_cachedCredentials);



                // If you want to secure your high quality input media files with strong encryption at rest on disk,
                // use AssetCreationOptions.StorageEncrypted instead of AssetCreationOptions.None.

                Console.WriteLine("Upload a file.\n");
                IAsset inputAsset =
                    UploadFile(Path.Combine(_mediaFiles, @"BigBuckBunny.mp4"), AssetCreationOptions.None);

                
                Console.WriteLine("Generate thumbnails and get URLs.\n");

                IAsset thumbnailAsset = GenerateThumbnail(inputAsset, AssetCreationOptions.None);
                PublishAssetGetURLs(thumbnailAsset, false, ".bmp");


                Console.WriteLine("Encode to audio and get an on demand URL.\n");

                IAsset audioOnly = EncodeToAudioOnly(inputAsset, AssetCreationOptions.None);
                PublishAssetGetURLs(audioOnly);

                Console.WriteLine("Encode to adaptive bitraite MP4s and get on demand URLs.\n");

                // If you want to secure your high quality encoded media files with strong encryption at rest on disk,
                // use AssetCreationOptions.StorageEncrypted instead of AssetCreationOptions.None.
                // 
                // If your asset is AssetCreationOptions.StorageEncrypted, 
                // make sure to call ConfigureClearAssetDeliveryPolicy defined below.

                IAsset encodedAsset =
                    EncodeToAdaptiveBitrateMP4s(inputAsset, AssetCreationOptions.None);


                // If your want to delivery a storage encrypted asset, 
                // you must configure the asset’s delivery policy.
                // Before your asset can be streamed, 
                // the streaming server removes the storage encryption and 
                //streams your content using the specified delivery policy.

                // ConfigureClearAssetDeliveryPolicy(encodedAsset);

                PublishAssetGetURLs(encodedAsset);
            }
            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();
            }
        }
        /// <summary>
        /// Example where I encode 2 video files (_singleWMVInputFilePath.wmv and 2.mp4)
        /// </summary>
        /// <param name="aOutputFileFolder"></param>
        /// <returns></returns>
        public static bool CreateandEncodeOnDemandFile(string aOutputFileFolder, string _singleMP4InputFilePath, string _singleWMVInputFilePath)
        {
            bool tempresult = true;
            try
            {
                // Create and cache the Media Services credentials in a static class variable.
                _cachedCredentials = new MediaServicesCredentials(
                    _mediaServicesAccountName,
                    _mediaServicesAccountKey);
                // Used the chached credentials to create CloudMediaContext.
                _context = new CloudMediaContext(_cachedCredentials);

                IAsset singleWMVAsset = CreateAssetAndUploadSingleFile(AssetCreationOptions.None,
                                                                       _singleWMVInputFilePath);

                // EncodeToH264 creates a job with one task
                // that converts a mezzanine file (in this case interview1.wmv)
                // into an MP4 file (in this case, "H264 Broadband 720p").
                IAsset MP4Asset = CreateEncodingJob(singleWMVAsset, "H264 Broadband 720p", aOutputFileFolder);


                // BuildSasUrlForMP4File creates a SAS Locator
                // and builds the SAS Url that can be used to 
                // progressively download the MP4 file.
                string fullSASURL = BuildSasUrlForMP4File(MP4Asset);

                Console.WriteLine("Progressive download URL: {0}", fullSASURL);

                // Download all the files in the asset locally
                // (that includes the mainifest.xml file).
                DownloadAssetToLocal(MP4Asset, _outputFilesFolder);

                Console.WriteLine();

                IAsset singleMP4Asset = CreateAssetAndUploadSingleFile(AssetCreationOptions.None,
                                                                       _singleMP4InputFilePath);
                // EncodeToAdaptiveBitrate creates a job with one task
                // that encodes a mezzanine file (in this case BigBuckBunny.mp4)
                // into an adaptive bitrate MP4 set (in this case, "H264 Adaptive Bitrate MP4 Set 720p").
                IAsset adaptiveBitrateAsset = CreateEncodingJob(singleMP4Asset, "H264 Adaptive Bitrate MP4 Set 720p", aOutputFileFolder);

                // Get the Streaming Origin Locator URL.
                string streamingURL = GetStreamingOriginLocatorURL(adaptiveBitrateAsset);

                // Add Smooth Streaming, HLS, and DASH format to the streaming URL.  
                // NOTE: To be able to play these streams based on the 
                // adaptiveBitrateAsset asset, you MUST have at least one
                // On-demand Streaming reserved unit. 
                // For more information, see: 
                //    Dynamic Packaging (http://msdn.microsoft.com/en-us/library/azure/jj889436.aspx)
                Console.WriteLine("Smooth Streaming format:");
                Console.WriteLine("{0}", streamingURL + "/Manifest");
                Console.WriteLine("Apple HLS format:");
                Console.WriteLine("{0}", streamingURL + "/Manifest(format=m3u8-aapl)");
                Console.WriteLine("MPEG DASH format:");
                Console.WriteLine("{0}", streamingURL + "/Manifest(format=mpd-time-csf)");
            }
            catch (Exception)
            {
                tempresult = false;
            }
            return tempresult;
        }
        static void Main(string[] args)
        {
            _cachedCredentials = new MediaServicesCredentials(
                            _accountName,
                            _accountKey);
            // Use the cached credentials to create CloudMediaContext.
            _context = new CloudMediaContext(_cachedCredentials);

            // In this example the storage account from which we copy blobs is not
            // associated with the Media Services account into which we copy blobs.
            // But the same code will work for coping blobs from a storage account that is
            // associated with the Media Services account.
            //
            // Get a reference to a storage account that is not associated with a Media Services account
            // (an external account).
            StorageCredentials externalStorageCredentials =
                new StorageCredentials(_externalStorageAccountName, _externalStorageAccountKey);
            _sourceStorageAccount = new CloudStorageAccount(externalStorageCredentials, true);

            //Get a reference to the storage account that is associated with a Media Services account.
            StorageCredentials mediaServicesStorageCredentials =
                new StorageCredentials(_storageAccountName, _storageAccountKey);
            _destinationStorageAccount = new CloudStorageAccount(mediaServicesStorageCredentials, false);

            // Upload Smooth Streaming files into a storage account.
            string localMediaDir = @"C:\supportFiles\streamingfiles";
            CloudBlobContainer blobContainer =
                UploadContentToStorageAccount(localMediaDir);

            // Create a new asset and copy the smooth streaming files into
            // the container that is associated with the asset.
            IAsset asset = CreateAssetFromExistingBlobs(blobContainer);

            // Get the streaming URL for the smooth streaming files
            // that were copied into the asset.
            string urlForClientStreaming = CreateStreamingLocator(asset);
            Console.WriteLine("Smooth Streaming URL: " + urlForClientStreaming);

            Console.ReadLine();
        }