public void StreamingPolicyComboTest()
        {
            using (MockContext context = this.StartMockContextAndInitializeClients(this.GetType()))
            {
                try
                {
                    CreateMediaServicesAccount();

                    // List StreamingPolicies, which should only contain the predefined policies
                    var policies = MediaClient.StreamingPolicies.List(ResourceGroup, AccountName);
                    Assert.Empty(policies.Where(p => !p.Name.StartsWith("Predefined_")));

                    string policyName = TestUtilities.GenerateName("StreamingPolicy");

                    // Get the StreamingPolicy, which should not exist
                    StreamingPolicy policy = MediaClient.StreamingPolicies.Get(ResourceGroup, AccountName, policyName);
                    Assert.Null(policy);

                    // Create a new StreamingPolicy
                    string defaultContentKeyPolicyName        = null;
                    CommonEncryptionCbcs commonEncryptionCbcs = null;
                    CommonEncryptionCenc commonEncryptionCenc = null;
                    EnvelopeEncryption   envelopeEncryption   = new EnvelopeEncryption(enabledProtocols: new EnabledProtocols(false, false, true, false));
                    NoEncryption         noEncryption         = null;
                    var             input         = new StreamingPolicy(envelopeEncryption: envelopeEncryption);
                    StreamingPolicy createdPolicy = MediaClient.StreamingPolicies.Create(ResourceGroup, AccountName, policyName, input);
                    ValidateStreamingPolicy(createdPolicy, policyName, defaultContentKeyPolicyName, commonEncryptionCbcs, commonEncryptionCenc, envelopeEncryption, noEncryption);

                    // List StreamingPolicies and validate the newly created one shows up
                    policies = MediaClient.StreamingPolicies.List(ResourceGroup, AccountName);
                    policy   = policies.Where(p => !p.Name.StartsWith("Predefined_")).First();
                    ValidateStreamingPolicy(policy, policyName, defaultContentKeyPolicyName, commonEncryptionCbcs, commonEncryptionCenc, envelopeEncryption, noEncryption);

                    // Get the newly created StreamingPolicy
                    policy = MediaClient.StreamingPolicies.Get(ResourceGroup, AccountName, policyName);
                    Assert.NotNull(policy);
                    ValidateStreamingPolicy(policy, policyName, defaultContentKeyPolicyName, commonEncryptionCbcs, commonEncryptionCenc, envelopeEncryption, noEncryption);

                    // Delete the StreamingPolicy
                    MediaClient.StreamingPolicies.Delete(ResourceGroup, AccountName, policyName);

                    // List StreamingPolicies, which should only contain the predefined policies
                    policies = MediaClient.StreamingPolicies.List(ResourceGroup, AccountName);
                    Assert.Empty(policies.Where(p => !p.Name.StartsWith("Predefined_")));

                    // Get the StreamingPolicy, which should not exist
                    policy = MediaClient.StreamingPolicies.Get(ResourceGroup, AccountName, policyName);
                    Assert.Null(policy);
                }
                finally
                {
                    DeleteMediaServicesAccount();
                }
            }
        }
        public static async Task <StreamingPolicy> CreateStreamingPolicyIrdeto(ConfigWrapper config,
                                                                               IAzureMediaServicesClient client, string uniqueness = null)
        {
            if (uniqueness == null)
            {
                uniqueness = Guid.NewGuid().ToString().Substring(0, 13);
            }

            var dash_smooth_protocol = new EnabledProtocols(false, true, false, true);
            var hls_dash_protocol    = new EnabledProtocols(false, true, true, false);
            var cenc_config          = new CencDrmConfiguration(
                new StreamingPolicyPlayReadyConfiguration
            {
                CustomLicenseAcquisitionUrlTemplate = config.IrdetoPlayReadyLAURL
            },
                new StreamingPolicyWidevineConfiguration
            {
                CustomLicenseAcquisitionUrlTemplate = config.IrdetoWidevineLAURL
            }
                );
            var cbcs_config = new CbcsDrmConfiguration(
                new StreamingPolicyFairPlayConfiguration
            {
                CustomLicenseAcquisitionUrlTemplate = config.IrdetoFairPlayLAURL
            }
                );

            var ContentKeysEnc = new StreamingPolicyContentKeys
            {
                DefaultKey = new DefaultKey
                {
                    Label = labelCenc
                }
            };

            var ContentKeysCbcsc = new StreamingPolicyContentKeys
            {
                DefaultKey = new DefaultKey
                {
                    Label = labelCbcs
                }
            };

            var cenc = new CommonEncryptionCenc(dash_smooth_protocol, null, ContentKeysEnc, cenc_config);
            var cbcs = new CommonEncryptionCbcs(hls_dash_protocol, null, ContentKeysCbcsc, cbcs_config);

            var policyName      = uniqueness;
            var streamingPolicy = new StreamingPolicy(Guid.NewGuid().ToString(), policyName, null, DateTime.Now, null,
                                                      null, cenc, cbcs, null);

            streamingPolicy = await client.StreamingPolicies.CreateAsync(config.ResourceGroup, config.AccountName,
                                                                         policyName, streamingPolicy);

            return(streamingPolicy);
        }
        internal static void ValidateStreamingPolicy(
            StreamingPolicy policy,
            string expectedName,
            string expectedDefaultContentKeyPolicyName,
            CommonEncryptionCbcs expectedCommonEncryptionCbcs,
            CommonEncryptionCenc expectedCommonEncryptionCenc,
            EnvelopeEncryption expectedEnvelopeEncryption,
            NoEncryption expectedNoEncryption)
        {
            Assert.Equal(expectedName, policy.Name);
            Assert.Equal(expectedDefaultContentKeyPolicyName, policy.DefaultContentKeyPolicyName);
            Assert.False(string.IsNullOrEmpty(policy.Id));

            if (expectedCommonEncryptionCbcs == null)
            {
                Assert.Null(policy.CommonEncryptionCbcs);
            }
            else
            {
                ValidateEnabledProtocols(expectedCommonEncryptionCbcs.EnabledProtocols, policy.CommonEncryptionCbcs.EnabledProtocols);
            }

            if (expectedCommonEncryptionCenc == null)
            {
                Assert.Null(policy.CommonEncryptionCenc);
            }
            else
            {
                ValidateEnabledProtocols(expectedCommonEncryptionCenc.EnabledProtocols, policy.CommonEncryptionCenc.EnabledProtocols);
            }

            if (expectedEnvelopeEncryption == null)
            {
                Assert.Null(policy.EnvelopeEncryption);
            }
            else
            {
                ValidateEnabledProtocols(expectedEnvelopeEncryption.EnabledProtocols, policy.EnvelopeEncryption.EnabledProtocols);
            }

            if (expectedNoEncryption == null)
            {
                Assert.Null(policy.NoEncryption);
            }
            else
            {
                ValidateEnabledProtocols(expectedNoEncryption.EnabledProtocols, policy.NoEncryption.EnabledProtocols);
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"AMS v3 Function - CreateStreamingPolicy was triggered!");

            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            if (data.streamingPolicyName == null)
            {
                return(new BadRequestObjectResult("Please pass streamingPolicyName in the input object"));
            }
            if (data.defaultContentKeyPolicyName == null)
            {
                return(new BadRequestObjectResult("Please pass defaultContentKeyPolicyName in the input object"));
            }
            string streamingPolicyName         = data.streamingPolicyName;
            string defaultContentKeyPolicyName = data.defaultContentKeyPolicyName;

            string mode = data.mode;

            if (mode != "simple" && mode != "advanced")
            {
                return(new BadRequestObjectResult("Please pass valid mode in the input object"));
            }
            //
            // Simple Mode
            //
            if (mode == "simple")
            {
                if (data.noEncryptionProtocols == null &&
                    data.cbcsProtocols == null &&
                    data.cencProtocols == null &&
                    data.envelopeProtocols == null)
                {
                    return(new BadRequestObjectResult("Please pass one protocol for any encryption scheme at least in the input object"));
                }
            }
            //
            // Advanced Mode
            //
            if (mode == "advanced")
            {
                if (data.jsonNoEncryption == null &&
                    data.jsonCommonEncryptionCbcs == null &&
                    data.jsonCommonEncryptionCenc == null &&
                    data.jsonEnvelopeEncryption == null)
                {
                    return(new BadRequestObjectResult("Please pass one encryption scheme JSON at least in the input object"));
                }
            }

            MediaServicesConfigWrapper amsconfig = new MediaServicesConfigWrapper();
            StreamingPolicy            policy    = null;

            JsonConverter[] jsonReaders =
            {
                new MediaServicesHelperJsonReader(),
                new MediaServicesHelperTimeSpanJsonConverter()
            };

            try
            {
                IAzureMediaServicesClient client = MediaServicesHelper.CreateMediaServicesClientAsync(amsconfig);

                policy = client.StreamingPolicies.Get(amsconfig.ResourceGroup, amsconfig.AccountName, streamingPolicyName);
                if (policy == null)
                {
                    StreamingPolicy parameters = new StreamingPolicy();
                    parameters.DefaultContentKeyPolicyName = defaultContentKeyPolicyName;

                    if (mode == "simple")
                    {
                        // NoEncryption Arguments
                        if (data.noEncryptionProtocols != null)
                        {
                            String[] noEncryptionProtocols = data.noEncryptionProtocols.ToString().Split(';');
                            if (Array.IndexOf(noEncryptionProtocols, "Dash") > -1)
                            {
                                parameters.NoEncryption.EnabledProtocols.Dash = true;
                            }
                            if (Array.IndexOf(noEncryptionProtocols, "Download") > -1)
                            {
                                parameters.NoEncryption.EnabledProtocols.Download = true;
                            }
                            if (Array.IndexOf(noEncryptionProtocols, "Hls") > -1)
                            {
                                parameters.NoEncryption.EnabledProtocols.Hls = true;
                            }
                            if (Array.IndexOf(noEncryptionProtocols, "SmoothStreaming") > -1)
                            {
                                parameters.NoEncryption.EnabledProtocols.SmoothStreaming = true;
                            }
                        }

                        // Common Encryption CBCS Argument
                        if (data.cbcsClearTracks != null)
                        {
                            List <TrackSelection> tracks = JsonConvert.DeserializeObject <List <TrackSelection> >(data.cbcsClearTracks.ToString(), jsonReaders);
                            parameters.CommonEncryptionCbcs.ClearTracks = tracks;
                        }
                        if (data.cbcsDefaultKeyLabel != null)
                        {
                            parameters.CommonEncryptionCbcs.ContentKeys.DefaultKey.Label = data.cbcsDefaultKeyLabel;
                        }
                        if (data.cbcsDefaultKeyPolicyName != null)
                        {
                            parameters.CommonEncryptionCbcs.ContentKeys.DefaultKey.PolicyName = data.cbcsDefaultKeyPolicyName;
                        }
                        if (data.cbcsClearTracks != null)
                        {
                            List <StreamingPolicyContentKey> mappings = JsonConvert.DeserializeObject <List <StreamingPolicyContentKey> >(data.cbcsKeyToTrackMappings.ToString(), jsonReaders);
                            parameters.CommonEncryptionCbcs.ContentKeys.KeyToTrackMappings = mappings;
                        }
                        if (data.cbcsFairPlayTemplate != null)
                        {
                            parameters.CommonEncryptionCbcs.Drm.FairPlay.CustomLicenseAcquisitionUrlTemplate = data.cbcsFairPlayTemplate;
                        }
                        if (data.cbcsFairPlayAllowPersistentLicense != null)
                        {
                            parameters.CommonEncryptionCbcs.Drm.FairPlay.AllowPersistentLicense = data.cbcsFairPlayAllowPersistentLicense;
                        }
                        if (data.cbcsPlayReadyTemplate != null)
                        {
                            parameters.CommonEncryptionCbcs.Drm.PlayReady.CustomLicenseAcquisitionUrlTemplate = data.cbcsPlayReadyTemplate;
                        }
                        if (data.cbcsPlayReadyAttributes != null)
                        {
                            parameters.CommonEncryptionCbcs.Drm.PlayReady.PlayReadyCustomAttributes = data.cbcsPlayReadyAttributes;
                        }
                        if (data.cbcsWidevineTemplate != null)
                        {
                            parameters.CommonEncryptionCbcs.Drm.Widevine.CustomLicenseAcquisitionUrlTemplate = data.cbcsWidevineTemplate;
                        }
                        if (data.cbcsProtocols != null)
                        {
                            String[] commonEncryptionCbcsProtocols = data.cbcsProtocols.ToString().Split(';');
                            if (Array.IndexOf(commonEncryptionCbcsProtocols, "Dash") > -1)
                            {
                                parameters.CommonEncryptionCbcs.EnabledProtocols.Dash = true;
                            }
                            if (Array.IndexOf(commonEncryptionCbcsProtocols, "Download") > -1)
                            {
                                parameters.CommonEncryptionCbcs.EnabledProtocols.Download = true;
                            }
                            if (Array.IndexOf(commonEncryptionCbcsProtocols, "Hls") > -1)
                            {
                                parameters.CommonEncryptionCbcs.EnabledProtocols.Hls = true;
                            }
                            if (Array.IndexOf(commonEncryptionCbcsProtocols, "SmoothStreaming") > -1)
                            {
                                parameters.CommonEncryptionCbcs.EnabledProtocols.SmoothStreaming = true;
                            }
                        }

                        // Common Encryption CENC Argument
                        if (data.cencClearTracks != null)
                        {
                            List <TrackSelection> tracks = JsonConvert.DeserializeObject <List <TrackSelection> >(data.cencClearTracks.ToString(), jsonReaders);
                            parameters.CommonEncryptionCenc.ClearTracks = tracks;
                        }
                        if (data.cencDefaultKeyLabel != null)
                        {
                            parameters.CommonEncryptionCenc.ContentKeys.DefaultKey.Label = data.cencDefaultKeyLabel;
                        }
                        if (data.cencDefaultKeyPolicyName != null)
                        {
                            parameters.CommonEncryptionCenc.ContentKeys.DefaultKey.PolicyName = data.cencDefaultKeyPolicyName;
                        }
                        if (data.cencClearTracks != null)
                        {
                            List <StreamingPolicyContentKey> mappings = JsonConvert.DeserializeObject <List <StreamingPolicyContentKey> >(data.cencKeyToTrackMappings.ToString(), jsonReaders);
                            parameters.CommonEncryptionCenc.ContentKeys.KeyToTrackMappings = mappings;
                        }
                        if (data.cencPlayReadyTemplate != null)
                        {
                            parameters.CommonEncryptionCenc.Drm.PlayReady.CustomLicenseAcquisitionUrlTemplate = data.cencPlayReadyTemplate;
                        }
                        if (data.cencPlayReadyAttributes != null)
                        {
                            parameters.CommonEncryptionCenc.Drm.PlayReady.PlayReadyCustomAttributes = data.cencPlayReadyAttributes;
                        }
                        if (data.cencWidevineTemplate != null)
                        {
                            parameters.CommonEncryptionCenc.Drm.Widevine.CustomLicenseAcquisitionUrlTemplate = data.cencWidevineTemplate;
                        }
                        if (data.cencProtocols != null)
                        {
                            String[] commonEncryptionCencProtocols = data.cencProtocols.ToString().Split(';');
                            if (Array.IndexOf(commonEncryptionCencProtocols, "Dash") > -1)
                            {
                                parameters.CommonEncryptionCenc.EnabledProtocols.Dash = true;
                            }
                            if (Array.IndexOf(commonEncryptionCencProtocols, "Download") > -1)
                            {
                                parameters.CommonEncryptionCenc.EnabledProtocols.Download = true;
                            }
                            if (Array.IndexOf(commonEncryptionCencProtocols, "Hls") > -1)
                            {
                                parameters.CommonEncryptionCenc.EnabledProtocols.Hls = true;
                            }
                            if (Array.IndexOf(commonEncryptionCencProtocols, "SmoothStreaming") > -1)
                            {
                                parameters.CommonEncryptionCenc.EnabledProtocols.SmoothStreaming = true;
                            }
                        }

                        // Envelope Encryption Argument
                        if (data.envelopeClearTracks != null || data.envelopeDefaultKeyLabel != null || data.envelopeDefaultKeyPolicyName != null ||
                            data.envelopeClearTracks || data.envelopeTemplate != null || data.envelopeTemplate != null || data.envelopeProtocols != null)
                        {
                            parameters.EnvelopeEncryption = new EnvelopeEncryption();
                            if (data.envelopeClearTracks != null)
                            {
                                List <TrackSelection> tracks = JsonConvert.DeserializeObject <List <TrackSelection> >(data.envelopeClearTracks.ToString(), jsonReaders);
                                parameters.EnvelopeEncryption.ClearTracks = tracks;
                            }

                            parameters.EnvelopeEncryption.ContentKeys            = new StreamingPolicyContentKeys();
                            parameters.EnvelopeEncryption.ContentKeys.DefaultKey = new DefaultKey(data.envelopeDefaultKeyLabel as string, data.envelopeDefaultKeyPolicyName as string);
                            if (data.envelopeClearTracks != null)
                            {
                                List <StreamingPolicyContentKey> mappings = JsonConvert.DeserializeObject <List <StreamingPolicyContentKey> >(data.envelopeKeyToTrackMappings.ToString(), jsonReaders);
                                parameters.EnvelopeEncryption.ContentKeys.KeyToTrackMappings = mappings;
                            }

                            if (data.envelopeTemplate != null)
                            {
                                parameters.EnvelopeEncryption.CustomKeyAcquisitionUrlTemplate = data.envelopeTemplate;
                            }
                            if (data.envelopeProtocols != null)
                            {
                                parameters.EnvelopeEncryption.EnabledProtocols = new EnabledProtocols();
                                String[] envelopeEncryptionProtocols = data.envelopeProtocols.ToString().Split(';');
                                if (Array.IndexOf(envelopeEncryptionProtocols, "Dash") > -1)
                                {
                                    parameters.EnvelopeEncryption.EnabledProtocols.Dash = true;
                                }
                                if (Array.IndexOf(envelopeEncryptionProtocols, "Download") > -1)
                                {
                                    parameters.EnvelopeEncryption.EnabledProtocols.Download = true;
                                }
                                if (Array.IndexOf(envelopeEncryptionProtocols, "Hls") > -1)
                                {
                                    parameters.EnvelopeEncryption.EnabledProtocols.Hls = true;
                                }
                                if (Array.IndexOf(envelopeEncryptionProtocols, "SmoothStreaming") > -1)
                                {
                                    parameters.EnvelopeEncryption.EnabledProtocols.SmoothStreaming = true;
                                }
                            }
                        }
                    }
                    else if (mode == "advanced")
                    {
                        NoEncryption         noEncryptionArguments         = null;
                        CommonEncryptionCbcs commonEncryptionCbcsArguments = null;
                        CommonEncryptionCenc commonEncryptionCencArguments = null;
                        EnvelopeEncryption   envelopeEncryptionArguments   = null;

                        if (data.jsonNoEncryption != null)
                        {
                            noEncryptionArguments = JsonConvert.DeserializeObject <NoEncryption>(data.configNoEncryption.ToString(), jsonReaders);
                        }
                        if (data.jsonCommonEncryptionCbcs != null)
                        {
                            commonEncryptionCbcsArguments = JsonConvert.DeserializeObject <CommonEncryptionCbcs>(data.jsonCommonEncryptionCbcs.ToString(), jsonReaders);
                        }
                        if (data.jsonCommonEncryptionCenc != null)
                        {
                            commonEncryptionCencArguments = JsonConvert.DeserializeObject <CommonEncryptionCenc>(data.jsonCommonEncryptionCenc.ToString(), jsonReaders);
                        }
                        if (data.jsonEnvelopeEncryption != null)
                        {
                            envelopeEncryptionArguments = JsonConvert.DeserializeObject <EnvelopeEncryption>(data.jsonEnvelopeEncryption.ToString(), jsonReaders);
                        }
                        parameters.NoEncryption         = noEncryptionArguments;
                        parameters.CommonEncryptionCbcs = commonEncryptionCbcsArguments;
                        parameters.CommonEncryptionCenc = commonEncryptionCencArguments;
                        parameters.EnvelopeEncryption   = envelopeEncryptionArguments;
                    }
                    parameters.Validate();
                    policy = client.StreamingPolicies.Create(amsconfig.ResourceGroup, amsconfig.AccountName, streamingPolicyName, parameters);
                }
            }
            catch (ApiErrorException e)
            {
                log.LogError($"ERROR: AMS API call failed with error code: {e.Body.Error.Code} and message: {e.Body.Error.Message}");
                return(new BadRequestObjectResult("AMS API call error: " + e.Message + "\nError Code: " + e.Body.Error.Code + "\nMessage: " + e.Body.Error.Message));
            }
            catch (Exception e)
            {
                log.LogError($"ERROR: Exception with message: {e.Message}");
                return(new BadRequestObjectResult("Error: " + e.Message));
            }

            return((ActionResult) new OkObjectResult(new
            {
                streamingPolicyName = streamingPolicyName,
                streamingPolicyId = policy.Id
            }));
        }