Custom Connector for Web API
This tutorial will discuss how to create an ASP.Net Web application and use this web API.
a.Create a new ASP .Net Web application project using Visual Studio
b.Build, Deploy & Secure a Web API in Azure
1. Create a new ASP .Net Web application project using Visual Studio
Open visual studio 2019, select ASP.NET web application (.Net Framework), give the project name, and click Create.
Add a new empty controller to the project. Right click on the “Controllers” folder & select Add -> Controller
-> Web API 2 Controller -Empty.
Name this “ProductsController” as shown in the below screen shorts
The Project structure looks like below format
Next step, right click on the “Models” folder & select Add -> cs file-> and name it “ProductsControllers.cs”.
Add again take a new empty controller to the project. Right click on the “Controllers” folder & select Add -> Controller -> Web API 2 Controller -Empty. Name this “ProductsController”
using System;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using static WebAPI.Models.ProductsControllers;
using ProductsApp.Models;
namespace WebAPI.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = “RICE”, Category = “Groceries”, Price = 1500 },
new Product { Id = 2, Name = “Fish”, Category = “SeaFood”, Price = 500 },
new Product { Id = 3, Name = “Fruits and vegetables”, Category = “vegetables”, Price = 100 }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
Our API returns will return the response as XML. We will modify the code such that the API returns the response as JSON. In the “WebApiConfig.cs” add a new class as shown below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web;
using System.Xml;
namespace WebAPI.Views
{
public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
public BrowserJsonFormatter()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));
this.SerializerSettings.Formatting = (Newtonsoft.Json.Formatting)Formatting.Indented;
}
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
headers.ContentType = new MediaTypeHeaderValue(“application/json”);
}
}
}
In the “Register” function of the “WebApiConfig” class, add the newly created Formatter
config.Formatters.Add(new Views.BrowserJsonFormatter());
Build and Run the app – Browse to the URL – http://localhost: {portnumber}/api/products. You should observe the response being returned as JSON
2. Build, Deploy & Secure a Web API in Azure
Now Let’s publish the app to Azure. Right click on the project and select “Publish”.
Select Azure and Click on “Next”. Click on Next and choose “Azure App Service” as you publish target and click Next from the Azure App service window. Select “Create New”. Also, choose “Create Profile” to modify the app service details.
On the next screen, choose the “Azure App Service(Windows)” and click next.
We need to select the subscription name, Resource group, and app service instance from Azure; if you don’t have an app service instance please create new app service instance by clicking “+” as shown in below screen; after filling in all information click on finish and click on publish.
Currently, we are having the API has anonymous access. We will now secure the API with Azure AD Authentication.
Log in to the Azure Portal. Under “App Services”, select the App service that we just provisioned above. Select “Authentication” and click on Add provider and in Identity provider as “sign in Microsoft and Azure AD identities and call Microsoft API’s” as shown in the below screenshot.
3. Connect API To Power Apps Using Custom Connector
For Power Apps to access the secure API, we will need to register a client application in Azure AD.
Log in to the Azure Portal and navigate to Azure Active Directory. In the left navigation, select “App Registrations” and select “New Registration”.
Enter a name for your app and select the kind of accounts you want to give access to the API.
For the types of accounts supported in this case, we select “Multitenant”. We wanted to access our API in a different tenant leave the “Redirect Uri” as blank for now and click on “Register”.
From the “Overview” section, make a note of the “Client ID” & “Tenant ID”. Keep this handy; we will need these details when we configure the custom connector.
Click on “API Permissions” from the left navigation and click “Add a permission”. From the side pane that opens, search for your app & select the app.
Next, we need to Generate a “Client secret” for the app.
From the left navigation, select “Certificates & secrets” under “Client Secret”, and click on “New client secret”. Choose when you want the secret to expire from the available choice and click on “Add”.
The secret will be displayed only once. Note the secret ID and keep it handy for later use, as shown in the screenshot below for reference.
In this blog how to connect the Custom connectors by using power Automate please follow this link
Custom Connector from an OpenAPI definition
For any Help or Queries Contact us on info@crmonce.com or +91 8096556344
The CreatePass OnWorkerStatusApproved
plugin is a custom plugin developed for Microsoft Dynamics 365 (CRM). It triggers when the status of a worker entity (crm_worker
) is updated. Specifically, it runs when the worker’s status is changed to “Approved”. When triggered, the plugin automatically creates a related “Pass” entity (crm_pass
) with details pulled from the worker record.
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
public class CreatePassOnWorkerStatusApproved : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
tracingService.Trace(“CreatePassOnWorkerStatusApproved Plugin: Execution started.”);
try
{
if (context.MessageName != “Update”)
return;
tracingService.Trace(“Message is Update.”);
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
Entity entity = (Entity)context.InputParameters[“Target”];
if (entity.LogicalName == “crm_worker” && entity.Contains(“crm_workerstatus”))
{
tracingService.Trace(“Entity is crm_worker and contains workstatus.”);
Entity workerEntity = service.Retrieve(“crm_worker”, entity.Id, new ColumnSet(true));
tracingService.Trace(“Worker entity retrieved. Worker Id: {0}”, workerEntity.Id);
if (workerEntity.GetAttributeValue<OptionSetValue>(“crm_workerstatus”).Value == 770060001)
{
tracingService.Trace(“Worker status is Approved.”);
Entity passEntity = new Entity(“crm_pass”);
passEntity[“crm_name”] = workerEntity.GetAttributeValue<string>(“crm_passnumber”);
passEntity[“crm_passexpiredate”] = workerEntity.GetAttributeValue<DateTime>(“crm_passexpiredate”);
passEntity[“crm_passissuedate”] = workerEntity.GetAttributeValue<DateTime>(“crm_passissuedate”);
passEntity[“crm_department”] = workerEntity.GetAttributeValue<string>(“crm_department”);
passEntity[“crm_designation”] = workerEntity.GetAttributeValue<string>(“crm_designation”);
passEntity[“crm_worker”] = new EntityReference(“crm_worker”, workerEntity.Id);
tracingService.Trace(“crm_worker lookup set.”);
passEntity[“crm_passstatus”] = workerEntity.GetAttributeValue<OptionSetValue>(“crm_passstatus”);
tracingService.Trace(“crm_passstatus set.”);
passEntity[“crm_passtype”] = workerEntity.GetAttributeValue<OptionSetValue>(“crm_passtype”);
tracingService.Trace(“crm_passtype set.”);
if (workerEntity.Contains(“crm_companyname”))
{
EntityReference accountRef = workerEntity.GetAttributeValue<EntityReference>(“crm_companyname”);
Entity accountEntity = service.Retrieve(“crm_company”, accountRef.Id, new ColumnSet(“crm_name”));
passEntity[“crm_companyname”] = accountEntity.GetAttributeValue<string>(“crm_name”);
tracingService.Trace(“Account name set in crm_company field.”);
}
service.Create(passEntity);
tracingService.Trace(“Pass record created successfully.”);
}
}
}
catch (Exception ex)
{
tracingService.Trace(“CreatePassOnWorkerStatusApproved Plugin: {0}”, ex.ToString());
throw;
}
}
}