Forcing a Device Channel

2 minute read

Device channels are a way of using different master pages for different devices. MSDN describes the functionality as followed:

 

“Browsing the web on a mobile device is now so common that a SharePoint site must be optimized for readability and ease of use on smartphones and other mobile devices such as tablets. With device channels in SharePoint 2013, you can render a single publishing site in multiple ways by using different designs that target different devices. This article can help you plan for using the device channels feature in SharePoint 2013. It provides a detailed overview of the feature itself, and provides the necessary information for creating a device channel. Also, after reading this article, you'll know what device channels you need to implement, and how to implement those channels.”

 

Using the out of the box settings you can set the master page by information that is in the user agent string. The information in this string will give SharePoint the information to select the right master page. How the out of the box functionality works can be found here:

 

https://msdn.microsoft.com/en-us/library/office/jj862343.aspx

 

This functionality can also be used for other scenarios for example in a CMS setup. When you want to apply this to other scenarios you will have to force a device channel. Forcing device channels can be done using two options:

 

  • Query String: Append the “DeviceChannel” query string to your URL and set the value to the “Alias” of your device channel.
  • Cookie: You can set a cookie named “DeviceChannel”  and set the value of the cookie to the name of your “Alias”.

 

You can set this cookie in code in order to persist the use of the master page.

 

if (HttpContext.Current.Request.Cookies["DeviceChannel"] == null) {

    string url = HttpContext.Current.Request.Url.ToString();
    using (SPSite site = new SPSite(url)) {
        string authUrl = site.GetProperty(PropertyBagKeys.AuthoringSiteKey, string.Empty);
        string devChannel = site.GetProperty(PropertyBagKeys.AuthDeviceChannel, string.Empty);

        if (!string.IsNullOrEmpty(authUrl)) {
            if (url.StartsWith(authUrl)) {
                HttpCookie cookie = new HttpCookie("DeviceChannel");
                cookie.Value = string.IsNullOrEmpty(devChannel) ? "Default" : devChannel;
                HttpContext.Current.Request.Cookies.Add(cookie);
            } else {
                HttpContext.Current.Request.Cookies.Remove("DeviceChannel");
            }
        }
    }               
}