当前位置: 首页>>代码示例>>C#>>正文


C# Azure.TokenCloudCredentials类代码示例

本文整理汇总了C#中Microsoft.Azure.TokenCloudCredentials的典型用法代码示例。如果您正苦于以下问题:C# TokenCloudCredentials类的具体用法?C# TokenCloudCredentials怎么用?C# TokenCloudCredentials使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


TokenCloudCredentials类属于Microsoft.Azure命名空间,在下文中一共展示了TokenCloudCredentials类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CreateClusterAsync

        /// <summary>
        /// Initiates creation of a new cluster.
        /// </summary>
        /// <remarks>
        /// If a cluster with the given domain could not be created, an exception should be thrown indicating the failure reason.
        /// </remarks>
        /// <param name="name">A unique name for the cluster.</param>
        /// <returns>The FQDN of the new cluster.</returns>
        public async Task<string> CreateClusterAsync(string name, IEnumerable<int> ports)
        {
            string token = await this.GetAuthorizationTokenAsync();
            TokenCloudCredentials credential = new TokenCloudCredentials(this.settings.SubscriptionID.ToUnsecureString(), token);

            string rgStatus = await this.CreateResourceGroupAsync(credential, name);

            if (rgStatus == "Exists")
            {
                throw new System.InvalidOperationException(
                    "ResourceGroup/Cluster already exists. Please try passing a different name, or delete the ResourceGroup/Cluster first.");
            }

            string templateContent = this.armTemplate;
            string parameterContent = this.armParameters
                .Replace("_CLUSTER_NAME_", name)
                .Replace("_CLUSTER_LOCATION_", this.settings.Region)
                .Replace("_USER_", this.settings.Username.ToUnsecureString())
                .Replace("_PWD_", this.settings.Password.ToUnsecureString());

            int ix = 1;
            foreach(int port in ports)
            {
                parameterContent = parameterContent.Replace($"_PORT{ix}_", port.ToString());
                ++ix;
            }

            await this.CreateTemplateDeploymentAsync(credential, name, templateContent, parameterContent);

            return (name + "." + this.settings.Region + ".cloudapp.azure.com");
        }
开发者ID:TylerAngell,项目名称:service-fabric-dotnet-management-party-cluster,代码行数:39,代码来源:ArmClusterOperator.cs

示例2: Main

        private const double days = -10; //max = -90  (90 days of logs is stored by audit logs)

        static void Main(string[] args)
        {
            Console.WriteLine("Starting operations log export.");

            string token = GetAuthorizationHeader();

            TokenCloudCredentials credentials = new TokenCloudCredentials(SubscriptionID, token);
            InsightsClient client = new InsightsClient(credentials);

            DateTime endDateTime = DateTime.Now;
            DateTime startDateTime = endDateTime.AddDays(days);
            
            string filterString = FilterString.Generate<ListEventsForResourceProviderParameters>(eventData => (eventData.EventTimestamp >= startDateTime) && (eventData.EventTimestamp <= endDateTime));
                     
            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);
            List<EventData> logList = new List<EventData>(response.EventDataCollection.Value);

            while (!string.IsNullOrEmpty(response.EventDataCollection.NextLink))
            {
                Console.WriteLine($"Retrieving page {response.EventDataCollection.NextLink}");

                response = client.EventOperations.ListEventsNext(response.EventDataCollection.NextLink);
                logList.AddRange(response.EventDataCollection.Value);
            }

            ResourceManagementClient resClient = new ResourceManagementClient(credentials);
          
            Console.WriteLine($"Page retrieval completed, preparing to write to a file {CSVExportNamePath}.");

            ExportOpsLogToCSV(logList, resClient);

            Console.WriteLine("Export completed.");
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
开发者ID:renatafigueiral,项目名称:networking-dotnet-log-converter,代码行数:37,代码来源:Program.cs

