Azure. NET Libraries, azurelibraries

Source: Internet
Author: User
Tags strong password

Azure. NET Libraries, azurelibraries

This guide demonstrates the usage of the following Azure. NET APIs, including setting up authentication, creating and using Azure storage, creating and using Azure SQL databases, deploying virtual machines, and deploying Azure Web applications from GitHub. All the operations completed in this tutorial meet the $1 trial conditions.

Before getting started

If you do not have an Azure account, you can apply for a 1 yuan trial account.
Install Azure PowerShell

Set Authentication

To use Azure. NET Management Libraires, the application you create requires the permission to read and create resources in the Azure subscription. First, we need to create a service principal for the application. service principal can grant the permissions required by the application in non-interactive mode. 1. Run the following PoweShell command to log on to Azure in China:
    

Login-AzureRmAccount -EnvironmentName AzureChinaClou

  

 

Note that the TenandId and SubscriptionId must be recorded in subsequent steps.

2. Run the following command to create 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

Note the ApplicationId.

3. Enter the following content in a txt file named Azureauth. properties:

# sample management library properties filesubscription=dd9eebf5-eae4-4d04-a371-29ba614032e8client=67699411-1af6-4341-a47e-5d4cf0b62484key=P@ssword1tenant=dd8210ad-5216-499c-ab57-6d297fc0e5d2managementURI=https://management.core.chinacloudapi.cn/baseURL=https://management.chinacloudapi.cn/authURL=https://login.chinacloudapi.cn/graphURL=https://graph.chinacloudapi.cn/

• SubscriptionId recorded in subscription1
• Client: ApplicationId recorded in 2
• Key:-Password parameter value in 2
• Tenant: The TenantId recorded in 1


4. Save Azureauth. properties and run the following command to set the storage path of Azureauth. properties to the environment variable AZURE_AUTH_LOCATION.
[Environment]: SetEnvironmentVariable ("AZURE_AUTH_LOCATION", "C: \ src \ azureauth.properties.txt", "User ")

Set Visual Studio to connect to Azure in China

Based on the Visual Studio version you are using, see setting up the development computer in Azure Application Development instructions in China. This tutorial uses Visual Studio 2017 community.
Step 3: Create a new console application.
Open Visual Studio, "File"-> "New"-> "Project", and select Console App (. NET Core ).

After the Package Manager is created, open the Package Manager Console and run the following command to install Azure. NET Management Libraries:

# Azure Management Libraries for .NET (Fluent)Install-Package Microsoft.Azure.Management.Fluent# Azure Store client librariesInstall-Package WindowsAzure.Storage# SQL Database client librariesInstall-Package System.Data.SqlClient

Create a virtual machine

Open the Program. cs file and add the following namespace:

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;

In the following example, a Windows virtual machine is created in your Azure subscription. The virtual machine runs in north China. The virtual machine type is StandardD2V2 and the system is WindowsServer2012R2Datacenter.
Replace the Main method with the following code. Replace the username and password variables with your values:

static void Main(string[] args){// Set some variables...string username = "vmuser1";string password = "Password0123!";string rgName = "sampleResourceGroup";string windowsVmName = "sampleWindowsVM";string publicIpDnsLabel = "samplePublicIP";// Authenticatevar credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));var azure = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(credentials).WithDefaultSubscription();// Create the VMConsole.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 userConsole.WriteLine("Press enter to continue...");Console.ReadLine();}

Press F5 to run the program. A few minutes later, when you see "Press enter to continue...", it indicates that the VM has been created. You can run the following PowerShell command to check whether the VM has been created successfully:

Get-AzureRmVm -ResourceGroupName sampleResourceGroup 

You can also view the following information in the Azure Portal:

Deploy Azure Web applications from the GitHub Repository

Now we will modify the code to deploy Web applications from the GitHub repository. Replace the Main method with the following code:

static void Main(string[] args){// Set some variables...string rgName = "sampleWebAppGroup";string appName = SdkContext.RandomResourceName("WebApp", 20);// Authenticatevar credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));var azure = Azure.Configure().Authenticate(credentials).WithDefaultSubscription();// Create the web appConsole.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 userConsole.WriteLine("Press enter to continue...");Console.ReadLine();}

Press F5 to run the program and return the following results.

Access the https://webapp0513224523a.chinacloudsites.cn to see the. NET Program deployed in the Azure web application.

 

Connect to Azure SQL database

Next we will demonstrate how to create an Azure SQL database, connect to the database to create a table, and insert values. Replace the Main method with the following code:

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!";// Authenticatevar credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));var azure = Azure.Configure().Authenticate(credentials).WithDefaultSubscription();// Create the SQL server and databaseConsole.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 stringvar 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 itusing (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 userConsole.WriteLine("Press enter to continue...");Console.ReadLine();}

Press F5 to run the program. After running the program, we verify it through SQL Server Management Studio:

Open SSMS. Based on the output of the above program, ServerName is sql646624.database.chinacloudapi.cn, username is db51559 @ sql64662, and password is the value of the variable dbPassword defined in the Code P @ ssword01 !, Use SQL Server Authenticaiton to log on:

We can see that we created a table named dbo. CLOUD in the Azure SQL database and inserted a piece of data.

 

Upload files to Azure Storage

Next we will demonstrate how to create a storage account in Azure and upload files to Blob storage. Replace the Main method with the following code:
Static void Main (string [] args)

{// Set some variables...string rgName = "sampleStorageGroup";string storageAccountName = SdkContext.RandomResourceName("st", 10);// Authenticatevar credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));var azure = Azure.Configure().Authenticate(credentials).WithDefaultSubscription();// Create the storage accountConsole.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 publicvar containerPermissions = new BlobContainerPermissions(){ PublicAccess = BlobContainerPublicAccessType.Container };container.SetPermissionsAsync(containerPermissions).Wait();// write a blob to the containerConsole.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 userConsole.WriteLine("Press enter to continue...");Console.ReadLine();}

Press F5 to run the program. Open the Azure portal to verify that the file has been uploaded to Azure storage.

From the Azure portal, we can see that the file has been uploaded to Azure storage.

So far, you have learned how to use Azure. NET Management Libraries to create and manage some important Azure resources!

Subsequent steps
For more Azure. NET examples:
Virtual Machine
Web Applications
SQL database

For more highlights, click to view

You are welcome to talk with others.
Graduate school A Azurecommunity@qq.com

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.