az-203 Archives - Learn Smart Coding https://blogs.learnsmartcoding.com/tag/az-203/ Everyone can code! Sun, 05 Jul 2020 15:24:23 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 209870635 Microsoft Azure Developer: Create Serverless Functions in Azure Portal https://blogs.learnsmartcoding.com/2020/07/05/microsoft-azure-developer-create-serverless-functions-in-azure-portal/ https://blogs.learnsmartcoding.com/2020/07/05/microsoft-azure-developer-create-serverless-functions-in-azure-portal/#respond Sun, 05 Jul 2020 15:24:23 +0000 https://karthiktechblog.com/?p=556 Create Serverless Functions in the Azure Portal. Azure functions have the capability to greatly speed up your development, reduce your cost, and allows you to automatically scale to meet the high demand. What is Azure Functions? Functions as a Service (FaaS) – A platform for running “functions”, which are nothing but your code running in […]

The post Microsoft Azure Developer: Create Serverless Functions in Azure Portal appeared first on Learn Smart Coding.

]]>
Create Serverless Functions in the Azure Portal. Azure functions have the capability to greatly speed up your development, reduce your cost, and allows you to automatically scale to meet the high demand.

What is Azure Functions?

Functions as a Service (FaaS) – A platform for running “functions”, which are nothing but your code running in response to an event.

Features of Serverless Functions

  • Automated and flexible scaling based on your workload volume.
  • Integrated programming model based on triggers and bindings.
  • End-to-end development experience, from building and debugging to deploying and monitoring with integrated tools and built-in DevOps capabilities.
  • Variety of programming languages and hosting options.
azure functions supported language

Triggers

Various triggers used to invoke Azure Functions.

  • A function runs at a specific time using a timer trigger.
  • Message Trigger: Listen to a message in a queue and process it as and when a message arrives.
  • HTTP Request: create a web API that responds to different HTTP methods.
  • Azure functions respond to the webhook callback. Third-party service triggers callbacks.
azure serverless functions trigger
Triggers

Bindings

Binding to a function is used to connect another resource to the function.

Different bindings, input bindings, output bindings, or both can be used. Data from bindings are provided to the function as parameters.

You can mix and match different bindings to suit your needs. Bindings are optional. A function might have one or multiple inputs and/or output bindings.

azure serverless functions bindings

Read more on Azure Functions triggers and bindings concepts this has details on supported bindings.

Serverless Architecture

What is Serverless Architecture? what are the benefits that brings to us ?

  • Azure will manage servers.
  • Per-second billing model. Pay only when your code runs. There is also a monthly free grant which is sufficient for any developers who are exploring serverless functions.
  • Automatic scaling. Application demands met automatically.

Azure functions is simpler, cheaper and more scalable.

azure serverless functions hosting models

Creating Functions in the Azure Portal

In this module, I will show how to create azure functions in a azure portal.

Visit https://Portal.azure.com and login with your azure portal account.

If you are new or do not have Azure subscription, visit Create your Azure free account today and get your free $200 credit.

Create Azure Function App

Search for “Function App” in the search box in the top and click on “Function App” to create.

Creating Functions in the Azure Portal
dashboard of function app

Above page is the dashboard of Function App. Click on “Create Function App” to create a new one.

Basic Configuration

creating function app basic configuration

Always create a new resource group for any new service that you create. This will help in managing it easily.

What is a resource group? A resource group is a container that holds related resources for an Azure solution.

Choose a unique name for the Function App. I have provided as “karthiktechblog-function-app” that will end up forming a base URL as http://karthiktechblog-function-app.azurewebsites.net/.

Choose the publish option as code or docker. In this example, we choose as code and in docker post, I will show how to use Docker as publish option.

Next is to choose the Runtime Stack and its version. last part in the basic configuration section is to choose the region. Choose the close one near by your location.

Hosting Configuration

creating function app hosting configuration

Monitoring Configuration

creating function app monitoring configuration

Select Application Insights which is useful to find details of request in case of error.

Tags used to apply in your Azure resources, resource groups, and subscriptions to logically organize them into a taxonomy. Each tag consists of a name and a value pair. To read more about Tags visit here Use tags to organize your Azure resources and management hierarchy

Review & Create Configuration

This is the final page to verify the configuration made so far.

Review and create function app

Alright, now we have successfully created Function App. Now its time to create a new function and consume it from portal.

Creating a Function in Azure Portal

azure function app dashboard

From the azure Function App dashboard, click on Function in the left navigation bar. This will show you the available functions under this Function App.

azure function dashboard

Click on Add to create a new Function.

Next is to choose a template. There are many inbuilt templates that are available to the right-side panel, choose the one that fits your requirement. In my example, I will choose the HTTP Trigger.

azure function template

Next is to name the function and select the authorization level for the function.

function trigger details
  • anonymous: No API key is required.
  • function: A function-specific API key is required. This is the default value if none is provided.
  • admin: The master key is required.
Microsoft Azure Developer: Create Serverless Functions in Azure Portal

Now the function is ready. Click on Code and Test, you will see the default code created by the template.

This simple API will read the request and try to find a parameter called “name” and send a hello message. If name parameter is not sent, you will get a Bad Request (HTTP 400 status code).

Output is seen in the output tab and logs can be seen in the console.

Related Post

This post is part of Implement Azure functions, skill measured in AZ-204 and Exam AZ-203: Developing Solutions for Microsoft Azure

