Panduan memulai .NET untuk pelanggan

Ikuti langkah-langkah dalam panduan memulai ini, dan dalam waktu sekitar 10 menit, Anda memiliki aplikasi konsol .NET C# sederhana yang membuat permintaan ke API pelanggan pendaftaran zero-touch.

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan:

  • Akun Google, yang merupakan anggota akun pelanggan pendaftaran zero-touch Anda. Lihat Akun pelanggan.
  • Visual Studio 2013 atau yang lebih baru.
  • Akses ke internet dan browser web.

Langkah 1: Aktifkan API pendaftaran zero-touch

  1. Gunakan wizard ini untuk membuat atau memilih project di Google Developers Console dan otomatis mengaktifkan API. Klik Continue, lalu Go to credentials .
  2. Klik Batal di bagian Buat kredensial.
  3. Di bagian atas halaman, pilih tab Layar izin OAuth. Pilih Alamat email, masukkan Nama produk jika belum ditetapkan, lalu klik tombol Simpan.
  4. Pilih tab Credentials, klik tombol Create credentials, lalu pilih OAuth client ID.
  5. Pilih jenis aplikasi Other, masukkan nama "Quickstart", lalu klik tombol Create.
  6. Klik OK untuk menutup panel OAuth client.
  7. Klik Download JSON.
  8. Pindahkan file ke direktori kerja Anda dan ganti namanya menjadi client_secret.json.

Langkah 2: Siapkan project

  1. Buat project Console Console dari Aplikasi .NET Core C# baru di Visual Studio.
  2. Buka Pengelola Paket, pilih sumber paket nuget.org, lalu tambahkan paket berikut:
    • Google.Apis.AndroidProvisioningPartner.v1
    • Google.Apis.Auth

Untuk mempelajari lebih lanjut, baca dokumen Microsoft Menginstal dan menggunakan paket.

Langkah 3: Siapkan contoh file

  1. Tarik client_secret.json (didownload pada Langkah 1) ke Penjelajah Solusi Visual Studio Anda.
  2. Pilih client_secret.json, lalu buka jendela Properties dan setel kolom Copy to output direktori ke Selalu salin.
  3. Ganti konten Program.cs dengan kode berikut:
using Google.Apis.AndroidProvisioningPartner.v1;
using Google.Apis.AndroidProvisioningPartner.v1.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace ZeroTouchCustomerQuickstart
{
    class Program
    {
        // A single scope is used for the zero-touch enrollment customer API.
        static readonly string[] Scopes =
            { "https://www.googleapis.com/auth/androidworkzerotouchemm" };
        static string ApplicationName = "Zero-touch Enrollment .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            // Ask the user to authorize the request using their Google Account
            // in their browser.
            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/zero-touch.quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.FromStream(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create a zero-touch enrollment API service endpoint.
            var service = new AndroidProvisioningPartnerService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName
            });

            // Get the customer's account. Because a customer might have more
            // than one, limit the results to the first account found.
            CustomersResource.ListRequest accountRequest = service.Customers.List();
            accountRequest.PageSize = 1;
            CustomerListCustomersResponse accountResponse = accountRequest.Execute();
            if (accountResponse.Customers.Count == 0)
            {
                // No accounts found for the user. Confirm the Google Account
                // that authorizes the request can access the zero-touch portal.
                Console.WriteLine("No zero-touch enrollment account found.");
                Environment.Exit(-1);
            }
            Company customer = accountResponse.Customers[0];
            var customerAccount = String.Format("customers/{0}", customer.CompanyId);


            // Send an API request to list all the DPCs available.
            CustomersResource.DpcsResource.ListRequest request = service.Customers.Dpcs.
                List(customerAccount);
            CustomerListDpcsResponse response = request.Execute();

            // Print out the details of each DPC.
            IList<Dpc> dpcs = response.Dpcs;
            foreach (Dpc dpcApp in dpcs)
            {
                Console.WriteLine("Name:{0}  APK:{1}",
                                  dpcApp.DpcName,
                                  dpcApp.PackageName);
            }

        }
    }
}

Langkah 4: Jalankan contoh aplikasi

Untuk membuat dan menjalankan contoh, klik Start di toolbar Visual Studio.

Saat pertama kali menjalankan aplikasi, Anda perlu mengizinkan akses:

  1. Aplikasi akan mencoba membuka tab baru di browser default Anda. Jika gagal, salin URL dari konsol dan buka di browser. Jika belum login ke Akun Google, Anda akan diminta untuk login. Jika Anda login ke beberapa Akun Google, halaman tersebut akan meminta Anda memilih akun untuk otorisasi.
  2. Klik Accept.
  3. Tutup tab browser—aplikasi akan terus berjalan.

Catatan

  • Karena library klien Google API menyimpan data otorisasi di sistem file, peluncuran berikutnya tidak akan meminta Anda melakukan otorisasi.
  • Untuk mereset data otorisasi aplikasi, hapus file ~/.credentials/zero-touch.quickstart.json dan jalankan kembali aplikasi.
  • Alur otorisasi di panduan memulai ini ideal untuk aplikasi command line. Untuk mempelajari cara menambahkan otorisasi ke aplikasi web, lihat Menggunakan OAuth 2.0, Aplikasi web (ASP.NET MVC).

Pemecahan masalah

Berikut adalah beberapa hal umum yang sebaiknya Anda periksa. Beri tahu kami apa yang salah dengan panduan memulai dan kami akan berupaya memperbaikinya.

  • Pastikan Anda mengizinkan panggilan API dengan Akun Google yang sama dengan yang menjadi anggota akun pelanggan pendaftaran zero-touch Anda. Coba login ke portal pendaftaran zero-touch menggunakan Akun Google yang sama untuk menguji akses Anda.
  • Konfirmasi bahwa akun telah menyetujui Persyaratan Layanan terbaru di portal. Lihat Akun pelanggan.

Mempelajari lebih lanjut