skip to Main Content

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.

This is the objective I’m currently working on.

2

Answers


  1. Chosen as BEST ANSWER

    Below is end to end code that works for me.

        using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
        using Microsoft.Azure.Management.ResourceManager.Fluent;
        using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
        using Microsoft.Azure.Management.AppService.Fluent;
        using Microsoft.Azure.Management.Storage.Fluent;
        
        namespace HostAzureFunctionViaCode
        {
            internal class WorkingSDK
            {
                public void MethodName()
                {
                    //Make sure you give Contributer level permission to your app within subscription. To do this. Go to your subscription in Azure portal. Then click on Access Control (IAM) from left panel. Then from Right Panel click on Add icon And select Add role assignment. Then within Privileged Administrator roles Click on Contibuter. Then next and then click on Select Member. And then add your app into it.
                    string TenantId = "Your Tenant ID";
                    string ClientSecret = "Your APP Client Secret";
                    string ClientId = "Your APP Client ID";
        
                    var functionAppName = "yourfunctionappname";
                    var storageAccountName = "mystorageaccountname"; //Storage account name should be in lowercase and numbers only.
                    var vaultName = "yourvaultname";
                    string resourceGroupName = "myRgName";
                    Region region = Region.USEast;
        
                    AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(ClientId, ClientSecret, TenantId, AzureEnvironment.AzureGlobalCloud);
        
                    var azure = Microsoft.Azure.Management.Fluent.Azure.Configure()
                      .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                      .Authenticate(credentials)
                      .WithDefaultSubscription();
        
                    Console.WriteLine("Attempting to create a resource group in Azure.");
                    bool isResourceGroupExists = azure.ResourceGroups.Contain(resourceGroupName);
                    if (isResourceGroupExists)
                    {
                        Console.WriteLine($"Resource Group {resourceGroupName} : already exists.");
                    }
                    else
                    {
                        azure.ResourceGroups.Define(resourceGroupName)
                        .WithRegion(region)
                        .Create();
                        Console.WriteLine($"Resource group {resourceGroupName} created.");
                    }
        
                    Console.WriteLine("nAttempting to create a Storage Account in Azure.");
                    bool isStorageAccountExists = azure.StorageAccounts.GetByResourceGroup(resourceGroupName, storageAccountName) != null;
                    IStorageAccount? storageAccount = null;
                    if (isStorageAccountExists)
                    {
                        storageAccount = azure.StorageAccounts.GetByResourceGroup(resourceGroupName, storageAccountName);
                        Console.WriteLine($"Storage Account {storageAccountName} : already exists.");
                    }
                    else
                    {
                        storageAccount = azure.StorageAccounts.Define(storageAccountName)
                        .WithRegion(region)
                        .WithExistingResourceGroup(resourceGroupName)
                        .Create();
                        Console.WriteLine($"Storage Account {storageAccountName} : created.");
                    }
        
                    Console.WriteLine("nAttempting to create a Key Vault in Azure.");
                    bool isVaultExists = azure.Vaults.ListByResourceGroup(resourceGroupName).Where(x => x.Name == vaultName).Any();
                    if (isVaultExists)
                    {
                        Console.WriteLine($"Key Vault {vaultName} already exists.");
                    }
                    else
                    {
                        azure.Vaults.Define(vaultName)
                        .WithRegion(region)
                        .WithExistingResourceGroup(resourceGroupName)
                        .WithEmptyAccessPolicy()
                        .Create();
                        Console.WriteLine($"Key Vault {vaultName} created.");
                    }
        
                    Console.WriteLine("nAttempting to create a Azure Function in Azure.");
                    bool isFunctionExists = azure.AppServices.FunctionApps.ListByResourceGroup(resourceGroupName).Where(x => x.Name == functionAppName).Any();
        
                    IFunctionApp? funcapp = null;
                    if (isFunctionExists)
                    {
                        funcapp = azure.AppServices.FunctionApps.ListByResourceGroup(resourceGroupName).Where(x => x.Name == functionAppName).FirstOrDefault();
                        Console.WriteLine($"Function App {funcapp!.Name} : Already Exists");
                    }
                    else
                    {
                        funcapp = azure.AppServices.FunctionApps.Define(functionAppName)
                        .WithRegion(region)
                        .WithExistingResourceGroup(resourceGroupName)
                        .WithExistingStorageAccount(storageAccount)
                        .WithLatestRuntimeVersion()
                        .Create();
                        Console.WriteLine($"Function App {funcapp!.Name} : Created.");
                    }
        
                    Console.WriteLine("Deploying a local function app to " + funcapp.Name + " throuh web deploy...");
                    
                    string publishedCodePath = @"https://XXX.blob.core.windows.net/XXXX/functionPublish.zip";
        
                    funcapp.Deploy()
                        .WithPackageUri(publishedCodePath)
                        .WithExistingDeploymentsDeleted(true)
                        .Execute();
        
                    
        
                    Console.WriteLine("Deployment to function app " + funcapp.Name + " is successful.");
                }
            }
        }
    

  2. Follow below steps to create function app via console application:

    1. Create a Service Principal in Azure:

    Open Active Directory=> App Registrations=>create new Registration=> Register a new application.

    enter image description here

    Go to overview of the newly registered app => copy the client id & Tenant id
    enter image description here

    And Navigate to Certificates & Secrets, create a new secret and copy the secret value, it’ll be used as client_secret.

    enter image description here

    Try below code to create an Azure function App via console application:

    var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
        clientId: "<your-client-id>",
        clientSecret: "<your-client-secret>",
        tenantId: "<your-tenant-id>",
        environment: AzureEnvironment.AzureGlobalCloud);
    
     var azure = Azure.Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithDefaultSubscription();
    
    // resource group creation
    var resourceGroupName = "<resource-group-name>";
    var region = Region.AsiaSouthEast;
    var resourceGroup = await azure.ResourceGroups.Define(resourceGroupName)
                    .WithRegion(region)
                    .CreateAsync();
     Console.WriteLine("Resource group created.");
    
    // storage account
    var storageAccountName = "<storage-account-name>";
    var storageAccount = await azure.StorageAccounts.Define(storageAccountName)
                    .WithRegion(region)
                    .WithExistingResourceGroup(resourceGroup)
                    .CreateAsync();
    Console.WriteLine("Storage account created.");
    
    // function app
    var functionAppName = "<function-app-name>";
    var functionApp = await azure.AppServices.FunctionApps.Define(functionAppName)
                    .WithRegion(region)
                    .WithExistingResourceGroup(resourceGroup)
                    .WithExistingStorageAccount(storageAccount)
                    .WithRuntimeVersion("~3")
                    .CreateAsync();
    Console.WriteLine("Function app created.");
    
     // you can Deploy the function code from a zip file
    var zipFilePath = "functionapp.zip";
    using (var fileStream = File.OpenRead(zipFilePath))
                {
                    await functionApp.ZipDeployAsync(fileStream);
                }
                Console.WriteLine("Function code deployed.");
    
    
    var functionName = "HelloWorld";
    // Get the function URL and key
    var function = await functionApp.GetFunctionAsync(functionName);
    var url = function.Url;
    var key = await function.GetMasterKeyAsync();
    Console.WriteLine($"The function URL is: {url}?code={key}");
            }
        }
    }
    
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search