Conclusion

In this post, I showed you how to create Serverless Functions in the Azure Portal. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Microsoft Azure Developer: Create Serverless Functions in Azure Portal appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/07/05/microsoft-azure-developer-create-serverless-functions-in-azure-portal/feed/ 0 556
Enabling Diagnostics Logging in Azure App Service https://blogs.learnsmartcoding.com/2020/02/05/enabling-diagnostics-logging-in-azure-app-service/ https://blogs.learnsmartcoding.com/2020/02/05/enabling-diagnostics-logging-in-azure-app-service/#respond Wed, 05 Feb 2020 00:21:25 +0000 https://karthiktechblog.com/?p=346 Introduction If you are looking at this post “enabling diagnostics logging” then you are already familiar with building and hosting web application with in a azure app service. You may also be looking for options to support your application. I will show how to use diagnostics logs that are available with in azure app service. […]

The post Enabling Diagnostics Logging in Azure App Service appeared first on Learn Smart Coding.

]]>
Introduction

If you are looking at this post “enabling diagnostics logging” then you are already familiar with building and hosting web application with in a azure app service. You may also be looking for options to support your application.

I will show how to use diagnostics logs that are available with in azure app service. I will show the options available to configure diagnostics logs.

Reasons for logging

There are various reasons why we log information. However, we should not log for each and every scenario in our application which then creates too much of information from which an useful information can be taken.
To mitigate this problem, Logging Strategies are in place to clarify what, when and why something should be logged.

Most important logging strategies are listed below.

Auditing

This type of information helps to find who has logged in and who performed a particular action in business context. This acts as tracking mechanism.

Detecting Suspicious Activity

Auditing helps in determining any Suspicious Activity by hackers to break into your system by many login attempts or SQL injection, XSS and etc.

Performance Monitoring

Useful logs created to perform an baseline performance and to see whether application is performing as expected.

Error Notification

Generated error logs are useful in timely notification to the team to inform error occurred and you can act accordingly.

Tracing

To troubleshoot issues that do occur in your application, trace messages can be added to the application logic that helps to create path that user has navigated to reach to your application.

Difference between enabling diagnostics logging and application insights

Diagnostic logs has built-in diagnostics to assist with debugging an App Service web app. It can only track just the app Service instance and allow basic log viewing and downloading.

It does supports trace messages and will not capture AI trace or Exceptions from your application. All the logged data are available in files that needs to be manually analysed. This logging affects web app performance.

Application Insights, a feature of Azure Monitor, is an extensible Application Performance Management (APM) service. It can trace across all the layers in a web application and has enhanced analytics. Also, application insights has SDK with enhanced custom telemetry. E.g. Exceptions and traces plus Pageviews, Events and Metrics.
App insights can also capture diagnostics trace messages. Compared to diagnostics logs, the impact on your app’s performance is very small.

Read more about application insights

You might feel by now that we can go with application insight instead of leaning diagnostics log. You might be here to learn about diagnostics log as this is part of azure AZ-203 certification skill assessment.

To configure the logging, go to your app service and search with keyword “Monitoring” as shown in the below image. You will see “App Service Log” menu in the left side menu.

Enabling Diagnostics Logging in Azure App Service

Types of Diagnostic Logs

There are four types of diagnostics logging namely

  • Application Logging
  • Web Server Logging
  • Detailed Error Message
  • Failed Request Tracing

Application Logging:

Application logging is the place where the coded trace message can be viewed. Each trace messages give specific log level.

Log Levels

  1. Off
  2. Error
  3. Warning
  4. Info
  5. Verbose
Enabling Diagnostics Logging in Azure App Service

You can see that each log level has been given a level number to it, you can choose this level when configuring the application log to see the highest level of logging.

For example, if you choose Warning when configuring, then the Info and Verbose are ignored.

Application logging in file system

Application Logging (Blob)

You can store the log in Blob. If you wish to choose, then you need to create a container first and then use it.

Application logging in blob storage

Web Server Logging:

This contains the Raw HTTP data, like IIS logs that helps to capture the URI, client IP address, port, browser and much more for troubleshooting.

Quota option is used to configure the space used to store the logs.

Retention period option will delete the logs older than the specified number of days.

web server logging

Detailed Error Message:

With custom error response, you can hide the server error response. For example, when there is an 500 – Internal server error occurs, the use gets to see custom error page that is configured instead of seeing server error page.

Detailed error message logging
Detailed error message that is part of Enabling Diagnostics Logging in Azure App Service

Failed Request Tracing:

This is a detailed error logging that shows almost all the logs that you can trace and find the cause of error.

Failed request logging

Diagnose and Solve Problems

There are different types of App Service Diagnostics available. You can choose one or more from the listed options. Each option is useful in its own way of solving problems.

Diagnose and Solve Problems

Conclusion

In this post, I showed enabling diagnostics logging in app service and showed various options that are available for Azure App Service. The details in this post will help to cover a part of knowledge required to complete Azure AZ-203 certification.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Enabling Diagnostics Logging in Azure App Service appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/02/05/enabling-diagnostics-logging-in-azure-app-service/feed/ 0 346
Configure elastic pools for Azure SQL Databases https://blogs.learnsmartcoding.com/2020/01/11/configure-elastic-pools-for-azure-sql-databases/ https://blogs.learnsmartcoding.com/2020/01/11/configure-elastic-pools-for-azure-sql-databases/#respond Sat, 11 Jan 2020 01:15:52 +0000 https://karthiktechblog.com/?p=315 Introduction This post, I show how to configure elastic pools for Azure SQL Database. Microsoft Azure SQL Database are great for both predictable and unpredictable workloads. Unpredictability is specially challenging for software as service or called as SaaS Providers. SaaS providers have hundreds or even thousands of customers who then have their own unique mix […]

