/// <summary>
        /// Deserializes a string containing an Xml representation of a PlayReadyLicenseResponseTemplate
        /// back into a PlayReadyLicenseResponseTemplate class instance.
        /// </summary>
        /// <param name="templateXml">Contains the Xml representation of a PlayReadyLicenseResponseTemplate</param>
        /// <returns></returns>
        public static PlayReadyLicenseResponseTemplate Deserialize(string templateXml)
        {
            PlayReadyLicenseResponseTemplate templateToReturn = null;
            DataContractSerializer           serializer       = GetSerializer();

            StringReader stringReader = null;
            XmlReader    reader       = null;

            try
            {
                stringReader = new StringReader(templateXml);

                reader = XmlReader.Create(stringReader);

                templateToReturn = (PlayReadyLicenseResponseTemplate)serializer.ReadObject(reader);
            }
            finally
            {
                if (reader != null)
                {
                    // This will close the underlying StringReader instance
                    reader.Close();
                }
                else if (stringReader != null)
                {
                    stringReader.Close();
                }
            }

            ValidateLicenseResponseTemplate(templateToReturn);

            return(templateToReturn);
        }
        /// <summary>
        /// Serializes a PlayReadyLicenseResponseTemplate to a string containing an xml representation of
        /// the license response template.
        /// </summary>
        /// <param name="responseTemplate">The PlayReadyLicenseResponseTemplate instance to serialize to a string.</param>
        /// <returns></returns>
        public static string Serialize(PlayReadyLicenseResponseTemplate responseTemplate)
        {
            ValidateLicenseResponseTemplate(responseTemplate);

            DataContractSerializer serializer = GetSerializer();

            return SerializeToXml(responseTemplate, serializer);
        }
        /// <summary>
        /// Serializes a PlayReadyLicenseResponseTemplate to a string containing an xml representation of
        /// the license response template.
        /// </summary>
        /// <param name="responseTemplate">The PlayReadyLicenseResponseTemplate instance to serialize to a string.</param>
        /// <returns></returns>
        public static string Serialize(PlayReadyLicenseResponseTemplate responseTemplate)
        {
            ValidateLicenseResponseTemplate(responseTemplate);

            DataContractSerializer serializer = GetSerializer();

            return(SerializeToXml(responseTemplate, serializer));
        }
        public void DigitalVideoOnlyContentRestrictionAndAllowPassingVideoContentToUnknownOutputMutuallyExclusive()
        {
            string serializedTemplate = null;
            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();
            responseTemplate.LicenseTemplates.Add(licenseTemplate);

            // Part 1: Make sure we cannot set DigitalVideoOnlyContentRestriction to true if
            //         UnknownOutputPassingOption.Allowed is set
            licenseTemplate.PlayRight.AllowPassingVideoContentToUnknownOutput = UnknownOutputPassingOption.Allowed;
            licenseTemplate.PlayRight.DigitalVideoOnlyContentRestriction = true;

            try
            {
                serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
                Assert.Fail("Expected ArgumentException");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual(ErrorMessages.DigitalVideoOnlyMutuallyExclusiveWithPassingToUnknownOutputError, ae.Message);
            }

            // Part 2: Make sure we cannot set UnknownOutputPassingOption.AllowedWithVideoConstriction
            //         if DigitalVideoOnlyContentRestriction is true
            licenseTemplate.PlayRight.AllowPassingVideoContentToUnknownOutput = UnknownOutputPassingOption.AllowedWithVideoConstriction;

            try
            {
                serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
                Assert.Fail("Expected ArgumentException");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual(ErrorMessages.DigitalVideoOnlyMutuallyExclusiveWithPassingToUnknownOutputError, ae.Message);
            }

            // Part 3: Make sure we can set DigitalVideoOnlyContentRestriction to true if
            //         UnknownOutputPassingOption.NotAllowed is set
            licenseTemplate.PlayRight.AllowPassingVideoContentToUnknownOutput = UnknownOutputPassingOption.NotAllowed;
            licenseTemplate.PlayRight.DigitalVideoOnlyContentRestriction = true;

            serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
            Assert.IsNotNull(serializedTemplate);

            Assert.IsNotNull(MediaServicesLicenseTemplateSerializer.Deserialize(serializedTemplate));
        }
        public void ContentKeyAuthorizationPolicyOptionTestEnumQuery()
        {
            var policyOptions = _mediaContext.ContentKeyAuthorizationPolicyOptions;

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());

            string optionName = "integrationtest-crud-746";
            string requirements = null;
            string configuration = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
            ContentKeyRestrictionType restrictionType = ContentKeyRestrictionType.Open;

            IContentKeyAuthorizationPolicyOption option = CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.PlayReadyLicense, requirements, configuration, restrictionType);

            var ok = policyOptions.Where(o => o.KeyDeliveryType == ContentKeyDeliveryType.PlayReadyLicense).AsEnumerable().Any();

            Assert.IsTrue(ok, "Can not find option by DeliveryType");
        }
        public void AddingOptionsToCreatedPolicy()
        {
            string optionName = "AddingOptionsToCreatedPolicy Test Option";

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());

            TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);
            tokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(); // the default constructor automatically generates a random key
            tokenRestrictionTemplate.Audience = "urn:someaudience";
            tokenRestrictionTemplate.Issuer = "http://someissuerurl";

            string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
            string configuration = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);

            ContentKeyRestrictionType restrictionType = ContentKeyRestrictionType.TokenRestricted;

            IContentKeyAuthorizationPolicy policy = _mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(testRun).Result;
            var option1 = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.PlayReadyLicense, requirements, configuration, restrictionType);
            policy.Options.Add(option1);
        }
        public static void ClassInit(TestContext context)
        {
            CreateCounters();
            InitilizeChallenges();
            _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();
            IContentKeyAuthorizationPolicyOption policyOption = null;

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());
            string licenseTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _mediaContext.ContentKeyAuthorizationPolicies.CreateAsync("PerfTest"+Guid.NewGuid().ToString()).Result;

            policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty,
                ContentKeyDeliveryType.PlayReadyLicense, null, licenseTemplate, ContentKeyRestrictionType.Open);
            contentKeyAuthorizationPolicy.Options.Add(policyOption);

            foreach (var tuple in _keys)
            {
                IContentKey contentKey =
                _mediaContext.ContentKeys.Where(c => c.Id == tuple.Item1)
                    .FirstOrDefault();
                if (contentKey != null)
                {
                    contentKey.Delete();

                }
                contentKey = GetKeyDeliveryUrlTests.CreateTestKeyWithSpecified(tuple.Item1,
                   _mediaContext, ContentKeyType.CommonEncryption);

                // Associate the content key authorization policy with the content key
                contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
                contentKey = contentKey.UpdateAsync().Result;
                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);
                Assert.IsNotNull(keyDeliveryServiceUri);
                _testData.Add(new Tuple<Uri, string>(keyDeliveryServiceUri, contentKey.Id));
            }
        }
        public void RoundTripTestErrorWithRelativeExpirationDateExpirationDate()
        {
            try
            {
                PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
                responseTemplate.ResponseCustomData = "This is my response custom data";
                PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();
                responseTemplate.LicenseTemplates.Add(licenseTemplate);

                licenseTemplate.LicenseType = PlayReadyLicenseType.Persistent;
                licenseTemplate.RelativeExpirationDate = TimeSpan.FromHours(1);
                licenseTemplate.ExpirationDate = DateTime.Now.AddHours(1);

                string serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
                Assert.Fail();
            }
            catch (ArgumentException ae)
            {
                Assert.IsTrue(ae.Message.Contains(ErrorMessages.ExpirationDateAndRelativeExpirationDateCannotbeSetSimultaneouslyError));
                throw;
            }
        }
        public void SetupTest()
        {
            _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());

            TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);
            tokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(); // the default constructor automatically generates a random key
            tokenRestrictionTemplate.Audience = "http://sampleIssuerUrl";
            tokenRestrictionTemplate.Issuer = "http://sampleAudience";

            string optionName = "integrationtest-crud-749";
            string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
            string configuration = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
            ContentKeyRestrictionType restrictionType = ContentKeyRestrictionType.TokenRestricted;

            _testOption = CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.PlayReadyLicense, requirements, configuration, restrictionType);
        }
        private static string ConfigurePlayReadyLicenseTemplate()
        {
            // The following code configures PlayReady License Template using .NET classes
            // and returns the XML string.

            //The PlayReadyLicenseResponseTemplate class represents the template for the response sent back to the end user.
            //It contains a field for a custom data string between the license server and the application
            //(may be useful for custom app logic) as well as a list of one or more license templates.
            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();

            // The PlayReadyLicenseTemplate class represents a license template for creating PlayReady licenses
            // to be returned to the end users.
            //It contains the data on the content key in the license and any rights or restrictions to be
            //enforced by the PlayReady DRM runtime when using the content key.
            PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();
            //Configure whether the license is persistent (saved in persistent storage on the client)
            //or non-persistent (only held in memory while the player is using the license).
            licenseTemplate.LicenseType = PlayReadyLicenseType.Nonpersistent;

            // AllowTestDevices controls whether test devices can use the license or not.
            // If true, the MinimumSecurityLevel property of the license
            // is set to 150.  If false (the default), the MinimumSecurityLevel property of the license is set to 2000.
            licenseTemplate.AllowTestDevices = true;

            // You can also configure the Play Right in the PlayReady license by using the PlayReadyPlayRight class.
            // It grants the user the ability to playback the content subject to the zero or more restrictions
            // configured in the license and on the PlayRight itself (for playback specific policy).
            // Much of the policy on the PlayRight has to do with output restrictions
            // which control the types of outputs that the content can be played over and
            // any restrictions that must be put in place when using a given output.
            // For example, if the DigitalVideoOnlyContentRestriction is enabled,
            //then the DRM runtime will only allow the video to be displayed over digital outputs
            //(analog video outputs won’t be allowed to pass the content).

            //IMPORTANT: These types of restrictions can be very powerful but can also affect the consumer experience.
            // If the output protections are configured too restrictive,
            // the content might be unplayable on some clients. For more information, see the PlayReady Compliance Rules document.

            // For example:
            //licenseTemplate.PlayRight.AgcAndColorStripeRestriction = new AgcAndColorStripeRestriction(1);

            responseTemplate.LicenseTemplates.Add(licenseTemplate);

            return MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
        }
        public void ValidateNonPersistentLicenseConstraints()
        {
            string serializedTemplate = null;
            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();
            responseTemplate.LicenseTemplates.Add(licenseTemplate);

            // Part 1: Make sure we cannot set GracePeriod on a NonPersistent license
            licenseTemplate.LicenseType = PlayReadyLicenseType.Nonpersistent;
            licenseTemplate.GracePeriod = TimeSpan.FromDays(1);

            try
            {
                serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
                Assert.Fail("Expected ArgumentException");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual(ErrorMessages.GracePeriodCannotBeSetOnNonPersistentLicense, ae.Message);
            }

            // Part 2: Make sure we cannot set a FirstPlayExpiration on a NonPersistent license.
            licenseTemplate.GracePeriod = null;
            licenseTemplate.PlayRight.FirstPlayExpiration = TimeSpan.FromDays(1);

            try
            {
                serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
                Assert.Fail("Expected ArgumentException");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual(ErrorMessages.FirstPlayExpirationCannotBeSetOnNonPersistentLicense, ae.Message);
            }

            // Part 3: Make sure we cannot set a BeginDate on a NonPersistent license.
            licenseTemplate.PlayRight.FirstPlayExpiration = null;
            licenseTemplate.BeginDate = DateTime.UtcNow;

            try
            {
                serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
                Assert.Fail("Expected ArgumentException");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual(ErrorMessages.BeginDateCannotBeSetOnNonPersistentLicense, ae.Message);
            }

            // Part 4: Make sure we cannot set an ExpirationDate on a NonPersistent license.
            licenseTemplate.BeginDate = null;
            licenseTemplate.ExpirationDate = DateTime.UtcNow;

            try
            {
                serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
                Assert.Fail("Expected ArgumentException");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual(ErrorMessages.ExpirationCannotBeSetOnNonPersistentLicense, ae.Message);
            }
        }
        public void RoundTripTest()
        {
            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            responseTemplate.ResponseCustomData = "This is my response custom data";
            PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();
            responseTemplate.LicenseTemplates.Add(licenseTemplate);

            licenseTemplate.LicenseType = PlayReadyLicenseType.Persistent;
            licenseTemplate.BeginDate = DateTime.Now.AddHours(-1);
            licenseTemplate.ExpirationDate = DateTime.Now.AddDays(30).ToUniversalTime();

            licenseTemplate.PlayRight.CompressedDigitalAudioOpl = 300;
            licenseTemplate.PlayRight.CompressedDigitalVideoOpl = 400;
            licenseTemplate.PlayRight.UncompressedDigitalAudioOpl = 250;
            licenseTemplate.PlayRight.UncompressedDigitalVideoOpl = 270;
            licenseTemplate.PlayRight.AnalogVideoOpl = 100;
            licenseTemplate.PlayRight.AgcAndColorStripeRestriction = new AgcAndColorStripeRestriction(1);
            licenseTemplate.PlayRight.AllowPassingVideoContentToUnknownOutput = UnknownOutputPassingOption.Allowed;
            licenseTemplate.PlayRight.ExplicitAnalogTelevisionOutputRestriction = new ExplicitAnalogTelevisionRestriction(0, true);
            licenseTemplate.PlayRight.ImageConstraintForAnalogComponentVideoRestriction = true;
            licenseTemplate.PlayRight.ImageConstraintForAnalogComputerMonitorRestriction = true;
            licenseTemplate.PlayRight.ScmsRestriction = new ScmsRestriction(2);

            string serializedTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
            Assert.IsFalse(String.IsNullOrWhiteSpace(serializedTemplate));

            PlayReadyLicenseResponseTemplate responseTemplate2 = MediaServicesLicenseTemplateSerializer.Deserialize(serializedTemplate);
            Assert.IsNotNull(responseTemplate2);
        }
        public void GetPlayReadyLicenseDeliveryUrl()
        {
            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            try
            {
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.CommonEncryption);

                PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
                responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());
                string licenseTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);

                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty, ContentKeyDeliveryType.PlayReadyLicense, null, licenseTemplate, ContentKeyRestrictionType.Open);

                List<IContentKeyAuthorizationPolicyOption> options = new List<IContentKeyAuthorizationPolicyOption>
                {
                    policyOption
                };

                contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey);

                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);

                Assert.IsNotNull(keyDeliveryServiceUri);
                Assert.IsTrue(0 == String.Compare(keyDeliveryServiceUri.AbsolutePath, "/PlayReady/", StringComparison.OrdinalIgnoreCase));
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
        public void EnsureEnvelopeKeyDeliveryUrlForCommonKeyFails()
        {
            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());
            string licenseTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);

            try
            {
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.CommonEncryption);

                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty, ContentKeyDeliveryType.PlayReadyLicense, null, licenseTemplate, ContentKeyRestrictionType.Open);

                List<IContentKeyAuthorizationPolicyOption> options = new List<IContentKeyAuthorizationPolicyOption>
                {
                    policyOption
                };

                contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey);

                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
        static private string ConfigurePlayReadyLicenseTemplate()
        {
            // The following code configures PlayReady License Template using .NET classes
            // and returns the XML string.

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();

            responseTemplate.LicenseTemplates.Add(licenseTemplate);

            return MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
        }
        private static void ValidateLicenseResponseTemplate(PlayReadyLicenseResponseTemplate templateToValidate)
        {
            // Validate the PlayReadyLicenseResponseTemplate has at least one license
            if (templateToValidate.LicenseTemplates.Count <= 0)
            {
                throw new ArgumentException(ErrorMessages.AtLeastOneLicenseTemplateRequired);
            }

            foreach (PlayReadyLicenseTemplate template in templateToValidate.LicenseTemplates)
            {
                // This is actually enforced in the DataContract with the IsRequired attribute
                // so this check should never fail.
                if (template.ContentKey == null)
                {
                    throw new ArgumentException(ErrorMessages.PlayReadyContentKeyRequired);
                }

                // A PlayReady license must have at least one Right in it.  Today we only
                // support the PlayRight so it is required.  In the future we might support
                // other types of rights (CopyRight, perhaps an extensible Right, whatever)
                // so we enforce this in code and not in the DataContract itself.
                if (template.PlayRight == null)
                {
                    throw new ArgumentException(ErrorMessages.PlayReadyPlayRightRequired);
                }

                //
                //  Per the PlayReady Compliance rules (section 3.8 - Output Control for Unknown Outputs), passing content to
                //  unknown output is prohibited if the DigitalVideoOnlyContentRestriction is enabled.
                //
                if (template.PlayRight.DigitalVideoOnlyContentRestriction)
                {
                    if ((template.PlayRight.AllowPassingVideoContentToUnknownOutput == UnknownOutputPassingOption.Allowed) ||
                        (template.PlayRight.AllowPassingVideoContentToUnknownOutput == UnknownOutputPassingOption.AllowedWithVideoConstriction))
                    {
                        throw new ArgumentException(ErrorMessages.DigitalVideoOnlyMutuallyExclusiveWithPassingToUnknownOutputError);
                    }
                }

                if (template.LicenseType == PlayReadyLicenseType.Nonpersistent)
                {
                    //
                    //  The PlayReady Rights Manager SDK will return an error if you try to specify a license
                    //  that is non-persistent and has a first play expiration set.  The event log message related
                    //  to the error will say "LicenseGenerationFailure: FirstPlayExpiration can not be set on Non
                    //  Persistent license PlayRight."
                    //
                    if (template.PlayRight.FirstPlayExpiration.HasValue)
                    {
                        throw new ArgumentException(ErrorMessages.FirstPlayExpirationCannotBeSetOnNonPersistentLicense);
                    }

                    //
                    //  The PlayReady Rights Manager SDK will return an error if you try to specify a license
                    //  that is non-persistent and has a GracePeriod set.
                    //
                    if (template.GracePeriod.HasValue)
                    {
                        throw new ArgumentException(ErrorMessages.GracePeriodCannotBeSetOnNonPersistentLicense);
                    }

                    //
                    //  The PlayReady Rights Manager SDK will return an error if you try to specify a license
                    //  that is non-persistent and has a GracePeriod set.  The event log message related
                    //  to the error will say "LicenseGenerationFailure: BeginDate or ExpirationDate should not be set
                    //  on Non Persistent licenses"
                    //
                    if (template.BeginDate.HasValue)
                    {
                        throw new ArgumentException(ErrorMessages.BeginDateCannotBeSetOnNonPersistentLicense);
                    }

                    //
                    //  The PlayReady Rights Manager SDK will return an error if you try to specify a license
                    //  that is non-persistent and has a GracePeriod set.  The event log message related
                    //  to the error will say "LicenseGenerationFailure: BeginDate or ExpirationDate should not be set
                    //  on Non Persistent licenses"
                    //
                    if (template.ExpirationDate.HasValue)
                    {
                        throw new ArgumentException(ErrorMessages.ExpirationCannotBeSetOnNonPersistentLicense);
                    }
                }
            }
        }
        private static void ValidateLicenseResponseTemplate(PlayReadyLicenseResponseTemplate templateToValidate)
        {
            // Validate the PlayReadyLicenseResponseTemplate has at least one license
            if (templateToValidate.LicenseTemplates.Count <= 0)
            {
                throw new ArgumentException(ErrorMessages.AtLeastOneLicenseTemplateRequired);
            }

            foreach (PlayReadyLicenseTemplate template in templateToValidate.LicenseTemplates)
            {
                // This is actually enforced in the DataContract with the IsRequired attribute
                // so this check should never fail.
                if (template.ContentKey == null)
                {
                    throw new ArgumentException(ErrorMessages.PlayReadyContentKeyRequired);
                }

                // A PlayReady license must have at least one Right in it.  Today we only
                // support the PlayRight so it is required.  In the future we might support
                // other types of rights (CopyRight, perhaps an extensible Right, whatever)
                // so we enforce this in code and not in the DataContract itself.
                if (template.PlayRight == null)
                {
                    throw new ArgumentException(ErrorMessages.PlayReadyPlayRightRequired);
                }

                //
                //  Per the PlayReady Compliance rules (section 3.8 - Output Control for Unknown Outputs), passing content to
                //  unknown output is prohibited if the DigitalVideoOnlyContentRestriction is enabled.
                //
                if (template.PlayRight.DigitalVideoOnlyContentRestriction)
                {
                    if ((template.PlayRight.AllowPassingVideoContentToUnknownOutput == UnknownOutputPassingOption.Allowed) ||
                        (template.PlayRight.AllowPassingVideoContentToUnknownOutput == UnknownOutputPassingOption.AllowedWithVideoConstriction))
                    {
                        throw new ArgumentException(ErrorMessages.DigitalVideoOnlyMutuallyExclusiveWithPassingToUnknownOutputError);
                    }
                }

                //
                //  License template should not have both BeginDate and RelativeBeginDate set.
                //  Only one of these two values should be set.
                if ((template.BeginDate.HasValue) && (template.RelativeBeginDate.HasValue))
                {
                    throw new ArgumentException(ErrorMessages.BeginDateAndRelativeBeginDateCannotbeSetSimultaneouslyError);
                }

                //
                //  License template should not have both ExpirationDate and RelativeExpirationDate set.
                //  Only one of these two values should be set.
                if ((template.ExpirationDate.HasValue) && (template.RelativeExpirationDate.HasValue))
                {
                    throw new ArgumentException(ErrorMessages.ExpirationDateAndRelativeExpirationDateCannotbeSetSimultaneouslyError);
                }

                if (template.LicenseType == PlayReadyLicenseType.Nonpersistent)
                {
                    //
                    //  The PlayReady Rights Manager SDK will return an error if you try to specify a license
                    //  that is non-persistent and has a first play expiration set.  The event log message related
                    //  to the error will say "LicenseGenerationFailure: FirstPlayExpiration can not be set on Non
                    //  Persistent license PlayRight."
                    //
                    if (template.PlayRight.FirstPlayExpiration.HasValue)
                    {
                        throw new ArgumentException(ErrorMessages.FirstPlayExpirationCannotBeSetOnNonPersistentLicense);
                    }

                    //
                    //  The PlayReady Rights Manager SDK will return an error if you try to specify a license
                    //  that is non-persistent and has a GracePeriod set.
                    //
                    if (template.GracePeriod.HasValue)
                    {
                        throw new ArgumentException(ErrorMessages.GracePeriodCannotBeSetOnNonPersistentLicense);
                    }

                    //
                    //  The PlayReady Rights Manager SDK will return an error if you try to specify a license
                    //  that is non-persistent and has a GracePeriod set.  The event log message related
                    //  to the error will say "LicenseGenerationFailure: BeginDate or ExpirationDate should not be set
                    //  on Non Persistent licenses"
                    //
                    if (template.BeginDate.HasValue)
                    {
                        throw new ArgumentException(ErrorMessages.BeginDateCannotBeSetOnNonPersistentLicense);
                    }

                    //
                    //  The PlayReady Rights Manager SDK will return an error if you try to specify a license
                    //  that is non-persistent and has a GracePeriod set.  The event log message related
                    //  to the error will say "LicenseGenerationFailure: BeginDate or ExpirationDate should not be set
                    //  on Non Persistent licenses"
                    //
                    if (template.ExpirationDate.HasValue)
                    {
                        throw new ArgumentException(ErrorMessages.ExpirationCannotBeSetOnNonPersistentLicense);
                    }
                }
            }
        }
        /// <summary>
        /// Configures authorization policy. 
        /// Creates a content key. 
        /// Updates the PlayReady configuration XML file.
        /// </summary>
        /// <returns>The content key.</returns>
        public static IContentKey ConfigureKeyDeliveryServiceForPlayReady(CloudMediaContext _context, Guid keyId, byte[] keyValue, PlayReadyLicenseTemplate licenseTemplate,
            ContentKeyRestrictionType PlayReadyKeyRestriction, string PlayReadyPolicyName)
        {

            var contentKey = _context.ContentKeys.Create(keyId, keyValue, "key test", ContentKeyType.CommonEncryption);

            var restrictions = new List<ContentKeyAuthorizationPolicyRestriction>
                {
                    new ContentKeyAuthorizationPolicyRestriction { Requirements = null, Name = Enum.GetName(typeof(ContentKeyRestrictionType),PlayReadyKeyRestriction),
                        KeyRestrictionType = (int)PlayReadyKeyRestriction }
                };

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                        ContentKeyAuthorizationPolicies.
                        CreateAsync("Deliver Common Content Key with no restrictions").
                        Result;

            // Configure PlayReady license template.

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();

            responseTemplate.LicenseTemplates.Add(licenseTemplate);

            string newLicenseTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);

            IContentKeyAuthorizationPolicyOption policyOption =
                _context.ContentKeyAuthorizationPolicyOptions.Create(
                PlayReadyPolicyName,
                    ContentKeyDeliveryType.PlayReadyLicense,
                        restrictions, newLicenseTemplate);

            contentKeyAuthorizationPolicy.Options.Add(policyOption);

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

            return contentKey;
        }
        static private string ConfigurePlayReadyLicenseTemplate()
        {
            // The following code configures PlayReady License Template using .NET classes
            // and returns the XML string.

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();
            licenseTemplate.PlayRight.AllowPassingVideoContentToUnknownOutput = UnknownOutputPassingOption.Allowed;
            licenseTemplate.AllowTestDevices = true;

            responseTemplate.LicenseTemplates.Add(licenseTemplate);

            return MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
        }