/// <summary>
        /// Get an instance of a web app
        /// </summary>
        /// <param name="bearerToken">Azure bearer token</param>
        /// <param name="appServiceUri">Resource Uri to the app service</param>
        /// <param name="slotName">(Optional) Name of the slot to fetch</param>
        /// <returns>App service or NULL</returns>
        public static async Task <AppServiceWebApp?> Get(string bearerToken, ResourceUri appServiceUri, string?slotName = null)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if ((!appServiceUri.IsValid) || (!appServiceUri.Is(ResourceUriCompareLevel.Provider, "Microsoft.Web")) || (!appServiceUri.Is(ResourceUriCompareLevel.Type, "sites")))
            {
                throw new ArgumentException(nameof(appServiceUri));
            }

            string endpoint = string.Empty;

            if (!string.IsNullOrWhiteSpace(slotName))
            {
                endpoint = $"slots/{slotName}";
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                appServiceUri.ToAbsoluteAzureRMEndpointUri(endpoint),
                CLIENT_API_VERSION,
                null, null,
                new int[] { 200, 404 }
                );

            if ((!response.IsExpectedSuccess) || (response.HttpStatus == 404) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(null);
            }

            return(JsonConvert.DeserializeObject <AppServiceWebApp>(response.Body));
        }
Example #2
0
        /// <summary>
        /// Get the VM sizes available by name of the virtual machine. These are the sizes that particular VM may be resized to.
        /// </summary>
        /// <param name="bearerToken">Authorization bearer token</param>
        /// <param name="subscription">Subscription Guid</param>
        /// <param name="resourceGroupName">Resource group the VM resides in</param>
        /// <param name="virtualMachineName">Name of the virtual machine</param>
        /// <returns>List of available sizes or empty list</returns>
        public static async Task <List <VirtualMachineSize> > GetAvailableSizesByVM(string bearerToken, Guid subscription, string resourceGroupName, string virtualMachineName)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if (subscription == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(subscription));
            }
            if (string.IsNullOrWhiteSpace(resourceGroupName))
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (string.IsNullOrWhiteSpace(virtualMachineName))
            {
                throw new ArgumentNullException(nameof(virtualMachineName));
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/subscriptions/{subscription.ToString("d")}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{virtualMachineName}/vmSizes",
                CLIENT_API_VERSION,
                null, null,
                new int[] { 200 }
                );

            if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(new List <VirtualMachineSize>());
            }

            return(JsonConvert.DeserializeObject <List <VirtualMachineSize> >(response.Body));
        }
Example #3
0
        /// <summary>
        /// Get metadata about a single web app that has been deleted
        /// </summary>
        /// <param name="bearerToken">Azure Bearer Token</param>
        /// <param name="subscription">Subscription Id for authorization</param>
        /// <param name="locationCode">(Optional) The location code (eg: "westus") where the app was hosted</param>
        /// <param name="siteId">Numeric Id of the web app</param>
        /// <returns>Metadata about the deleted web app or NULL</returns>
        public static async Task <DeletedWebApp?> GetDeletedWebApp(string bearerToken, Guid subscription, string locationCode, int siteId)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if (subscription == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(subscription));
            }
            if (string.IsNullOrWhiteSpace(locationCode))
            {
                throw new ArgumentNullException(nameof(locationCode));
            }
            if (siteId < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(siteId));
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/subscriptions/{subscription:d}/providers/Microsoft.Web/locations/{locationCode}/deletedSites/{siteId}",
                CLIENT_API_VERSION,
                null, null,
                new int[] { 200 }
                );

            if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(null);
            }

            return(JsonConvert.DeserializeObject <DeletedWebApp>(response.Body));
        }
Example #4
0
        /// <summary>
        /// Get a single subscription
        /// </summary>
        /// <param name="bearerToken">Authorization bearer token</param>
        /// <param name="id">Guid of the subscription</param>
        /// <returns>The subscription. NULL if the item was not found or there was a problem.</returns>
        public static async Task <Subscription?> Get(string bearerToken, Guid id)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if ((id == Guid.Empty) || (id == default))
            {
                throw new ArgumentNullException(nameof(id));
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/subscriptions/{id:d}",
                CLIENT_API_VERSION,
                null, null,
                new int[] { 200 }
                );

            if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(null);
            }

            return(JsonConvert.DeserializeObject <Subscription>(response.Body));
        }