The post Configure elastic pools for Azure SQL Databases appeared first on Learn Smart Coding.

]]>
Introduction

This post, I show how to configure elastic pools for Azure SQL Database. Microsoft Azure SQL Database are great for both predictable and unpredictable workloads.

Unpredictability is specially challenging for software as service or called as SaaS Providers. SaaS providers have hundreds or even thousands of customers who then have their own unique mix of performance demands.

A common output is found that SaaS providers over provision their databases to meet variable and peak demands(resource demands) which is not cost effective and brings in management issues.

To solve this and operate cost effective, a predictable cost can be found by using elastic pool databases.

What are SQL elastic pools

SQL Database elastic pools are a simple, cost-effective solution for managing and scaling multiple databases that have varying and unpredictable usage demands.

Elastic pools help solve this problem by enabling you to set a policy for a group of elastic database ensuring that databases get the performance resources they need when they need it.

They provide a simple resource allocation mechanism within a predictable budget.

You don’t need to worry about each database or over provisioning for peak demands.

To check price for various service tier, visit Explore all SQL Database pricing options

Configure elastic pools for Azure SQL Database

Within the database server blade, you can see I have many databases. simply click on Add Pool.

Configure elastic pools for Azure SQL Databases
providing name for elastic pool

Next is to give it a name. Provide name to the pool .

To choose different elastic pool configuration, click on ConfigurePool option as shown in the above image.

Configure elastic pools for Azure SQL Databases

There are many Service Tier available and the pricing differ for each one. Once you chose the right options, click on Databases.

Choose database for elastic pool

Click on the Plus symbol to see the available databases. Choose the databases from the right side menu.

choosing service tier and configure elastic pool

Next option is to choose “PerDatabase” configuration and click on Apply.

Right side you can see the pricing shown per month. Likewise, you can see pricing for different option that you may choose.

Now you will see “Your deployment is underway” message, please be patience and give few minutes time for the process to complete.

Important to note:

There is no per-database charge for elastic pools. You will be billed for each hour a pool exists at the highest eDTU or vCores, regardless of usage or whether the pool was active for less than an hour.

When should you consider a SQL Database elastic pool

Pools are well suited for a very large number of databases with specific utilization patterns. The more databases you can add to a pool the greater your savings become.

Conclusion

In this post, I showed how to configure elastic pools for Azure SQL Database. The details in this post will help to cover a part of knowledge required to complete Azure AZ-203 certification.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Configure elastic pools for Azure SQL Databases appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/01/11/configure-elastic-pools-for-azure-sql-databases/feed/ 0 315
Implement create, read, update, and delete functionalities using Entity Framework Core https://blogs.learnsmartcoding.com/2020/01/10/implement-curd-functionalities-in-aspnetcore-using-entity-framework-core/ https://blogs.learnsmartcoding.com/2020/01/10/implement-curd-functionalities-in-aspnetcore-using-entity-framework-core/#comments Fri, 10 Jan 2020 11:02:02 +0000 https://karthiktechblog.com/?p=310 Introduction In this post, I show how to Implement CURD functionality in ASPNETCORE using Entity Framework Core. I have my existing project with bare minimum configuration setup to start and to start with this post demo, I will be using it. To follow along with me for this post, you need to know some basic […]

The post Implement create, read, update, and delete functionalities using Entity Framework Core appeared first on Learn Smart Coding.

]]>
Introduction

In this post, I show how to Implement CURD functionality in ASPNETCORE using Entity Framework Core. I have my existing project with bare minimum configuration setup to start and to start with this post demo, I will be using it.

To follow along with me for this post, you need to know some basic knowledge on setting up a SQL Database to use as our back end.

To know more, take a look at my post CONFIGURE AZURE SQL RELATIONAL DATABASE USING VS 2019

The full demo application is available for free and you may download from my GitHub repository. Take “feature/ImplementCURDFunctionality” branch for this demo.

Getting Started

Now with the demo application in place, we have setup our back end database which has shopping related entities. I will show you how to implement create, read, update, and delete functionalities using Entity Framework Core.

I will be implementing CURD functionalities for Product entity.

To speed up the development work and also to encapsulate the logic required to access data sources, I will be using Repository pattern in this demo and to my demo project.

What is Repository pattern ?

Repositories are classes or components that encapsulate the logic required to access data sources. The functionality written in the repository is centralized and providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.

As we are using Object-Relational Mapper (ORM) like Entity Framework Core in our project, the code that must be implemented is simplified and it is easy to use.

If you ever think why not to use UnitOfWork pattern along with the repository patter, the answer is NO in my opinion.

This is because, the ORM, in our case Entity Framework Core itself is designed using UnitOfWork design patter as it is tracking all the changes that we make and commits all at once.

It is good idea not to bring in a wrapper for EntityFramework Core.

Repository Setup

