Monday 29 May 2023

Call Azure API using Bearer acess token

using System;

using System.Drawing;

using System.Net;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Threading.Tasks;

using System.Web;

using Azure.Identity;

using Azure.Core;

using Nancy.Json;

using Newtonsoft.Json;

 

namespace AzCallAzureApi

{

    internal class Program1

    {

        static async Task Main()

        {

            try

            {

                // get the access first token first.

                string token = await GetAccessToken("TenantID", "ClientID", "ClientSecret");

                // get the API and process the result

                await GetResults(token);

            }

            catch (Exception ex)

            {

                Console.WriteLine($"Exception: {ex.Message}");

            }

        }

 

        private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)

        {

            Console.WriteLine("Begin GetAccessToken");

 

            var credentials = new ClientSecretCredential(tenantId, clientId, clientKey);

            var result = await credentials.GetTokenAsync(new TokenRequestContext(new[] { "https://management.azure.com/.default" }), CancellationToken.None);

            return result.Token;

        }

 

        // Set authorization and call the required api method

        private static async Task<string> GetResults(string token)

        {

            var httpClient = new HttpClient

            {

                BaseAddress = new Uri("https://management.azure.com/subscriptions/")

            };

            string URI = "Your URI";

            httpClient.DefaultRequestHeaders.Remove("Authorization");

            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            HttpResponseMessage response = await httpClient.GetAsync(URI);

            if (response.IsSuccessStatusCode)

            {

                var HttpsResponse = await response.Content.ReadAsStringAsync();

                var JSONObject = JsonConvert.DeserializeObject<object>(HttpsResponse);

            Console.WriteLine(JSONObject);

            var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>((string)JSONObject);

            return response.StatusCode.ToString();

            }

            return string.Empty;

        }  

    }

}

 


Monday 1 February 2021

Power shell script to start, stop and restart windows services.

 With the help you below power shell script you check windows service's status and can restart, stop etc. even on remote servers.


 

[string]$computerName

 

## Create a log file

$LogFile = "E:\Logs\logs_"+(Get-Date).ToString('yyyy-MM-dd')+".txt"

## Count: 3

[string[]]$computerNames ="ServerName1", "ServerName2", "ServerName3"

try {

 #Function that logs a message to a text file

function LogWrite

{   param([string]$Message)

    ((Get-Date).ToString() + " - " + $Message) >> $LogFile;

}

Write-Host "Execution started"

LogWrite -Message "Execution started";

  ForEach ( $computerName in $computerNames ) {

    Write-Host "++++++++++++++++++++++++++++++++++++++++++++" -ForegroundColor Magenta

    try {

     #get a service to check current status

    $svc = get-service -Name "ServiceName" -computername $computerName

      #check if service’s current status is stopped if yes then start it

     if ( $svc.Status -eq "Stopped") {

          (Get-Service -Name "ServiceName" -Computername $computerName).Start();

           Write-Host $computerName -NoNewline

         Write-Host ": the service has started successfully"

         LogWrite -Message "$computerName : the service has started successfully"

         }

         else{

           Write-Host $computerName -NoNewline

           Write-Host ": the service is already up and running"

           LogWrite -Message "$computerName : the service is already up and running"

            }

     }  

        catch {

        LogWrite -Message "$computerName : service reset failed- $_"

        Write-Host ": service start failed"

        Write-Host "Error : $_"

         }

     }

 Write-Host "Execution finished"

 LogWrite -Message "Execution finished"    

 }

    catch {

        LogWrite -Message "$computerName : service reset failed- $_"

        Write-Host ": service start failed"

        Write-Host "Error : $_"

         }