Gaurav Mantri's Personal Blog.

Windows Azure Media Service-Part IV (Managing Access Policies via REST API)

In the last post about Windows Azure Media Service (Media Service), I talked about how you can manage assets using REST API. You can read that post here: https://gauravmantri.com/2012/10/10/windows-azure-media-service-part-iii-managing-assets-via-rest-api/.

In this post, I’m going to take this further and talk about how to manage access policies using REST API. This post makes extensive use of concepts covered in earlier posts so I would recommend you go through them first.

Let’s get cracking!!!

Definition

Simply put, an access policy defines the permissions and duration of access to an asset. To explain, you could create an access policy which would grant say read permission on an asset for a duration of 60 minutes.

From the definition, it may seem like you create an access policy for an asset i.e. one-to-one kind of relationship, however that’s not the case. Access policies and assets share a many-to-many kind of relationship. What that means is that you can define an access policy and apply that access policy to one or more assets. Similarly an asset can have one or more access policies. The association between them is facilitated through what is called as “Locators”. We’ll cover locators in one of the next posts but for now let’s just define it: A locator is a URI which provides time-based access to a specific asset.

Access Policy Entity

An access policy entity defines the abstract concept of an access policy in Media Service. You can read about the attributes of an access policy entity here on MSDN: http://msdn.microsoft.com/en-us/library/windowsazure/hh974297.aspx#accesspolicy_properties.

Based on this, we’ll create our own class. Let’s call it AccessPolicy. Here’s the code for that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WAMSRestWrapper
{
    /// <summary>
    /// Class representing an access policy in a media service
    /// </summary>
    public class AccessPolicy
    {
        private readonly MediaServiceContext _context;

        /// <summary>
        /// Creates an instance of <see cref="AccessPolicy"/>
        /// </summary>
        /// <param name="context">
        /// <see cref="MediaServiceContext"/>
        /// </param>
        internal AccessPolicy(MediaServiceContext context)
        {
            _context = context;
        }

        /// <summary>
        /// Creates an instance of <see cref="AccessPolicy"/>
        /// </summary>
        /// <param name="context">
        /// <see cref="MediaServiceContext"/>
        /// </param>
        /// <param name="id">
        /// Access policy id
        /// </param>
        internal AccessPolicy(MediaServiceContext context, string id)
            : this(context)
        {
            Id = id;
        }

        /// <summary>
        /// Creates an instance of <see cref="AccessPolicy"/>
        /// </summary>
        /// <param name="context">
        /// <see cref="MediaServiceContext"/>
        /// </param>
        /// <param name="name">
        /// Access policy friendly name.
        /// </param>
        /// <param name="durationInMinutes">
        /// Timespan for which this access policy will be effective.
        /// </param>
        /// <param name="permissions">
        /// Effective permissions
        /// </param>
        internal AccessPolicy(MediaServiceContext context, string name, TimeSpan durationInMinutes, AccessPolicyPermission permissions) : this(context)
        {
            Name = name;
            DurationInMinutes = durationInMinutes;
            Permissions = permissions;
        }

        /// <summary>
        /// Access policy Id.
        /// </summary>
        public string Id
        {
            get;
            internal set;
        }

        /// <summary>
        /// Access policy friendly name.
        /// </summary>
        public string Name
        {
            get;
            internal set;
        }

        /// <summary>
        /// Timespan for which this access policy will be effective.
        /// </summary>
        public TimeSpan DurationInMinutes
        {
            get;
            internal set;
        }

        /// <summary>
        /// Effective permissions
        /// </summary>
        public AccessPolicyPermission Permissions
        {
            get;
            internal set;
        }

        /// <summary>
        /// Date/time access policy was created.
        /// </summary>
        public DateTime Created
        {
            get;
            internal set;
        }

        /// <summary>
        /// Date/time access policy was last modified.
        /// </summary>
        public DateTime LastModified
        {
            get;
            internal set;
        }

    }

    public enum AccessPolicyPermission
    {
        None = 0,
        Read = 1,
        Write = 2,
        Delete = 4,
        List = 8,
    }
}

Operations

REST API allows you to perform following operations on an access policy:

  • Create
  • Delete
  • List

Rest of the blog post will be focused on these operations.