Let’s have a generic repository which will have most of the common logic that is required to perform CURD operation on a given entity.

 public interface IGenericRepository
    {
        Task> GetAsync(
            Expression> filter = null,
            Func, IOrderedQueryable> orderBy = null,
            string includeProperties = "", CancellationToken cancellationToken = default, bool trackable = true);

        Task GetByIdAsync(object id, CancellationToken cancellationToken = default);

        Task InsertAsync(TEntity entity, CancellationToken cancellationToken = default);
        void Delete(object id);
        void Delete(TEntity entityToDelete);
        void Update(TEntity entityToUpdate);
        void UpdateStateAlone(TEntity entityToUpdate);
        void DetachEntities(TEntity entityToDetach);
        void DetachEntities(List entitiesToDetach);
    }
 public class GenericRepository : IGenericRepository
   where TEntity : class, new()
    {
        private readonly ManageTextDbContext context;
        internal DbSet dbSet;

        public GenericRepository(ManageTextDbContext context)
        {
            this.context = context;
            dbSet = context.Set();
        }

        public virtual Task> GetAsync(
            Expression> filter = null,
            Func, IOrderedQueryable> orderBy = null,
            string includeProperties = "", CancellationToken cancellationToken = default, bool trackable = true)
        {
            IQueryable query = dbSet;

            if (filter != null)
            {
                query = trackable ? query.Where(filter).AsNoTracking() : query.Where(filter).AsNoTracking();
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty).AsNoTracking();
            }

            if (orderBy != null)
            {
                return orderBy(query).AsNoTracking().ToListAsync();
            }
            else
            {
                return query.AsNoTracking().ToListAsync();
            }
        }

        public virtual Task GetByIdAsync(object id, CancellationToken cancellationToken = default)
        {
            return dbSet.FindAsync(id);
        }

        public virtual Task InsertAsync(TEntity entity, CancellationToken cancellationToken = default)
        {
            return dbSet.AddAsync(entity, cancellationToken);
        }

        public virtual void Delete(object id)
        {
            TEntity entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
        }

        public virtual void Delete(TEntity entityToDelete)
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
        }

        public virtual void Update(TEntity entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }

        public virtual void UpdateStateAlone(TEntity entityToUpdate)
        {            
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }

        public void DetachEntities(TEntity entityToDetach)
        {
            context.Entry(entityToDetach).State = EntityState.Detached;            
        }

        public void DetachEntities(List entitiesToDetach)
        {
            foreach (var entity in entitiesToDetach)
            {
                context.Entry(entity).State = EntityState.Detached;
            }
        }

    }

Setup repository for Entities

In this demo, I need a repository for Product entity, below is the code to setup IProductRepository.

using KarthikTechBlog.Shopping.Core;
using System.Threading.Tasks;

namespace KarthikTechBlog.Shopping.Data
{
    public interface IProductRepository : IGenericRepository
    {
        Task CommitAsync();
    }
}
using KarthikTechBlog.Shopping.Core;
using System.Threading.Tasks;

namespace KarthikTechBlog.Shopping.Data
{
    public class ProductRepository : GenericRepository, IProductRepository
    {
        private readonly ShoppingDbContext _context;
        public ProductRepository(ShoppingDbContext context) : base(context)
        {
            _context = context;
        }

        public Task CommitAsync()
        {
            return _context.SaveChangesAsync();
        }
    }
}

Create Product Service

Let’s create a service for the Product entity and this will access all product related functionality.

using KarthikTechBlog.Shopping.Core;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace KarthikTechBlog.Shopping.Service
{
    public interface IProductService
    {
        Task CreateProductAsync(Product product);
        Task UpdateProductAsync(Product product);
        Task DeleteProductAsync(int productId);
        Task> GetProductsAsync();
        Task GetProductAsync(int productId);
    }
}

using KarthikTechBlog.Shopping.Core;
using KarthikTechBlog.Shopping.Data;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace KarthikTechBlog.Shopping.Service
{
    public class ProductService: IProductService
    {
        public ProductService(IProductRepository productRepository)
        {
            ProductRepository = productRepository;
        }

        public IProductRepository ProductRepository { get; }

        public async Task CreateProductAsync(Product product)
        {
            await ProductRepository.InsertAsync(product);
            return await ProductRepository.CommitAsync();
        }

        public async Task DeleteProductAsync(int productId)
        {
            ProductRepository.Delete(productId);
            return await ProductRepository.CommitAsync();
        }

        public Task GetProductAsync(int productId)
        {
            return ProductRepository.GetByIdAsync(productId);
        }

        public Task> GetProductsAsync()
        {
            return ProductRepository.GetAsync();
        }

        public async Task UpdateProductAsync(Product product)
        {
            ProductRepository.Update(product);
            return await ProductRepository.CommitAsync();
        }
    }
}

Now all we left here is controller, come let’s write some minimum code to complete our CURD functionality for Product entity.

Read Product data (GET API)

    public class ProductController : ControllerBase
    {
        public ProductController(IProductService productService)
        {
            ProductService = productService;
        }

        public IProductService ProductService { get; }

        public async Task GetProduct(
           [FromQuery] int productId)
        {
            var product = await ProductService.GetProductAsync(productId);
            return Ok(product);
        }
    }

The controller code is pretty simply, that is the beauty of using right layers to talk to back end database. In this case, we inject the Service layer for Product and call the required methods to get Product data.

Now, one thing in this I would like to change. Currently we are returning the entity model itself from the controller. what if we need to add custom data annotation or custom model validation? I will show you the custom validation in another post.

For now, let’s create view model for that we need to send to client which is our API consuming client.