Example #5
0
        /// <summary>
        /// Get an existing App Service Domain
        /// </summary>
        /// <param name="bearerToken">The Azure bearer token</param>
        /// <param name="subscription">Subscription Id for authorization</param>
        /// <param name="resourceGroupName">Name of the Azure resource group the Azure App Service Domain is homed in</param>
        /// <param name="domainName">App Service Domain name</param>
        /// <returns>App Service Domain metadata, or NULL if not found</returns>
        public static async Task <AppServiceDomain?> Get(string bearerToken, Guid subscription, string resourceGroupName, string domainName)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if (subscription == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(subscription));
            }
            if (string.IsNullOrWhiteSpace(resourceGroupName))
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (string.IsNullOrWhiteSpace(domainName))
            {
                throw new ArgumentNullException(nameof(domainName));
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.DomainRegistration/domains/{domainName}",
                CLIENT_API_VERSION,
                null, null,
                new int[] { 200 }
                );

            if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(null);
            }

            return(JsonConvert.DeserializeObject <AppServiceDomain>(response.Body));
        }
Example #6
0
        /// <summary>
        /// Get a list of all supported top level domains (TLDs)
        /// </summary>
        /// <param name="bearerToken">The Azure bearer token</param>
        /// <param name="subscription">Subscription Id for authorization</param>
        /// <returns>List of supported TLDs or empty list</returns>
        public static async Task <IList <TopLevelDomain> > GetSupportedTopLevelDomains(string bearerToken, Guid subscription)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if (subscription == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(subscription));
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/subscriptions/{subscription:d}/providers/Microsoft.DomainRegistration/topLevelDomains",
                CLIENT_API_VERSION,
                null, null,
                new int[] { 200 }
                );

            if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(new List <TopLevelDomain>());
            }

            return(JsonConvert.DeserializeObject <ListResultWithContinuations <TopLevelDomain> >(response.Body).Values);
        }
        /// <summary>
        /// Get the rate card. This method will take a LONG time to run! It runs with a upstream timeout of 1 min, so
        /// consuming method should be set to a larger timeout.
        /// </summary>
        /// <param name="bearerToken">Authorization bearer token</param>
        /// <param name="subscription">Guid of the subscription</param>
        /// <param name="azureSubscriptionOfferId">The Offer Id of the Azure subscription</param>
        /// <param name="isoCurrencyCode">3-letter ISO currency code (eg: USD)</param>
        /// <param name="isoLocaleCode">4-letter ISO locale code (eg: en-US)</param>
        /// <param name="isoRegionCode">2-letter ISO region name (eg: US)</param>
        /// <returns>The ratecard response, or NULL if there was a problem</returns>
        public static async Task <RateCardResponse?> GetRates(string bearerToken, Guid subscription, string azureSubscriptionOfferId, string isoCurrencyCode, string isoLocaleCode, string isoRegionCode)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if ((subscription == Guid.Empty) || (subscription == default))
            {
                throw new ArgumentNullException(nameof(subscription));
            }
            if (string.IsNullOrWhiteSpace(azureSubscriptionOfferId))
            {
                throw new ArgumentNullException(nameof(azureSubscriptionOfferId));
            }
            if (string.IsNullOrWhiteSpace(isoCurrencyCode))
            {
                throw new ArgumentNullException(nameof(isoCurrencyCode));
            }
            if (string.IsNullOrWhiteSpace(isoLocaleCode))
            {
                throw new ArgumentNullException(nameof(isoLocaleCode));
            }
            if (string.IsNullOrWhiteSpace(isoRegionCode))
            {
                throw new ArgumentNullException(nameof(isoRegionCode));
            }

            RestApiResponse originalResponse = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/subscriptions/{subscription:d}/providers/Microsoft.Commerce/RateCard",
                CLIENT_API_VERSION,
                new Dictionary <string, string>()
            {
                { "$filter", $"OfferDurableId eq '{azureSubscriptionOfferId}' and Currency eq '{isoCurrencyCode}' and Locale eq '{isoLocaleCode}' and RegionInfo eq '{isoRegionCode}'" }
            },
                null,
                new int[] { 302 }
                );

            if ((!originalResponse.IsExpectedSuccess) || originalResponse.WasException || (originalResponse.Headers == null) || (originalResponse.Headers !.Location == null))
            {
                return(null);
            }

            RestApiResponse response = await RestApiClient.GETWithoutAuthentication(
                originalResponse.Headers !.Location.AbsoluteUri,
                null, null, null,
                new int[] { 200 },
                60                      // set timeout to 1 min
                );

            if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(null);
            }

            return(JsonConvert.DeserializeObject <RateCardResponse>(response.Body));
        }
        public List <Message> getPins()
        {
            List <Message> pins = new List <Message>();
            dynamic        data = JSONDeserializeAndHandleErrors.DeserializeJSON(RestApiClient.GET($"channels/{ID}/pins"));

            for (int i = 0; i < data.Length; i++)
            {
                pins.Add(Message.fromJSON(data[i]));
            }
            return(pins);
        }
