Converting Dynamics's Geolocation to SQL Geolocation using Microsoft Flow and Azure Function
Recently I have been
working on a proof of concept to integrate Power Platform with Azure Search to
facilitate enterprise search. I have been amazed by the power of integrating
Power Platform with Azure Search and I will share my experience shortly in my
upcoming blog posts. However, today I want to explain how did I met a small
requirement in my proof of concept.
Background
One of the awesome
features of the Azure Search service is the ability to search information based
on location. Azure Search processes, filters, and displays geographic
locations. It enables users to explore data based on the proximity of a search
result to a physical location. This feature is powered by SQL Server
Geolocation data type. Since SQL Server 2008, developers are able store
geospatial data in SQL server using Geolocation fields. Geolocation fields
allow querying data with location based queries. To facilitate the Azure Search
service to search within CRM accounts and contact, I had to pushed my account
and contact searchable information to SQL server hosted in Azure. To copy
information from Dynamics to Azure SQL server, I used Microsoft flow.
Everything worked good except, copying CRM longitude and Latitude to SQL
Server.
The problem
The problem with
copying longitude and latitude to SQL server Geolocation field is the
compatibility. When you try to insert longitude and latitude fields to
Geolocation you encounter casting error.
The solution
The solution I used
to tackle this problem is making use of Azure Function and converting Longitude
and Latitude to Geolocation type in the Azure function and return the response
before the Insert action in the flow. See the below steps:
- Step 1 is self-explanatory.
- The step "CC Contact" extracts the Contact name (or any lookup name property) from a lookup.
- The "Http" step, calls the Azure Function to converts the CRM longitude and Latitude to SQL Geolocation field
- The "Insert Row" step, inserts our data to SQL server row.
The Azure Function
The Azure function
is a very simple function. You will need to import Microsoft.SqlServer.Types
Nuget package and use the below code:
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
Coordinates data = JsonConvert.DeserializeObject<Coordinates>(requestBody);
SqlGeography point = data.GetGeography();
return ( ActionResult ) new OkObjectResult ( $"{point}" );
public class Coordinates
{
public double Longitude { get; set; }
public double Latitude { get; set; }
public SqlGeography GetGeography ( )
{
try
{
return SqlGeography. Point ( Latitude , Longitude , 4326 );
}
catch ( Exception ex )
{
// Log ex and handle exception
throw ex;
}
}
}
Comments
Post a Comment