Optimizing for mobile devices

Follow these steps take to make our Tic-Tac-Toe demo application more and more responsive for mobile devices, with the end goal of having a more convenient interface:

  1. We want to change the display so that it's specifically for mobile devices. To do this, start Visual Studio 2019, go to the Solution Explorer, create a new folder called Filters, and add a new class called DetectMobileFilter that inherits from the IActionFilter interface. Then, we will create the MobileCheck and MobileVersionCheck regular expressions (regex), as follows:
static Regex MobileCheck = new Regex(@"android|(android|bbd+|meego).+mobile|avantgo|bada/|blackberry|blazer
|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle
|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian
|treo|up.
(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);


static Regex MobileVersionCheck = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)
|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);

  1. Now, let's create a method that will check whether a user agent is mobile or not: 
        public static bool IsMobileUserAgent( ActionExecuted
Context context)
{

var userAgent = context.HttpContext.
Request.Headers["User-Agent"].ToString();

if (context.HttpContext != null && userAgent != null)
{
if (userAgent.Length < 4)
return false;
if (MobileCheck.IsMatch(userAgent) ||
MobileVersionCheck.IsMatch(userAgent.
Substring(0, 4)))
return true;
}
return false;
}
  1. Let's implement the OnActionExecuted method from IActionFilter, as follows: 
        public void OnActionExecuted(ActionExecutedContext context)
{
var viewResult = (context.Result as ViewResult);
if (viewResult == null)
return;
if (IsMobileUserAgent(context))
{
viewResult.ViewData["Layout"] =
"~/Views/Shared/_LayoutMobile.cshtml";
}
else
{
viewResult.ViewData["Layout"] =
"~/Views/Shared/_Layout.cshtml";
}
}
  1. Duplicate the existing Views/Shared/_Layout.cshtml file and rename the resulting copy _LayoutMobile.cshtml.
  2. Update the home page index view, remove the existing layout definition, and display a different title, depending on the device, by adding two dedicated sections called Desktop and Mobile:
@{
ViewData["Title"] = "Home Page";
}
<div class="row">
<div class="col-lg-12">
@section Desktop {<h2>@Localizer["DesktopTitle"]</h2>}
@section Mobile {<h2>@Localizer["MobileTitle"]</h2>}
<div class="alert alert-info">
  1. These sections will be made use of exclusively when a respective device is in use. This means that if a user is using a mobile phone for browsing, then only the Mobile section will appear on the screen.
Note that you must also update all the other views of the application (GameInvitation/GameInvitationConfirmation, GameInvitation/IndexHome/Index, UserRegistration/EmailConfirmationUserRegistration/Index) with the section tags from the preceding code for now:
@section Desktop{<h2>@Localizer["DesktopTitle"]</h2>}
@section Mobile {<h2>@Localizer["MobileTitle"]</h2>}
If you do not add them to your other views, you will get errors when you complete the steps that follow. However, this is only a temporary solution; later in this chapter, you will learn how to address this problem more effectively by using conditional statements.
  1. Update the resource files. Here is an example of the English home page index resource file; you should also add the French translations:

  1. Modify the Views/Shared/_LayoutMobile.cshtml file by replacing the @RenderBody() element with the following instructions; the Desktop section should be displayed and the Mobile section should be ignored:
@RenderSection("Desktop", required: false)
@{IgnoreSection("Mobile");}
@RenderBody()
  1. Modify the Views/Shared/_Layout.cshtml file by replacing the @RenderBody() element with the following instructions; the Mobile section should be displayed and the Desktop section should be ignored:
@RenderSection("Mobile", required: false)
@{IgnoreSection("Desktop");}
@RenderBody()
  1. Go to the Views/_ViewStart.cshtml file and change the layout assignment for all your web pages to be able to use the layout definitions from the preceding code:
@{Layout = Convert.ToString(ViewData["Layout"]);}
  1. Update the Startup class and add DetectMobileFilter to the MVC service registration as a parameter:
services.AddControllersWithViews(o => 
o.Filters.Add(typeof(DetectMobileFilter)))
  1. Start the Tic-Tac-Toe application normally in the Microsoft Edge browser. Note that the localized title already shows Desktop as the detected browser: 

Open the Developer Tools in Microsoft Edge by pressing F12, go to the Emulation tab, and select a mobile device: 

Now, reload the Tic-Tac-Toe application; it will be displayed as if you had opened it on the emulated device:

 

In this section, you have learned how to provide specific layouts for specific devices. Now, you are going to learn how to apply other advanced ASP.NET Core 3 MVC features for better productivity and better applications. But first, let's have a look at what's available to us in the state management between different requests, controllers, and views. We will have to deal with all of these at some point, even in the most basic of applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.31.206