I have created ProductViewModel as the model for any GET API calls.

public class ProductViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public DateTime? AvailableSince { get; set; }
        public int StockCount { get; set; }
        public int CategoryId { get; set; }
    }

Configure AutoMapper

Now, we need to map our Entity properties to custom view model. There are two ways we can do this, one is to manually assign values and other best one is to use AutoMapper.

Add auto mapper package to the API project to setup AutoMapper

AutoMapper Version="8.0.0" AutoMapper.Extensions.Microsoft.DependencyInjection Version="6.0.0"

Configure AutoMapper for the Entities

Add a class AutoMapperConfiguration to the API project and inherit Profile class from AutoMapper. Create configuration for Product and ProductViewModel.

 public class AutoMapperConfiguration : Profile
    {
        public AutoMapperConfiguration()
        {
            CreateMap(); //source, destination
        }
    }

Modified Controller Code

using AutoMapper;
using KarthikTechBlog.Shopping.API.ViewModel;
using KarthikTechBlog.Shopping.Service;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace KarthikTechBlog.Shopping.API.Controllers
{
    public class ProductController : ControllerBase
    {
        public ProductController(IProductService productService, IMapper mapper)
        {
            ProductService = productService;
            Mapper = mapper;
        }

        public IProductService ProductService { get; }
        public IMapper Mapper { get; }

        public async Task GetProduct(
           [FromQuery] int productId)
        {
            var product = await ProductService.GetProductAsync(productId);
            var model = Mapper.Map(product);
            return new OkObjectResult(model);
        }
    }
}

Complete Controller Code to Implement CURD functionality in ASPNETCORE

using AutoMapper;
using KarthikTechBlog.Shopping.API.ViewModel;
using KarthikTechBlog.Shopping.Service;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using KarthikTechBlog.Shopping.Core;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;

namespace KarthikTechBlog.Shopping.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        public ProductController(IProductService productService, IMapper mapper)
        {
            ProductService = productService;
            Mapper = mapper;
        }

        public IProductService ProductService { get; }
        public IMapper Mapper { get; }

        [HttpGet("{productId}")]
        [ProducesResponseType(typeof(ProductViewModel), StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status404NotFound)]
        public async Task GetProduct(
           [FromRoute] int productId)
        {
            var product = await ProductService.GetProductAsync(productId);

            if (product == null)
                return NotFound();

            var model = Mapper.Map(product);
            return new OkObjectResult(model);
        }

        [HttpGet("")]
        [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status404NotFound)]
        public async Task GetProducts()
        {
            var products = await ProductService.GetProductsAsync();

            var model = Mapper.Map>(products);
            return new OkObjectResult(model);
        }

        [HttpPost("", Name = "CreateProduct")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status400BadRequest)]
        public async Task CreateProduct(
           [FromBody] CreateProduct product)
        {
            var entityToAdd = Mapper.Map(product);

            await ProductService.CreateProductAsync(entityToAdd);

            return Ok();
        }

        [HttpPut("{productId}", Name = "UpdateProduct")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task UpdateProduct(
           [FromRoute] int productId, [FromBody] UpdateProduct product)
        {

            var existingProduct = await ProductService.GetProductAsync(productId);

            if (existingProduct == null)
                return NotFound();

            var entityToUpdate = Mapper.Map(product);

            await ProductService.UpdateProductAsync(entityToUpdate);

            return Ok();
        }


        [HttpDelete("{productId}", Name = "DeleteProduct")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task DeleteProduct(
          [FromRoute] int productId)
        {

            var existingProduct = await ProductService.GetProductAsync(productId);

            if (existingProduct == null)
                return NotFound();

            await ProductService.DeleteProductAsync(productId);

            return Ok();
        }

    }
}

One last thing to include is to configure the DI in the ConfigureServices method of startup class.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext(options =>
               options.UseSqlServer(Configuration.GetConnectionString("DbContext")));
                        
            services.AddScoped();
            services.AddScoped();
            services.AddAutoMapper();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

Additional Resource

Design the infrastructure persistence layer

Conclusion

In this post, I showed how to implement create, read, update, and delete functionalities using Entity Framework Core. This post is part of learning track for azure AZ-203 certification. I have covered end to end coding that is required to write a good Restful API. In next post, I will show how to create API documentation using OpenAPI & Swagger.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Implement create, read, update, and delete functionalities using Entity Framework Core appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/01/10/implement-curd-functionalities-in-aspnetcore-using-entity-framework-core/feed/ 1 310
How to: Create an Azure App Service API app https://blogs.learnsmartcoding.com/2020/01/07/how-to-create-an-azure-app-service-api-app-for-free/ https://blogs.learnsmartcoding.com/2020/01/07/how-to-create-an-azure-app-service-api-app-for-free/#comments Tue, 07 Jan 2020 21:41:29 +0000 https://karthiktechblog.com/?p=290 Introduction In this short post, I’m going to cover topic “create an Azure App Service API app”. The details in this post will help to cover a part of knowledge required to complete Azure AZ-203 certification. Getting Started To publish any Web or API application that may have been developed using any programming language, we […]

The post How to: Create an Azure App Service API app appeared first on Learn Smart Coding.

]]>
Introduction

In this short post, I’m going to cover topic “create an Azure App Service API app”. The details in this post will help to cover a part of knowledge required to complete Azure AZ-203 certification.

Getting Started

