Monday, 13 January 2025

EF Core 9 Generate Code First from Existing DB

1.Install EF Core, EF core Design, EF sql server using nuget packages.

2. Open package manger console 

3. Select the project where need to place entity and DbContext

4.Run below comments with modified inputs which is highlighted.

dotnet ef dbcontext scaffold "Server={Server};Database={DBname};User Id={db user name};Password={PWD};Encrypt=True;TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer --output-dir DbEntity --context-dir DbContext --context CoreDbContext --use-database-names --force --project D:/Source_vs2022/Core.Data/Core.Data.csproj

5. Now we can see Db context and db entity



6.Migrate to Full Code-First

If you want to start using migrations with the generated context execute below in same package mager console.

  1. Add migrations:
    dotnet ef migrations add InitialCreate --project Core.Data
  2. Update the database:
    dotnet ef database update --project Core.Data --verbose
Where :
  • InitialCreate is migration name
  • Core.Data is pr
NOTE: 
  • In case any other error occurs like missing OnConfigure then add below code in DBContext file.
  • after migration generated remove it below code due to security reason.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("Server={DB-Server};Initial Catalog={DB};User ID={UserName};Password={PWD};");
    }
}


Sunday, 12 January 2025

Azure Cloud Services

Public cloud

Services are offered over the public internet and available to anyone who wants to purchase them. Cloud resources, such as servers and storage, are owned and operated by a third-party cloud service provider, and delivered over the internet.


Private cloud

A private cloud consists of computing resources used exclusively by users from one business or organization. A private cloud can be physically located at your organization's on-site (on-premises) datacenter, or it can be hosted by a third-party service provider.


Hybrid cloud

A hybrid cloud is a computing environment that combines a public cloud and a private cloud by allowing data and applications to be shared between them.

Public cloud Private cloud Hybrid cloud
No capital expenditures to scale up.
Applications can be quickly provisioned and deprovisioned.
Organizations pay only for what they use.
Hardware must be purchased for start-up and maintenance.
Organizations have complete control over resources and security.
Organizations are responsible for hardware maintenance and updates.
Provides the most flexibility.
Organizations determine where to run their applications.
Organizations control security, compliance, or legal requirements.

cloud service models
IaaS: Infrastructure-as-a-Service

This cloud service model is the closest to managing physical servers; a cloud provider will keep the hardware up-to-date, but operating system maintenance and network configuration is up to you as the cloud tenant.
For example, Azure virtual machines are fully operational virtual compute devices running in Microsoft datacenters. An advantage of this cloud service model is rapid deployment of new compute devices. Setting up a new virtual machine is considerably faster than procuring, installing, and configuring a physical server.
The most flexible cloud service. You configure and manage the hardware for your application.


PaaS: Platform-as-a-Service

This cloud service model is a managed hosting environment. The cloud provider manages the virtual machines and networking resources, and the cloud tenant deploys their applications into the managed hosting environment.
For example, Azure App Services provides a managed hosting environment where developers can upload their web applications, without having to worry about the physical hardware and software requirements.
Focus on application development. Platform management is handled by the cloud provider.


SaaS: Software-as-a-Service

In this cloud service model, the cloud provider manages all aspects of the application environment, such as virtual machines, networking resources, data storage, and applications. The cloud tenant only needs to provide their data to the application managed by the cloud provider.
For example, Microsoft Office 365 provides a fully working version of Microsoft Office that runs in the cloud. All you need to do is create your content, and Office 365 takes care of everything else.
Pay-as-you-go pricing model. Users pay for the software they use on a subscription model.



Cloud service model comparison

Thursday, 2 January 2025

Each table wise total records in sql

To retrieve the total number of records (rows) for each table in a SQL Server database, you can use the sys.tables and sys.dm_db_partition_stats views. Here's a query to accomplish this:


Query to Get Row Counts for All Tables

SELECT 
    t.name AS TableName,
    SUM(p.rows) AS TotalRecords
FROM 
    sys.tables t
INNER JOIN 
    sys.partitions p ON t.object_id = p.object_id
WHERE 
    p.index_id IN (0, 1) -- 0 = Heap, 1 = Clustered index
GROUP BY 
    t.name
ORDER BY 
    TotalRecords DESC;

Explanation of Query:

  1. sys.tables: Contains information about all tables in the database.
  2. sys.partitions: Provides information about partitions of tables and indexes. The rows column contains the number of rows for each partition.
  3. index_id IN (0, 1): Ensures you count rows only for heap (no clustered index) or clustered index partitions.