Create

As the name suggests, this operation will create a new access policy for a media service. A few things to consider here:

Endpoint https://media.windows.net/AccessPolicies

OR

the URI received when we checked for redirection (see "Connecting to the Media Service" section in the blog post about managing assets) and append “AccessPolicies” to that.
HTTP Method POST
Request Headers DataServiceVersion

MaxDataServiceVersion

x-ms-version

Authorization
Request Content Type application/json;odata=verbose
Accept application/json;odata=verbose
Request Body Format {

    "Name": "<Access Policy Name>",

    "DurationInMinutes": "100",

    "Permissions":"<Access policy permission (as Integer)"

}

e.g.

{

    "Name": "Test Access Policy",

    "DurationInMinutes": "100",

    "Permissions":"2"

}

Here’s the code for creating an access policy:

        /// <summary>
        /// Creates an access policy.
        /// </summary>
        public void Create()
        {
            if (string.IsNullOrWhiteSpace(Name))
            {
                Name = Guid.NewGuid().ToString();
            }
            string accessPolicyCreateRequestPayloadFormat = @"{0} ""Name"": ""{1}"", ""DurationInMinutes"": ""{2}"", ""Permissions"":""{3}""  {4}";
            string requestBody = string.Format(CultureInfo.InvariantCulture, accessPolicyCreateRequestPayloadFormat, "{", Name, DurationInMinutes.TotalMinutes, (int)Permissions, "}");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}AccessPolicies/", _context.WamsEndpoint));
            request.Method = HttpVerbs.Post;
            request.ContentType = RequestContentType.Json;
            request.Accept = RequestContentType.Json;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, _context.AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            request.ContentLength = Encoding.UTF8.GetByteCount(requestBody);

            using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(requestBody);
            }
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    var returnBody = streamReader.ReadToEnd();
                    JObject responseJsonObject = JObject.Parse(returnBody);
                    var d = responseJsonObject["d"];
                    Id = d.Value<string>("Id");
                    DurationInMinutes = TimeSpan.FromMinutes(d.Value<double>("DurationInMinutes"));
                    Permissions = (AccessPolicyPermission)d.Value<int>("Permissions");
                    Name = d.Value<string>("Name");
                    Created = d.Value<DateTime>("Created");
                    LastModified = d.Value<DateTime>("LastModified");
                }
            }
        }

and the helper code for calling this function:

var accessPolicy = context.GetAccessPolicyReference("Test", TimeSpan.FromMinutes(10), AccessPolicyPermission.Read | AccessPolicyPermission.Write);
accessPolicy.Create();

Delete

Again, as the name suggests this operation deletes an existing policy. A few things to consider here:

Endpoint https://media.windows.net/AccessPolicies(‘<access policy id’>)

OR

the URI received when we checked for redirection (see "Connecting to the Media Service" section in the blog post about managing assets) and append “AccessPolicies(‘<access policy id>’)” to that[Don’t forget to replace <access policy id> with the actual access policy id value Smile].
HTTP Method DELETE
Request Headers DataServiceVersion

MaxDataServiceVersion

x-ms-version

Authorization

Here’s the code for deleting an access policy:

        /// <summary>
        /// Deletes the access policy.
        /// </summary>
        public void Delete()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}AccessPolicies('{1}')", _context.WamsEndpoint, Id));
            request.Method = HttpVerbs.Delete;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, _context.AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            var response = (HttpWebResponse)request.GetResponse();
        }

and the helper code for calling this function:

var accessPolicyId = "<access policy id>";
var accessPolicy = context.GetAccessPolicyReference(accessPolicyId);
accessPolicy.Delete();

List

List operation allows you to fetch information about access policies. Using this operation, you can

  • Fetch information about all access policies for a given media service
  • Fetch information about a particular access policy in a media service
  • Fetch information about all access policies associated with an asset

As mentioned above, the association between an access policy and an asset is established through a locator and since we haven’t covered locator just yet, we will not cover the 3rd option in this post.

Fetch information about all access policies for a given media service

As the title suggests, you can fetch information about all access policies for a given media service. A few things to consider here

Endpoint https://media.windows.net/AccessPolicies

OR