To publish any Web or API application that may have been developed using any programming language, we need a place to host. “Azure App Service API app” comes handy for such case.

Yes, it is easy to create and publish API app in few minutes with Azure portal.

Take a look at my post how to create an Azure App Service Web App

Create Azure App Service API App

This is almost identical to my previous post on how to create an Azure App Service Web App.

Currently all of Web, Mobile and API Apps are collectively called App Services.

Azure still offer customer to be able to create a Mobile App and a Web App in the gallery but that is basically resolve into an App Service App.

There are two topics under ” Create Azure App Service API apps ” and they are as below. We will cover the first part in this post.

  • create an Azure App Service API app
  • create documentation for the API by using open source and other tools

To create API App, simply go to the search bar in the top and search with “API App” keyword. Search results that looks like below image.

Click on API App to begin deployment.

Create an Azure App Service API app

It is relatively simple to create and get this app deployed in few minutes using azure portal.

Follow the steps below

How to: Create an Azure App Service API app

Step by step guide to create API App

  1. Provide a unique name for the API App.
  2. Choose a subscription you have. E.g. If you have created a free account, you will see “Free trial” as subscription. I have Pay as you go plan so I have chosen that.
  3. Choose a resource group or create one. This helps to group various resource together.
  4. Choose an App service plan, I have selected existing one which is a Free tier F1. Refer this post for more details
  5. Leave the default for Application Insight, it is very useful one to app and it is almost free. I will cover more about this in a different post.
  6. Deployment is complete by clicking Create button.

Now you will see “Your deployment is underway” message, please be patience and give few minutes time for the process to complete.

After the deployment is complete, you may go the created resource. By clicking App Services from All Services menu, you can see our newly created app service “karthiktechblog-shopping-api”.

Click on it and you can see the details of the created app service.

deployment status of azure app service API App

According to Microsoft, there are many free services for 12 months and always free services. You can refer this information in the FAQ mentioned in the this link.

Conclusion

In this post, I have shown how to Create Azure App Service API Apps. This post is part of learning track for azure AZ-203 certification. In the upcoming post, I will cover how to create API App and deploy the application to this Web App and API App.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to: Create an Azure App Service API app appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/01/07/how-to-create-an-azure-app-service-api-app-for-free/feed/ 1 290
How to: Create Azure App Service Web Apps https://blogs.learnsmartcoding.com/2020/01/07/how-to-create-azure-app-service-web-apps-for-free/ https://blogs.learnsmartcoding.com/2020/01/07/how-to-create-azure-app-service-web-apps-for-free/#respond Tue, 07 Jan 2020 16:32:19 +0000 https://karthiktechblog.com/?p=274 Introduction In this post, I’m going to cover topic “create an Azure App Service Web App”. The details in this post will help to cover a part of knowledge required to complete Azure AZ-203 certification. Let’s focus on the one of the five below topic that is part of skills measured under “Develop Azure Platform […]

The post How to: Create Azure App Service Web Apps appeared first on Learn Smart Coding.

]]>
Introduction

In this post, I’m going to cover topic “create an Azure App Service Web App”. The details in this post will help to cover a part of knowledge required to complete Azure AZ-203 certification.

Let’s focus on the one of the five below topic that is part of skills measured under “Develop Azure Platform as a Service compute solution“.

To know more on AZ-203 certification, visit my detailed post “EXAM AZ-203: DEVELOPING SOLUTIONS FOR MICROSOFT AZURE

Getting Started

In order to start with Azure, you need Azure subscription. To follow along this post, you may use your subscription that you have or create a one for Free. Yes, it is free. Check this link for more details Free Azure

Why we need to Create Azure App Service Web Apps ?

According to App service documentation,

“Azure App Service enables you to build and host web apps, mobile back ends, and RESTful APIs in the programming language of your choice without managing infrastructure. It offers auto-scaling and high availability, supports both Windows and Linux, and enables automated deployments from GitHub, Azure DevOps, or any Git repo.”

By Microsoft

Create App Service

The process of creating app service is simple. Follow the below steps and you can refer the screenshot. Most of the below steps is common while creating a new resource for any services in Azure.

Create Azure App Service
Create App Service
  1. Choose a subscription you have. E.g. If you have created a free account, you will see “Free trial” as subscription. I have Pay as you go plan so I have chosen that.
  2. Choose a resource group or create one. This helps to group various resource together.
  3. Provide a unique name for the app service.
  4. Choose code since we are going to see how to publish a web application in our upcoming post. I will explain how to publish a docker container in a separate post.
  5. Choose a run time stack that suits the best for your application. In my case, I’m going to publish a .net core 2.2 version web app.
  6. choosing windows as operating system will reduce cost.
  7. choose a region that is close your location
  8. Name a plan or leave the default
  9. This is important to choose. As per the demand, you may choose your required plan. Since it is a demo, I have chosen Free F1 Shared infrastructure, 1 GB memory plan.
Create Azure App Service
Create Azure App Service for free

Click on review and create button. Confirm the selection and the service will be created.

Now you will see “Your deployment is underway” message, please be patience and give few minutes time for the process to complete.

Once the deployment is completed, you may go the created resource. By clicking App Services from All Services menu, you can see our newly created app service “karthiktechblog-shopping”.

Click on it and you can see the details of the created app service.

dashboard for Create Azure App Service web app

Benefits of Azure App Service

