Tuesday, 31 December 2024

AZ-204 Scenario based Questions

Mock Test: AZ-204

Question 1: Azure Functions

You are developing an HTTP-triggered Azure Function that processes image uploads. You want to ensure that the function automatically scales to handle increasing load.

  1. What hosting plan should you choose?
  2. How will you secure the HTTP endpoint to allow only authenticated users?

Question 2: Azure App Service

You have deployed an ASP.NET Core web app to Azure App Service. Users report intermittent downtime.

  1. Which Azure service would you use to monitor and diagnose the issue?
  2. How can you ensure the app remains available during maintenance or failures?

Question 3: Azure Key Vault

You are implementing Azure Key Vault to store sensitive information for your app.

  1. How do you grant your app access to retrieve secrets?
  2. Write a sample code snippet to retrieve a secret using .NET SDK.

Question 4: Azure Storage

You need to implement a solution to upload large files to Azure Blob Storage. The solution must support resumable uploads in case of network failures.

  1. Which upload method will you use?
  2. Write a pseudocode snippet for this implementation.

Question 5: Monitoring and Logging

Your app logs errors to Application Insights. However, you want to track custom metrics related to user activity.

  1. How can you implement custom metrics logging?
  2. Provide a code example using Application Insights SDK.

Question 6: Authentication with Azure AD

You are building an API that requires token-based authentication with Azure AD.

  1. How will you validate the tokens in your API?
  2. What scopes should be included in the access token?

Question 7: Azure CLI

You need to create an Azure Function App with a Linux Consumption Plan using Azure CLI.

  1. Write the command to create the Function App.
  2. Include the steps to configure deployment using Azure CLI.

Here's the evaluation of your answers for the mock test:


Question 1: Azure Functions

  1. Correct: Consumption Plan is ideal for scaling automatically to handle load.
  2. Partially Correct: Managed Identity is useful for securing access to resources. However, for securing an HTTP endpoint for only authenticated users, Azure AD Authentication (Easy Auth) should be configured for the Function App.

Question 2: Azure App Service

  1. Correct: Application Insights and logs can help monitor and diagnose issues.
  2. Partially Correct: App Health Check ensures the app is running but does not address availability during maintenance. Use Azure Traffic Manager or App Service Deployment Slots for high availability during updates or failures.

Question 3: Azure Key Vault

  1. Correct: Managed Identity is the best practice for granting secure access to Key Vault.
  2. Correct but needs more clarity: Your explanation of initializing SecretClient using Managed Identity is valid. A full code snippet like the following would be ideal:
var client = new SecretClient(new Uri("<KeyVaultURI>"), new DefaultAzureCredential());
var secret = await client.GetSecretAsync("<SecretName>");

Question 4: Azure Storage

  1. Correct: Block Blob Storage with chunked upload is the right choice.
  2. Partially Correct: Your explanation is correct, but pseudocode is expected. Example:
1. Read file and divide into 1MB chunks.
2. Upload each chunk using PutBlockAsync.
3. Commit all chunks with PutBlockListAsync.

Question 5: Monitoring and Logging

  1. Partially Correct: log.info can write logs, but for custom metrics, use TrackMetric API in Application Insights SDK.
  2. Partially Correct: A better approach is:
TelemetryClient telemetryClient = new TelemetryClient();
telemetryClient.TrackMetric("CustomMetricName", value);

