Panduan memulai .NET untuk pelanggan

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

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan:

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

Langkah 1: Aktifkan API pendaftaran zero-touch

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

Langkah 2: Menyiapkan proyek

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

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

Langkah 3: Menyiapkan contoh aplikasi

  1. Tarik client_secret.json (didownload pada Langkah 1) ke Visual Studio Anda Penjelajah Solusi.
  2. Pilih client_secret.json, lalu buka jendela {i>Properties<i} dan setel Kolom Copy to output directory ke Always copy.
  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

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 membukanya di browser Anda. Jika Anda belum {i>login<i} ke Akun Google, diminta untuk {i>log in<i}. Jika Anda login ke beberapa Akun Google, halaman akan meminta Anda memilih akun untuk otorisasi.
  2. Klik Setuju.
  3. Tutup tab browser—aplikasi terus berjalan.

Catatan

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

Pemecahan masalah

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

  • Pastikan Anda memberi otorisasi panggilan API dengan Akun Google yang sama dengan yang menjadi anggota akun pelanggan pendaftaran zero-touch. 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.

Pelajari lebih lanjut