With the free azure app service that I have created in this post, I will be able to host any web, mobile, or API apps with Azure App Service with 1 GB storage. This is always free according to Microsoft and you can refer this information in the FAQ mentioned in the this link.

Conclusion

In this post, I have shown how to Create Azure App Service Web Apps. This post is part of learning track for azure AZ-203 certification. In the upcoming post, I will cover how to create API App and deploy the application to this Web App and API App.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to: Create Azure App Service Web Apps appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/01/07/how-to-create-azure-app-service-web-apps-for-free/feed/ 0 274
Exam AZ-203: Developing Solutions for Microsoft Azure https://blogs.learnsmartcoding.com/2019/12/26/exam-az-203-developing-solutions-for-microsoft-azure/ https://blogs.learnsmartcoding.com/2019/12/26/exam-az-203-developing-solutions-for-microsoft-azure/#respond Thu, 26 Dec 2019 08:37:30 +0000 https://karthiktechblog.com/?p=247 Introduction In this post, we will see the skills measured for the Exam AZ-203: Developing Solutions for Microsoft Azure and various examples for exam preparation. Note: The content of this exam was updated on November 6, 2019. I have highlighted in bold where the content is updated as of November 6, 2019. This exam retired […]

The post Exam AZ-203: Developing Solutions for Microsoft Azure appeared first on Learn Smart Coding.

]]>
Introduction

In this post, we will see the skills measured for the Exam AZ-203: Developing Solutions for Microsoft Azure and various examples for exam preparation.

Note: The content of this exam was updated on November 6, 2019. I have highlighted in bold where the content is updated as of November 6, 2019.

This exam retired on August 31, 2020. A replacement exam, AZ-204, is available. For more information, visit the AZ-204 exam details page.

There are several sections in each skill measured. I will be posting examples for each skill that is measured under this exam. By going through those posts, you will be able to cover this exam preparation.

Examples for each skill will have links on it, click on the link to navigate to the post.

However, I will recommend you to learn and practice more on each topic to be an expert.

Skills Measured: Developing Solutions for Microsoft Azure (AZ-203)

Develop Azure Infrastructure as a Service compute solutions (10-15%)

This part is further divided into three more sub-skills and they are measured as below.

Implement solutions that use virtual machines (VM)

  • provision VMs
  • create ARM templates
  • configure Azure Disk Encryption for VMs

Implement batch jobs by using Azure Batch Services

  • manage batch jobs by using Batch Service API
  • run a batch job by using Azure CLI, Azure portal, and other tools
  • write code to run an Azure Batch Services batch job

Create containerized solutions

  • create an Azure Managed Kubernetes Service (AKS) cluster
  • create container images for solutions
  • publish an image to the Azure Container Registry
  • run containers by using Azure Container Instance or AKS

Develop Azure Platform as a Service compute solution (20-25%)

This part is further divided into four more sub-skills and they are measured as below.

Create Azure App Service Web Apps

Create Azure App Service mobile apps

  • add push notifications for mobile apps
  • enable offline sync for mobile app
  • implement a remote instrumentation strategy for mobile devices

Create Azure App Service API apps

Implement Azure functions

  • implement input and output bindings for a function
  • implement function triggers by using data operations, timers, and webhooks
  • implement Azure Durable Functions
  • create Azure Function apps by using Visual Studio
  • implement Python Azure functions

Develop for Azure storage (15-20%)

This part is further divided into four more sub-skills and they are measured as below.

Develop solutions that use storage tables

  • design and implement policies for tables
  • query table storage by using code
  • implement partitioning schemes

Develop solutions that use Cosmos DB storage

  • create, read, update, and delete data by using appropriate APIs
  • implement partitioning schemes
  • set the appropriate consistency level for operations

Develop solutions that use a relational database

Develop solutions that use blob storage

  • move items in Blob storage between storage accounts or containers
  • set and retrieve properties and metadata
  • implement blob leasing
  • implement data archiving and retention
  • implement Geo Zone Redundant storage

Implement Azure security (10-15%)

This part is further divided into three more sub-skills and they are measured as below.

Implement authentication

  • implement authentication by using certificates, forms-based authentication, or tokens
  • implement multi-factor or Windows authentication by using Azure AD
  • implement OAuth2 authentication
  • implement Managed identities/Service Principal authentication •
  • implement Microsoft identity platform

Implement access control

  • implement CBAC (Claims-Based Access Control) authorization
  • implement RBAC (Role-Based Access Control) authorization
  • create shared access signatures

Implement secure data solutions

  • encrypt and decrypt data at rest and in transit
  • create, read, update, and delete keys, secrets, and certificates by using the KeyVault API

Monitor, troubleshoot, and optimize Azure solutions (10-15%)

This part is further divided into three more sub-skills and they are measured as below.

Develop code to support scalability of apps and services

  • implement autoscaling rules and patterns (schedule, operational/system metrics, singleton applications)
  • implement code that handles transient faults
  • implement AKS scaling strategies

Integrate caching and content delivery within solutions

  • store and retrieve data in Azure Redis cache
  • develop code to implement CDN’s in solutions
  • invalidate cache content (CDN or Redis)

Instrument solutions to support monitoring and logging

  • configure instrumentation in an app or service by using Application Insights
  • analyze and troubleshoot solutions by using Azure Monitor
  • implement Application Insights Web Test and Alerts

Connect to and consume Azure services and third-party services (20- 25%)

This part is further divided into five more sub-skills and they are measured as below.

