Search code examples
c#azuresdkazure-functionsazure-analysis-services

Microsoft AnalysisServices - start and stop server using Azure Functions


I wanted to write an Azure Function to stop and resume MS Analysis Sevice. I have been tasked to do this using API Resume and API Suspend. It's my first time with C# (I have Python/Javascript background). What am I doing wrong? Can someone provide correct solution? Would be grateful from the bottom of my heart.

Here is my current code sample:

using System;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

static HttpClient client = new HttpClient();
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req)
{
    var subscriptionId = "mySId";
    var resourceGroupName = "myRGName";
    var serverName = "mySName";
    var APIurl = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}/resume?api-version=2017-08-01";

    var response = await client.PostAsync(APIurl, null);
    string result = await response.Content.ReadAsStringAsync();
    return req.CreateResponse(HttpStatusCode.OK);
}

This is what I get in console. Server is not stopping though. enter image description here


Solution

  • For those in times of need - this is my complete working solution.

    using System;
    using System.Threading.Tasks;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.Extensions.Logging;
    using System.Net.Http.Headers;
    using System.Net;
    using System.Net.Http;
    using System.Collections.Generic;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    
    namespace ManageAS
    {
        public class ManageAS
        {
            string accessToken = null;
            string responseString = null;
            string serverStatus = null;
            string serverFullURI = Environment.GetEnvironmentVariable("FULL_SERVER_URI");
            static string shortServerName = Environment.GetEnvironmentVariable("SHORT_SERVER_NAME");
            string resourceURI = "https://management.core.windows.net/";
            string clientID = Environment.GetEnvironmentVariable("CLIENT_ID");
            string clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
            string tenantID = Environment.GetEnvironmentVariable("TENANT_ID");
            static string resourceGroupName = Environment.GetEnvironmentVariable("RESOURCE_GROUP_NAME");
            static string subscriptionId = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
            static Uri apiURI = null;
    
            [FunctionName("PerformAction")]
            public async Task<HttpResponseMessage> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
                ILogger log)
            {    
                await GetAccessToken();
                await GetServerStatus(accessToken);
    
                if (serverStatus == "Paused")
                {
                    apiURI = new Uri(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.AnalysisServices/servers/{2}/resume?api-version=2017-08-01", subscriptionId, resourceGroupName, shortServerName));
                    this.responseString = await ServerManagement(apiURI, accessToken);
                }
    
                if (serverStatus == "Succeeded")
                {
                    apiURI = new Uri(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.AnalysisServices/servers/{2}/suspend?api-version=2017-08-01", subscriptionId, resourceGroupName, shortServerName));
                    this.responseString = await ServerManagement(apiURI, accessToken);
                }
    
                return req.CreateResponse(HttpStatusCode.OK, responseString);
            }
    
            protected async Task<string> GetAccessToken()
            {
                string authority = "https://login.microsoftonline.com/" + tenantID;
                AuthenticationContext authenticationContext = new AuthenticationContext(authority);
                var token = await authenticationContext.AcquireTokenAsync(resourceURI, new ClientCredential(clientID, clientSecret));
                accessToken = token.AccessToken;
                return accessToken;
            }
    
            protected async Task<string> ServerManagement(Uri url, string token)
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    
                HttpResponseMessage response = await client.PostAsync(url.ToString(), null);
                response.EnsureSuccessStatusCode();
                HttpContent content = response.Content;
    
                string json;
                json = await content.ReadAsStringAsync();
                return json;
            }
    
            protected async Task<string> GetServerStatus(string token)
            {
                var url = new Uri(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.AnalysisServices/servers/{2}?api-version=2017-08-01", subscriptionId, resourceGroupName, shortServerName));
    
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                HttpResponseMessage response = await client.GetAsync(url.ToString());
    
                response.EnsureSuccessStatusCode();
                string sJson = await response.Content.ReadAsStringAsync();
                var dictResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(sJson);
                if (!dictResult.ContainsKey("properties")) return null;
                var dictProperties = dictResult["properties"] as Newtonsoft.Json.Linq.JObject;
                if (dictProperties == null || !dictProperties.ContainsKey("state")) return null;
                serverStatus = Convert.ToString(dictProperties["state"]);
                return serverStatus;
            }
        }
    }