the URI received when we checked for redirection (see "Connecting to the Media Service" section in the blog post about managing assets) and append “AccessPolicies” to that.
HTTP Method GET
Request Headers DataServiceVersion

MaxDataServiceVersion

x-ms-version

Authorization
Accept application/json;odata=verbose

Here’s the code for fetching information about all access policies:

        /// <summary>
        /// List all access policies in a media service.
        /// </summary>
        /// <returns>
        /// </returns>
        public IEnumerable<AccessPolicy> ListAccessPolicies()
        {
            List<AccessPolicy> accessPolicies = new List<AccessPolicy>();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}AccessPolicies", WamsEndpoint));
            request.Accept = RequestContentType.Json;
            request.Method = HttpVerbs.Get;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    var returnBody = streamReader.ReadToEnd();
                    JObject responseJsonObject = JObject.Parse(returnBody);
                    var items = responseJsonObject["d"]["results"];
                    foreach (var d in items)
                    {
                        var Id = d.Value<string>("Id");
                        var DurationInMinutes = TimeSpan.FromMinutes(d.Value<double>("DurationInMinutes"));
                        var Permissions = (AccessPolicyPermission)d.Value<int>("Permissions");
                        var Name = d.Value<string>("Name");
                        var Created = d.Value<DateTime>("Created");
                        var LastModified = d.Value<DateTime>("LastModified");
                        accessPolicies.Add(new AccessPolicy(this, Id)
                        {
                            Name = Name,
                            DurationInMinutes = DurationInMinutes,
                            Permissions = Permissions,
                            Created = Created,
                            LastModified = LastModified,
                        });
                    }
                }
            }
            return accessPolicies;
        }

and the helper code for calling this function:

var accessPolicies = context.ListAccessPolicies();

Fetch information about a particular access policy in a media service

You can also fetch information about a particular access policy in a media service. To do so, you need to know the Id of that access policy. A few things to consider here:

Endpoint https://media.windows.net/AccessPolicies(‘<access policy id’>)

OR

the URI received when we checked for redirection (see "Connecting to the Media Service" section in the blog post about managing assets) and append “AccessPolicies(‘<access policy id>’)” to that[Don’t forget to replace <access policy id> with the actual access policy id value Smile].
HTTP Method GET
Request Headers DataServiceVersion

MaxDataServiceVersion

x-ms-version

Authorization
Accept application/json;odata=verbose

Here’s the code for fetching information about all access policies:

        /// <summary>
        /// Gets information about an access policy.
        /// </summary>
        public void Get()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}AccessPolicies('{1}')", _context.WamsEndpoint, Id));
            request.Method = HttpVerbs.Get;
            request.Accept = RequestContentType.Json;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, _context.AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    var returnBody = streamReader.ReadToEnd();
                    JObject responseJsonObject = JObject.Parse(returnBody);
                    var d = responseJsonObject["d"];
                    Id = d.Value<string>("Id");
                    DurationInMinutes = TimeSpan.FromMinutes(d.Value<double>("DurationInMinutes"));
                    Permissions = (AccessPolicyPermission)d.Value<int>("Permissions");
                    Name = d.Value<string>("Name");
                    Created = d.Value<DateTime>("Created");
                    LastModified = d.Value<DateTime>("LastModified");
                }
            }
        }

and the helper code for calling this function:

var accessPolicyId = "<access policy id>";
var accessPolicy = context.GetAccessPolicyReference(accessPolicyId);
accessPolicy.Get();

Fetch information about all access policies associated with an asset

You can also fetch all access policies associated with an asset. Even though I will not write the code here for that because of the reasons I mentioned above, I still want to mention the things you would need to consider in case you wish to write code for the same. So here they are:

Endpoint https://media.windows.net/Assets(‘assetid’)/AccessPolicies

OR

the URI received when we checked for redirection (see "Connecting to the Media Service" section in the blog post about managing assets) and append “Assets(‘<assetid>’)/AccessPolicies” to that[Don’t forget to replace <assetid> with the actual assetid value Smile].
HTTP Method GET
Request Headers DataServiceVersion

MaxDataServiceVersion

x-ms-version

Authorization
Accept application/json;odata=verbose

 

Wrapping Up

