Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Azure生成资源组C#_C#_Json_Azure_Azure Sdk .net_Azure Resource Manager - Fatal编程技术网

Azure生成资源组C#

Azure生成资源组C#,c#,json,azure,azure-sdk-.net,azure-resource-manager,C#,Json,Azure,Azure Sdk .net,Azure Resource Manager,我希望你能在代码方面帮助我,我在生成创建资源组的代码时遇到了麻烦,但由于某些原因,我无法理解错误是什么。。。我使用github的代码:我需要为工作中的项目使用此示例。。。如果你能帮我找到这个代码的解决方案,我将非常感激 代码如下: Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using M

我希望你能在代码方面帮助我,我在生成创建资源组的代码时遇到了麻烦,但由于某些原因,我无法理解错误是什么。。。我使用github的代码:我需要为工作中的项目使用此示例。。。如果你能帮我找到这个代码的解决方案,我将非常感激

代码如下:

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.WindowsAzure;

namespace pruebaazure
{
    class Program
    {
        static void Main(string[] args)
        {
            var token = GetAuthorizationHeader();
            var credential = new Microsoft.WindowsAzure.TokenCloudCredentials("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxef", token);


            CreateResourceGroup(credential);
            Console.ReadLine();

            CreateTemplateDeployment(credential);
            Console.ReadLine();

            DeleteResourceGroup(credential);
            Console.ReadLine();


        }
        private static string GetAuthorizationHeader()
        {
            ClientCredential cc = new ClientCredential("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx8", "xxxxxxxK2");
            var context = new AuthenticationContext("https://login.windows.net/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx4");
            var result = context.AcquireToken("https://management.azure.com/", cc);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            string token = result.AccessToken;

            return token;
        }

        public async static void CreateResourceGroup(TokenCloudCredentials credential)
        {
            Console.WriteLine("Creating the resource group...");
            var resourceGroup = new ResourceGroup { Location = "West US" };
            using (var resourceManagementClient = new ResourceManagementClient(credential))
            {
                var rgResult = await resourceManagementClient.ResourceGroups.CreateOrUpdateAsync("mytestrg1", resourceGroup);
                Console.WriteLine(rgResult.StatusCode);
            }
        }

        public async static void CreateTemplateDeployment(TokenCloudCredentials credential)
        {
            Console.WriteLine("Creating the template deployment...");
            var deployment = new Deployment();
            deployment.Properties = new DeploymentProperties
            {
                Mode = DeploymentMode.Incremental,
                TemplateLink = new TemplateLink
                {
                    Uri = new Uri("https://xxxxxxxxxxxxya.blob.core.windows.net/templates/VirtualMachineTemplate.json").ToString()
                },
                ParametersLink = new ParametersLink
                {
                    Uri = new Uri("https://xxxxxxxxxxxxxya.blob.core.windows.net/templates/Parameters.json").ToString()
                }
            };
            using (var templateDeploymentClient = new ResourceManagementClient(credential))
                {
                var dpResult = await templateDeploymentClient.Deployments.CreateOrUpdateAsync("mytestrg1", "mytestdp1", deployment);
                Console.WriteLine(dpResult.StatusCode);
            }
        }

        public async static void DeleteResourceGroup(TokenCloudCredentials credential)
        {
            using (var resourceGroupClient = new ResourceManagementClient(credential))
            {
                var rgResult = await resourceGroupClient.ResourceGroups.DeleteAsync("mytestrg1");
                Console.WriteLine(rgResult.StatusCode);
            }
        }
    }
}
Parameters.json