Sample Output:

TableName TotalRecords
Customers 1200
Orders 450
Products 150

Wednesday, 1 January 2025

Types of publish dotnet core

Publish the app as a framework-dependent deployment

 dotnet publish -c Release -o publish-fd

In the preceding command:

  • -c Release specifies that the app should be built in release mode. This optimizes the app for performance.
  • -o specifies the name of the output directory. In this case, the output directory will be named publish-fd.

This command publishes the app as a framework-dependent deployment to the publish-fd directory.


Publish for self-contained deployment

Self-contained deployments include the app and its dependencies, as well as the .NET runtime. Since the .NET runtime is included with the app, the target machine doesn't need to have the .NET runtime installed in order to run the app. This makes self-contained deployments larger than framework-dependent deployments. Self-contained apps must also handle deploying .NET runtime updates to receive the latest patches.

publish the app as a self-contained deployment for 64-bit Windows:

.NET CLI
dotnet publish -c Release -r win-x64 -o publish-scd-win64 --self-contained

In the previous command:

  • -c Release specifies that the app should be built in release mode. This optimizes the app for performance.
  • -r win-x64 specifies that the app should be published for 64-bit Windows. win-x64 is the runtime identifier (RID) for 64-bit Windows, so the app is published as a self-contained deployment for 64-bit Windows.
  • -o publish-scd-win64 specifies the output directory for the published app.
  • --self-contained specifies that the app should be published as a self-contained deployment.

publish the app as a self-contained deployment for 64-bit Linux:

.NET CLI
dotnet publish -c Release -r linux-x64 -o publish-scd-linux64 --self-contained

This time, the -r linux-x64 option specifies that the app should be published for 64-bit Linux.


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.



6 API Architecture Styles You Should Know.

API architectural styles determine how applications communicate.

The choice of an API architecture can have significant implications on the efficiency, flexibility, and robustness of an application.

So it is very important to choose based on your application's requirements, not just what is often used.

Let’s examine some prominent styles:

𝗥𝗘𝗦𝗧

A cornerstone in web services, REST leverages HTTP methods for streamlined operations and a consistent interface.

Its stateless nature ensures scalability, while URI-based resource identification provides structure.

REST's strength lies in its simplicity, enabling scalable and maintainable systems.

Learn more about REST here: https://lnkd.in/gMy4RnpY

𝗚𝗿𝗮𝗽𝗵𝗤𝗟

Whilst REST uses multiple endpoints for each resource and necessitates multiple requests to obtain interconnected data;

GraphQL uses a single endpoint, allowing users to specify exact data needs, and delivers the requested data in a single query.

This approach reduces over-fetching, improving both performance and user experience.

Learn more about GraphQL here: https://lnkd.in/gp-hbh7g

𝗦𝗢𝗔𝗣

Once dominant, SOAP remains vital in enterprises for its security and transactional robustness.

It’s XML-based, versatile across various transport protocols, and includes WS-Security for comprehensive message security.

Learn more about SOAP here: https://lnkd.in/g7zTUA4b

𝗴𝗥𝗣𝗖

gRPC is efficient in distributed systems, offering bidirectional streaming and multiplexing.

Its use of Protocol Buffers ensures efficient serialization and is suitable for a variety of programming languages & use cases across different domains.

Learn more about gRPC here: https://lnkd.in/ggP8BgEx

𝗪𝗲𝗯𝗦𝗼𝗰𝗸𝗲𝘁𝘀

For applications demanding real-time communication, WebSockets provide a full-duplex communication channel over a single, long-lived connection.

It's popular for applications requiring low latency & continuous data exchange.

Learn more about WebSockets here: https://lnkd.in/gUExtMmQ

𝗠𝗤𝗧𝗧

MQTT is a lightweight messaging protocol optimized for high-latency or unreliable networks.

Its pub/sub model ensures efficient data dissemination among a vast array of devices, making it a go-to choice for IoT applications.

Learn more about MQTT here: https://lnkd.in/gqyiH5Ug

API architectural styles are more than just communication protocols; they are strategic choices that influence the very fabric of application interactions.

There is no best architectural style.

Each offers unique benefits, shaping the functionality and interaction of applications. It's about making the right choice(s) based on your application's requirements.

Learn more about API design here: https://lnkd.in/g92Cu2J3

P.S. If you like this post, then you'll love our newsletter. Subscribe here: https://lnkd.in/gCqFUtNz