Create Azure Function App in Azure portal Programmatically via C# & .NET6.

Amit Singh Rawat 731 Reputation points
2023-10-19T05:41:53.8833333+00:00

I manually published the Azure Function code via Visual Studio 2022.

My next task is to create a console application responsible for creating an Azure Function directly on Azure and hosting the published code. Essentially, I want to replicate the same process as clicking the "Publish" button in Visual Studio for Azure, but I'd like to achieve this through C# code.

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,179 questions
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,134 questions
Azure Blob Storage
Azure Blob Storage
An Azure service that stores unstructured data in the cloud as blobs.
2,934 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,930 questions
0 comments No comments
{count} votes

Accepted answer
  1. navba-MSFT 25,075 Reputation points Microsoft Employee
    2023-10-19T09:45:23.8066667+00:00

    @Amit Singh Rawat Welcome to Microsoft Q&A Forum, Thank you for posting your query here!
    I see that you are looking to create an Azure Function App programmatically via C# and .NET6. You have already published the Azure Function code via Visual Studio 2022 and want to replicate the same process as clicking the "Publish" button in Visual Studio for Azure, but through C# code.

    The below code does the following:

    1. Create a resource group (if it doesn't exist)
    2. Create storage account required for func app if it doesnt exist
    3. Create a function app in azure
    4. Deploy the code to azure function app

    Pre-Requisites:

    • Read and understand the code.
    • Read the comments carefully and uncomment the required lines.
    • Ensure that the required packages are installed via nuget
    • Create the Azure AD app and get the ClienTID, tennatID and Client Secret required for the app to run.
    • Ensure that this Azure AD app has privileges to create a resource in the subscription ( Atleast Contributor role in your subscription)

    Please Note: You need to update the below code and test it in a dev environment. Please don't copy / paste the code directly and execute, as it might not work.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Azure.Core;
    using Azure;
    using Azure.Identity;
    using Azure.ResourceManager;
    using Azure.ResourceManager.Resources;
    using Azure.ResourceManager.Resources.Models;
    using System.Security.Policy;
    using Microsoft.Azure.Management.AppService.Fluent.Models;
    using Microsoft.Azure.Management.Storage.Fluent.Models;
    using Microsoft.Azure.Management.AppService.Fluent;
    using Microsoft.Azure.Management.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
    using System.Net.Http.Headers;
    using System.Net.Http;
    using System.IO;
    
    namespace FunctionAppCreate
    {
        internal class Program
        {
            public static async Task Main(string[] args)
            {
                var ClientId = "ad8a06b6-XXXXXXXXXX-28fd86b57777";
                var ClientSecret = "5dY8Q~pPmXXXXXXXXXXXXXXXXXXkhS5aJo";
                var TenantId = "72f988bf-XXXXXXXXXXXX-2d7cd011db47";
    
                var credential = new DefaultAzureCredential();
               // var resourceClient = new ResourceManagementClient(credential);
    
                //var resourceGroupName = "myResourceGroup";
                var functionAppName = "myFunctionApp";
                var subscriptionId = "b83c1ed3-XXXXXXXXXXX-2b83a074c23f";
                var storageAccountName = "StorageAccountName";
             
                string resourceGroupName = "myRgName";
                var region = "eastus";
    
                var storageConnectionString = " ";
    
                AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(ClientId, ClientSecret, TenantId, AzureEnvironment.AzureGlobalCloud);
    
                //UNCOMMENT THE BELOW LINES IF YOU WANT TO CREATE A NEW RESOURCE GROUP
    
                        //ArmClient client = new ArmClient(new DefaultAzureCredential());
                        //// Now we get a ResourceGroupResource collection for that subscription
                        //SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
                        //ResourceGroupCollection resourceGroups = subscription.GetResourceGroups();
    
                        //// With the collection, we can create a new resource group with an specific name         
    
                        //AzureLocation location = AzureLocation.WestUS2;
                        //ResourceGroupData resourceGroupData = new ResourceGroupData(location);
                        //ArmOperation<ResourceGroupResource> operation = await resourceGroups.CreateOrUpdateAsync(WaitUntil.Completed, resourceGroupName, resourceGroupData);
                        //var resourceGroup = operation.Value;
    
    
                var azure = Microsoft.Azure.Management.Fluent.Azure
                         .Configure()
                         .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                         .Authenticate(credentials)
                         .WithDefaultSubscription();
    
    
    
    
                // UNCOMMENT THE BELOW LINES IF YOU WANT TO CREATE A NEW STORAGE ACCOUNT
    
                        //var storageAccount = await azure.StorageAccounts.Define(storageAccountName)
                        //             .WithRegion(Region.USEast)
                        //.WithNewResourceGroup(resourceGroupName)
                        //             .CreateAsync();
    
                        ////  Uncomment the below to get the storage connection string
                        //var storageAccount = azure.StorageAccounts.GetByResourceGroup(resourceGroupName, storageAccountName);
                        //var storageKeys = storageAccount.GetKeys();
                        // storageConnectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageKeys[0].Value};EndpointSuffix=core.windows.net";
    
    
    
                // The below code will create a new function app with new storage account and resource group.
                IFunctionApp funcapp = azure.AppServices.FunctionApps.Define(functionAppName)
                                        .WithRegion(region)
                                        .WithNewResourceGroup(resourceGroupName)
                                        .WithLocalGitSourceControl()
                                        .Create();
    
    
                // Deploy the code to newly created funcapp through web deploy.
                //Ensure that you have zipped up your entire code and placed it in git or any other location
    
                Console.WriteLine("Deploying a local function app to " + funcapp + " throuh web deploy...");
    
                        funcapp.Deploy()
                        .WithPackageUri("https://github.com/Azure/azure-libraries-for-net/raw/master/Samples/Asset/square-function-app-function-auth.zip")
                        .WithExistingDeploymentsDeleted(false)
                        .Execute();
    
                Console.WriteLine("Deployment to function app " + funcapp.Name + " completed");
    
    
                // Alternatively if you want to deploy using the zip deployment method directly by invoking the REST API
                //Uncomment the below code:
    
                        //var deploymentUser = "";
                        //var zipFilePath = "";
                        //var appName = funcapp.Name;
    
                        //var client = new HttpClient();
                        //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{deploymentUser}:")));
    
                        //var content = new StreamContent(File.OpenRead(zipFilePath));
                        //content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    
                        //var response = await client.PostAsync($"https://{appName}.scm.azurewebsites.net/api/zipdeploy", content);
    
                        //if (response.IsSuccessStatusCode)
                        //{
                        //    Console.WriteLine("Deployment successful.");
                        //}
                        //else
                        //{
                        //    Console.WriteLine($"Deployment failed with status code {response.StatusCode}.");
                        //}
    
    
                Console.ReadLine();
    
    
                // If you want to delete the entire resource group you can uncomment the below
                // azure.ResourceGroups.DeleteByName(resourceGroupName);
                // Console.WriteLine("RG Deleted successfully.");
    
            }
        }
    }
    
    

    Hope this helps.

    **
    Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.