Question 6: Authentication with Azure AD

  1. Correct: Validating tokens using JWT Token Validator is a good approach. Use Microsoft.IdentityModel.Tokens library in .NET.
  2. Incorrect: Scopes like ai_user and ai_session are unrelated to Azure AD. Correct answer: Include API-specific scopes defined during Azure AD App Registration (e.g., api://<client-id>/read).

Question 7: Azure CLI

  1. Incorrect: A command like this is expected:
az functionapp create --resource-group <ResourceGroupName> --consumption-plan-location <Location> --runtime dotnet --functions-version 4 --name <AppName> --storage-account <StorageAccountName>
  1. Partially Correct: CI/CD deployment is valid but the question asks for CLI steps. Include deployment configuration:
az functionapp deployment source config --name <AppName> --resource-group <ResourceGroupName> --repo-url <RepoURL> --branch main --manual-integration


Here’s your next set of AZ-204 mock test questions. Try to answer them and let me know when you're done!


Mock Test: AZ-204 - Set 2

Question 1: Azure Functions

You are developing a time-triggered Azure Function to clean up unused blob storage containers daily at midnight.

  1. What binding type will you use for this Function?
    A Time Trigger binding is the right choice for scheduling tasks in Azure Functions.
  2. Provide an example of a CRON expression for the schedule.
    Partially Correct: The CRON expression 0 59 23 * * * is incorrect for midnight. Correct expression: 0 0 0 * * *.


Question 2: Azure App Configuration

Your application retrieves configuration values from Azure App Configuration. To ensure performance, you need to update the values in near real-time when they change.

  1. How would you implement this functionality?
    Incorrect: The correct approach to update configuration in near real-time is to use Azure App Configuration Refresh with a registered configuration provider in the application.

  2. Write a code snippet to register Azure App Configuration in a .NET Core application.
        builder.Configuration.AddAzureAppConfiguration(options =>
{
    options.Connect("<AppConfigurationConnectionString>")
           .UseFeatureFlags();
});
services.AddAzureAppConfiguration();





Question 3: Azure Logic Apps

You need to create a Logic App that is triggered by an HTTP request and sends an email using Office 365 when the request contains valid JSON.

  1. How would you validate the incoming JSON in the Logic App?
    Partially Correct: Using System.Text.Json in a Logic App is not possible. Logic Apps have a built-in "Parse JSON" action to validate incoming JSON.

  2. What is the next step if the JSON validation fails?
    Correct: Logging the error and sending a failure response is a valid next step.

Question 4: Azure Cosmos DB

You are developing a solution using Azure Cosmos DB with the SQL API. The application performs frequent read operations on a large dataset.

  1. Which consistency level would you choose to optimize performance for reads?
    Incorrect: "No Track" is unrelated. The best consistency level for frequent reads to optimize performance is Eventual Consistency.

  2. How would you structure the database to reduce latency?
    Partially Correct: Using partition keys is correct, but ensure they distribute data evenly. For example, structure your data to avoid hot partitions.

Question 5: Azure Identity

You are securing an Azure App Service that exposes a REST API. The API must only allow requests from applications registered in Azure AD.

  1. What Azure AD feature would you configure to enforce this?
    Correct: Registering Azure AD authentication and enforcing authorization is the correct approach.

  2. Write a sample appsettings.json configuration for authenticating using Azure AD.
    Partially Correct: The JSON structure is mostly correct, but SharedSecret is not standard. Use ClientSecret instead:

    "AzureAd":
    {
         "Instance": "https://login.microsoftonline.com/",
         "TenantId": "<TenantId>",
         "ClientId": "<ClientId>",
         "ClientSecret": "<KeyVaultSecret>"
    }

Question 6: Azure CLI - Networking

You need to create a virtual network with two subnets using Azure CLI.

  1. Provide the CLI commands to create the virtual network and subnets.
az network vnet create --resource-group <ResourceGroupName> --name <VNetName> --address-prefix <AddressPrefix>
az network vnet subnet create --resource-group <ResourceGroupName> --vnet-name <VNetName> --name <SubnetName1> --address-prefix <SubnetAddressPrefix1>
az network vnet subnet create --resource-group <ResourceGroupName> --vnet-name <VNetName> --name <SubnetName2> --address-prefix <SubnetAddressPrefix2>

2. How would you associate a network security group (NSG) with one of the subnets?

az network vnet subnet update --vnet-name <VNetName> --name <SubnetName> --resource-group <ResourceGroupName> --network-security-group <NSGName>


Question 7: Azure Service Bus

Your application needs to send and receive messages reliably using Azure Service Bus.

  1. What is the difference between a Queue and a Topic?
    Queue used to send message with single process
    Topic we can use filter and same object will call different subscription

  2. Write a code snippet to send a message to a Service Bus Queue in .NET.



Here’s a detailed explanation and answers to the mock test questions, along with additional questions to help you prepare comprehensively for the AZ-204 exam.


Mock Test Questions with Detailed Answers

Question 1: Azure Functions

You are developing a time-triggered Azure Function to clean up unused blob storage containers daily at midnight.
1. What binding type will you use for this Function?

  • Answer: Use the Time Trigger binding. Azure Functions supports bindings for various triggers, and the Time Trigger is ideal for scheduling tasks.

2. Provide an example of a CRON expression for the schedule.

  • Answer: 0 0 0 * * *
    This runs the function at midnight every day. The format for CRON expressions in Azure Functions is:
    {second} {minute} {hour} {day} {month} {day-of-week}
    

Question 2: Azure App Configuration

Your application retrieves configuration values from Azure App Configuration. To ensure performance, you need to update the values in near real-time when they change.

1. How would you implement this functionality?

  • Answer: Use the Azure App Configuration Refresh feature.
    Register the configuration provider in the program, then call the ConfigurationRefresher service periodically to update the configuration values.

2. Code Snippet:

builder.Configuration.AddAzureAppConfiguration(options =>
{
    options.Connect("<ConnectionString>")
           .ConfigureRefresh(refresh =>
           {
               refresh.Register("Settings:Sentinel", refreshAll: true);
           });
});

services.AddAzureAppConfiguration();
app.UseAzureAppConfiguration();

Question 3: Azure Logic Apps

You need to create a Logic App that is triggered by an HTTP request and sends an email using Office 365 when the request contains valid JSON.

1. How would you validate the incoming JSON in the Logic App?

  • Answer: Use the "Parse JSON" action in the Logic App. Provide the JSON schema to validate the incoming payload.

2. What is the next step if the JSON validation fails?

  • Answer: Add a conditional action. If validation fails, log the error and return an appropriate HTTP failure response using the "Response" action.

Question 4: Azure Cosmos DB

You are developing a solution using Azure Cosmos DB with the SQL API. The application performs frequent read operations on a large dataset.

1. Which consistency level would you choose to optimize performance for reads?

  • Answer: Use Eventual Consistency. It offers the lowest latency for read operations, sacrificing strict consistency guarantees.

2. How would you structure the database to reduce latency?

  • Answer:
    • Use a Partition Key that ensures even data distribution (e.g., user ID or region).
    • Structure containers and queries to align with access patterns.
    • Avoid hot partitions by choosing partition keys with high cardinality.

Question 5: Azure Identity

You are securing an Azure App Service that exposes a REST API. The API must only allow requests from applications registered in Azure AD.

1. What Azure AD feature would you configure to enforce this?

  • Answer: Use Azure AD App Registration to enforce authentication for the REST API. This involves configuring the API to accept only tokens issued by Azure AD.

2. Sample appsettings.json:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "TenantId": "<TenantId>",
  "ClientId": "<ClientId>",
  "ClientSecret": "<KeyVaultSecret>"
}