In this blog post, we learnt about the REST API for managing access policies in Media Service. Here’s the complete source code for what we have done so far. As I said in my previous post, this is definitely not the best code and desires a lot of optimization / refactoring. Please feel free to modify the code to suit your need.

MediaServiceContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using Newtonsoft.Json;
using System.Globalization;
using System.IO;
using Newtonsoft.Json.Linq;

namespace WAMSRestWrapper
{
    public class MediaServiceContext
    {
        private const string acsEndpoint = "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13";

        private const string acsRequestBodyFormat = "grant_type=client_credentials&client_id={0}&client_secret={1}&scope=urn%3aWindowsAzureMediaServices";

        private string _accountName;

        private string _accountKey;

        private string _accessToken;

        private DateTime _accessTokenExpiry;

        private string _wamsEndpoint = "https://media.windows.net/";

        /// <summary>
        /// Creates a new instance of <see cref="MediaServiceContext"/>
        /// </summary>
        /// <param name="accountName">
        /// Media service account name.
        /// </param>
        /// <param name="accountKey">
        /// Media service account key.
        /// </param>
        public MediaServiceContext(string accountName, string accountKey)
        {
            this._accountName = accountName;
            this._accountKey = accountKey;
        }

        /// <summary>
        /// Gets the access token. If access token is not yet fetched or the access token has expired,
        /// it gets a new access token.
        /// </summary>
        public string AccessToken
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_accessToken) || _accessTokenExpiry < DateTime.UtcNow)
                {
                    var tuple = FetchAccessToken();
                    _accessToken = tuple.Item1;
                    _accessTokenExpiry = tuple.Item2;
                }
                return _accessToken;
            }
        }

        /// <summary>
        /// Gets the endpoint for making REST API calls.
        /// </summary>
        public string WamsEndpoint
        {
            get
            {
                return _wamsEndpoint;
            }
        }

        /// <summary>
        /// This function makes the web request and gets the access token.
        /// </summary>
        /// <returns>
        /// <see cref="System.Tuple"/> containing 2 items - 
        /// 1. The access token. 
        /// 2. Token expiry date/time.
        /// </returns>
        private Tuple<string, DateTime> FetchAccessToken()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(acsEndpoint);
            request.Method = HttpVerbs.Post;
            string requestBody = string.Format(CultureInfo.InvariantCulture, acsRequestBodyFormat, _accountName, HttpUtility.UrlEncode(_accountKey));
            request.ContentLength = Encoding.UTF8.GetByteCount(requestBody);
            request.ContentType = "application/x-www-form-urlencoded";
            using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(requestBody);
            }
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    var returnBody = streamReader.ReadToEnd();
                    var acsToken = JsonConvert.DeserializeObject<AcsToken>(returnBody);
                    return new Tuple<string, DateTime>(acsToken.access_token, DateTime.UtcNow.AddSeconds(acsToken.expires_in));
                }
            }
        }

        /// <summary>
        /// This function checks if we need to redirect all WAMS requests.
        /// </summary>
        public void CheckForRedirection()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(WamsEndpoint);
            request.AllowAutoRedirect = false;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, AccessToken));
            request.Method = HttpVerbs.Get;

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.MovedPermanently)
                {
                    string newLocation = response.Headers["Location"];
                    if (!newLocation.Equals(_wamsEndpoint))
                    {
                        _wamsEndpoint = newLocation;
                        _accessToken = string.Empty;//So that we can force to get a new access token.
                        _accessTokenExpiry = DateTime.MinValue;
                    }
                }
            }
        }

        public Asset GetAssetReference(string assetId)
        {
            return new Asset(this, assetId);
        }

        public Asset GetAssetReference()
        {
            return new Asset(this);
        }

        /// <summary>
        /// List all assets in a media service.
        /// </summary>
        /// <returns>
        /// </returns>
        public IEnumerable<Asset> ListAssets()
        {
            List<Asset> assets = new List<Asset>();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}Assets", WamsEndpoint));
            request.Accept = RequestContentType.Json;
            request.Method = HttpVerbs.Get;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    var returnBody = streamReader.ReadToEnd();
                    JObject responseJsonObject = JObject.Parse(returnBody);
                    var items = responseJsonObject["d"]["results"];
                    foreach (var d in items)
                    {
                        var Id = d.Value<string>("Id");
                        var State = (AssetState)d.Value<int>("State");
                        var Options = (AssetEncryptionOption)d.Value<int>("Options");
                        var AlternateId = d.Value<string>("AlternateId");
                        var Created = d.Value<DateTime>("Created");
                        var LastModified = d.Value<DateTime>("LastModified");
                        var Name = d.Value<string>("Name");
                        assets.Add(new Asset(this, Id)
                        {
                            Name = Name,
                            State = State,
                            Options = Options,
                            AlternateId = AlternateId,
                            Created = Created,
                            LastModified = LastModified,
                        });
                    }
                }
            }
            return assets;
        }

        public AccessPolicy GetAccessPolicyReference(string accessPolicyId)
        {
            return new AccessPolicy(this, accessPolicyId);
        }

        public AccessPolicy GetAccessPolicyReference(string name, TimeSpan durationInMinutes, AccessPolicyPermission permission)
        {
            return new AccessPolicy(this, name, durationInMinutes, permission);
        }

        /// <summary>
        /// List all access policies in a media service.
        /// </summary>
        /// <returns>
        /// </returns>
        public IEnumerable<AccessPolicy> ListAccessPolicies()
        {
            List<AccessPolicy> accessPolicies = new List<AccessPolicy>();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}AccessPolicies", WamsEndpoint));
            request.Accept = RequestContentType.Json;
            request.Method = HttpVerbs.Get;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    var returnBody = streamReader.ReadToEnd();
                    JObject responseJsonObject = JObject.Parse(returnBody);
                    var items = responseJsonObject["d"]["results"];
                    foreach (var d in items)
                    {
                        var Id = d.Value<string>("Id");
                        var DurationInMinutes = TimeSpan.FromMinutes(d.Value<double>("DurationInMinutes"));
                        var Permissions = (AccessPolicyPermission)d.Value<int>("Permissions");
                        var Name = d.Value<string>("Name");
                        var Created = d.Value<DateTime>("Created");
                        var LastModified = d.Value<DateTime>("LastModified");
                        accessPolicies.Add(new AccessPolicy(this, Id)
                        {
                            Name = Name,
                            DurationInMinutes = DurationInMinutes,
                            Permissions = Permissions,
                            Created = Created,
                            LastModified = LastModified,
                        });
                    }
                }
            }
            return accessPolicies;
        }

    }
}