Example #9
0
        /// <summary>
        /// Get a single disk image
        /// </summary>
        /// <param name="bearerToken">Authorization bearer token</param>
        /// <param name="imageResourceId">Absolute resource Id of the disk image</param>
        /// <returns>Disk image or NULL</returns>
        public static async Task <DiskImage?> Get(string bearerToken, string imageResourceId)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if (string.IsNullOrWhiteSpace(imageResourceId) || ((!imageResourceId.StartsWith("/subscriptions/")) && (!imageResourceId.StartsWith("subscriptions/"))))
            {
                throw new ArgumentException("imageResourceId must be an absolute resource Id.");
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/{(imageResourceId.StartsWith("/") ? imageResourceId[1..] : imageResourceId)}",
        public static Message getMessage(long channel, long ID)
        {
            CarrotcordLogger.log(CarrotcordLogger.LogSource.BOT, $"channels/{channel}/messages/{ID}");
            dynamic data    = JSONDeserializeAndHandleErrors.DeserializeJSON(RestApiClient.GET($"channels/{channel}/messages/{ID}"));
            Message message = new Message();

            message.ID        = data.id;
            message.channelID = data.channel_id;
            message.author    = User.fromData(data.author);
            message.pinned    = data.pinned;
            message.Guild     = Guild.getGuild(message.guildID);
            message.content   = Convert.ToString(data.content);
            return(message);
        }
        public static List <Channel> getDMs()
        {
            dynamic data = JSONDeserializeAndHandleErrors.DeserializeJSON(RestApiClient.GET("users/@me/channels"));

            if (data.Length <= 0)
            {
                return(null);
            }
            List <Channel> channels = new List <Channel>();

            for (int i = 0; i < data.Length; i++)
            {
                channels.Add(Channel.fromData(data[i]));
            }
            return(channels);
        }
Example #12
0
        /// <summary>
        /// Get a resource provider at subscription scope
        /// </summary>
        /// <param name="bearerToken">Authorization bearer token</param>
        /// <param name="subscription">Guid of the subscription</param>
        /// <param name="resourceProviderNamespace">Namespace name of the resource provider (eg: "Microsoft.Web")</param>
        /// <param name="fetchMetadata">If true, adds additional metadata (mutually exclusive with <paramref name="fetchAliases"/>)</param>
        /// <param name="fetchAliases">If true, adds type aliases to the metdata (mutually exclusive with <paramref name="fetchMetadata"/>)</param>
        /// <returns>Resource Provider or NULL</returns>
        public static async Task <ResourceProvider?> Get(string bearerToken, Guid subscription, string resourceProviderNamespace, bool fetchMetadata = false, bool fetchAliases = false)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if ((subscription == Guid.Empty) || (subscription == default))
            {
                throw new ArgumentNullException(nameof(subscription));
            }
            if (string.IsNullOrWhiteSpace(resourceProviderNamespace))
            {
                throw new ArgumentNullException(nameof(resourceProviderNamespace));
            }

            Dictionary <string, string> query = new Dictionary <string, string>();

            if (fetchMetadata)
            {
                query.Add("$expand", "metadata");
            }
            else if (fetchAliases)
            {
                query.Add("$expand", "resourceTypes/aliases");
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/subscriptions/{subscription:d}/providers/{resourceProviderNamespace}",
                CLIENT_API_VERSION,
                query, null,
                new int[] { 200 }
                );

            if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(null);
            }

            return(JsonConvert.DeserializeObject <ResourceProvider>(response.Body));
        }
        /// <summary>
        /// Gets details about a single VM
        /// </summary>
        /// <param name="bearerToken">Authorization bearer token</param>
        /// <param name="virtualMachineResourceUri">Resource Uri to the VM</param>
        /// <param name="expandInstanceView">If set, the InstanceView structure is also populated. Else (default) this will be NULL.</param>
        /// <returns>Virtual Machine or NULL</returns>
        public static async Task <VirtualMachine?> Get(string bearerToken, string virtualMachineResourceUri, bool expandInstanceView = false)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if (string.IsNullOrWhiteSpace(virtualMachineResourceUri))
            {
                throw new ArgumentNullException(nameof(virtualMachineResourceUri));
            }

            Dictionary <string, string> parameters = new Dictionary <string, string>();

            if (expandInstanceView)
            {
                parameters.Add("expand", "instanceView");
            }

            RestApiResponse response = await RestApiClient.GET(
                bearerToken,
                $"https://management.azure.com/{virtualMachineResourceUri[1..]}",
Example #14
0
 public void trigger404()
 {
     RestApiClient.GET("hahayes");
 }
        public static Channel getChannel(long ID)
        {
            //Console.WriteLine(RestApiClient.GET("channels/" + ID).Content);
            if (Storage.cachedChannels.TryGetValue(ID, out Channel value))
            {
                return(value);
            }
            Channel channel = fromData(JSONDeserializeAndHandleErrors.DeserializeJSON(RestApiClient.GET("channels/" + ID)));

            Storage.cachedChannels.Add(channel.ID, channel);
            return(channel);
        }
Example #16
0
        /// <summary>
        /// Create a new storage account
        /// </summary>
        /// <param name="bearerToken">Azure bearer token</param>
        /// <param name="subscription">Subscription for authorization</param>
        /// <param name="resourceGroupName">Name of the resource group the account is to be placed in</param>
        /// <param name="storageAccountName">Name of the storage account to create</param>
        /// <param name="location">Geographic location where account is to be placed (eg: "uswest")</param>
        /// <param name="kind">Kind of storage account to create</param>
        /// <param name="sku">SKU of storage account</param>
        /// <param name="properties">Additional properties (optional)</param>
        /// <returns>Storage Account</returns>
        public static async Task <StorageAccount?> Create(string bearerToken, Guid subscription, string resourceGroupName, string storageAccountName, string location,
                                                          StorageAccountKind kind = StorageAccountKind.StorageV2, StorageAccountSkuNames sku        = StorageAccountSkuNames.Standard_LRS,
                                                          StorageAccountCreateRequestProperties?properties = null, Dictionary <string, string>?tags = null)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if (string.IsNullOrWhiteSpace(resourceGroupName))
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (string.IsNullOrWhiteSpace(storageAccountName))
            {
                throw new ArgumentNullException(nameof(storageAccountName));
            }
            if (string.IsNullOrWhiteSpace(location))
            {
                throw new ArgumentNullException(nameof(location));
            }
            if (!Enum.IsDefined(typeof(StorageAccountKind), kind))
            {
                throw new ArgumentOutOfRangeException(nameof(kind));
            }
            if (!Enum.IsDefined(typeof(StorageAccountSkuNames), sku))
            {
                throw new ArgumentOutOfRangeException(nameof(sku));
            }

            StorageAccountCreateRequest request = new StorageAccountCreateRequest()
            {
                Kind = kind,
                Sku  = new StorageAccountSku()
                {
                    Name = sku,
                    Tier = StorageAccountSkuTiers.Standard
                },
                Location = location,
                Tags     = tags,

                Properties = properties ?? new StorageAccountCreateRequestProperties()
            };

            RestApiResponse response = await RestApiClient.PUT(
                bearerToken,
                $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}",
                CLIENT_API_VERSION,
                null,
                request,
                new int[] { 200, 202 }
                );

            if ((!response.IsExpectedSuccess) || response.WasException)
            {
                return(null);
            }

            if ((response.HttpStatus == 202) && (!string.IsNullOrWhiteSpace(response.Headers?.Location.ToString())))
            {
                string pollUrl  = response.Headers !.Location.ToString();
                bool   complete = false;

                while (!complete)
                {
                    response = await RestApiClient.GET(
                        bearerToken,
                        pollUrl,
                        string.Empty, null, null,
                        new int[] { 200, 202 }
                        );

                    if ((!response.IsExpectedSuccess) || response.WasException)
                    {
                        return(null);
                    }

                    if ((response.HttpStatus == 200) && (!string.IsNullOrWhiteSpace(response.Body)))
                    {
                        complete = true;
                    }
                }
            }


            return(JsonConvert.DeserializeObject <StorageAccount>(response.Body !));
        }