Question 6: Azure CLI - Networking

You need to create a virtual network with two subnets using Azure CLI.

1. Provide the CLI commands to create the virtual network and subnets.

  • Answer:
# Create a virtual network
az network vnet create --resource-group MyResourceGroup --name MyVNet --address-prefix 10.0.0.0/16

# Create subnets
az network vnet subnet create --resource-group MyResourceGroup --vnet-name MyVNet --name Subnet1 --address-prefix 10.0.1.0/24
az network vnet subnet create --resource-group MyResourceGroup --vnet-name MyVNet --name Subnet2 --address-prefix 10.0.2.0/24

2. How would you associate a network security group (NSG) with one of the subnets?

az network vnet subnet update --resource-group MyResourceGroup --vnet-name MyVNet --name Subnet1 --network-security-group MyNSG

Question 7: Azure Service Bus

Your application needs to send and receive messages reliably using Azure Service Bus.

1. What is the difference between a Queue and a Topic?

  • Answer:
    • A Queue is a point-to-point messaging model where a single consumer processes each message.
    • A Topic is a publish/subscribe model where multiple subscribers can receive the same message.

2. Code Snippet to Send a Message:

var client = new ServiceBusClient("<ConnectionString>");
var sender = client.CreateSender("<QueueName>");

var message = new ServiceBusMessage("Hello, Service Bus!");
await sender.SendMessageAsync(message);