{
  "contentVersion": "1.0.0.0",
  "parameters": { 
    "vmName": { "value": "mytestvm1" },
    "newStorageAccountName": { "value": "mytestsa1" },
    "storageAccountType": { "value": "Standard_LRS" },
    "publicIPaddressName": { "value": "mytestip1" },
    "location": { "value": "West US" },
    "vmStorageAccountContainerName": { "value": "vhds" },
    "vmSize": { "value": "Standard_A1" },
    "subscriptionId": { "value": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxef" },
    "vmSourceImageName": { "value": "sourceimgtest1" },
    "adminUserName": { "value": "mytestacct1" },
    "adminPassword": { "value": "mytestpass1" },
    "virtualNetworkName": { "value": "mytestvn1" },
    "dnsName": { "value": "mytestdns1" }, 
    "nicName": { "value": "mytestnic1" } 
  }
}
VirtualMachineTemplate.json

{
  "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/VM.json",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "location": {
      "type": "String",
      "defaultValue": "West US",
      "allowedValues": [ "West US", "East US" ]
    },
    "newStorageAccountName": { "type": "string" },
    "storageAccountType": {
      "type": "string",
      "defaultValue": "Standard_LRS",
      "allowedValues": [ "Standard_LRS", "Standard_GRS" ]
    },
    "publicIPAddressName": { "type": "string" },
    "publicIPAddressType": {
      "type": "string",
      "defaultValue": "Dynamic",
      "allowedValues": [ "Dynamic" ]
    },
    "vmStorageAccountContainerName": {
      "type": "string",
      "defaultValue": "vhds"
    },
    "vmName": { "type": "string" },
    "vmSize": {
      "type": "string",
      "defaultValue": "Standard_A0",
      "allowedValues": [ "Standard_A0", "Standard_A1" ]
    },
    "vmSourceImageName": { "type": "string" },
    "adminUserName": { "type": "string" },
    "adminPassword": { "type": "securestring" },
    "virtualNetworkName": { "type": "string" },
    "addressPrefix": {
      "type": "string",
      "defaultValue": "10.0.0.0/16"
        },
        "subnet1Name": {
          "type": "string",
          "defaultValue": "Subnet-1"
        },
        "subnet2Name": {
          "type": "string",
          "defaultValue": "Subnet-2"
        },
        "subnet1Prefix": {
      "type": "string",
      "defaultValue": "10.0.0.0/24"
    },
    "subnet2Prefix": {
      "type": "string",
      "defaultValue": "10.0.1.0/24"
    },
    "dnsName": { "type": "string" },
    "subscriptionId": { "type": "string" },
    "nicName": { "type": "string" }
  },
  "resources": [
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[parameters('newStorageAccountName')]",
      "location": "[parameters('location')]",
      "properties": { "accountType": "[parameters('storageAccountType')]" }
    },
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Network/publicIPAddresses",
      "name": "[parameters('publicIPAddressName')]",
      "location": "[parameters('location')]",
      "properties": {
        "publicIPAllocationMethod": "[parameters('publicIPAddressType')]",
        "dnsSettings": { "domainNameLabel": "[parameters('dnsName')]" }
      }
    },
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Network/virtualNetworks",
      "name": "[parameters('virtualNetworkName')]",
      "location": "[parameters('location')]",
      "properties": {
        "addressSpace": { "addressPrefixes": [ "[parameters('addressPrefix')]" ] },
        "subnets": [
          {
            "name": "[parameters('subnet1Name')]",
            "properties": { "addressPrefix": "[parameters('subnet1Prefix')]"     }
          },
          {
            "name": "[parameters('subnet2Name')]",
            "properties": { "addressPrefix": "[parameters('subnet2Prefix')]"     }
          }
        ]
      }
    },
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Network/networkInterfaces",
      "name": "[parameters('nicName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[concat('Microsoft.Network/publicIPAddresses/', parameters('publicIPAddressName'))]",
        "[concat('Microsoft.Network/virtualNetworks/', parameters('virtualNetworkName'))]"
      ],
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddressName'))]"
              },
              "subnet": { "id": "[variables('subnet1Ref')]" }
            }
          }
        ]
      }
    },
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Compute/virtualMachines",
      "name": "[parameters('vmName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[concat('Microsoft.Storage/storageAccounts/', parameters('newStorageAccountName'))]",
        "[concat('Microsoft.Network/networkInterfaces/', parameters('nicName'))]"
      ],
      "properties": {
        "hardwareProfile": { "vmSize": "[parameters('vmSize')]" },
        "osProfile": {
          "computername": "[parameters('vmName')]",
          "adminUsername": "[parameters('adminUsername')]",
          "adminPassword": "[parameters('adminPassword')]",
          "windowsProfile": { "provisionVMAgent": "true" }
        },
        "storageProfile": {
          "sourceImage": { "id": "[variables('sourceImageName')]" },
          "destinationVhdsContainer": "[concat('http://',parameters('newStorageAccountName'),'.blob.core.windows.net/',    parameters('vmStorageAccountContainerName'),'/')]"
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces',parameters('nicName'))]"
            }
          ]
        }
      }
    }
  ],
  "variables": {
    "sourceImageName": "[concat('/',parameters('subscriptionId'),'/services/images/',parameters('vmSourceImageName'))]",
    "vnetID": "[resourceId('Microsoft.Network/virtualNetworks',parameters('virtualNetworkName'))]",
    "subnet1Ref": [concat(variables('vnetID'),'/subnets/',parameters('subnet1Name'))]"
      }
   }
}
问题出在program.cs中

    public async static void CreateResourceGroup(TokenCloudCredentials credential)
    {
        Console.WriteLine("Creating the resource group...");
        var resourceGroup = new ResourceGroup { Location = "West US" };
        using (var resourceManagementClient = new ResourceManagementClient(credential))
        {
            var rgResult = await resourceManagementClient.ResourceGroups.CreateOrUpdateAsync("mytestrg1", resourceGroup);
            Console.WriteLine(rgResult.StatusCode);
        }
    }