AccessPolicy.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WAMSRestWrapper
{
    /// <summary>
    /// Class representing an access policy in a media service
    /// </summary>
    public class AccessPolicy
    {
        private readonly MediaServiceContext _context;

        /// <summary>
        /// Creates an instance of <see cref="AccessPolicy"/>
        /// </summary>
        /// <param name="context">
        /// <see cref="MediaServiceContext"/>
        /// </param>
        internal AccessPolicy(MediaServiceContext context)
        {
            _context = context;
        }

        /// <summary>
        /// Creates an instance of <see cref="AccessPolicy"/>
        /// </summary>
        /// <param name="context">
        /// <see cref="MediaServiceContext"/>
        /// </param>
        /// <param name="id">
        /// Access policy id
        /// </param>
        internal AccessPolicy(MediaServiceContext context, string id)
            : this(context)
        {
            Id = id;
        }

        /// <summary>
        /// Creates an instance of <see cref="AccessPolicy"/>
        /// </summary>
        /// <param name="context">
        /// <see cref="MediaServiceContext"/>
        /// </param>
        /// <param name="name">
        /// Access policy friendly name.
        /// </param>
        /// <param name="durationInMinutes">
        /// Timespan for which this access policy will be effective.
        /// </param>
        /// <param name="permissions">
        /// Effective permissions
        /// </param>
        internal AccessPolicy(MediaServiceContext context, string name, TimeSpan durationInMinutes, AccessPolicyPermission permissions) : this(context)
        {
            Name = name;
            DurationInMinutes = durationInMinutes;
            Permissions = permissions;
        }

        /// <summary>
        /// Access policy Id.
        /// </summary>
        public string Id
        {
            get;
            internal set;
        }

        /// <summary>
        /// Access policy friendly name.
        /// </summary>
        public string Name
        {
            get;
            internal set;
        }

        /// <summary>
        /// Timespan for which this access policy will be effective.
        /// </summary>
        public TimeSpan DurationInMinutes
        {
            get;
            internal set;
        }

        /// <summary>
        /// Effective permissions
        /// </summary>
        public AccessPolicyPermission Permissions
        {
            get;
            internal set;
        }

        /// <summary>
        /// Date/time access policy was created.
        /// </summary>
        public DateTime Created
        {
            get;
            internal set;
        }

        /// <summary>
        /// Date/time access policy was last modified.
        /// </summary>
        public DateTime LastModified
        {
            get;
            internal set;
        }


        /// <summary>
        /// Creates an access policy.
        /// </summary>
        public void Create()
        {
            if (string.IsNullOrWhiteSpace(Name))
            {
                Name = Guid.NewGuid().ToString();
            }
            string accessPolicyCreateRequestPayloadFormat = @"{0} ""Name"": ""{1}"", ""DurationInMinutes"": ""{2}"", ""Permissions"":""{3}""  {4}";
            string requestBody = string.Format(CultureInfo.InvariantCulture, accessPolicyCreateRequestPayloadFormat, "{", Name, DurationInMinutes.TotalMinutes, (int)Permissions, "}");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}AccessPolicies", _context.WamsEndpoint));
            request.Method = HttpVerbs.Post;
            request.ContentType = RequestContentType.Json;
            request.Accept = RequestContentType.Json;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, _context.AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            request.ContentLength = Encoding.UTF8.GetByteCount(requestBody);

            using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(requestBody);
            }
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    var returnBody = streamReader.ReadToEnd();
                    JObject responseJsonObject = JObject.Parse(returnBody);
                    var d = responseJsonObject["d"];
                    Id = d.Value<string>("Id");
                    DurationInMinutes = TimeSpan.FromMinutes(d.Value<double>("DurationInMinutes"));
                    Permissions = (AccessPolicyPermission)d.Value<int>("Permissions");
                    Name = d.Value<string>("Name");
                    Created = d.Value<DateTime>("Created");
                    LastModified = d.Value<DateTime>("LastModified");
                }
            }
        }

        /// <summary>
        /// Deletes the access policy.
        /// </summary>
        public void Delete()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}AccessPolicies('{1}')", _context.WamsEndpoint, Id));
            request.Method = HttpVerbs.Delete;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, _context.AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            var response = (HttpWebResponse)request.GetResponse();
        }

        /// <summary>
        /// Gets information about an access policy.
        /// </summary>
        public void Get()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture, "{0}AccessPolicies('{1}')", _context.WamsEndpoint, Id));
            request.Method = HttpVerbs.Get;
            request.Accept = RequestContentType.Json;
            request.Headers.Add(RequestHeaders.XMsVersion, RequestHeaderValues.XMsVersion);
            request.Headers.Add(RequestHeaders.Authorization, string.Format(CultureInfo.InvariantCulture, RequestHeaderValues.Authorization, _context.AccessToken));
            request.Headers.Add(RequestHeaders.DataServiceVersion, RequestHeaderValues.DataServiceVersion);
            request.Headers.Add(RequestHeaders.MaxDataServiceVersion, RequestHeaderValues.MaxDataServiceVersion);
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    var returnBody = streamReader.ReadToEnd();
                    JObject responseJsonObject = JObject.Parse(returnBody);
                    var d = responseJsonObject["d"];
                    Id = d.Value<string>("Id");
                    DurationInMinutes = TimeSpan.FromMinutes(d.Value<double>("DurationInMinutes"));
                    Permissions = (AccessPolicyPermission)d.Value<int>("Permissions");
                    Name = d.Value<string>("Name");
                    Created = d.Value<DateTime>("Created");
                    LastModified = d.Value<DateTime>("LastModified");
                }
            }
        }

    }

    public enum AccessPolicyPermission
    {
        None = 0,
        Read = 1,
        Write = 2,
        Delete = 4,
        List = 8,
    }
}

Summary

That’s it for this post. In the next post, we will deal with more REST API functionality and expand this library. I hope you have found this information useful. As always, if you find some issues with this blog post please let me know immediately and I will fix them ASAP.

So long and stay tuned!


[This is the latest product I'm working on]