await sender.DisposeAsync();
await client.DisposeAsync();

Comprehensive List of Questions for AZ-204

Azure App Services

  1. How do you configure auto-scaling for an Azure App Service?
  2. How would you implement a deployment slot for testing changes before production?

Azure Functions

  1. How do you create an Azure Function triggered by a queue message?
  2. How do you implement retries for failed executions in Azure Functions?

Azure Storage

  1. What is the difference between Blob Storage and File Storage?
  2. How do you implement a chunked file upload in Azure Blob Storage?

Azure Cosmos DB

  1. How do you create a stored procedure in Cosmos DB?
  2. What are the differences between partition key and unique key?

Azure AD and Identity

  1. How do you implement OpenID Connect for authentication in .NET Core?
  2. How do you use Managed Identity to access Azure resources?

Azure DevOps

  1. How do you create a pipeline to deploy a .NET Core application to Azure?
  2. What is YAML and how is it used in Azure Pipelines?

Azure Monitoring and Diagnostics

  1. How do you configure Application Insights for a .NET Core application?
  2. What are the key metrics you would monitor for an App Service?

Azure Networking

  1. How do you set up a VPN Gateway in Azure?
  2. What are the differences between Azure Front Door and Azure Application Gateway?

Azure Service Bus

  1. How do you implement a dead-letter queue in Azure Service Bus?
  2. How would you secure Azure Service Bus using Azure AD?

Azure Kubernetes Service (AKS)

  1. How do you deploy a Docker container to AKS?
  2. What is a Helm chart, and how do you use it?

Below is a detailed explanation for each question category with answers and examples. This is designed to provide you with in-depth knowledge for AZ-204 preparation.


Azure App Services

Q1. How do you configure auto-scaling for an Azure App Service?

Auto-scaling enables your app to handle varying loads by scaling out (adding instances) or scaling in (reducing instances).

Steps:

  1. Go to the Azure PortalApp Services → Select your App Service.
  2. Under Settings, click on Scale out (App Service plan).
  3. Choose between Manual Scaling or Custom Auto-Scaling.
  4. In custom scaling, configure rules based on metrics like CPU utilization, memory usage, or request count.

Example Rule:

  • Scale out when CPU usage > 75% for 5 minutes.
  • Scale in when CPU usage < 25% for 10 minutes.

Q2. How would you implement a deployment slot for testing changes before production?

Deployment slots allow you to deploy to a staging environment and then swap it with production after testing.

Steps:

  1. Go to your App Service in Azure Portal.
  2. Under Deployment, click Deployment Slots → Add Slot.
  3. Deploy your app to the new slot (e.g., staging).
  4. Test the app in the staging slot.
  5. Swap the staging slot with production once validated.

Benefit: Zero-downtime deployment with rollback capability.


Azure Functions

Q1. How do you create an Azure Function triggered by a queue message?

You can use the ServiceBusQueueTrigger attribute to bind an Azure Function to an Azure Service Bus queue.

Example Code:

[FunctionName("QueueTriggeredFunction")]
public async Task Run(
    [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] string queueMessage,
    ILogger log)
{
    log.LogInformation($"Queue message received: {queueMessage}");
}

Steps:

  1. Add a Service Bus connection string in the local.settings.json.
  2. Deploy the function to Azure.
  3. Send a message to the queue using Azure Portal or Service Bus SDK.

