本指南演示了以下 Azure .NET API 的用法,包括設置認證、創建並使用 Azure 存儲、創建並使用 Azure SQL 資料庫、部署虛擬機、從 GitHub 部署 Azure Web 應用。在本教程中完成的所有操作均符合1元試用條件。 開始之前 如果您還沒有 Azure 賬戶,可以申請1 ...
本指南演示了以下 Azure .NET API 的用法,包括設置認證、創建並使用 Azure 存儲、創建並使用 Azure SQL 資料庫、部署虛擬機、從 GitHub 部署 Azure Web 應用。在本教程中完成的所有操作均符合1元試用條件。
開始之前
如果您還沒有 Azure 賬戶,可以申請1元試用賬戶。
安裝 Azure PowerShell
設置認證
為了使用 Azure .NET Management Libraires ,您創建的應用程式需要許可權來讀取和創建 Azure 訂閱中的資源。我們首先需要為應用程式創建一個 service principal , service principal 可以通過非交互方式授予應用程式所需的許可權 。1. 以下 PoweShell 命令登陸中國區 Azure:
Login-AzureRmAccount -EnvironmentName AzureChinaClou
註意記錄 TenandId 和 SubscriptionId,在後續步驟中需要用到。
2. 以下命令創建 service principal:
# Create the service principal (use a strong password) $sp = New-AzureRmADServicePrincipal -DisplayName "AzureDotNetTest" -Password "password" # Give it the permissions it needs... New-AzureRmRoleAssignment -ServicePrincipalName $sp.ApplicationId -RoleDefinitionName Contributor # Display the Application ID, because we'll need it later. $sp | Select DisplayName, ApplicationId
註意記錄 ApplicationId。
3. 一個名為 Azureauth.properties 的 txt 文件,輸入以下內容:
# sample management library properties file subscription=dd9eebf5-eae4-4d04-a371-29ba614032e8 client=67699411-1af6-4341-a47e-5d4cf0b62484 key=P@ssword1 tenant=dd8210ad-5216-499c-ab57-6d297fc0e5d2 managementURI=https://management.core.chinacloudapi.cn/ baseURL=https://management.chinacloudapi.cn/ authURL=https://login.chinacloudapi.cn/ graphURL=https://graph.chinacloudapi.cn/
• subscription:1中記錄的 SubscriptionId
• client:2中記錄的 ApplicationId
• key:2中的 -Password 參數值
• tenant:1中記錄的 TenantId
4. 保存 Azureauth.properties,運行以下命令將 Azureauth.properties 的存放路徑設置為環境變數 AZURE_AUTH_LOCATION。
[Environment]::SetEnvironmentVariable("AZURE_AUTH_LOCATION", "C:\src\azureauth.properties.txt", "User")
設置 Visual Studio 連接到中國區 Azure
根據您使用的 Visual Studio 版本,請參考中國區 Azure 應用程式開發說明中的設置開發電腦,本教程使用的是 Visual Studio 2017 community 版本。
步驟3:創建新的 console 應用程式。
打開 Visual Studio, “File”->”New”->”Project”,選擇 Console App (.NET Core)。
創建完成後,打開 Package Manager Console,運行以下命令安裝 Azure .NET Management Libraries:
# Azure Management Libraries for .NET (Fluent) Install-Package Microsoft.Azure.Management.Fluent # Azure Store client libraries Install-Package WindowsAzure.Storage # SQL Database client libraries Install-Package System.Data.SqlClient
創建虛擬機
打開 Program.cs 文件,添加以下命名空間:
using System; using System.Linq; using Microsoft.Azure.Management.Compute.Fluent; using Microsoft.Azure.Management.Compute.Fluent.Models; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System.Data.SqlClient;
以下示例將在您的 Azure 訂閱中創建一臺 Windows 虛擬機,該虛擬機運行在“中國北部”,虛擬機類型為 StandardD2V2,系統為 WindowsServer2012R2Datacenter。
將 Main 方法替換為以下代碼,請將 username 和 password 變數替換成您的值:
static void Main(string[] args) { // Set some variables... string username = "vmuser1"; string password = "Password0123!"; string rgName = "sampleResourceGroup"; string windowsVmName = "sampleWindowsVM"; string publicIpDnsLabel = "samplePublicIP"; // Authenticate var credentials = SdkContext.AzureCredentialsFactory .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); // Create the VM Console.WriteLine("Creating VM..."); var windowsVM = azure.VirtualMachines.Define(windowsVmName) .WithRegion(Region.ChinaEast) .WithNewResourceGroup(rgName) .WithNewPrimaryNetwork("10.0.0.0/28") .WithPrimaryPrivateIPAddressDynamic() .WithNewPrimaryPublicIPAddress(publicIpDnsLabel) .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter) .WithAdminUsername(username) .WithAdminPassword(password) .WithSize(VirtualMachineSizeTypes.StandardD2V2) .Create(); // Wait for the user Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }
按 F5 運行程式。幾分鐘後,當看到“Press enter to continue...”時,說明虛擬機已經創建完畢,您可以運行以下 PowerShell 命令來確認虛擬機是否創建成功:
Get-AzureRmVm -ResourceGroupName sampleResourceGroup
或者在 Azure 門戶中查看:
從 GitHub 倉庫部署 Azure Web 應用
現在我們將修改代碼來實現從 GitHub 倉庫部署 Web 應用程式。將 Main 方法替換為以下代碼:
static void Main(string[] args) { // Set some variables... string rgName = "sampleWebAppGroup"; string appName = SdkContext.RandomResourceName("WebApp", 20); // Authenticate var credentials = SdkContext.AzureCredentialsFactory .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .Authenticate(credentials) .WithDefaultSubscription(); // Create the web app Console.WriteLine("Creating Web App..."); var app = azure.WebApps.Define(appName) .WithRegion(Region.ChinaNorth) .WithNewResourceGroup(rgName) .WithNewFreeAppServicePlan() .DefineSourceControl() .WithPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started") .WithBranch("master") .Attach() .Create(); Console.WriteLine("Your web app is live at: https://{0}", app.HostNames.First()); // Wait for the user Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }
按 F5 運行程式,完成後返回如下結果。
訪問 https://webapp0513224523a.chinacloudsites.cn 就能看到部署在 Azure web 應用中的.NET 程式啦。
連接到 Azure SQL 資料庫
下麵我們將演示如何創建 Azure SQL 資料庫,連接到資料庫創建表並插入值。將 Main 方法替換為以下代碼:
static void Main(string[] args) { // Set some variables... string rgName = "sampleSQLDBGroup"; string adminUser = SdkContext.RandomResourceName("db", 8); string sqlServerName = SdkContext.RandomResourceName("sql", 10); string sqlDbName = SdkContext.RandomResourceName("dbname", 8); string dbPassword = "P@ssword01!"; // Authenticate var credentials = SdkContext.AzureCredentialsFactory .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .Authenticate(credentials) .WithDefaultSubscription(); // Create the SQL server and database Console.WriteLine("Creating server..."); var sqlServer = azure.SqlServers.Define(sqlServerName) .WithRegion(Region.ChinaNorth) .WithNewResourceGroup(rgName) .WithAdministratorLogin(adminUser) .WithAdministratorPassword(dbPassword) .WithNewFirewallRule("0.0.0.0", "255.255.255.255") .Create(); Console.WriteLine("Creating database..."); var sqlDb = sqlServer.Databases.Define(sqlDbName).Create(); // Display information for connecting later... Console.WriteLine("Created database {0} in server {1}.", sqlDbName, sqlServer.FullyQualifiedDomainName); Console.WriteLine("Your user name is {0}.", adminUser + "@" + sqlServer.Name); // Build the connection string var builder = new SqlConnectionStringBuilder(); builder.DataSource = sqlServer.FullyQualifiedDomainName; builder.InitialCatalog = sqlDbName; builder.UserID = adminUser + "@" + sqlServer.Name; // Format user ID as "user@server" builder.Password = dbPassword; builder.Encrypt = true; builder.TrustServerCertificate = true; // connect to the database, create a table and insert an entry into it using (var conn = new SqlConnection(builder.ConnectionString)) { conn.Open(); Console.WriteLine("Populating database..."); var createCommand = new SqlCommand("CREATE TABLE CLOUD (name varchar(255), code int);", conn); createCommand.ExecuteNonQuery(); var insertCommand = new SqlCommand("INSERT INTO CLOUD (name, code ) VALUES ('Azure', 1);", conn); insertCommand.ExecuteNonQuery(); Console.WriteLine("Reading from database..."); var selectCommand = new SqlCommand("SELECT * FROM CLOUD", conn); var results = selectCommand.ExecuteReader(); while (results.Read()) { Console.WriteLine("Name: {0} Code: {1}", results[0], results[1]); } } // Wait for the user Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }
按 F5 運行程式,運行完成後我們通過 SQL Server Management Studio 來驗證:
打開 SSMS,根據上面程式的輸出結果,ServerName 為 sql646624.database.chinacloudapi.cn,用戶名為:db51559@sql64662, 密碼為代碼中定義的變數 dbPassword 的值 P@ssword01!,使用 SQL Server Authenticaiton 方式登錄:
可以看到我們在 Azure SQL 資料庫中創建了一張名為 dbo.CLOUD 的表,並插入了一條數據。
將文件上傳到 Azure Storage
下麵我們將演示如何在 Azure 中創建存儲賬戶並將文件上傳到 Blob 存儲。將 Main 方法替換為以下代碼:
static void Main(string[] args)
{ // Set some variables... string rgName = "sampleStorageGroup"; string storageAccountName = SdkContext.RandomResourceName("st", 10); // Authenticate var credentials = SdkContext.AzureCredentialsFactory .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .Authenticate(credentials) .WithDefaultSubscription(); // Create the storage account Console.WriteLine("Creating storage account..."); var storage = azure.StorageAccounts.Define(storageAccountName) .WithRegion(Region.ChinaNorth) .WithNewResourceGroup(rgName) .Create(); var storageKeys = storage.GetKeys(); string storageConnectionString = "DefaultEndpointsProtocol=https;" + "AccountName=" + storage.Name + ";AccountKey=" + storageKeys[0].Value + ";EndpointSuffix=core.chinacloudapi.cn"; var account = CloudStorageAccount.Parse(storageConnectionString); var serviceClient = account.CreateCloudBlobClient(); // Create container. Name must be lower case. Console.WriteLine("Creating container..."); var container = serviceClient.GetContainerReference("helloazure"); container.CreateIfNotExistsAsync().Wait(); // Make the container public var containerPermissions = new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Container }; container.SetPermissionsAsync(containerPermissions).Wait(); // write a blob to the container Console.WriteLine("Uploading blob..."); var blob = container.GetBlockBlobReference("helloazure.txt"); blob.UploadTextAsync("Hello, Azure!").Wait(); Console.WriteLine("Your blob is located at {0}", blob.StorageUri.PrimaryUri); // Wait for the user Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }
按 F5 運行程式,運行完成後。我們打開 Azure 門戶,來驗證文件是否已經上傳到 Azure 存儲中。
從 Azure 門戶中我們可以看到文件已經上傳到 Azure 存儲中了。
至此,您已經學會瞭如何使用 Azure .NET Management Libraries 來創建並管理一些重要的 Azure 資源啦!
後續步驟
更多 Azure .NET 示例:
虛擬機
Web 應用
SQL 資料庫
歡迎有興趣的朋友多多交流
A究院研究生 [email protected]