The book "C # 7 and .NET Core. Cross-platform development for professionals. 3rd edition "

image Hello everyone, we have already written about the new book by Mark Price, now we are publishing an excerpt from the book “Developing mobile applications with Xamarin.Forms”

We will create a mobile application to manage the list of clients in the Northwind database, which can be run on iOS or Android.

Install Android SDK


To create Android applications, you must install at least one set of Android SDK development tools. Installing Visual Studio for Mac by default already includes one Android SDK, however, this is often the old version to support the largest number of Android devices. To use the newest features of Xamarin.Forms, you need to install a newer version of the Android SDK.

Launch Visual Studio for Mac and run the Visual Studio Community → Preferences command (Visual Studio Community → Preferences).

In the Preferences dialog box, go to Projects → SDK Locations and select the desired platforms, for example, Android 8.0 - Oreo (Figure 18.1).
image

Creating a Xamarin.Forms Solution


Run the command File → New Solution (File → New Solution).

In the dialog box that opens, select App (Application) in the Multiplatform category (Cross-platform projects). In the Xamarin.Forms section, select the Blank Forms App (Blank 18.2).

image

Click Next.

In the App Name field, type NorthwindMobile, and in the Organization Identifier field, type com.packt. Set the Shared Code switch to Use Shared Library and activate the Use XAML checkbox for the user interface files (Figure 18.3).

Click Next.

In the Solution name field, specify the value of Part3Mobile, and in the Location field, specify the value / Users / your_name / Code (Fig. 18.4). Click the Create button. In a few moments, a solution and three projects will be created. In Visual Studio for Mac, run the command Build → Build All (Build → Collect All) and wait for the program to download all the updated packages and build the projects (Figure 18.5).

Right-click on the Part3Mobile solution and select Update NuGet Packages.

image

image

image

Creating a model


We could use the previously created library of data models with .NET Standard 2.0 entities, but we need to implement two-way data binding, so we will create a new class for representing client entities in a mobile application.

Right-click on the NorthwindMobile project, select Add → New Folder in the context menu and name the created directory Models.

Right-click on the Models directory and select Add → New File in the context menu.

In the New File dialog box, execute the General → Empty Class command, name the class Customer (fig. 18.6), and click the New button.

Modify the instructions as shown in the listing below:

using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; namespace NorthwindMobile.Models { public class Customer : INotifyPropertyChanged { 


image


 public static IList<Customer> Customers; static Customer() { Customers = new ObservableCollection<Customer>(); } public event PropertyChangedEventHandler PropertyChanged; private string customerID; private string companyName; private string contactName; private string city; private string country; private string phone; public string CustomerID { get { return customerID; } set   { customerID = value;  PropertyChanged?.Invoke(this,  new PropertyChangedEventArgs("CustomerID"));  } } public string CompanyName { get { return companyName; } set  {  companyName = value; PropertyChanged?.Invoke(this,  new PropertyChangedEventArgs("CompanyName")); } } public string ContactName { get { return contactName; } set { contactName = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ContactName"));  } } public string City { get { return city; } set { city = value;   PropertyChanged?.Invoke(this,   new PropertyChangedEventArgs("City"));    }    }    public string Country { get { return country; } set { country = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Country")); } } public string Phone { get { return phone; } set { phone = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Phone")); } }  public string Location { get { return string.Format("{0}, {1}", City, Country); } } //     - public static void SampleData() {   Customers.Clear(); Customers.Add(new Customer { CustomerID = "ALFKI", CompanyName = "Alfreds Futterkiste",  ContactName = "Maria Anders", City = "Berlin", Country = "Germany", Phone = "030-0074321" }); Customers.Add(new Customer { CustomerID = "FRANK",  CompanyName = "Frankenversand",    ContactName = "Peter Franken",   City = "München", Country = "Germany", Phone = "089-0877310"  }); Customers.Add(new Customer  {  CustomerID = "SEVES", CompanyName = "Seven Seas Imports", ContactName = "Hari Kumar", City = "London", Country = "UK", Phone = "(171) 555-1717" });    }  } } 

Pay attention to the following points.


Creating an interface for dialing phone numbers


Right-click on the NorthwindMobile directory and select the Add → New File command from the context menu.

In the New File dialog box, select the General → Empty Interface command, name the interface IDialer, and click the New button.
Change the IDialer interface code, as shown in the following listing:

 namespace NorthwindMobile { public interface IDialer { bool Dial(string number); } } 

Interface implementation for dialing iOS phone numbers


Right-click on the NorthwindMobile.iOS directory and select the Add → New File command from the context menu.

In the New File dialog box, execute the General → Empty Class command, name the class PhoneDialer, and click the New button.

Modify its contents as shown in the listing below:

 using Foundation; using NorthwindMobile.iOS; using UIKit; using Xamarin.Forms; [assembly: Dependency(typeof(PhoneDialer))] namespace NorthwindMobile.iOS {  public class PhoneDialer : IDialer {    public bool Dial(string number) { return UIApplication.SharedApplication.OpenUrl( new NSUrl("tel:" + number));  }  } } 

Interface implementation for dialing Android phone numbers


Right-click on the NorthwindMobile.Droid directory in the context menu and execute the command Add—> New File.

In the New File dialog box, run the command General —> Empty Class (General —> Empty Class), name the class PhoneDialer, and click the New button.

Modify its contents as shown in the following listing:

 using Android.Content; using Android.Telephony; using NorthwindMobile.Droid; using System.Linq; using Xamarin.Forms; using Uri = Android.Net.Uri; [assembly: Dependency(typeof(PhoneDialer))] namespace NorthwindMobile.Droid { public class PhoneDialer : IDialer { public bool Dial(string number) { var context = Forms.Context; if (context == null) return false; var intent = new Intent(Intent.ActionCall); intent.SetData(Uri.Parse("tel:" + number)); if (IsIntentAvailable(context, intent))  {  context.StartActivity(intent); return true; } return false; } public static bool IsIntentAvailable(Context context, Intent intent) { var packageManager = context.PackageManager; var list = packageManager.QueryIntentServices(intent, 0) .Union(packageManager.QueryIntentActivities(intent, 0)); if (list.Any()) return true; var manager = TelephonyManager.FromContext(context); return manager.PhoneType != PhoneType.None; } } } 

In the NorthwindMobile.Droid directory, expand the Properties subdirectory and open the AndroidManifest.xml file. In the Required permissions area, select the CallPhone check box (Figure 18.7).

image

about the author


Mark J. Price is a Microsoft Certified Solutions Developer (MCSD), Microsoft Specialist: Programming in C # and Episerver Certified Developer with more than 20 years of experience in training and programming.

Since 1993, Mark has passed over 80 exams of Microsoft Corp. programming and specializes in preparing other people for successful testing. His students are both 16-year-old novices and professionals with years of experience. Mark conducts effective training, combining educational activities with real-world practice in consulting and designing systems for corporations around the world.

Between 2001 and 2003, Mark devoted all his time to developing official training software at Microsoft headquarters in the US city of Redmond. As part of the team, he wrote the first training course on C #, when only the alpha version of the language was released. During his collaboration with Microsoft, he worked as an advanced education instructor of corporation-certified specialists in special trainings on C # and. NET.

Currently, Mark is developing and supporting training courses for the Episerver Digital Experience Cloud, the best .NET CMS in digital marketing and e-commerce.

In 2010, Mark received a certificate of completion of the postgraduate program of study, giving the right to teach. He teaches high school math in high school in London, preparing to receive GCSE and A-Level certificates. In addition, Mark received a Computer Science BSc certificate. Hons. Degree at the University of Bristol, England.

About reviewers


Dustin Heffron (Dustin Heffron) is a software and games developer. He has more than a decade of programming experience in different languages, eight of which are related to C # and. NET.

Currently he is developing programs for the automation and testing of medical instruments at Becton Dickinson. In addition, he is co-founder and CEO of SunFlake Studios.

Dustin has been working with Packt for a long time and has participated in work on books such as XNA 4.0 Game Development by Example: Beginner's Guide, C # 6 and. NET Core 1.0: Modern Cross-Platform Development, and also on a series of XNA 3D video lessons. by Example. In addition, Dustin, along with Larry Louisiana (Larry Louisiana), co-authored a series of XNA 3D Toolkit video tutorials.

Efraim Kyriakidis (Efraim Kyriakidis) is a software engineer with more than ten years experience in developing and implementing software solutions for various clients and projects. He is well versed in all stages of the software creation cycle. His first acquaintance with computers and programming occurred in childhood, at the time of the popularity of the Commodore 64 computer, in the 80s of the twentieth century. Since then, he grew up and received a diploma at the University of Aristotle in Thessaloniki (Aristotle University Thessaloniki), Greece. During his career, he worked mainly with Microsoft technologies, using C # and. NET, starting from version 1.0. He is currently working as a software developer at Siemens AG in Germany.

»More information about the book can be found on the publisher site.
» Table of Contents
» Excerpt

For Habrozhiteley 20% discount on coupon - Packt

Source: https://habr.com/ru/post/415275/


All Articles