在:

错误是:

cannot convert from Microsoft.WindowsAzure.TokenCloudCredentials credentials to Microsoft.Rest.CerviceClientCredentials 
ResourcesGroup does not contain the definition for "StatusCode" and no extension method "StatusCode" accepting a first argument of type 'ResourceGroup' Could be found 

错误是:

cannot convert from Microsoft.WindowsAzure.TokenCloudCredentials credentials to Microsoft.Rest.CerviceClientCredentials 
ResourcesGroup does not contain the definition for "StatusCode" and no extension method "StatusCode" accepting a first argument of type 'ResourceGroup' Could be found 

错误与此相同。无法在此处将Microsoft.WindowsAzure.TokenCloudCredentials凭据转换为Microsoft.Rest.CervicClientCredentials凭据

using (var templateDeploymentClient = new ResourceManagementClient(credential))
            {
                var dpResult = await templateDeploymentClient.Deployments.CreateOrUpdateAsync("mytestrg1", "mytestdp1", deployment);
                Console.WriteLine(dpResult.StatusCode);
            } 
对于这一点:

    public async static void DeleteResourceGroup(TokenCloudCredentials credential)
    {
        using (var resourceGroupClient = new ResourceManagementClient(credential))
        {
            var rgResult = await resourceGroupClient.ResourceGroups.DeleteAsync("mytestrg1");
            Console.WriteLine(rgResult.StatusCode);
        }
    }

我假设您使用的是
“Microsoft.Azure.Management.Resources”
nuget软件包的最新预览版本,即版本=
“3.3.0-preview”

根据您的代码和显示的错误,问题的根本原因在于这一行代码:

var-credential=新的Microsoft.WindowsAzure.TokenCloudCredentials(“xxxxxxxx-xxxx-xxxx-XXXXXXXXXXXX-XXXXXXXXXX EF”,令牌)

更清楚地说,Microsoft.WindowsAzure命名空间下的TokenCloudCredentials类不是ResourceManagementClient中ServiceClientCredentials抽象类的子类

您应该使用Microsoft.Rest命名空间下的TokenCloudCredentials

因此,您可以按如下方式修复它:

var credential = new Microsoft.Rest.TokenCloudCredentials(token);
您还可以参考下面GitHub存储库中的一些示例代码: 介绍如何使用最新的“Microsoft.Azure.Management.Resources”nuget软件包创建/读取/更新/删除资源组以及创建资源组模板部署


希望这有帮助

为什么不使用SDK呢?我的回答有助于解决您的问题吗?我使用的是Microsoft.Azure.Management.Resources的最新版本。。。我已经下载了最新的Azure SDK 2.8.14,并且我处于相同的情况,我无法执行程序,因为使用了(var resourceManagementClient=new resourceManagementClient(凭据))错误是:无法将Microsoft.WindowsAzure.TokenCloudCredentials凭据转换为Microsoft.Rest.CerviceClientCredentials我已编辑了我的答案,希望答案更清晰易懂。让我知道,如果你需要任何进一步的澄清,它是否解决你的问题。
var credential = new Microsoft.Rest.TokenCloudCredentials(token);