示例3: GetShare

        public void GetShare()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(ExpectedResults.ShareGetResponse)
            };

            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            var subscriptionId = Guid.NewGuid().ToString();

            var token = new TokenCloudCredentials(subscriptionId, Constants.TokenString);
            var client = GetClient(handler, token);

            var result = client.Shares.Get(Constants.ResourceGroupName, Constants.FarmId, Constants.ShareAName);

            var expectedUri = string.Format(
                GetUriTemplate,
                Constants.BaseUri,
                subscriptionId,
                Constants.ResourceGroupName,
                Constants.FarmId, 
                Uri.EscapeDataString(Constants.ShareAName)
                );

            Assert.Equal(handler.Uri.AbsoluteUri, expectedUri);

            Assert.Equal(HttpMethod.Get, handler.Method);
            
            CompareExpectedResult(result.Share);
        }
开发者ID:bganapa,项目名称:azure-sdk-for-net,代码行数:34,代码来源:ShareTests.cs

示例4: CallSDK

        private static void CallSDK(string resourceManagementEndpoint, string subscriptionId, string header, string resourceGroupName)
        {
            TokenCloudCredentials aadTokenCredentials = new TokenCloudCredentials(subscriptionId, header);
            Uri resourceManagerUri = new Uri(resourceManagementEndpoint);
            DataPipelineManagementClient client = new DataPipelineManagementClient(aadTokenCredentials, resourceManagerUri);

            // create a data factory
            Console.WriteLine("Creating a data factory");
            try
            { 
                client.DataFactories.CreateOrUpdate(resourceGroupName,
                    new DataFactoryCreateOrUpdateParameters()
                    {
                        DataFactory = new DataFactory()
                        {
                            Name = dataFactoryName,
                            Location = "westus",
                            Properties = new DataFactoryProperties() { }
                        }
                    }
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
开发者ID:laurikoobas,项目名称:Azure,代码行数:27,代码来源:Program.cs

示例5: GetWebSiteManagementClient

 public WebSiteManagementClient GetWebSiteManagementClient(RecordedDelegatingHandler handler)
 {
     handler.IsPassThrough = false;
     var token = new TokenCloudCredentials(Guid.NewGuid().ToString(), "abc123");
     var client = new WebSiteManagementClient(token).WithHandler(handler);
     client = client.WithHandler(handler);
     return client;
 }
开发者ID:ChandraSogali,项目名称:azure-sdk-for-net,代码行数:8,代码来源:WebHostingPlans.ScenarioTests.cs

示例6: GetUsageAggregationManagementClient

        public UsageAggregationManagementClient GetUsageAggregationManagementClient(RecordedDelegatingHandler handler)
        {
            handler.IsPassThrough = false;

            var token = new TokenCloudCredentials(Guid.NewGuid().ToString(), "abc123");
            UsageAggregationManagementClient client = new UsageAggregationManagementClient(token, new Uri("https://mn-azure/management/"));
            client = client.WithHandler(handler);
            return client;
        }
开发者ID:pattipaka,项目名称:azure-sdk-for-net,代码行数:9,代码来源:UsageAggregatesScenarioTests.cs

示例7: GetFeatureClient

        public FeatureClient GetFeatureClient(RecordedDelegatingHandler handler)
        {
            var token = new TokenCloudCredentials(Guid.NewGuid().ToString(), "abc123");
            handler.IsPassThrough = false;
            var client = new FeatureClient(token).WithHandler(handler);

            HttpMockServer.Mode = HttpRecorderMode.Playback;
            return client;
        }
开发者ID:theadriangreen,项目名称:azure-sdk-for-net,代码行数:9,代码来源:FeatureTests.InMemory.cs

示例8: RefreshTokenAsync

 private async Task RefreshTokenAsync()
 {
     var token = await GetTokenAsync(Guid.Parse(_connectionData.AzureRMTenantId));
     
     if (token == null)
         throw new InvalidOperationException("Sorry, a token could not be accquired. Please verify your Service Principal.");
     
     if (_accessToken == null)
         _accessToken = new TokenCloudCredentials(_connectionData.AzureSubscriptionId, token.access_token);
 }
开发者ID:peterschen,项目名称:SMAStudio,代码行数:10,代码来源:AzureRMService.cs

示例9: TestAsyncOperationWithEmptyPayload

 public void TestAsyncOperationWithEmptyPayload()
 {
     var tokenCredentials = new TokenCloudCredentials("123", "abc");
     var handler = new PlaybackTestHandler(MockAsyncOperaionWithEmptyBody());
     var fakeClient = new RedisManagementClient(tokenCredentials, handler);
     fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0;
     var error = Assert.Throws<CloudException>(() =>
         fakeClient.RedisOperations.Delete("rg", "redis", "1234"));
     Assert.Equal("The response from long running operation does not contain a body.", error.Message);
 }
开发者ID:juvchan,项目名称:autorest,代码行数:10,代码来源:LongRunningOperationsTest.cs

示例10: TokenCloudCredentialAddsHeader

        public void TokenCloudCredentialAddsHeader()
        {
            var tokenCredentials = new TokenCloudCredentials("123","abc");
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
            var fakeClient = new FakeServiceClientWithCredentials(tokenCredentials);
            fakeClient = new FakeServiceClientWithCredentials(tokenCredentials, handler);
            fakeClient.DoStuff().Wait();

            Assert.Equal("Bearer", handler.RequestHeaders.Authorization.Scheme);
            Assert.Equal("abc", handler.RequestHeaders.Authorization.Parameter);
        }
开发者ID:juvchan,项目名称:autorest,代码行数:11,代码来源:TokenCloudCredentialsTest.cs

示例11: ListHistoryActiveFaults

        public void ListHistoryActiveFaults()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(ExpectedResults.HistoryActiveFaultListResponse)
            };

            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            var subscriptionId = Guid.NewGuid().ToString();

            var token = new TokenCloudCredentials(subscriptionId, Constants.TokenString);
            var client = GetClient(handler, token);
            var startTime = new DateTime(2015, 3, 18);
            var endTime = new DateTime(2015, 3, 18);
            var ResourceUri = "/subscriptions/serviceAdmin/resourceGroups/system/providers/Microsoft.Storage.Admin/farms/WEST_US_1/tableserverinstances/woss-node1";

            var result = client.Faults.ListHistoryFaults(
                Constants.ResourceGroupName,
                Constants.FarmId,
                startTime.ToString("o"),
                endTime.ToString("o"),
                ResourceUri);

            // validate requestor
            Assert.Equal(handler.Method, HttpMethod.Get);

            var expectedUri = string.Format(
                FaultListUriTemplate,
                Constants.BaseUri,
                subscriptionId,
                Constants.ResourceGroupName,
                Constants.FarmId);

            var expectedFilterUri = string.Format(
                HistoryFaultFilterUriTemplate,
                Uri.EscapeDataString(startTime.ToString("o")),
                Uri.EscapeDataString(endTime.ToString("o")),
                Uri.EscapeDataString(ResourceUri));

            expectedUri = string.Concat(expectedUri, expectedFilterUri);
            expectedUri = expectedUri.Replace(" ", "%20");

            Assert.Equal(handler.Uri.AbsoluteUri, expectedUri);

            Assert.True(result.Faults.Count > 1);
            CompareExpectedResult(result.Faults[0], false);
        }
开发者ID:bganapa,项目名称:azure-sdk-for-net,代码行数:51,代码来源:FaultTests.cs

示例12: Main

        static void Main(string[] args)
        {
            //https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx#bk_portal
            string token = GetAuthorizationHeader();

            TokenCloudCredentials creds = new TokenCloudCredentials(subscriptionId,token);

            RedisManagementClient client = new RedisManagementClient(creds);
            var redisProperties = new RedisProperties();
            redisProperties.Sku = new Sku(redisSKUName,redisSKUFamily,redisSKUCapacity);
            redisProperties.RedisVersion = redisVersion;
            var redisParams = new RedisCreateOrUpdateParameters(redisProperties, redisCacheRegion);
            client.Redis.CreateOrUpdate(resourceGroupName,cacheName, redisParams);
        }
开发者ID:bibhaspaul,项目名称:RedisSamples,代码行数:14,代码来源:Program.cs

示例13: Main

        static void Main(string[] args)
        {
            // Define the base URI for management operations
            Uri baseUri = new Uri("https://management.azure.com");

            string token = GetAuthorizationHeader();
            var startTime = DateTime.Now;
            var endTime = startTime.ToUniversalTime().AddHours(1.0).ToLocalTime();
            var redisConnection = "";

            ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(redisConnection);
            IDatabase cachedb = connection.GetDatabase();
            for (int i = 0; i < 10; i++)
            {
                cachedb.StringIncrement(i.ToString());
                Console.WriteLine("value=" + cachedb.StringGet(i.ToString()));

            }

            // Get the credentials
            // You can find instructions on how to get the token here:
            // http://msdn.microsoft.com/en-us/library/azure/dn790557.aspx
            SubscriptionCloudCredentials credentials = new TokenCloudCredentials(subscriptionId, token);

            // Create an instance of the InsightsClient from Microsoft.Azure.Insights
            InsightsClient client = new InsightsClient(credentials, baseUri);

            // Get the events for an Azure Resource (e.g. Website) (as described by the Azure Resource Manager APIs here:http://msdn.microsoft.com/en-us/library/azure/dn790569.aspx)
            // A resource URI looks like the following string:
            //"/subscriptions/########-####-####-####-############/resourceGroups/resourcegroupname1/providers/resourceprovider1/resourcename1"
            string resourceUri = string.Format("subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Cache/redis/{2}", subscriptionId,resourceGroupName, cacheName);

            //Define a FilterString
            string filterString = FilterString.Generate<ListEventsForResourceParameters>(eventData => (eventData.EventTimestamp >= startTime) && (eventData.EventTimestamp <= endTime) && (eventData.ResourceUri == resourceUri));

            //Get the events logs
            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);

            //Check the status code of the response
            Console.WriteLine("HTTP Status Code returned for the call:" + response.StatusCode);

            var response2 = client.MetricDefinitionOperations.GetMetricDefinitions(resourceUri, "");
            var metrics = client.MetricOperations.GetMetrics(resourceUri, "startTime eq 2015-01-14T02:19:03.0712821Z and endTime eq 2015-01-14T03:19:03.0712821Z and timeGrain eq duration'PT5M'", response2.MetricDefinitionCollection.Value);
            Console.WriteLine("Print out the metrics logs");
            foreach (var item in metrics.MetricCollection.Value)
            {
                Console.WriteLine(item.Name.Value + "--" +item.MetricValues.Count);
            }
        }
