private void DoDynamicEncryptionWithAES(List<IAsset> SelectedAssets, AddDynamicEncryptionFrame1 form1, AddDynamicEncryptionFrame2_AESKeyConfig form2, AddDynamicEncryptionFrame3_AESDelivery form3_AES, List<AddDynamicEncryptionFrame4> form4list, bool DisplayUI)
        {
            bool ErrorCreationKey = false;
            string aeskey = string.Empty;
            bool firstkeycreation = true;
            Uri aeslaurl = null;
            IContentKey formerkey = null;
            bool reusekey = false;

            if (!form2.ContentKeyRandomGeneration)
            {
                aeskey = form2.AESContentKey;
                aeslaurl = form3_AES.AESLaUrl;
            }


            if (!form2.ContentKeyRandomGeneration && (form2.AESKeyId != null))  // user want to manually enter the cryptography data and key if providedd 
            {
                // if the key already exists in the account (same key id), let's 
                formerkey = SelectedAssets.FirstOrDefault().GetMediaContext().ContentKeys.Where(c => c.Id == Constants.ContentKeyIdPrefix + form2.AESKeyId.ToString()).FirstOrDefault();
                if (formerkey != null)
                {
                    if (DisplayUI && MessageBox.Show("A Content key with the same Key Id exists already in the account.\nDo you want to try to replace it?\n(If not, the existing key will be used)", "Content key Id", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        // user wants to replace the key
                        try
                        {
                            formerkey.Delete();
                        }
                        catch (Exception e)
                        {
                            // Add useful information to the exception
                            TextBoxLogWriteLine("There is a problem when deleting the content key {0}.", formerkey.Id, true);
                            TextBoxLogWriteLine(e);
                            TextBoxLogWriteLine("The former key will be reused.", true);
                            reusekey = true;
                        }
                    }
                    else
                    {
                        reusekey = true;
                    }
                }
            }



            foreach (IAsset AssetToProcess in SelectedAssets)
            {

                if (AssetToProcess != null)
                {
                    IContentKey contentKey = null;

                    var contentkeys = AssetToProcess.ContentKeys.Where(c => c.ContentKeyType == form1.GetContentKeyType);

                    if (contentkeys.Count() == 0) // no content key existing so we need to create one
                    {
                        ErrorCreationKey = false;


                        if (form3_AES.GetNumberOfAuthorizationPolicyOptions > 0 && (form2.ContentKeyRandomGeneration))
                        // Azure will deliver the license and user want to auto generate the key, so we can create a key with a random content key
                        {
                            try
                            {
                                contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess);
                            }
                            catch (Exception e)
                            {
                                // Add useful information to the exception
                                TextBoxLogWriteLine("There is a problem when creating the content key for '{0}'.", AssetToProcess.Name, true);
                                TextBoxLogWriteLine(e);
                                ErrorCreationKey = true;
                            }
                            if (!ErrorCreationKey)
                            {
                                TextBoxLogWriteLine("Created key {0} for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                            }
                        }
                        else // user wants to deliver with an external key server or want to provide some cryptography, so let's create the key based on what the user input
                        {
                            if ((firstkeycreation && !reusekey) || form2.AESKeyId == null) // if we need to generate a new key id for each asset
                            {
                                try
                                {
                                    if ((!form2.ContentKeyRandomGeneration) && !string.IsNullOrEmpty(aeskey)) // user provides custom crypto (key, or key id)
                                    {
                                        contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess, Convert.FromBase64String(aeskey), form2.AESKeyId);
                                    }
                                    else // content key if random. Perhaps key id has been provided
                                    {
                                        contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess, form2.AESKeyId);
                                    }
                                }
                                catch (Exception e)
                                {
                                    // Add useful information to the exception
                                    TextBoxLogWriteLine("There is a problem when creating the content key for asset '{0}'.", AssetToProcess.Name, true);
                                    TextBoxLogWriteLine(e);
                                    ErrorCreationKey = true;
                                }
                                if (!ErrorCreationKey)
                                {
                                    TextBoxLogWriteLine("Created key {0} for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                                }

                                formerkey = contentKey;
                                firstkeycreation = false;
                            }
                            else
                            {
                                contentKey = formerkey;
                                AssetToProcess.ContentKeys.Add(contentKey);
                                AssetToProcess.Update();
                                TextBoxLogWriteLine("Reusing key {0} for the asset {1} ", contentKey.Id, AssetToProcess.Name);
                            }
                        }

                    }
                    else if (form3_AES.GetNumberOfAuthorizationPolicyOptions == 0)  // user wants to deliver with an external key server but the key exists already !
                    {
                        TextBoxLogWriteLine("Warning for asset '{0}'. A AES key already exists. You need to make sure that your external key server can deliver the key for this asset.", AssetToProcess.Name, true);
                    }

                    else // let's use existing content key
                    {
                        contentKey = contentkeys.FirstOrDefault();
                        TextBoxLogWriteLine("Existing key {0} will be used for asset {1}.", contentKey.Id, AssetToProcess.Name);
                    }


                    if (form3_AES.GetNumberOfAuthorizationPolicyOptions > 0) // AES Key and delivery from Azure Media Services
                    {

                        // let's create the Authorization Policy
                        IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                       ContentKeyAuthorizationPolicies.
                                       CreateAsync("Authorization Policy").Result;

                        // Associate the content key authorization policy with the content key.
                        contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
                        contentKey = contentKey.UpdateAsync().Result;


                        foreach (var form3 in form4list)
                        {
                            IContentKeyAuthorizationPolicyOption policyOption = null;
                            ErrorCreationKey = false;
                            try
                            {
                                switch (form3.GetKeyRestrictionType)
                                {
                                    case ContentKeyRestrictionType.Open:

                                        policyOption = DynamicEncryption.AddOpenAuthorizationPolicyOption(contentKey, ContentKeyDeliveryType.BaselineHttp, null, _context);
                                        TextBoxLogWriteLine("Created Open authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                        contentKeyAuthorizationPolicy.Options.Add(policyOption);
                                        break;

                                    case ContentKeyRestrictionType.TokenRestricted:
                                        TokenVerificationKey mytokenverifkey = null;
                                        string OpenIdDoc = null;
                                        switch (form3.GetDetailedTokenType)
                                        {
                                            case ExplorerTokenType.SWT:
                                            case ExplorerTokenType.JWTSym:
                                                mytokenverifkey = new SymmetricVerificationKey(Convert.FromBase64String(form3.SymmetricKey));
                                                break;

                                            case ExplorerTokenType.JWTOpenID:
                                                OpenIdDoc = form3.GetOpenIdDiscoveryDocument;
                                                break;

                                            case ExplorerTokenType.JWTX509:
                                                mytokenverifkey = new X509CertTokenVerificationKey(form3.GetX509Certificate);
                                                break;
                                        }

                                        policyOption = DynamicEncryption.AddTokenRestrictedAuthorizationPolicyAES(contentKey, form3.GetAudience, form3.GetIssuer, form3.GetTokenRequiredClaims, form3.AddContentKeyIdentifierClaim, form3.GetTokenType, form3.GetDetailedTokenType, mytokenverifkey, _context, OpenIdDoc);
                                        TextBoxLogWriteLine("Created Token AES authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                        contentKeyAuthorizationPolicy.Options.Add(policyOption);

                                        if (form3.GetDetailedTokenType != ExplorerTokenType.JWTOpenID) // not possible to create a test token if OpenId is used
                                        {
                                            // let display a test token
                                            X509SigningCredentials signingcred = null;
                                            if (form3.GetDetailedTokenType == ExplorerTokenType.JWTX509)
                                            {
                                                signingcred = new X509SigningCredentials(form3.GetX509Certificate);
                                            }

                                            _context = Program.ConnectAndGetNewContext(_credentials); // otherwise cache issues with multiple options
                                            DynamicEncryption.TokenResult testToken = DynamicEncryption.GetTestToken(AssetToProcess, _context, form1.GetContentKeyType, signingcred, policyOption.Id);
                                            TextBoxLogWriteLine("The authorization test token for option #{0} ({1} with Bearer) is:\n{2}", form4list.IndexOf(form3), form3.GetTokenType.ToString(), Constants.Bearer + testToken.TokenString);
                                            System.Windows.Forms.Clipboard.SetText(Constants.Bearer + testToken.TokenString);

                                        }
                                        break;

                                    default:
                                        break;
                                }
                            }
                            catch (Exception e)
                            {
                                // Add useful information to the exception
                                TextBoxLogWriteLine("There is a problem when creating the authorization policy for '{0}'.", AssetToProcess.Name, true);
                                TextBoxLogWriteLine(e);
                                ErrorCreationKey = true;
                            }

                        }
                        contentKeyAuthorizationPolicy.Update();
                    }

                    // Let's create the Asset Delivery Policy now
                    IAssetDeliveryPolicy DelPol = null;
                    string name = string.Format("AssetDeliveryPolicy {0} ({1})", form1.GetContentKeyType.ToString(), form1.GetAssetDeliveryProtocol.ToString());

                    try
                    {
                        DelPol = DynamicEncryption.CreateAssetDeliveryPolicyAES(AssetToProcess, contentKey, form1.GetAssetDeliveryProtocol, name, _context, aeslaurl);
                        TextBoxLogWriteLine("Created asset delivery policy {0} for asset {1}.", DelPol.AssetDeliveryPolicyType, AssetToProcess.Name);
                    }
                    catch (Exception e)
                    {
                        TextBoxLogWriteLine("There is a problem when creating the delivery policy for '{0}'.", AssetToProcess.Name, true);
                        TextBoxLogWriteLine(e);
                    }
                }
            }
        }
        private void DoDynamicEncryptionWithAES(List<IAsset> SelectedAssets, AddDynamicEncryptionFrame1 form1, AddDynamicEncryptionFrame2_AESKeyConfig form2, List<AddDynamicEncryptionFrame3> form3list)
        {
            bool Error = false;
            string aeskey = string.Empty;
            if (!form2.ContentKeyRandomGeneration)
            {
                aeskey = form2.AESContentKey;
            }

            foreach (IAsset AssetToProcess in SelectedAssets)
            {

                if (AssetToProcess != null)
                {
                    IContentKey contentKey = null;

                    var contentkeys = AssetToProcess.ContentKeys.Where(c => c.ContentKeyType == form1.GetContentKeyType);
                    if (contentkeys.Count() == 0) // no content key existing so we need to create one
                    {
                        Error = false;
                        try
                        {
                            if ((!form2.ContentKeyRandomGeneration) && !string.IsNullOrEmpty(aeskey)) // user has to provide the key
                            {
                                contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess, Convert.FromBase64String(aeskey));
                            }
                            else
                            {
                                contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess);
                            }
                        }
                        catch (Exception e)
                        {
                            // Add useful information to the exception
                            TextBoxLogWriteLine("There is a problem when creating the content key for '{0}'.", AssetToProcess.Name, true);
                            TextBoxLogWriteLine(e);
                            Error = true;
                        }
                        if (!Error)
                        {
                            TextBoxLogWriteLine("Created key {0} for the asset {1} ", contentKey.Id, AssetToProcess.Name);
                        }

                    }

                    else // let's use existing content key
                    {
                        contentKey = contentkeys.FirstOrDefault();
                        TextBoxLogWriteLine("Existing key {0} will be used for asset {1}.", contentKey.Id, AssetToProcess.Name);
                    }


                    // let's create the Authorization Policy
                    IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                   ContentKeyAuthorizationPolicies.
                                   CreateAsync("My Authorization Policy").Result;

                    // Associate the content key authorization policy with the content key.
                    contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
                    contentKey = contentKey.UpdateAsync().Result;


                    foreach (var form3 in form3list)
                    {
                        IContentKeyAuthorizationPolicyOption policyOption = null;
                        Error = false;
                        try
                        {
                            switch (form3.GetKeyRestrictionType)
                            {
                                case ContentKeyRestrictionType.Open:

                                    policyOption = DynamicEncryption.AddOpenAuthorizationPolicyOption(contentKey, ContentKeyDeliveryType.BaselineHttp, null, _context);
                                    TextBoxLogWriteLine("Created Open authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                    contentKeyAuthorizationPolicy.Options.Add(policyOption);
                                    break;

                                case ContentKeyRestrictionType.TokenRestricted:
                                    TokenVerificationKey mytokenverifkey = null;
                                    string OpenIdDoc = null;
                                    switch (form3.GetDetailedTokenType)
                                    {
                                        case ExplorerTokenType.SWT:
                                        case ExplorerTokenType.JWTSym:
                                            mytokenverifkey = new SymmetricVerificationKey(Convert.FromBase64String(form3.SymmetricKey));
                                            break;

                                        case ExplorerTokenType.JWTOpenID:
                                            OpenIdDoc = form3.GetOpenIdDiscoveryDocument;
                                            break;

                                        case ExplorerTokenType.JWTX509:
                                            mytokenverifkey = new X509CertTokenVerificationKey(form3.GetX509Certificate);
                                            break;
                                    }

                                    policyOption = DynamicEncryption.AddTokenRestrictedAuthorizationPolicyAES(contentKey, form3.GetAudience, form3.GetIssuer, form3.GetTokenRequiredClaims, form3.AddContentKeyIdentifierClaim, form3.GetTokenType, form3.GetDetailedTokenType, mytokenverifkey, _context, OpenIdDoc);
                                    TextBoxLogWriteLine("Created Token AES authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                    contentKeyAuthorizationPolicy.Options.Add(policyOption);

                                    if (form3.GetDetailedTokenType != ExplorerTokenType.JWTOpenID) // not possible to create a test token if OpenId is used
                                    {
                                        // let display a test token
                                        X509SigningCredentials signingcred = null;
                                        if (form3.GetDetailedTokenType == ExplorerTokenType.JWTX509)
                                        {
                                            signingcred = new X509SigningCredentials(form3.GetX509Certificate);
                                        }

                                        _context = Program.ConnectAndGetNewContext(_credentials); // otherwise cache issues with multiple options
                                        DynamicEncryption.TokenResult testToken = DynamicEncryption.GetTestToken(AssetToProcess, _context, form1.GetContentKeyType, signingcred, policyOption.Id);
                                        TextBoxLogWriteLine("The authorization test token for option #{0} ({1} with Bearer) is:\n{2}", form3list.IndexOf(form3), form3.GetTokenType.ToString(), Constants.Bearer + testToken.TokenString);
                                        System.Windows.Forms.Clipboard.SetText(Constants.Bearer + testToken.TokenString);

                                    }
                                    break;

                                default:
                                    break;
                            }
                        }
                        catch (Exception e)
                        {
                            // Add useful information to the exception
                            TextBoxLogWriteLine("There is a problem when creating the authorization policy for '{0}'.", AssetToProcess.Name, true);
                            TextBoxLogWriteLine(e);
                            Error = true;
                        }

                    }
                    contentKeyAuthorizationPolicy.Update();

                    // Let's create the Asset Delivery Policy now
                    IAssetDeliveryPolicy DelPol = null;
                    string name = string.Format("AssetDeliveryPolicy {0} ({1})", form1.GetContentKeyType.ToString(), form1.GetAssetDeliveryProtocol.ToString());

                    try
                    {
                        DelPol = DynamicEncryption.CreateAssetDeliveryPolicyAES(AssetToProcess, contentKey, form1.GetAssetDeliveryProtocol, name, _context);
                        TextBoxLogWriteLine("Created asset delivery policy {0} for asset {1}.", DelPol.AssetDeliveryPolicyType, AssetToProcess.Name);
                    }
                    catch (Exception e)
                    {
                        TextBoxLogWriteLine("There is a problem when creating the delivery policy for '{0}'.", AssetToProcess.Name, true);
                        TextBoxLogWriteLine(e);
                    }
                }
            }
        }
        private bool SetupDynamicEncryption(List<IAsset> SelectedAssets, bool forceusertoprovidekey)
        {
            if (SelectedAssets.Count == 0) return false;

            string labelAssetName;
            bool oktoproceed = false;

            // check if assets are published
            var publishedAssets = SelectedAssets.Where(a => a.Locators.Count > 0).ToList();
            if (publishedAssets.Count > 0)
            {
                if (MessageBox.Show("Some selected asset(s) are published.\nYou need to unpublish them before doing any dynamic encryption change.\n\nOk to unpublish (delete locators) ?", "Published assets", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DoDeleteAllLocatorsOnAssets(publishedAssets, true);
                }
                else
                {
                    return false;
                }
            }



            labelAssetName = "Dynamic encryption will be applied for Asset '" + SelectedAssets.FirstOrDefault().Name + "'.";
            if (SelectedAssets.Count > 1)
            {
                labelAssetName = "Dynamic encryption will applied to the " + SelectedAssets.Count.ToString() + " selected assets.";
            }
            AddDynamicEncryptionFrame1 form1 = new AddDynamicEncryptionFrame1(_context);

            if (form1.ShowDialog() == DialogResult.OK)
            {

                switch (form1.GetDeliveryPolicyType)
                {
                    ///////////////////////////////////////////// CENC Dynamic Encryption
                    case AssetDeliveryPolicyType.DynamicCommonEncryption:
                    case AssetDeliveryPolicyType.None: // in that case, user want to configure license delivery on an asset already encrypted

                        AddDynamicEncryptionFrame2_CENCKeyConfig form2_CENC = new AddDynamicEncryptionFrame2_CENCKeyConfig(

                            forceusertoprovidekey)
                        //  !NeedToDisplayPlayReadyLicense,
                        // ((form1.GetAssetDeliveryProtocol & AssetDeliveryProtocol.Dash) == AssetDeliveryProtocol.Dash) && (form1.GetDeliveryPolicyType == AssetDeliveryPolicyType.DynamicCommonEncryption))
                        { Left = form1.Left, Top = form1.Top };
                        if (form2_CENC.ShowDialog() == DialogResult.OK)
                        {
                            var form3_CENC = new AddDynamicEncryptionFrame3_CENCDelivery(_context, form1.PlayReadyPackaging, form1.WidevinePackaging);
                            if (form3_CENC.ShowDialog() == DialogResult.OK)
                            {
                                bool NeedToDisplayPlayReadyLicense = form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady > 0;
                                bool NeedToDisplayWidevineLicense = form3_CENC.GetNumberOfAuthorizationPolicyOptionsWidevine > 0;

                                List<AddDynamicEncryptionFrame4> form4list = new List<AddDynamicEncryptionFrame4>();
                                List<AddDynamicEncryptionFrame5_PlayReadyLicense> form5list = new List<AddDynamicEncryptionFrame5_PlayReadyLicense>();
                                List<AddDynamicEncryptionFrame6_WidevineLicense> form6list = new List<AddDynamicEncryptionFrame6_WidevineLicense>();

                                bool usercancelledform4or5 = false;
                                bool usercancelledform4or6 = false;

                                int step = 3;
                                string tokensymmetrickey = null;
                                for (int i = 0; i < form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady; i++)
                                {
                                    AddDynamicEncryptionFrame4 form4 = new AddDynamicEncryptionFrame4(_context, step, i + 1, "PlayReady", tokensymmetrickey, false) { Left = form2_CENC.Left, Top = form2_CENC.Top };

                                    if (form4.ShowDialog() == DialogResult.OK)
                                    {
                                        step++;
                                        form4list.Add(form4);
                                        tokensymmetrickey = form4.SymmetricKey;
                                        AddDynamicEncryptionFrame5_PlayReadyLicense form5_PlayReadyLicense = new AddDynamicEncryptionFrame5_PlayReadyLicense(step, i + 1, i == (form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady - 1)) { Left = form3_CENC.Left, Top = form3_CENC.Top };
                                        //AddDynamicEncryptionFrame6_WidevineLicense form6_WidevineLicense = new AddDynamicEncryptionFrame6_WidevineLicense(step, i + 1, i == (form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady - 1)) { Left = form3_CENC.Left, Top = form3_CENC.Top };
                                        step++;
                                        if (NeedToDisplayPlayReadyLicense) // it's a PlayReady license and user wants to deliver the license from Azure Media Services
                                        {
                                            if (form5_PlayReadyLicense.ShowDialog() == DialogResult.OK) // let's display the dialog box to configure the playready license
                                            {
                                                form5list.Add(form5_PlayReadyLicense);
                                            }
                                            else
                                            {
                                                usercancelledform4or5 = true;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        usercancelledform4or5 = true;
                                    }
                                }

                                // widevine
                                for (int i = 0; i < form3_CENC.GetNumberOfAuthorizationPolicyOptionsWidevine; i++)
                                {
                                    AddDynamicEncryptionFrame4 form4 = new AddDynamicEncryptionFrame4(_context, step, i + 1, "Widevine", tokensymmetrickey, false) { Left = form2_CENC.Left, Top = form2_CENC.Top };

                                    if (form4.ShowDialog() == DialogResult.OK)
                                    {
                                        step++;
                                        form4list.Add(form4);
                                        tokensymmetrickey = form4.SymmetricKey;
                                        AddDynamicEncryptionFrame6_WidevineLicense form6_WidevineLicense = new AddDynamicEncryptionFrame6_WidevineLicense(Constants.TemporaryWidevineLicenseServer, step, i + 1, i == (form3_CENC.GetNumberOfAuthorizationPolicyOptionsWidevine - 1)) { Left = form3_CENC.Left, Top = form3_CENC.Top };
                                        step++;

                                        if (form6_WidevineLicense.ShowDialog() == DialogResult.OK) // let's display the dialog box to configure the playready license
                                        {
                                            form6list.Add(form6_WidevineLicense);
                                        }
                                        else
                                        {
                                            usercancelledform4or6 = true;
                                        }
                                    }
                                    else
                                    {
                                        usercancelledform4or6 = true;
                                    }
                                }
                                if (!usercancelledform4or5 && !usercancelledform4or6)
                                {
                                    DoDynamicEncryptionAndKeyDeliveryWithCENC(SelectedAssets, form1, form2_CENC, form3_CENC, form4list, form5list, form6list, true);
                                    oktoproceed = true;
                                    dataGridViewAssetsV.PurgeCacheAssets(SelectedAssets);
                                    dataGridViewAssetsV.AnalyzeItemsInBackground();
                                }
                            }
                        }
                        break;

                    ///////////////////////////////////////////// AES Dynamic Encryption
                    case AssetDeliveryPolicyType.DynamicEnvelopeEncryption:
                        AddDynamicEncryptionFrame2_AESKeyConfig form2_AES =
                            new AddDynamicEncryptionFrame2_AESKeyConfig(forceusertoprovidekey) { Left = form1.Left, Top = form1.Top };
                        if (form2_AES.ShowDialog() == DialogResult.OK)
                        {
                            var form3_AES = new AddDynamicEncryptionFrame3_AESDelivery(_context);
                            if (form3_AES.ShowDialog() == DialogResult.OK)
                            {
                                List<AddDynamicEncryptionFrame4> form4list = new List<AddDynamicEncryptionFrame4>();
                                bool usercancelledform4 = false;
                                string tokensymmetrickey = null;
                                for (int i = 0; i < form3_AES.GetNumberOfAuthorizationPolicyOptions; i++)
                                {
                                    AddDynamicEncryptionFrame4 form4 = new AddDynamicEncryptionFrame4(_context, i + 3, i + 1, "AES", tokensymmetrickey, true) { Left = form2_AES.Left, Top = form2_AES.Top };
                                    if (form4.ShowDialog() == DialogResult.OK)
                                    {
                                        form4list.Add(form4);
                                        tokensymmetrickey = form4.SymmetricKey;
                                    }
                                    else
                                    {
                                        usercancelledform4 = true;
                                    }
                                }

                                if (!usercancelledform4)
                                {
                                    DoDynamicEncryptionWithAES(SelectedAssets, form1, form2_AES, form3_AES, form4list, true);
                                    oktoproceed = true;
                                    dataGridViewAssetsV.PurgeCacheAssets(SelectedAssets);
                                    dataGridViewAssetsV.AnalyzeItemsInBackground();
                                }
                            }
                        }
                        break;

                    ///////////////////////////////////////////// Decrypt storage protected content
                    case AssetDeliveryPolicyType.NoDynamicEncryption:
                        AddDynDecryption(SelectedAssets, form1, _context);
                        oktoproceed = true;
                        dataGridViewAssetsV.PurgeCacheAssets(SelectedAssets);
                        dataGridViewAssetsV.AnalyzeItemsInBackground();
                        break;

                    default:
                        break;

                }
            }

            return oktoproceed;
        }
        private bool SetupDynamicEncryption(List<IAsset> SelectedAssets, bool forceusertoprovidekey)
        {
            string labelAssetName;
            bool oktoproceed = false;
            if (SelectedAssets.Count > 0)
            {
                labelAssetName = "Dynamic encryption will be applied for Asset '" + SelectedAssets.FirstOrDefault().Name + "'.";
                if (SelectedAssets.Count > 1)
                {
                    labelAssetName = "Dynamic encryption will applied to the " + SelectedAssets.Count.ToString() + " selected assets.";
                }
                AddDynamicEncryptionFrame1 form1 = new AddDynamicEncryptionFrame1(_context);

                if (form1.ShowDialog() == DialogResult.OK)
                {

                    switch (form1.GetDeliveryPolicyType)
                    {
                        ///////////////////////////////////////////// CENC Dynamic Encryption
                        case AssetDeliveryPolicyType.DynamicCommonEncryption:
                        case AssetDeliveryPolicyType.None: // in that case, user want to configure license delivery on an asset already encrypted
                            bool NeedToDisplayPlayReadyLicense = form1.GetNumberOfAuthorizationPolicyOptions > 0;
                            AddDynamicEncryptionFrame2_PlayReadyKeyConfig form2_PlayReady = new AddDynamicEncryptionFrame2_PlayReadyKeyConfig(
                                SelectedAssets.Count > 1, form1.GetNumberOfAuthorizationPolicyOptions > 0, forceusertoprovidekey || (form1.GetNumberOfAuthorizationPolicyOptions == 0), !NeedToDisplayPlayReadyLicense) { Left = form1.Left, Top = form1.Top };
                            if (form2_PlayReady.ShowDialog() == DialogResult.OK)
                            {
                                List<AddDynamicEncryptionFrame3> form3list = new List<AddDynamicEncryptionFrame3>();
                                List<AddDynamicEncryptionFrame4_PlayReadyLicense> form4list = new List<AddDynamicEncryptionFrame4_PlayReadyLicense>();
                                bool usercancelledform3or4 = false;
                                int step = 3;
                                string tokensymmetrickey = null;
                                for (int i = 0; i < form1.GetNumberOfAuthorizationPolicyOptions; i++)
                                {
                                    AddDynamicEncryptionFrame3 form3 = new AddDynamicEncryptionFrame3(_context, step, i + 1, tokensymmetrickey, !NeedToDisplayPlayReadyLicense) { Left = form2_PlayReady.Left, Top = form2_PlayReady.Top };
                                    if (form3.ShowDialog() == DialogResult.OK)
                                    {
                                        step++;
                                        form3list.Add(form3);
                                        tokensymmetrickey = form3.SymmetricKey;
                                        AddDynamicEncryptionFrame4_PlayReadyLicense form4_PlayReadyLicense = new AddDynamicEncryptionFrame4_PlayReadyLicense(step, i + 1, i == (form1.GetNumberOfAuthorizationPolicyOptions - 1)) { Left = form3.Left, Top = form3.Top };
                                        if (NeedToDisplayPlayReadyLicense) // it's a PlayReady license and user wants to deliver the license from Azure Media Services
                                        {
                                            step++;
                                            if (form4_PlayReadyLicense.ShowDialog() == DialogResult.OK) // let's display the dialog box to configure the playready license
                                            {
                                                form4list.Add(form4_PlayReadyLicense);
                                            }
                                            else
                                            {
                                                usercancelledform3or4 = true;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        usercancelledform3or4 = true;
                                    }
                                }
                                if (!usercancelledform3or4)
                                {
                                    DoDynamicEncryptionAndKeyDeliveryWithPlayReady(SelectedAssets, form1, form2_PlayReady, form3list, form4list, true);
                                    oktoproceed = true;
                                    dataGridViewAssetsV.AnalyzeItemsInBackground();
                                }
                            }
                            break;

                        ///////////////////////////////////////////// AES Dynamic Encryption
                        case AssetDeliveryPolicyType.DynamicEnvelopeEncryption:
                            AddDynamicEncryptionFrame2_AESKeyConfig form2_AES = new AddDynamicEncryptionFrame2_AESKeyConfig(forceusertoprovidekey) { Left = form1.Left, Top = form1.Top };
                            if (form2_AES.ShowDialog() == DialogResult.OK)
                            {
                                List<AddDynamicEncryptionFrame3> form3list = new List<AddDynamicEncryptionFrame3>();
                                bool usercancelledform3 = false;
                                string tokensymmetrickey = null;
                                for (int i = 0; i < form1.GetNumberOfAuthorizationPolicyOptions; i++)
                                {
                                    AddDynamicEncryptionFrame3 form3 = new AddDynamicEncryptionFrame3(_context, i + 3, i + 1, tokensymmetrickey, true) { Left = form2_AES.Left, Top = form2_AES.Top };
                                    if (form3.ShowDialog() == DialogResult.OK)
                                    {
                                        form3list.Add(form3);
                                        tokensymmetrickey = form3.SymmetricKey;
                                    }
                                    else
                                    {
                                        usercancelledform3 = true;
                                    }
                                }

                                if (!usercancelledform3)
                                {
                                    DoDynamicEncryptionWithAES(SelectedAssets, form1, form2_AES, form3list);
                                    oktoproceed = true;
                                    dataGridViewAssetsV.AnalyzeItemsInBackground();
                                }
                            }
                            break;

                        ///////////////////////////////////////////// Decrypt storage protected content
                        case AssetDeliveryPolicyType.NoDynamicEncryption:
                            AddDynDecryption(SelectedAssets, form1, _context);
                            oktoproceed = true;
                            dataGridViewAssetsV.AnalyzeItemsInBackground();
                            break;

                        default:
                            break;

                    }

                }
            }


            return oktoproceed;
        }