Develop an App Service Logic App

  • create a Logic App
  • create a custom connector for Logic Apps
  • create a custom template for Logic Apps

Integrate Azure Search within solutions

  • create an Azure Search index
  • import searchable data
  • query the Azure Search index
  • implement cognitive search

Implement API Management

  • establish API Gateways
  • create an APIM instance
  • configure authentication for APIs
  • define policies for APIs

Develop event-based solutions

  • implement solutions that use Azure Event Grid
  • implement solutions that use Azure Notification Hubs
  • implement solutions that use Azure Event Hub

Develop message-based solutions

  • implement solutions that use Azure Service Bus
  • implement solutions that use Azure Queue Storage queues

For more details and latest update, visit https://docs.microsoft.com/en-us/learn/certifications/exams/az-203

Conclusion

In this post, you got to know what skills are measured for the Azure AZ-203 Developing Solutions for Microsoft Azure certification and links to various examples for the exam preparation.

That’s all from this article. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Exam AZ-203: Developing Solutions for Microsoft Azure appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2019/12/26/exam-az-203-developing-solutions-for-microsoft-azure/feed/ 0 247
Provision and Configure relational databases in azure portal: part 1 https://blogs.learnsmartcoding.com/2019/10/14/provision-and-configure-relational-databases-azure-portal/ https://blogs.learnsmartcoding.com/2019/10/14/provision-and-configure-relational-databases-azure-portal/#respond Mon, 14 Oct 2019 01:53:36 +0000 https://karthiktechblog.com/?p=206 Introduction This post is to provision and configure relational databases in the azure portal and is part of develop solutions that use a relational database. This post is part of the Azure AZ-203 certification path. The topic covered in this post is part of skills measurement, “Develop for Azure storage” and about 15-20 % of […]

The post Provision and Configure relational databases in azure portal: part 1 appeared first on Learn Smart Coding.

]]>
Introduction

This post is to provision and configure relational databases in the azure portal and is part of develop solutions that use a relational database.

This post is part of the Azure AZ-203 certification path. The topic covered in this post is part of skills measurement, “Develop for Azure storage” and about 15-20 % of skills are measured.

There are four topics under this skill measurement as shown below.

  • Develop solutions use
    1. storage tables
    2. Cosmos DB storage
    3. a relational database
    4. blob storage

Develop solutions that use a relational database

  1. provision and configure relational databases
  2. configure elastic pools for Azure SQL Database
  3. create, read, update, and delete data tables by using code
  4. provision and configure Azure SQL Database serverless instances
  5. provision and configure Azure SQL and Azure PostgreSQL Hyperscale instances

In this post, I will cover point # 1, how to provision and configure relational database using Azure SQL Server.

Before we get started, see take a look at Prerequisite below.

Prerequisite

  1. You need an Azure subscription. If you don’t have an account, you may create at “https://azure.microsoft.com/en-us/free/“. It is free and includes $200 to explore any Azure service for 30 days.
  2. Basic knowledge of the relational database.
  3. Visual Studio 2019 or 2017

Let’s get started..

Provision and configure relational databases

Once you have “Signed In” to the Azure portal, you will be able to see a bunch of links to the left side of the screen, refer below image. If you are yet to sign in, follow this link to sign in http://portal.azure.com.

Choosing SQL Database

Click in SQL Databases to the left side menu.

provision and configure relational databases

Click on “+ Add” to the top center of the screen as shown in the image. I have my SQL instance running so it is showing up in the available list.

add new database

Configuring SQL Server and SQL Database

Now, we need to provide some information to create a SQL Server and SQL database.

  • Choose subscription details from the drop-down, if you ave created your new account then you will see subscription as “Free Trail”.
  • Next is to create a resource group. Hey wait wait…, what is the resource group?

According to Microsoft, a resource group is described below.

resource group – A container that holds related resources for an Azure solution. The resource group includes those resources that you want to manage as a group. You decide which resources belong in a resource group based on what makes the most sense for your organization

From Microsoft

For more information, visit https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview

provision and configure relational databases

Create a new SQL server

We should create a new SQL server and provide a unique name to our database. Click on “Create New“, there will be a popup shown to your right side. Fill up the server name, provide username and password, choose a location.

I have created a database name “shopping“. I will cover how to configure this database and execute migration scripts using visual studio 2019.

configure SQL Database and choose SQL server

Click on “Review + Create” and you are done. It takes a few seconds to deploy the server.

list of SQL database

To check the connection string of the SQL server and database that we created, go to “SQL Databases” link in the left menu. You can then choose your newly created database and go to the Overview blade (menu).

overview blade of SQL server and database

To your top right side, click on “show database connection string” to copy the connection string.

Note:

Azure database is secured by default, meaning no external connections will be accepted by the firewall. In order to connect to your Azure database from your local, you need to add your IP (client IP) in the SQL Server in the Azure portal.

Read my post on how to SET UP CI PIPELINE FOR ANGULAR APPLICATION USING AZURE DEVOPS BUILD to learn azure DevOps pipeline.

Conclusion

In this post, you learned how to provision and configure relational databases in the Azure portal. In my next post, I will show how to design a database schema for a small application and push the changes to our SQL Database in Azure.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below. If you want to get a continuous update about my blog, make sure to follow me on Facebook and Twitter.

The post Provision and Configure relational databases in azure portal: part 1 appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2019/10/14/provision-and-configure-relational-databases-azure-portal/feed/ 0 206