Q2. How do you implement retries for failed executions in Azure Functions?

You can configure retry policies in the host.json file.
Example:

{
  "version": "2.0",
  "extensions": {
    "serviceBus": {
      "messageHandlerOptions": {
        "maxAutoRenewDuration": "00:05:00",
        "maxConcurrentCalls": 16
      }
    }
  },
  "retry": {
    "strategy": "exponentialBackoff",
    "maxRetryCount": 5,
    "minimumInterval": "00:00:02",
    "maximumInterval": "00:01:00"
  }
}

Azure Storage

Q1. What is the difference between Blob Storage and File Storage?

Feature Blob Storage File Storage
Use Case Unstructured data (e.g., images, videos). Shared file storage for applications.
Protocol REST API, HTTP/S SMB protocol.
Accessibility Via URL Mountable like a network drive.
Scalability Extremely scalable Limited by storage account limits.

Q2. How do you implement a chunked file upload in Azure Blob Storage?

Steps:

  1. Divide the file into smaller chunks (e.g., 1 MB each).
  2. Use BlockBlobClient.StageBlockAsync() to upload each chunk.
  3. Call BlockBlobClient.CommitBlockListAsync() to commit the uploaded blocks.

Example Code:

BlockBlobClient blockBlobClient = new BlockBlobClient(connectionString, containerName, blobName);

var blockIds = new List<string>();
for (int i = 0; i < chunks.Count; i++)
{
    var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()));
    await blockBlobClient.StageBlockAsync(blockId, chunks[i], null);
    blockIds.Add(blockId);
}

await blockBlobClient.CommitBlockListAsync(blockIds);

Azure Cosmos DB

Q1. How do you create a stored procedure in Cosmos DB?

Steps:

  1. Go to the Azure Cosmos DB accountData Explorer.
  2. Select the container → New Stored Procedure.
  3. Write a JavaScript function as the stored procedure.
    Example:
function sampleProcedure() {
    var context = getContext();
    var response = context.getResponse();
    response.setBody("Hello, Cosmos DB!");
}

Q2. What are the differences between partition key and unique key?

Feature Partition Key Unique Key
Purpose Distribute data across partitions. Enforce uniqueness within the container.
Scope Impacts performance and scalability. Logical constraint only.
Example userId or region. emailAddress or orderId.

Azure AD and Identity

Q1. How do you implement OpenID Connect for authentication in .NET Core?

Steps:

  1. Register the app in Azure AD.
  2. Configure middleware in Startup.cs.
    Example Code:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(options =>
        {
            options.ClientId = "<ClientId>";
            options.TenantId = "<TenantId>";
        });

Azure DevOps

Q1. How do you create a pipeline to deploy a .NET Core application to Azure?

Steps:

  1. Create a YAML pipeline in Azure DevOps.
  2. Define tasks for build, test, and deploy.

Example YAML:

trigger:
- main

pool:
  vmImage: 'windows-latest'

steps:
- task: UseDotNet@2
  inputs:
    packageType: sdk
    version: '6.x'
    installationPath: $(Agent.ToolsDirectory)/dotnet

- script: dotnet build
  displayName: 'Build project'

- script: dotnet test
  displayName: 'Run tests'

- task: AzureRmWebAppDeployment@4
  inputs:
    azureSubscription: '<Subscription>'
    appType: 'webApp'
    WebAppName: '<AppName>'
    package: '$(Build.ArtifactStagingDirectory)/**/*.zip'

Azure Monitoring and Diagnostics

Q1. How do you configure Application Insights for a .NET Core application?

  1. Install the NuGet package: Microsoft.ApplicationInsights.AspNetCore.
  2. Configure it in Program.cs:
builder.Services.AddApplicationInsightsTelemetry("<InstrumentationKey>");

Q2. What are the key metrics you would monitor for an App Service?

  1. CPU usage.
  2. Memory usage.
  3. HTTP response time.
  4. Error rates.
  5. Requests per second.



No comments:

Post a Comment