开发者ID:hahaxj,项目名称:RedisSamples,代码行数:49,代码来源:Program.cs

示例14: create_adf_client

        private void create_adf_client()
        {
            var authenticationContext = new AuthenticationContext($"https://login.windows.net/{tenant_id}");
            var credential = new ClientCredential(clientId: client_id, clientSecret: client_key);
            var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/", clientCredential: credential);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            var token = result.AccessToken;

            var _credentials = new TokenCloudCredentials(subscription_id, token);
            inner_client = new DataFactoryManagementClient(_credentials);
        }
开发者ID:JustLogic,项目名称:EatCodeLive,代码行数:16,代码来源:DataFactoryHelper.cs

示例15: TestCreateOrUpdateWithAsyncHeader

        public void TestCreateOrUpdateWithAsyncHeader()
        {
            var tokenCredentials = new TokenCloudCredentials("123", "abc");
            var handler = new PlaybackTestHandler(MockCreateOrUpdateWithTwoTries());
            var fakeClient = new RedisManagementClient(tokenCredentials, handler);
            fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0;
            fakeClient.RedisOperations.CreateOrUpdate("rg", "redis", new RedisCreateOrUpdateParameters(), "1234");

            Assert.Equal(HttpMethod.Put, handler.Requests[0].Method);
            Assert.Equal("https://management.azure.com/subscriptions/1234/resourceGroups/rg/providers/Microsoft.Cache/Redis/redis", 
                handler.Requests[0].RequestUri.ToString());
            Assert.Equal(HttpMethod.Get, handler.Requests[1].Method);
            Assert.Equal("http://custom/status",
                handler.Requests[1].RequestUri.ToString());
            Assert.Equal(HttpMethod.Get, handler.Requests[2].Method);
            Assert.Equal("https://management.azure.com/subscriptions/1234/resourceGroups/rg/providers/Microsoft.Cache/Redis/redis",
                handler.Requests[2].RequestUri.ToString());
        }
开发者ID:juvchan,项目名称:autorest,代码行数:18,代码来源:LongRunningOperationsTest.cs


注:本文中的Microsoft.Azure.TokenCloudCredentials类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。